effectLayer.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import { serialize, serializeAsColor4, serializeAsCameraReference } from "../Misc/decorators";
  2. import { Tools } from "../Misc/tools";
  3. import { SmartArray } from "../Misc/smartArray";
  4. import { Observable } from "../Misc/observable";
  5. import { Nullable } from "../types";
  6. import { Camera } from "../Cameras/camera";
  7. import { Scene } from "../scene";
  8. import { Color4, ISize } from "../Maths/math";
  9. import { Engine } from "../Engines/engine";
  10. import { EngineStore } from "../Engines/engineStore";
  11. import { VertexBuffer } from "../Meshes/buffer";
  12. import { SubMesh } from "../Meshes/subMesh";
  13. import { AbstractMesh } from "../Meshes/abstractMesh";
  14. import { Mesh } from "../Meshes/mesh";
  15. import { PostProcess } from "../PostProcesses/postProcess";
  16. import { _TimeToken } from "../Instrumentation/timeToken";
  17. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  18. import { BaseTexture } from "../Materials/Textures/baseTexture";
  19. import { Texture } from "../Materials/Textures/texture";
  20. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  21. import { Effect, EffectFallbacks } from "../Materials/effect";
  22. import { Material } from "../Materials/material";
  23. import { MaterialHelper } from "../Materials/materialHelper";
  24. import { Constants } from "../Engines/constants";
  25. import "../Shaders/glowMapGeneration.fragment";
  26. import "../Shaders/glowMapGeneration.vertex";
  27. import { _DevTools } from '../Misc/devTools';
  28. import { DataBuffer } from '../Meshes/dataBuffer';
  29. /**
  30. * Effect layer options. This helps customizing the behaviour
  31. * of the effect layer.
  32. */
  33. export interface IEffectLayerOptions {
  34. /**
  35. * Multiplication factor apply to the canvas size to compute the render target size
  36. * used to generated the objects (the smaller the faster).
  37. */
  38. mainTextureRatio: number;
  39. /**
  40. * Enforces a fixed size texture to ensure effect stability across devices.
  41. */
  42. mainTextureFixedSize?: number;
  43. /**
  44. * Alpha blending mode used to apply the blur. Default depends of the implementation.
  45. */
  46. alphaBlendingMode: number;
  47. /**
  48. * The camera attached to the layer.
  49. */
  50. camera: Nullable<Camera>;
  51. /**
  52. * The rendering group to draw the layer in.
  53. */
  54. renderingGroupId: number;
  55. }
  56. /**
  57. * The effect layer Helps adding post process effect blended with the main pass.
  58. *
  59. * This can be for instance use to generate glow or higlight effects on the scene.
  60. *
  61. * The effect layer class can not be used directly and is intented to inherited from to be
  62. * customized per effects.
  63. */
  64. export abstract class EffectLayer {
  65. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  66. private _indexBuffer: Nullable<DataBuffer>;
  67. private _cachedDefines: string;
  68. private _effectLayerMapGenerationEffect: Effect;
  69. private _effectLayerOptions: IEffectLayerOptions;
  70. private _mergeEffect: Effect;
  71. protected _scene: Scene;
  72. protected _engine: Engine;
  73. protected _maxSize: number = 0;
  74. protected _mainTextureDesiredSize: ISize = { width: 0, height: 0 };
  75. protected _mainTexture: RenderTargetTexture;
  76. protected _shouldRender = true;
  77. protected _postProcesses: PostProcess[] = [];
  78. protected _textures: BaseTexture[] = [];
  79. protected _emissiveTextureAndColor: { texture: Nullable<BaseTexture>, color: Color4 } = { texture: null, color: new Color4() };
  80. /**
  81. * The name of the layer
  82. */
  83. @serialize()
  84. public name: string;
  85. /**
  86. * The clear color of the texture used to generate the glow map.
  87. */
  88. @serializeAsColor4()
  89. public neutralColor: Color4 = new Color4();
  90. /**
  91. * Specifies wether the highlight layer is enabled or not.
  92. */
  93. @serialize()
  94. public isEnabled: boolean = true;
  95. /**
  96. * Gets the camera attached to the layer.
  97. */
  98. @serializeAsCameraReference()
  99. public get camera(): Nullable<Camera> {
  100. return this._effectLayerOptions.camera;
  101. }
  102. /**
  103. * Gets the rendering group id the layer should render in.
  104. */
  105. @serialize()
  106. public get renderingGroupId(): number {
  107. return this._effectLayerOptions.renderingGroupId;
  108. }
  109. /**
  110. * An event triggered when the effect layer has been disposed.
  111. */
  112. public onDisposeObservable = new Observable<EffectLayer>();
  113. /**
  114. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  115. */
  116. public onBeforeRenderMainTextureObservable = new Observable<EffectLayer>();
  117. /**
  118. * An event triggered when the generated texture is being merged in the scene.
  119. */
  120. public onBeforeComposeObservable = new Observable<EffectLayer>();
  121. /**
  122. * An event triggered when the generated texture has been merged in the scene.
  123. */
  124. public onAfterComposeObservable = new Observable<EffectLayer>();
  125. /**
  126. * An event triggered when the efffect layer changes its size.
  127. */
  128. public onSizeChangedObservable = new Observable<EffectLayer>();
  129. /** @hidden */
  130. public static _SceneComponentInitialization: (scene: Scene) => void = (_) => {
  131. throw _DevTools.WarnImport("EffectLayerSceneComponent");
  132. }
  133. /**
  134. * Instantiates a new effect Layer and references it in the scene.
  135. * @param name The name of the layer
  136. * @param scene The scene to use the layer in
  137. */
  138. constructor(
  139. /** The Friendly of the effect in the scene */
  140. name: string,
  141. scene: Scene) {
  142. this.name = name;
  143. this._scene = scene || EngineStore.LastCreatedScene;
  144. EffectLayer._SceneComponentInitialization(this._scene);
  145. this._engine = this._scene.getEngine();
  146. this._maxSize = this._engine.getCaps().maxTextureSize;
  147. this._scene.effectLayers.push(this);
  148. // Generate Buffers
  149. this._generateIndexBuffer();
  150. this._generateVertexBuffer();
  151. }
  152. /**
  153. * Get the effect name of the layer.
  154. * @return The effect name
  155. */
  156. public abstract getEffectName(): string;
  157. /**
  158. * Checks for the readiness of the element composing the layer.
  159. * @param subMesh the mesh to check for
  160. * @param useInstances specify wether or not to use instances to render the mesh
  161. * @return true if ready otherwise, false
  162. */
  163. public abstract isReady(subMesh: SubMesh, useInstances: boolean): boolean;
  164. /**
  165. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  166. * @returns true if the effect requires stencil during the main canvas render pass.
  167. */
  168. public abstract needStencil(): boolean;
  169. /**
  170. * Create the merge effect. This is the shader use to blit the information back
  171. * to the main canvas at the end of the scene rendering.
  172. * @returns The effect containing the shader used to merge the effect on the main canvas
  173. */
  174. protected abstract _createMergeEffect(): Effect;
  175. /**
  176. * Creates the render target textures and post processes used in the effect layer.
  177. */
  178. protected abstract _createTextureAndPostProcesses(): void;
  179. /**
  180. * Implementation specific of rendering the generating effect on the main canvas.
  181. * @param effect The effect used to render through
  182. */
  183. protected abstract _internalRender(effect: Effect): void;
  184. /**
  185. * Sets the required values for both the emissive texture and and the main color.
  186. */
  187. protected abstract _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void;
  188. /**
  189. * Free any resources and references associated to a mesh.
  190. * Internal use
  191. * @param mesh The mesh to free.
  192. */
  193. public abstract _disposeMesh(mesh: Mesh): void;
  194. /**
  195. * Serializes this layer (Glow or Highlight for example)
  196. * @returns a serialized layer object
  197. */
  198. public abstract serialize?(): any;
  199. /**
  200. * Initializes the effect layer with the required options.
  201. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  202. */
  203. protected _init(options: Partial<IEffectLayerOptions>): void {
  204. // Adapt options
  205. this._effectLayerOptions = {
  206. mainTextureRatio: 0.5,
  207. alphaBlendingMode: Constants.ALPHA_COMBINE,
  208. camera: null,
  209. renderingGroupId: -1,
  210. ...options,
  211. };
  212. this._setMainTextureSize();
  213. this._createMainTexture();
  214. this._createTextureAndPostProcesses();
  215. this._mergeEffect = this._createMergeEffect();
  216. }
  217. /**
  218. * Generates the index buffer of the full screen quad blending to the main canvas.
  219. */
  220. private _generateIndexBuffer(): void {
  221. // Indices
  222. var indices = [];
  223. indices.push(0);
  224. indices.push(1);
  225. indices.push(2);
  226. indices.push(0);
  227. indices.push(2);
  228. indices.push(3);
  229. this._indexBuffer = this._engine.createIndexBuffer(indices);
  230. }
  231. /**
  232. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  233. */
  234. private _generateVertexBuffer(): void {
  235. // VBO
  236. var vertices = [];
  237. vertices.push(1, 1);
  238. vertices.push(-1, 1);
  239. vertices.push(-1, -1);
  240. vertices.push(1, -1);
  241. var vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  242. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  243. }
  244. /**
  245. * Sets the main texture desired size which is the closest power of two
  246. * of the engine canvas size.
  247. */
  248. private _setMainTextureSize(): void {
  249. if (this._effectLayerOptions.mainTextureFixedSize) {
  250. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  251. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  252. }
  253. else {
  254. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  255. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  256. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  257. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  258. }
  259. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  260. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  261. }
  262. /**
  263. * Creates the main texture for the effect layer.
  264. */
  265. protected _createMainTexture(): void {
  266. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  267. {
  268. width: this._mainTextureDesiredSize.width,
  269. height: this._mainTextureDesiredSize.height
  270. },
  271. this._scene,
  272. false,
  273. true,
  274. Constants.TEXTURETYPE_UNSIGNED_INT);
  275. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  276. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  277. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  278. this._mainTexture.anisotropicFilteringLevel = 1;
  279. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  280. this._mainTexture.renderParticles = false;
  281. this._mainTexture.renderList = null;
  282. this._mainTexture.ignoreCameraViewport = true;
  283. // Custom render function
  284. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  285. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  286. var index: number;
  287. let engine = this._scene.getEngine();
  288. if (depthOnlySubMeshes.length) {
  289. engine.setColorWrite(false);
  290. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  291. this._renderSubMesh(depthOnlySubMeshes.data[index]);
  292. }
  293. engine.setColorWrite(true);
  294. }
  295. for (index = 0; index < opaqueSubMeshes.length; index++) {
  296. this._renderSubMesh(opaqueSubMeshes.data[index]);
  297. }
  298. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  299. this._renderSubMesh(alphaTestSubMeshes.data[index]);
  300. }
  301. const previousAlphaMode = engine.getAlphaMode();
  302. for (index = 0; index < transparentSubMeshes.length; index++) {
  303. this._renderSubMesh(transparentSubMeshes.data[index], true);
  304. }
  305. engine.setAlphaMode(previousAlphaMode);
  306. };
  307. this._mainTexture.onClearObservable.add((engine: Engine) => {
  308. engine.clear(this.neutralColor, true, true, true);
  309. });
  310. }
  311. /**
  312. * Adds specific effects defines.
  313. * @param defines The defines to add specifics to.
  314. */
  315. protected _addCustomEffectDefines(defines: string[]): void {
  316. // Nothing to add by default.
  317. }
  318. /**
  319. * Checks for the readiness of the element composing the layer.
  320. * @param subMesh the mesh to check for
  321. * @param useInstances specify wether or not to use instances to render the mesh
  322. * @param emissiveTexture the associated emissive texture used to generate the glow
  323. * @return true if ready otherwise, false
  324. */
  325. protected _isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable<BaseTexture>): boolean {
  326. let material = subMesh.getMaterial();
  327. if (!material) {
  328. return false;
  329. }
  330. if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
  331. return false;
  332. }
  333. var defines: string[] = [];
  334. var attribs = [VertexBuffer.PositionKind];
  335. var mesh = subMesh.getMesh();
  336. var uv1 = false;
  337. var uv2 = false;
  338. // Diffuse
  339. if (material) {
  340. const needAlphaTest = material.needAlphaTesting();
  341. const diffuseTexture = material.getAlphaTestTexture();
  342. const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
  343. ((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
  344. if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
  345. defines.push("#define DIFFUSE");
  346. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  347. diffuseTexture.coordinatesIndex === 1) {
  348. defines.push("#define DIFFUSEUV2");
  349. uv2 = true;
  350. }
  351. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  352. defines.push("#define DIFFUSEUV1");
  353. uv1 = true;
  354. }
  355. if (needAlphaTest) {
  356. defines.push("#define ALPHATEST");
  357. defines.push("#define ALPHATESTVALUE 0.4");
  358. }
  359. }
  360. var opacityTexture = (material as any).opacityTexture;
  361. if (opacityTexture) {
  362. defines.push("#define OPACITY");
  363. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  364. opacityTexture.coordinatesIndex === 1) {
  365. defines.push("#define OPACITYUV2");
  366. uv2 = true;
  367. }
  368. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  369. defines.push("#define OPACITYUV1");
  370. uv1 = true;
  371. }
  372. }
  373. }
  374. // Emissive
  375. if (emissiveTexture) {
  376. defines.push("#define EMISSIVE");
  377. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  378. emissiveTexture.coordinatesIndex === 1) {
  379. defines.push("#define EMISSIVEUV2");
  380. uv2 = true;
  381. }
  382. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  383. defines.push("#define EMISSIVEUV1");
  384. uv1 = true;
  385. }
  386. }
  387. // Vertex
  388. if (mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha) {
  389. attribs.push(VertexBuffer.ColorKind);
  390. defines.push("#define VERTEXALPHA");
  391. }
  392. if (uv1) {
  393. attribs.push(VertexBuffer.UVKind);
  394. defines.push("#define UV1");
  395. }
  396. if (uv2) {
  397. attribs.push(VertexBuffer.UV2Kind);
  398. defines.push("#define UV2");
  399. }
  400. // Bones
  401. const fallbacks = new EffectFallbacks();
  402. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  403. attribs.push(VertexBuffer.MatricesIndicesKind);
  404. attribs.push(VertexBuffer.MatricesWeightsKind);
  405. if (mesh.numBoneInfluencers > 4) {
  406. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  407. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  408. }
  409. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  410. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  411. if (mesh.numBoneInfluencers > 0) {
  412. fallbacks.addCPUSkinningFallback(0, mesh);
  413. }
  414. } else {
  415. defines.push("#define NUM_BONE_INFLUENCERS 0");
  416. }
  417. // Morph targets
  418. var manager = (<Mesh>mesh).morphTargetManager;
  419. let morphInfluencers = 0;
  420. if (manager) {
  421. if (manager.numInfluencers > 0) {
  422. defines.push("#define MORPHTARGETS");
  423. morphInfluencers = manager.numInfluencers;
  424. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  425. MaterialHelper.PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
  426. }
  427. }
  428. // Instances
  429. if (useInstances) {
  430. defines.push("#define INSTANCES");
  431. MaterialHelper.PushAttributesForInstances(attribs);
  432. }
  433. this._addCustomEffectDefines(defines);
  434. // Get correct effect
  435. var join = defines.join("\n");
  436. if (this._cachedDefines !== join) {
  437. this._cachedDefines = join;
  438. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  439. attribs,
  440. ["world", "mBones", "viewProjection",
  441. "glowColor", "morphTargetInfluences",
  442. "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"],
  443. ["diffuseSampler", "emissiveSampler", "opacitySampler"], join,
  444. fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  445. }
  446. return this._effectLayerMapGenerationEffect.isReady();
  447. }
  448. /**
  449. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  450. */
  451. public render(): void {
  452. var currentEffect = this._mergeEffect;
  453. // Check
  454. if (!currentEffect.isReady()) {
  455. return;
  456. }
  457. for (var i = 0; i < this._postProcesses.length; i++) {
  458. if (!this._postProcesses[i].isReady()) {
  459. return;
  460. }
  461. }
  462. var engine = this._scene.getEngine();
  463. this.onBeforeComposeObservable.notifyObservers(this);
  464. // Render
  465. engine.enableEffect(currentEffect);
  466. engine.setState(false);
  467. // VBOs
  468. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  469. // Cache
  470. var previousAlphaMode = engine.getAlphaMode();
  471. // Go Blend.
  472. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  473. // Blends the map on the main canvas.
  474. this._internalRender(currentEffect);
  475. // Restore Alpha
  476. engine.setAlphaMode(previousAlphaMode);
  477. this.onAfterComposeObservable.notifyObservers(this);
  478. // Handle size changes.
  479. var size = this._mainTexture.getSize();
  480. this._setMainTextureSize();
  481. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  482. // Recreate RTT and post processes on size change.
  483. this.onSizeChangedObservable.notifyObservers(this);
  484. this._disposeTextureAndPostProcesses();
  485. this._createMainTexture();
  486. this._createTextureAndPostProcesses();
  487. }
  488. }
  489. /**
  490. * Determine if a given mesh will be used in the current effect.
  491. * @param mesh mesh to test
  492. * @returns true if the mesh will be used
  493. */
  494. public hasMesh(mesh: AbstractMesh): boolean {
  495. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  496. return true;
  497. }
  498. return false;
  499. }
  500. /**
  501. * Returns true if the layer contains information to display, otherwise false.
  502. * @returns true if the glow layer should be rendered
  503. */
  504. public shouldRender(): boolean {
  505. return this.isEnabled && this._shouldRender;
  506. }
  507. /**
  508. * Returns true if the mesh should render, otherwise false.
  509. * @param mesh The mesh to render
  510. * @returns true if it should render otherwise false
  511. */
  512. protected _shouldRenderMesh(mesh: AbstractMesh): boolean {
  513. return true;
  514. }
  515. /**
  516. * Returns true if the mesh can be rendered, otherwise false.
  517. * @param mesh The mesh to render
  518. * @param material The material used on the mesh
  519. * @returns true if it can be rendered otherwise false
  520. */
  521. protected _canRenderMesh(mesh: AbstractMesh, material: Material): boolean {
  522. return !material.needAlphaBlendingForMesh(mesh);
  523. }
  524. /**
  525. * Returns true if the mesh should render, otherwise false.
  526. * @param mesh The mesh to render
  527. * @returns true if it should render otherwise false
  528. */
  529. protected _shouldRenderEmissiveTextureForMesh(): boolean {
  530. return true;
  531. }
  532. /**
  533. * Renders the submesh passed in parameter to the generation map.
  534. */
  535. protected _renderSubMesh(subMesh: SubMesh, enableAlphaMode: boolean = false): void {
  536. if (!this.shouldRender()) {
  537. return;
  538. }
  539. var material = subMesh.getMaterial();
  540. var mesh = subMesh.getRenderingMesh();
  541. var scene = this._scene;
  542. var engine = scene.getEngine();
  543. mesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
  544. if (!material) {
  545. return;
  546. }
  547. // Do not block in blend mode.
  548. if (!this._canRenderMesh(mesh, material)) {
  549. return;
  550. }
  551. // Culling
  552. engine.setState(material.backFaceCulling);
  553. // Managing instances
  554. var batch = mesh._getInstancesRenderList(subMesh._id);
  555. if (batch.mustReturn) {
  556. return;
  557. }
  558. // Early Exit per mesh
  559. if (!this._shouldRenderMesh(mesh)) {
  560. return;
  561. }
  562. var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id];
  563. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  564. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  565. engine.enableEffect(this._effectLayerMapGenerationEffect);
  566. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, Material.TriangleFillMode);
  567. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  568. this._effectLayerMapGenerationEffect.setFloat4("glowColor",
  569. this._emissiveTextureAndColor.color.r,
  570. this._emissiveTextureAndColor.color.g,
  571. this._emissiveTextureAndColor.color.b,
  572. this._emissiveTextureAndColor.color.a);
  573. const needAlphaTest = material.needAlphaTesting();
  574. const diffuseTexture = material.getAlphaTestTexture();
  575. const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
  576. ((material as any).useAlphaFromDiffuseTexture || (material as any)._useAlphaFromAlbedoTexture);
  577. if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
  578. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture);
  579. const textureMatrix = diffuseTexture.getTextureMatrix();
  580. if (textureMatrix) {
  581. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  582. }
  583. }
  584. const opacityTexture = (material as any).opacityTexture;
  585. if (opacityTexture) {
  586. this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture);
  587. this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level);
  588. const textureMatrix = opacityTexture.getTextureMatrix();
  589. if (textureMatrix) {
  590. this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix);
  591. }
  592. }
  593. // Glow emissive only
  594. if (this._emissiveTextureAndColor.texture) {
  595. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  596. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  597. }
  598. // Bones
  599. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  600. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  601. }
  602. // Morph targets
  603. MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  604. // Alpha mode
  605. if (enableAlphaMode) {
  606. engine.setAlphaMode(material.alphaMode);
  607. }
  608. // Draw
  609. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  610. (isInstance, world) => this._effectLayerMapGenerationEffect.setMatrix("world", world));
  611. } else {
  612. // Need to reset refresh rate of the main map
  613. this._mainTexture.resetRefreshCounter();
  614. }
  615. }
  616. /**
  617. * Rebuild the required buffers.
  618. * @hidden Internal use only.
  619. */
  620. public _rebuild(): void {
  621. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  622. if (vb) {
  623. vb._rebuild();
  624. }
  625. this._generateIndexBuffer();
  626. }
  627. /**
  628. * Dispose only the render target textures and post process.
  629. */
  630. private _disposeTextureAndPostProcesses(): void {
  631. this._mainTexture.dispose();
  632. for (var i = 0; i < this._postProcesses.length; i++) {
  633. if (this._postProcesses[i]) {
  634. this._postProcesses[i].dispose();
  635. }
  636. }
  637. this._postProcesses = [];
  638. for (var i = 0; i < this._textures.length; i++) {
  639. if (this._textures[i]) {
  640. this._textures[i].dispose();
  641. }
  642. }
  643. this._textures = [];
  644. }
  645. /**
  646. * Dispose the highlight layer and free resources.
  647. */
  648. public dispose(): void {
  649. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  650. if (vertexBuffer) {
  651. vertexBuffer.dispose();
  652. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  653. }
  654. if (this._indexBuffer) {
  655. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  656. this._indexBuffer = null;
  657. }
  658. // Clean textures and post processes
  659. this._disposeTextureAndPostProcesses();
  660. // Remove from scene
  661. var index = this._scene.effectLayers.indexOf(this, 0);
  662. if (index > -1) {
  663. this._scene.effectLayers.splice(index, 1);
  664. }
  665. // Callback
  666. this.onDisposeObservable.notifyObservers(this);
  667. this.onDisposeObservable.clear();
  668. this.onBeforeRenderMainTextureObservable.clear();
  669. this.onBeforeComposeObservable.clear();
  670. this.onAfterComposeObservable.clear();
  671. this.onSizeChangedObservable.clear();
  672. }
  673. /**
  674. * Gets the class name of the effect layer
  675. * @returns the string with the class name of the effect layer
  676. */
  677. public getClassName(): string {
  678. return "EffectLayer";
  679. }
  680. /**
  681. * Creates an effect layer from parsed effect layer data
  682. * @param parsedEffectLayer defines effect layer data
  683. * @param scene defines the current scene
  684. * @param rootUrl defines the root URL containing the effect layer information
  685. * @returns a parsed effect Layer
  686. */
  687. public static Parse(parsedEffectLayer: any, scene: Scene, rootUrl: string): EffectLayer {
  688. var effectLayerType = Tools.Instantiate(parsedEffectLayer.customType);
  689. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  690. }
  691. }