effectLayer.ts 32 KB

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