effectLayer.ts 29 KB

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