highlightLayer.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. import { serialize, SerializationHelper } from "../Misc/decorators";
  2. import { Observer, Observable } from "../Misc/observable";
  3. import { Nullable } from "../types";
  4. import { Camera } from "../Cameras/camera";
  5. import { Scene } from "../scene";
  6. import { Vector2 } from "../Maths/math.vector";
  7. import { Engine } from "../Engines/engine";
  8. import { VertexBuffer } from "../Meshes/buffer";
  9. import { SubMesh } from "../Meshes/subMesh";
  10. import { AbstractMesh } from "../Meshes/abstractMesh";
  11. import { Mesh } from "../Meshes/mesh";
  12. import { Effect } from "../Materials/effect";
  13. import { Material } from "../Materials/material";
  14. import { Texture } from "../Materials/Textures/texture";
  15. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  16. import { PostProcess, PostProcessOptions } from "../PostProcesses/postProcess";
  17. import { PassPostProcess } from "../PostProcesses/passPostProcess";
  18. import { BlurPostProcess } from "../PostProcesses/blurPostProcess";
  19. import { EffectLayer } from "./effectLayer";
  20. import { AbstractScene } from "../abstractScene";
  21. import { Constants } from "../Engines/constants";
  22. import { Logger } from "../Misc/logger";
  23. import { _TypeStore } from '../Misc/typeStore';
  24. import { Color4, Color3 } from '../Maths/math.color';
  25. import "../Shaders/glowMapMerge.fragment";
  26. import "../Shaders/glowMapMerge.vertex";
  27. import "../Shaders/glowBlurPostProcess.fragment";
  28. declare module "../abstractScene" {
  29. export interface AbstractScene {
  30. /**
  31. * Return a the first highlight layer of the scene with a given name.
  32. * @param name The name of the highlight layer to look for.
  33. * @return The highlight layer if found otherwise null.
  34. */
  35. getHighlightLayerByName(name: string): Nullable<HighlightLayer>;
  36. }
  37. }
  38. AbstractScene.prototype.getHighlightLayerByName = function(name: string): Nullable<HighlightLayer> {
  39. for (var index = 0; index < this.effectLayers.length; index++) {
  40. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  41. return (<any>this.effectLayers[index]) as HighlightLayer;
  42. }
  43. }
  44. return null;
  45. };
  46. /**
  47. * Special Glow Blur post process only blurring the alpha channel
  48. * It enforces keeping the most luminous color in the color channel.
  49. */
  50. class GlowBlurPostProcess extends PostProcess {
  51. constructor(name: string, public direction: Vector2, public kernel: number, options: number | PostProcessOptions, camera: Nullable<Camera>, samplingMode: number = Texture.BILINEAR_SAMPLINGMODE, engine?: Engine, reusable?: boolean) {
  52. super(name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53. this.onApplyObservable.add((effect: Effect) => {
  54. effect.setFloat2("screenSize", this.width, this.height);
  55. effect.setVector2("direction", this.direction);
  56. effect.setFloat("blurWidth", this.kernel);
  57. });
  58. }
  59. }
  60. /**
  61. * Highlight layer options. This helps customizing the behaviour
  62. * of the highlight layer.
  63. */
  64. export interface IHighlightLayerOptions {
  65. /**
  66. * Multiplication factor apply to the canvas size to compute the render target size
  67. * used to generated the glowing objects (the smaller the faster).
  68. */
  69. mainTextureRatio: number;
  70. /**
  71. * Enforces a fixed size texture to ensure resize independant blur.
  72. */
  73. mainTextureFixedSize?: number;
  74. /**
  75. * Multiplication factor apply to the main texture size in the first step of the blur to reduce the size
  76. * of the picture to blur (the smaller the faster).
  77. */
  78. blurTextureSizeRatio: number;
  79. /**
  80. * How big in texel of the blur texture is the vertical blur.
  81. */
  82. blurVerticalSize: number;
  83. /**
  84. * How big in texel of the blur texture is the horizontal blur.
  85. */
  86. blurHorizontalSize: number;
  87. /**
  88. * Alpha blending mode used to apply the blur. Default is combine.
  89. */
  90. alphaBlendingMode: number;
  91. /**
  92. * The camera attached to the layer.
  93. */
  94. camera: Nullable<Camera>;
  95. /**
  96. * Should we display highlight as a solid stroke?
  97. */
  98. isStroke?: boolean;
  99. /**
  100. * The rendering group to draw the layer in.
  101. */
  102. renderingGroupId: number;
  103. }
  104. /**
  105. * Storage interface grouping all the information required for glowing a mesh.
  106. */
  107. interface IHighlightLayerMesh {
  108. /**
  109. * The glowy mesh
  110. */
  111. mesh: Mesh;
  112. /**
  113. * The color of the glow
  114. */
  115. color: Color3;
  116. /**
  117. * The mesh render callback use to insert stencil information
  118. */
  119. observerHighlight: Nullable<Observer<Mesh>>;
  120. /**
  121. * The mesh render callback use to come to the default behavior
  122. */
  123. observerDefault: Nullable<Observer<Mesh>>;
  124. /**
  125. * If it exists, the emissive color of the material will be used to generate the glow.
  126. * Else it falls back to the current color.
  127. */
  128. glowEmissiveOnly: boolean;
  129. }
  130. /**
  131. * Storage interface grouping all the information required for an excluded mesh.
  132. */
  133. interface IHighlightLayerExcludedMesh {
  134. /**
  135. * The glowy mesh
  136. */
  137. mesh: Mesh;
  138. /**
  139. * The mesh render callback use to prevent stencil use
  140. */
  141. beforeBind: Nullable<Observer<Mesh>>;
  142. /**
  143. * The mesh render callback use to restore previous stencil use
  144. */
  145. afterRender: Nullable<Observer<Mesh>>;
  146. }
  147. /**
  148. * The highlight layer Helps adding a glow effect around a mesh.
  149. *
  150. * Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove
  151. * glowy meshes to your scene.
  152. *
  153. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  154. */
  155. export class HighlightLayer extends EffectLayer {
  156. /**
  157. * Effect Name of the highlight layer.
  158. */
  159. public static readonly EffectName = "HighlightLayer";
  160. /**
  161. * The neutral color used during the preparation of the glow effect.
  162. * This is black by default as the blend operation is a blend operation.
  163. */
  164. public static NeutralColor: Color4 = new Color4(0, 0, 0, 0);
  165. /**
  166. * Stencil value used for glowing meshes.
  167. */
  168. public static GlowingMeshStencilReference = 0x02;
  169. /**
  170. * Stencil value used for the other meshes in the scene.
  171. */
  172. public static NormalMeshStencilReference = 0x01;
  173. /**
  174. * Specifies whether or not the inner glow is ACTIVE in the layer.
  175. */
  176. @serialize()
  177. public innerGlow: boolean = true;
  178. /**
  179. * Specifies whether or not the outer glow is ACTIVE in the layer.
  180. */
  181. @serialize()
  182. public outerGlow: boolean = true;
  183. /**
  184. * Specifies the horizontal size of the blur.
  185. */
  186. public set blurHorizontalSize(value: number) {
  187. this._horizontalBlurPostprocess.kernel = value;
  188. }
  189. /**
  190. * Specifies the vertical size of the blur.
  191. */
  192. public set blurVerticalSize(value: number) {
  193. this._verticalBlurPostprocess.kernel = value;
  194. }
  195. /**
  196. * Gets the horizontal size of the blur.
  197. */
  198. @serialize()
  199. public get blurHorizontalSize(): number {
  200. return this._horizontalBlurPostprocess.kernel;
  201. }
  202. /**
  203. * Gets the vertical size of the blur.
  204. */
  205. @serialize()
  206. public get blurVerticalSize(): number {
  207. return this._verticalBlurPostprocess.kernel;
  208. }
  209. /**
  210. * An event triggered when the highlight layer is being blurred.
  211. */
  212. public onBeforeBlurObservable = new Observable<HighlightLayer>();
  213. /**
  214. * An event triggered when the highlight layer has been blurred.
  215. */
  216. public onAfterBlurObservable = new Observable<HighlightLayer>();
  217. private _instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  218. @serialize("options")
  219. private _options: IHighlightLayerOptions;
  220. private _downSamplePostprocess: PassPostProcess;
  221. private _horizontalBlurPostprocess: GlowBlurPostProcess;
  222. private _verticalBlurPostprocess: GlowBlurPostProcess;
  223. private _blurTexture: RenderTargetTexture;
  224. private _meshes: Nullable<{ [id: string]: Nullable<IHighlightLayerMesh> }> = {};
  225. private _excludedMeshes: Nullable<{ [id: string]: Nullable<IHighlightLayerExcludedMesh> }> = {};
  226. /**
  227. * Instantiates a new highlight Layer and references it to the scene..
  228. * @param name The name of the layer
  229. * @param scene The scene to use the layer in
  230. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  231. */
  232. constructor(public name: string, scene: Scene, options?: Partial<IHighlightLayerOptions>) {
  233. super(name, scene);
  234. this.neutralColor = HighlightLayer.NeutralColor;
  235. // Warn on stencil
  236. if (!this._engine.isStencilEnable) {
  237. Logger.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }");
  238. }
  239. // Adapt options
  240. this._options = {
  241. mainTextureRatio: 0.5,
  242. blurTextureSizeRatio: 0.5,
  243. blurHorizontalSize: 1.0,
  244. blurVerticalSize: 1.0,
  245. alphaBlendingMode: Constants.ALPHA_COMBINE,
  246. camera: null,
  247. renderingGroupId: -1,
  248. ...options,
  249. };
  250. // Initialize the layer
  251. this._init({
  252. alphaBlendingMode: this._options.alphaBlendingMode,
  253. camera: this._options.camera,
  254. mainTextureFixedSize: this._options.mainTextureFixedSize,
  255. mainTextureRatio: this._options.mainTextureRatio,
  256. renderingGroupId: this._options.renderingGroupId
  257. });
  258. // Do not render as long as no meshes have been added
  259. this._shouldRender = false;
  260. }
  261. /**
  262. * Get the effect name of the layer.
  263. * @return The effect name
  264. */
  265. public getEffectName(): string {
  266. return HighlightLayer.EffectName;
  267. }
  268. /**
  269. * Create the merge effect. This is the shader use to blit the information back
  270. * to the main canvas at the end of the scene rendering.
  271. */
  272. protected _createMergeEffect(): Effect {
  273. // Effect
  274. return this._engine.createEffect("glowMapMerge",
  275. [VertexBuffer.PositionKind],
  276. ["offset"],
  277. ["textureSampler"],
  278. this._options.isStroke ? "#define STROKE \n" : undefined);
  279. }
  280. /**
  281. * Creates the render target textures and post processes used in the highlight layer.
  282. */
  283. protected _createTextureAndPostProcesses(): void {
  284. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  285. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  286. blurTextureWidth = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  287. blurTextureHeight = this._engine.needPOTTextures ? Engine.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  288. var textureType = 0;
  289. if (this._engine.getCaps().textureHalfFloatRender) {
  290. textureType = Constants.TEXTURETYPE_HALF_FLOAT;
  291. }
  292. else {
  293. textureType = Constants.TEXTURETYPE_UNSIGNED_INT;
  294. }
  295. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  296. {
  297. width: blurTextureWidth,
  298. height: blurTextureHeight
  299. },
  300. this._scene,
  301. false,
  302. true,
  303. textureType);
  304. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  305. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  306. this._blurTexture.anisotropicFilteringLevel = 16;
  307. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  308. this._blurTexture.renderParticles = false;
  309. this._blurTexture.ignoreCameraViewport = true;
  310. this._textures = [this._blurTexture];
  311. if (this._options.alphaBlendingMode === Constants.ALPHA_COMBINE) {
  312. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  313. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  314. this._downSamplePostprocess.onApplyObservable.add((effect) => {
  315. effect.setTexture("textureSampler", this._mainTexture);
  316. });
  317. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  318. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  319. this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
  320. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  321. });
  322. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  323. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  324. this._verticalBlurPostprocess.onApplyObservable.add((effect) => {
  325. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  326. });
  327. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  328. }
  329. else {
  330. this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  331. width: blurTextureWidth,
  332. height: blurTextureHeight
  333. },
  334. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  335. this._horizontalBlurPostprocess.width = blurTextureWidth;
  336. this._horizontalBlurPostprocess.height = blurTextureHeight;
  337. this._horizontalBlurPostprocess.onApplyObservable.add((effect) => {
  338. effect.setTexture("textureSampler", this._mainTexture);
  339. });
  340. this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  341. width: blurTextureWidth,
  342. height: blurTextureHeight
  343. },
  344. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  345. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  346. }
  347. this._mainTexture.onAfterUnbindObservable.add(() => {
  348. this.onBeforeBlurObservable.notifyObservers(this);
  349. let internalTexture = this._blurTexture.getInternalTexture();
  350. if (internalTexture) {
  351. this._scene.postProcessManager.directRender(
  352. this._postProcesses,
  353. internalTexture,
  354. true);
  355. }
  356. this.onAfterBlurObservable.notifyObservers(this);
  357. });
  358. // Prevent autoClear.
  359. this._postProcesses.map((pp) => { pp.autoClear = false; });
  360. }
  361. /**
  362. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  363. */
  364. public needStencil(): boolean {
  365. return true;
  366. }
  367. /**
  368. * Checks for the readiness of the element composing the layer.
  369. * @param subMesh the mesh to check for
  370. * @param useInstances specify wether or not to use instances to render the mesh
  371. * @param emissiveTexture the associated emissive texture used to generate the glow
  372. * @return true if ready otherwise, false
  373. */
  374. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  375. let material = subMesh.getMaterial();
  376. let mesh = subMesh.getRenderingMesh();
  377. if (!material || !mesh || !this._meshes) {
  378. return false;
  379. }
  380. let emissiveTexture: Nullable<Texture> = null;
  381. let highlightLayerMesh = this._meshes[mesh.uniqueId];
  382. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  383. emissiveTexture = (<any>material).emissiveTexture;
  384. }
  385. return super._isReady(subMesh, useInstances, emissiveTexture);
  386. }
  387. /**
  388. * Implementation specific of rendering the generating effect on the main canvas.
  389. * @param effect The effect used to render through
  390. */
  391. protected _internalRender(effect: Effect): void {
  392. // Texture
  393. effect.setTexture("textureSampler", this._blurTexture);
  394. // Cache
  395. var engine = this._engine;
  396. engine.cacheStencilState();
  397. // Stencil operations
  398. engine.setStencilOperationPass(Constants.REPLACE);
  399. engine.setStencilOperationFail(Constants.KEEP);
  400. engine.setStencilOperationDepthFail(Constants.KEEP);
  401. // Draw order
  402. engine.setStencilMask(0x00);
  403. engine.setStencilBuffer(true);
  404. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  405. // 2 passes inner outer
  406. if (this.outerGlow) {
  407. effect.setFloat("offset", 0);
  408. engine.setStencilFunction(Constants.NOTEQUAL);
  409. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  410. }
  411. if (this.innerGlow) {
  412. effect.setFloat("offset", 1);
  413. engine.setStencilFunction(Constants.EQUAL);
  414. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  415. }
  416. // Restore Cache
  417. engine.restoreStencilState();
  418. }
  419. /**
  420. * Returns true if the layer contains information to display, otherwise false.
  421. */
  422. public shouldRender(): boolean {
  423. if (super.shouldRender()) {
  424. return this._meshes ? true : false;
  425. }
  426. return false;
  427. }
  428. /**
  429. * Returns true if the mesh should render, otherwise false.
  430. * @param mesh The mesh to render
  431. * @returns true if it should render otherwise false
  432. */
  433. protected _shouldRenderMesh(mesh: Mesh): boolean {
  434. // Excluded Mesh
  435. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  436. return false;
  437. }
  438. if (!super.hasMesh(mesh)) {
  439. return false;
  440. }
  441. return true;
  442. }
  443. /**
  444. * Sets the required values for both the emissive texture and and the main color.
  445. */
  446. protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void {
  447. var highlightLayerMesh = this._meshes![mesh.uniqueId];
  448. if (highlightLayerMesh) {
  449. this._emissiveTextureAndColor.color.set(
  450. highlightLayerMesh.color.r,
  451. highlightLayerMesh.color.g,
  452. highlightLayerMesh.color.b,
  453. 1.0);
  454. }
  455. else {
  456. this._emissiveTextureAndColor.color.set(
  457. this.neutralColor.r,
  458. this.neutralColor.g,
  459. this.neutralColor.b,
  460. this.neutralColor.a);
  461. }
  462. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  463. this._emissiveTextureAndColor.texture = (<any>material).emissiveTexture;
  464. this._emissiveTextureAndColor.color.set(
  465. 1.0,
  466. 1.0,
  467. 1.0,
  468. 1.0);
  469. }
  470. else {
  471. this._emissiveTextureAndColor.texture = null;
  472. }
  473. }
  474. /**
  475. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  476. * @param mesh The mesh to exclude from the highlight layer
  477. */
  478. public addExcludedMesh(mesh: Mesh) {
  479. if (!this._excludedMeshes) {
  480. return;
  481. }
  482. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  483. if (!meshExcluded) {
  484. this._excludedMeshes[mesh.uniqueId] = {
  485. mesh: mesh,
  486. beforeBind: mesh.onBeforeBindObservable.add((mesh: Mesh) => {
  487. mesh.getEngine().setStencilBuffer(false);
  488. }),
  489. afterRender: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  490. mesh.getEngine().setStencilBuffer(true);
  491. }),
  492. };
  493. }
  494. }
  495. /**
  496. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  497. * @param mesh The mesh to highlight
  498. */
  499. public removeExcludedMesh(mesh: Mesh) {
  500. if (!this._excludedMeshes) {
  501. return;
  502. }
  503. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  504. if (meshExcluded) {
  505. if (meshExcluded.beforeBind) {
  506. mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);
  507. }
  508. if (meshExcluded.afterRender) {
  509. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  510. }
  511. }
  512. this._excludedMeshes[mesh.uniqueId] = null;
  513. }
  514. /**
  515. * Determine if a given mesh will be highlighted by the current HighlightLayer
  516. * @param mesh mesh to test
  517. * @returns true if the mesh will be highlighted by the current HighlightLayer
  518. */
  519. public hasMesh(mesh: AbstractMesh): boolean {
  520. if (!this._meshes) {
  521. return false;
  522. }
  523. if (!super.hasMesh(mesh)) {
  524. return false;
  525. }
  526. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  527. }
  528. /**
  529. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  530. * @param mesh The mesh to highlight
  531. * @param color The color of the highlight
  532. * @param glowEmissiveOnly Extract the glow from the emissive texture
  533. */
  534. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  535. if (!this._meshes) {
  536. return;
  537. }
  538. var meshHighlight = this._meshes[mesh.uniqueId];
  539. if (meshHighlight) {
  540. meshHighlight.color = color;
  541. }
  542. else {
  543. this._meshes[mesh.uniqueId] = {
  544. mesh: mesh,
  545. color: color,
  546. // Lambda required for capture due to Observable this context
  547. observerHighlight: mesh.onBeforeBindObservable.add((mesh: Mesh) => {
  548. if (this.isEnabled) {
  549. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  550. this._defaultStencilReference(mesh);
  551. }
  552. else {
  553. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  554. }
  555. }
  556. }),
  557. observerDefault: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  558. if (this.isEnabled) {
  559. this._defaultStencilReference(mesh);
  560. }
  561. }),
  562. glowEmissiveOnly: glowEmissiveOnly
  563. };
  564. mesh.onDisposeObservable.add(() => {
  565. this._disposeMesh(mesh);
  566. });
  567. }
  568. this._shouldRender = true;
  569. }
  570. /**
  571. * Remove a mesh from the highlight layer in order to make it stop glowing.
  572. * @param mesh The mesh to highlight
  573. */
  574. public removeMesh(mesh: Mesh) {
  575. if (!this._meshes) {
  576. return;
  577. }
  578. var meshHighlight = this._meshes[mesh.uniqueId];
  579. if (meshHighlight) {
  580. if (meshHighlight.observerHighlight) {
  581. mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
  582. }
  583. if (meshHighlight.observerDefault) {
  584. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  585. }
  586. delete this._meshes[mesh.uniqueId];
  587. }
  588. this._shouldRender = false;
  589. for (var meshHighlightToCheck in this._meshes) {
  590. if (this._meshes[meshHighlightToCheck]) {
  591. this._shouldRender = true;
  592. break;
  593. }
  594. }
  595. }
  596. /**
  597. * Force the stencil to the normal expected value for none glowing parts
  598. */
  599. private _defaultStencilReference(mesh: Mesh) {
  600. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  601. }
  602. /**
  603. * Free any resources and references associated to a mesh.
  604. * Internal use
  605. * @param mesh The mesh to free.
  606. * @hidden
  607. */
  608. public _disposeMesh(mesh: Mesh): void {
  609. this.removeMesh(mesh);
  610. this.removeExcludedMesh(mesh);
  611. }
  612. /**
  613. * Dispose the highlight layer and free resources.
  614. */
  615. public dispose(): void {
  616. if (this._meshes) {
  617. // Clean mesh references
  618. for (let id in this._meshes) {
  619. let meshHighlight = this._meshes[id];
  620. if (meshHighlight && meshHighlight.mesh) {
  621. if (meshHighlight.observerHighlight) {
  622. meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
  623. }
  624. if (meshHighlight.observerDefault) {
  625. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  626. }
  627. }
  628. }
  629. this._meshes = null;
  630. }
  631. if (this._excludedMeshes) {
  632. for (let id in this._excludedMeshes) {
  633. let meshHighlight = this._excludedMeshes[id];
  634. if (meshHighlight) {
  635. if (meshHighlight.beforeBind) {
  636. meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);
  637. }
  638. if (meshHighlight.afterRender) {
  639. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  640. }
  641. }
  642. }
  643. this._excludedMeshes = null;
  644. }
  645. super.dispose();
  646. }
  647. /**
  648. * Gets the class name of the effect layer
  649. * @returns the string with the class name of the effect layer
  650. */
  651. public getClassName(): string {
  652. return "HighlightLayer";
  653. }
  654. /**
  655. * Serializes this Highlight layer
  656. * @returns a serialized Highlight layer object
  657. */
  658. public serialize(): any {
  659. var serializationObject = SerializationHelper.Serialize(this);
  660. serializationObject.customType = "BABYLON.HighlightLayer";
  661. // Highlighted meshes
  662. serializationObject.meshes = [];
  663. if (this._meshes) {
  664. for (var m in this._meshes) {
  665. var mesh = this._meshes[m];
  666. if (mesh) {
  667. serializationObject.meshes.push({
  668. glowEmissiveOnly: mesh.glowEmissiveOnly,
  669. color: mesh.color.asArray(),
  670. meshId: mesh.mesh.id
  671. });
  672. }
  673. }
  674. }
  675. // Excluded meshes
  676. serializationObject.excludedMeshes = [];
  677. if (this._excludedMeshes) {
  678. for (var e in this._excludedMeshes) {
  679. var excludedMesh = this._excludedMeshes[e];
  680. if (excludedMesh) {
  681. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  682. }
  683. }
  684. }
  685. return serializationObject;
  686. }
  687. /**
  688. * Creates a Highlight layer from parsed Highlight layer data
  689. * @param parsedHightlightLayer defines the Highlight layer data
  690. * @param scene defines the current scene
  691. * @param rootUrl defines the root URL containing the Highlight layer information
  692. * @returns a parsed Highlight layer
  693. */
  694. public static Parse(parsedHightlightLayer: any, scene: Scene, rootUrl: string): HighlightLayer {
  695. var hl = SerializationHelper.Parse(() => new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options), parsedHightlightLayer, scene, rootUrl);
  696. var index;
  697. // Excluded meshes
  698. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  699. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  700. if (mesh) {
  701. hl.addExcludedMesh(<Mesh>mesh);
  702. }
  703. }
  704. // Included meshes
  705. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  706. var highlightedMesh = parsedHightlightLayer.meshes[index];
  707. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  708. if (mesh) {
  709. hl.addMesh(<Mesh>mesh, Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  710. }
  711. }
  712. return hl;
  713. }
  714. }
  715. _TypeStore.RegisteredTypes["BABYLON.HighlightLayer"] = HighlightLayer;