babylon.highlightlayer.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. module BABYLON {
  2. /**
  3. * Special Glow Blur post process only blurring the alpha channel
  4. * It enforces keeping the most luminous color in the color channel.
  5. */
  6. class GlowBlurPostProcess extends PostProcess {
  7. constructor(name: string, public direction: Vector2, public blurWidth: number, options: number | PostProcessOptions, camera: Camera, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  8. super(name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  9. this.onApplyObservable.add((effect: Effect) => {
  10. effect.setFloat2("screenSize", this.width, this.height);
  11. effect.setVector2("direction", this.direction);
  12. effect.setFloat("blurWidth", this.blurWidth);
  13. });
  14. }
  15. }
  16. /**
  17. * Highlight layer options. This helps customizing the behaviour
  18. * of the highlight layer.
  19. */
  20. export interface IHighlightLayerOptions {
  21. /**
  22. * Multiplication factor apply to the canvas size to compute the render target size
  23. * used to generated the glowing objects (the smaller the faster).
  24. */
  25. mainTextureRatio?: number;
  26. /**
  27. * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size
  28. * of the picture to blur (the smaller the faster).
  29. */
  30. blurTextureSizeRatio?: number;
  31. /**
  32. * How big in texel of the blur texture is the vertical blur.
  33. */
  34. blurVerticalSize?: number;
  35. /**
  36. * How big in texel of the blur texture is the horizontal blur.
  37. */
  38. blurHorizontalSize?: number;
  39. /**
  40. * Alpha blending mode used to apply the blur. Default is combine.
  41. */
  42. alphaBlendingMode?: number
  43. }
  44. /**
  45. * Storage interface grouping all the information required for glowing a mesh.
  46. */
  47. interface IHighlightLayerMesh {
  48. /**
  49. * The glowy mesh
  50. */
  51. mesh: Mesh;
  52. /**
  53. * The color of the glow
  54. */
  55. color: Color3;
  56. /**
  57. * The mesh render callback use to insert stencil information
  58. */
  59. observerHighlight: Observer<Mesh>;
  60. /**
  61. * The mesh render callback use to come to the default behavior
  62. */
  63. observerDefault: Observer<Mesh>;
  64. /**
  65. * If it exists, the emissive color of the material will be used to generate the glow.
  66. * Else it falls back to the current color.
  67. */
  68. glowEmissiveOnly: boolean;
  69. }
  70. /**
  71. * The highlight layer Helps adding a glow effect around a mesh.
  72. *
  73. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  74. * glowy meshes to your scene.
  75. *
  76. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  77. */
  78. export class HighlightLayer {
  79. /**
  80. * The neutral color used during the preparation of the glow effect.
  81. * This is black by default as the blend operation is a blend operation.
  82. */
  83. public static neutralColor:Color4 = new Color4(0, 0, 0, 0);
  84. /**
  85. * Stencil value used for glowing meshes.
  86. */
  87. public static glowingMeshStencilReference = 0x02;
  88. /**
  89. * Stencil value used for the other meshes in the scene.
  90. */
  91. public static normalMeshStencilReference = 0x01;
  92. private _scene: Scene;
  93. private _engine: Engine;
  94. private _options: IHighlightLayerOptions;
  95. private _vertexBuffers: { [key: string]: VertexBuffer } = {};
  96. private _indexBuffer: WebGLBuffer;
  97. private _downSamplePostprocess: PassPostProcess;
  98. private _horizontalBlurPostprocess: GlowBlurPostProcess;
  99. private _verticalBlurPostprocess: GlowBlurPostProcess;
  100. private _cachedDefines: string;
  101. private _glowMapGenerationEffect: Effect;
  102. private _glowMapMergeEffect: Effect;
  103. private _blurTexture: RenderTargetTexture;
  104. private _mainTexture: RenderTargetTexture;
  105. private _mainTextureDesiredSize: ISize = { width:0, height:0 };
  106. private _meshes: {[id: string]: IHighlightLayerMesh} = {};
  107. private _maxSize:number = 0;
  108. private _shouldRender = false;
  109. private _instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  110. /**
  111. * Specifies whether or not the inner glow is ACTIVE in the layer.
  112. */
  113. public innerGlow: boolean = true;
  114. /**
  115. * Specifies whether or not the outer glow is ACTIVE in the layer.
  116. */
  117. public outerGlow: boolean = true;
  118. /**
  119. * Specifies the horizontal size of the blur.
  120. */
  121. public set blurHorizontalSize(value: number) {
  122. this._horizontalBlurPostprocess.blurWidth = value;
  123. }
  124. /**
  125. * Specifies the vertical size of the blur.
  126. */
  127. public set blurVerticalSize(value: number) {
  128. this._verticalBlurPostprocess.blurWidth = value;
  129. }
  130. /**
  131. * Gets the horizontal size of the blur.
  132. */
  133. public get blurHorizontalSize(): number {
  134. return this._horizontalBlurPostprocess.blurWidth
  135. }
  136. /**
  137. * Gets the vertical size of the blur.
  138. */
  139. public get blurVerticalSize(): number {
  140. return this._verticalBlurPostprocess.blurWidth;
  141. }
  142. /**
  143. * An event triggered when the highlight layer has been disposed.
  144. * @type {BABYLON.Observable}
  145. */
  146. public onDisposeObservable = new Observable<HighlightLayer>();
  147. /**
  148. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  149. * @type {BABYLON.Observable}
  150. */
  151. public onBeforeRenderMainTextureObservable = new Observable<HighlightLayer>();
  152. /**
  153. * An event triggered when the highlight layer is being blurred.
  154. * @type {BABYLON.Observable}
  155. */
  156. public onBeforeBlurObservable = new Observable<HighlightLayer>();
  157. /**
  158. * An event triggered when the highlight layer has been blurred.
  159. * @type {BABYLON.Observable}
  160. */
  161. public onAfterBlurObservable = new Observable<HighlightLayer>();
  162. /**
  163. * An event triggered when the glowing blurred texture is being merged in the scene.
  164. * @type {BABYLON.Observable}
  165. */
  166. public onBeforeComposeObservable = new Observable<HighlightLayer>();
  167. /**
  168. * An event triggered when the glowing blurred texture has been merged in the scene.
  169. * @type {BABYLON.Observable}
  170. */
  171. public onAfterComposeObservable = new Observable<HighlightLayer>();
  172. /**
  173. * An event triggered when the highlight layer changes its size.
  174. * @type {BABYLON.Observable}
  175. */
  176. public onSizeChangedObservable = new Observable<HighlightLayer>();
  177. /**
  178. * Instantiates a new highlight Layer and references it to the scene..
  179. * @param name The name of the layer
  180. * @param scene The scene to use the layer in
  181. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  182. */
  183. constructor(name: string, scene: Scene, options?: IHighlightLayerOptions) {
  184. this._scene = scene;
  185. var engine = scene.getEngine();
  186. this._engine = engine;
  187. this._maxSize = this._engine.getCaps().maxTextureSize;
  188. this._scene.highlightLayers.push(this);
  189. // Warn on stencil.
  190. if (!this._engine.isStencilEnable) {
  191. Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  192. }
  193. // Adapt options
  194. this._options = options || {
  195. mainTextureRatio: 0.25,
  196. blurTextureSizeRatio: 0.5,
  197. blurHorizontalSize: 1,
  198. blurVerticalSize: 1,
  199. alphaBlendingMode: Engine.ALPHA_COMBINE
  200. };
  201. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  202. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  203. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  204. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  205. this._options.alphaBlendingMode = this._options.alphaBlendingMode || Engine.ALPHA_COMBINE;
  206. // VBO
  207. var vertices = [];
  208. vertices.push(1, 1);
  209. vertices.push(-1, 1);
  210. vertices.push(-1, -1);
  211. vertices.push(1, -1);
  212. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  213. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  214. // Indices
  215. var indices = [];
  216. indices.push(0);
  217. indices.push(1);
  218. indices.push(2);
  219. indices.push(0);
  220. indices.push(2);
  221. indices.push(3);
  222. this._indexBuffer = engine.createIndexBuffer(indices);
  223. // Effect
  224. this._glowMapMergeEffect = engine.createEffect("glowMapMerge",
  225. [VertexBuffer.PositionKind],
  226. ["offset"],
  227. ["textureSampler"], "");
  228. // Render target
  229. this.setMainTextureSize();
  230. // Create Textures and post processes
  231. this.createTextureAndPostProcesses();
  232. }
  233. /**
  234. * Creates the render target textures and post processes used in the highlight layer.
  235. */
  236. private createTextureAndPostProcesses(): void {
  237. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  238. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  239. blurTextureWidth = Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  240. blurTextureHeight = Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  241. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  242. {
  243. width: this._mainTextureDesiredSize.width,
  244. height: this._mainTextureDesiredSize.height
  245. },
  246. this._scene,
  247. false,
  248. true,
  249. Engine.TEXTURETYPE_UNSIGNED_INT);
  250. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  251. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  252. this._mainTexture.anisotropicFilteringLevel = 1;
  253. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  254. this._mainTexture.renderParticles = false;
  255. this._mainTexture.renderList = null;
  256. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  257. {
  258. width: blurTextureWidth,
  259. height: blurTextureHeight
  260. },
  261. this._scene,
  262. false,
  263. true,
  264. Engine.TEXTURETYPE_UNSIGNED_INT);
  265. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  266. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  267. this._blurTexture.anisotropicFilteringLevel = 16;
  268. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  269. this._blurTexture.renderParticles = false;
  270. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  271. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  272. this._downSamplePostprocess.onApplyObservable.add(effect => {
  273. effect.setTexture("textureSampler", this._mainTexture);
  274. });
  275. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  276. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  277. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  278. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  279. });
  280. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  281. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  282. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  283. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  284. });
  285. this._mainTexture.onAfterUnbindObservable.add(() => {
  286. this.onBeforeBlurObservable.notifyObservers(this);
  287. this._scene.postProcessManager.directRender(
  288. [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess],
  289. this._blurTexture.getInternalTexture());
  290. this.onAfterBlurObservable.notifyObservers(this);
  291. });
  292. // Custom render function
  293. var renderSubMesh = (subMesh: SubMesh): void => {
  294. var mesh = subMesh.getRenderingMesh();
  295. var scene = this._scene;
  296. var engine = scene.getEngine();
  297. // Culling
  298. engine.setState(subMesh.getMaterial().backFaceCulling);
  299. // Managing instances
  300. var batch = mesh._getInstancesRenderList(subMesh._id);
  301. if (batch.mustReturn) {
  302. return;
  303. }
  304. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  305. var highlightLayerMesh = this._meshes[mesh.id];
  306. var material = subMesh.getMaterial();
  307. var emissiveTexture: Texture = null;
  308. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  309. emissiveTexture = (<any>material).emissiveTexture;
  310. }
  311. if (this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  312. engine.enableEffect(this._glowMapGenerationEffect);
  313. mesh._bind(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode);
  314. this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  315. if (highlightLayerMesh) {
  316. this._glowMapGenerationEffect.setFloat4("color",
  317. highlightLayerMesh.color.r,
  318. highlightLayerMesh.color.g,
  319. highlightLayerMesh.color.b,
  320. 1.0);
  321. }
  322. else {
  323. this._glowMapGenerationEffect.setFloat4("color",
  324. HighlightLayer.neutralColor.r,
  325. HighlightLayer.neutralColor.g,
  326. HighlightLayer.neutralColor.b,
  327. HighlightLayer.neutralColor.a);
  328. }
  329. // Alpha test
  330. if (material && material.needAlphaTesting()) {
  331. var alphaTexture = material.getAlphaTestTexture();
  332. this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  333. this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  334. }
  335. // Glow emissive only
  336. if (emissiveTexture) {
  337. this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  338. this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  339. }
  340. // Bones
  341. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  342. this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  343. }
  344. // Draw
  345. mesh._processRendering(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  346. (isInstance, world) => this._glowMapGenerationEffect.setMatrix("world", world));
  347. } else {
  348. // Need to reset refresh rate of the shadowMap
  349. this._mainTexture.resetRefreshCounter();
  350. }
  351. };
  352. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>): void => {
  353. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  354. var index: number;
  355. for (index = 0; index < opaqueSubMeshes.length; index++) {
  356. renderSubMesh(opaqueSubMeshes.data[index]);
  357. }
  358. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  359. renderSubMesh(alphaTestSubMeshes.data[index]);
  360. }
  361. for (index = 0; index < transparentSubMeshes.length; index++) {
  362. renderSubMesh(transparentSubMeshes.data[index]);
  363. }
  364. };
  365. this._mainTexture.onClearObservable.add((engine: Engine) => {
  366. engine.clear(HighlightLayer.neutralColor, true, true, true);
  367. });
  368. }
  369. /**
  370. * Checks for the readiness of the element composing the layer.
  371. * @param subMesh the mesh to check for
  372. * @param useInstances specify wether or not to use instances to render the mesh
  373. * @param emissiveTexture the associated emissive texture used to generate the glow
  374. * @return true if ready otherwise, false
  375. */
  376. private isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Texture): boolean {
  377. if (!subMesh.getMaterial().isReady()) {
  378. return false;
  379. }
  380. var defines = [];
  381. var attribs = [VertexBuffer.PositionKind];
  382. var mesh = subMesh.getMesh();
  383. var material = subMesh.getMaterial();
  384. var uv1 = false;
  385. var uv2 = false;
  386. // Alpha test
  387. if (material && material.needAlphaTesting()) {
  388. var alphaTexture = material.getAlphaTestTexture();
  389. if (alphaTexture) {
  390. defines.push("#define ALPHATEST");
  391. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  392. alphaTexture.coordinatesIndex === 1) {
  393. defines.push("#define DIFFUSEUV2");
  394. uv2 = true;
  395. }
  396. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  397. defines.push("#define DIFFUSEUV1");
  398. uv1 = true;
  399. }
  400. }
  401. }
  402. // Emissive
  403. if (emissiveTexture) {
  404. defines.push("#define EMISSIVE");
  405. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  406. emissiveTexture.coordinatesIndex === 1) {
  407. defines.push("#define EMISSIVEUV2");
  408. uv2 = true;
  409. }
  410. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  411. defines.push("#define EMISSIVEUV1");
  412. uv1 = true;
  413. }
  414. }
  415. if (uv1) {
  416. attribs.push(VertexBuffer.UVKind);
  417. defines.push("#define UV1");
  418. }
  419. if (uv2) {
  420. attribs.push(VertexBuffer.UV2Kind);
  421. defines.push("#define UV2");
  422. }
  423. // Bones
  424. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  425. attribs.push(VertexBuffer.MatricesIndicesKind);
  426. attribs.push(VertexBuffer.MatricesWeightsKind);
  427. if (mesh.numBoneInfluencers > 4) {
  428. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  429. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  430. }
  431. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  432. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  433. } else {
  434. defines.push("#define NUM_BONE_INFLUENCERS 0");
  435. }
  436. // Instances
  437. if (useInstances) {
  438. defines.push("#define INSTANCES");
  439. attribs.push("world0");
  440. attribs.push("world1");
  441. attribs.push("world2");
  442. attribs.push("world3");
  443. }
  444. // Get correct effect
  445. var join = defines.join("\n");
  446. if (this._cachedDefines !== join) {
  447. this._cachedDefines = join;
  448. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  449. attribs,
  450. ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"],
  451. ["diffuseSampler", "emissiveSampler"], join);
  452. }
  453. return this._glowMapGenerationEffect.isReady();
  454. }
  455. /**
  456. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  457. */
  458. public render(): void {
  459. var currentEffect = this._glowMapMergeEffect;
  460. // Check
  461. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  462. return;
  463. var engine = this._scene.getEngine();
  464. this.onBeforeComposeObservable.notifyObservers(this);
  465. // Render
  466. engine.enableEffect(currentEffect);
  467. engine.setState(false);
  468. // Cache
  469. var previousStencilBuffer = engine.getStencilBuffer();
  470. var previousStencilFunction = engine.getStencilFunction();
  471. var previousStencilMask = engine.getStencilMask();
  472. var previousAlphaMode = engine.getAlphaMode();
  473. // Texture
  474. currentEffect.setTexture("textureSampler", this._blurTexture);
  475. // VBOs
  476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  477. // Draw order
  478. engine.setAlphaMode(this._options.alphaBlendingMode);
  479. engine.setStencilMask(0x00);
  480. engine.setStencilBuffer(true);
  481. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  482. if (this.outerGlow) {
  483. currentEffect.setFloat("offset", 0);
  484. engine.setStencilFunction(Engine.NOTEQUAL);
  485. engine.draw(true, 0, 6);
  486. }
  487. if (this.innerGlow) {
  488. currentEffect.setFloat("offset", 1);
  489. engine.setStencilFunction(Engine.EQUAL);
  490. engine.draw(true, 0, 6);
  491. }
  492. // Restore Cache
  493. engine.setStencilFunction(previousStencilFunction);
  494. engine.setStencilMask(previousStencilMask);
  495. engine.setAlphaMode(previousAlphaMode);
  496. engine.setStencilBuffer(previousStencilBuffer);
  497. this.onAfterComposeObservable.notifyObservers(this);
  498. // Handle size changes.
  499. var size = this._mainTexture.getSize();
  500. this.setMainTextureSize();
  501. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  502. // Recreate RTT and post processes on size change.
  503. this.onSizeChangedObservable.notifyObservers(this);
  504. this.disposeTextureAndPostProcesses();
  505. this.createTextureAndPostProcesses();
  506. }
  507. }
  508. /**
  509. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  510. * @param mesh The mesh to highlight
  511. * @param color The color of the highlight
  512. * @param glowEmissiveOnly Extract the glow from the emissive texture
  513. */
  514. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  515. var meshHighlight = this._meshes[mesh.id];
  516. if (meshHighlight) {
  517. meshHighlight.color = color;
  518. }
  519. else {
  520. this._meshes[mesh.id] = {
  521. mesh: mesh,
  522. color: color,
  523. // Lambda required for capture due to Observable this context
  524. observerHighlight: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  525. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  526. }),
  527. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  528. glowEmissiveOnly: glowEmissiveOnly
  529. };
  530. }
  531. this._shouldRender = true;
  532. }
  533. /**
  534. * Remove a mesh from the highlight layer in order to make it stop glowing.
  535. * @param mesh The mesh to highlight
  536. */
  537. public removeMesh(mesh: Mesh) {
  538. var meshHighlight = this._meshes[mesh.id];
  539. if (meshHighlight) {
  540. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  541. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  542. }
  543. this._meshes[mesh.id] = undefined;
  544. this._shouldRender = false;
  545. for (var meshHighlightToCheck in this._meshes) {
  546. if (meshHighlightToCheck) {
  547. this._shouldRender = true;
  548. break;
  549. }
  550. }
  551. }
  552. /**
  553. * Returns true if the layer contains information to display, otherwise false.
  554. */
  555. public shouldRender(): boolean {
  556. return this._shouldRender;
  557. }
  558. /**
  559. * Sets the main texture desired size which is the closest power of two
  560. * of the engine canvas size.
  561. */
  562. private setMainTextureSize() : void {
  563. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  564. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  565. this._mainTextureDesiredSize.width = Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  566. this._mainTextureDesiredSize.height = Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  567. }
  568. /**
  569. * Force the stencil to the normal expected value for none glowing parts
  570. */
  571. private defaultStencilReference(mesh: Mesh) {
  572. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  573. }
  574. /**
  575. * Dispose only the render target textures and post process.
  576. */
  577. private disposeTextureAndPostProcesses(): void {
  578. this._blurTexture.dispose();
  579. this._mainTexture.dispose();
  580. this._downSamplePostprocess.dispose();
  581. this._horizontalBlurPostprocess.dispose();
  582. this._verticalBlurPostprocess.dispose();
  583. }
  584. /**
  585. * Dispose the highlight layer and free resources.
  586. */
  587. public dispose(): void {
  588. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  589. if (vertexBuffer) {
  590. vertexBuffer.dispose();
  591. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  592. }
  593. if (this._indexBuffer) {
  594. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  595. this._indexBuffer = null;
  596. }
  597. // Clean textures and post processes
  598. this.disposeTextureAndPostProcesses();
  599. // Clean mesh references
  600. for (var id in this._meshes) {
  601. var meshHighlight = this._meshes[id];
  602. if (meshHighlight && meshHighlight.mesh) {
  603. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  604. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  605. }
  606. }
  607. this._meshes = null;
  608. // Remove from scene
  609. var index = this._scene.highlightLayers.indexOf(this, 0);
  610. if (index > -1) {
  611. this._scene.highlightLayers.splice(index, 1);
  612. }
  613. // Callback
  614. this.onDisposeObservable.notifyObservers(this);
  615. this.onDisposeObservable.clear();
  616. this.onBeforeRenderMainTextureObservable.clear();
  617. this.onBeforeBlurObservable.clear();
  618. this.onBeforeComposeObservable.clear();
  619. this.onAfterComposeObservable.clear();
  620. this.onSizeChangedObservable.clear();
  621. }
  622. }
  623. }