babylon.highlightlayer.ts 34 KB

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