babylon.highlightlayer.ts 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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 kernel: number, options: number | PostProcessOptions, camera: Nullable<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.kernel);
  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: Nullable<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: Nullable<Observer<Mesh>>;
  68. /**
  69. * The mesh render callback use to come to the default behavior
  70. */
  71. observerDefault: Nullable<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: Nullable<Observer<Mesh>>;
  90. /**
  91. * The mesh render callback use to restore previous stencil use
  92. */
  93. afterRender: Nullable<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]: Nullable<VertexBuffer> } = {};
  121. private _indexBuffer: Nullable<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: Nullable<{ [id: string]: Nullable<IHighlightLayerMesh> }> = {};
  132. private _maxSize: number = 0;
  133. private _shouldRender = false;
  134. private _instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  135. private _excludedMeshes: Nullable<{ [id: string]: Nullable<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 wether the highlight layer is enabled or not.
  146. */
  147. public isEnabled: boolean = true;
  148. /**
  149. * Specifies the horizontal size of the blur.
  150. */
  151. public set blurHorizontalSize(value: number) {
  152. this._horizontalBlurPostprocess.kernel = value;
  153. }
  154. /**
  155. * Specifies the vertical size of the blur.
  156. */
  157. public set blurVerticalSize(value: number) {
  158. this._verticalBlurPostprocess.kernel = value;
  159. }
  160. /**
  161. * Gets the horizontal size of the blur.
  162. */
  163. public get blurHorizontalSize(): number {
  164. return this._horizontalBlurPostprocess.kernel
  165. }
  166. /**
  167. * Gets the vertical size of the blur.
  168. */
  169. public get blurVerticalSize(): number {
  170. return this._verticalBlurPostprocess.kernel;
  171. }
  172. /**
  173. * Gets the camera attached to the layer.
  174. */
  175. public get camera(): Nullable<Camera> {
  176. return this._options.camera;
  177. }
  178. /**
  179. * An event triggered when the highlight layer has been disposed.
  180. * @type {BABYLON.Observable}
  181. */
  182. public onDisposeObservable = new Observable<HighlightLayer>();
  183. /**
  184. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  185. * @type {BABYLON.Observable}
  186. */
  187. public onBeforeRenderMainTextureObservable = new Observable<HighlightLayer>();
  188. /**
  189. * An event triggered when the highlight layer is being blurred.
  190. * @type {BABYLON.Observable}
  191. */
  192. public onBeforeBlurObservable = new Observable<HighlightLayer>();
  193. /**
  194. * An event triggered when the highlight layer has been blurred.
  195. * @type {BABYLON.Observable}
  196. */
  197. public onAfterBlurObservable = new Observable<HighlightLayer>();
  198. /**
  199. * An event triggered when the glowing blurred texture is being merged in the scene.
  200. * @type {BABYLON.Observable}
  201. */
  202. public onBeforeComposeObservable = new Observable<HighlightLayer>();
  203. /**
  204. * An event triggered when the glowing blurred texture has been merged in the scene.
  205. * @type {BABYLON.Observable}
  206. */
  207. public onAfterComposeObservable = new Observable<HighlightLayer>();
  208. /**
  209. * An event triggered when the highlight layer changes its size.
  210. * @type {BABYLON.Observable}
  211. */
  212. public onSizeChangedObservable = new Observable<HighlightLayer>();
  213. /**
  214. * Instantiates a new highlight Layer and references it to the scene..
  215. * @param name The name of the layer
  216. * @param scene The scene to use the layer in
  217. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  218. */
  219. constructor(public name: string, scene: Scene, options?: IHighlightLayerOptions) {
  220. this._scene = scene || Engine.LastCreatedScene;
  221. var engine = scene.getEngine();
  222. this._engine = engine;
  223. this._maxSize = this._engine.getCaps().maxTextureSize;
  224. this._scene.highlightLayers.push(this);
  225. // Warn on stencil.
  226. if (!this._engine.isStencilEnable) {
  227. Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  228. }
  229. // Adapt options
  230. this._options = options || {
  231. mainTextureRatio: 0.5,
  232. blurTextureSizeRatio: 0.5,
  233. blurHorizontalSize: 1.0,
  234. blurVerticalSize: 1.0,
  235. alphaBlendingMode: Engine.ALPHA_COMBINE,
  236. camera: null
  237. };
  238. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  239. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  240. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  241. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  242. this._options.alphaBlendingMode = this._options.alphaBlendingMode || Engine.ALPHA_COMBINE;
  243. // VBO
  244. var vertices = [];
  245. vertices.push(1, 1);
  246. vertices.push(-1, 1);
  247. vertices.push(-1, -1);
  248. vertices.push(1, -1);
  249. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  250. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  251. this._createIndexBuffer();
  252. // Effect
  253. this._glowMapMergeEffect = engine.createEffect("glowMapMerge",
  254. [VertexBuffer.PositionKind],
  255. ["offset"],
  256. ["textureSampler"], "");
  257. // Render target
  258. this.setMainTextureSize();
  259. // Create Textures and post processes
  260. this.createTextureAndPostProcesses();
  261. }
  262. private _createIndexBuffer(): void {
  263. var engine = this._scene.getEngine();
  264. // Indices
  265. var indices = [];
  266. indices.push(0);
  267. indices.push(1);
  268. indices.push(2);
  269. indices.push(0);
  270. indices.push(2);
  271. indices.push(3);
  272. this._indexBuffer = engine.createIndexBuffer(indices);
  273. }
  274. public _rebuild(): void {
  275. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  276. if (vb) {
  277. vb._rebuild();
  278. }
  279. this._createIndexBuffer();
  280. }
  281. /**
  282. * Creates the render target textures and post processes used in the highlight layer.
  283. */
  284. private createTextureAndPostProcesses(): void {
  285. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  286. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  287. blurTextureWidth = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  288. blurTextureHeight = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  289. this._mainTexture = new RenderTargetTexture("HighlightLayerMainRTT",
  290. {
  291. width: this._mainTextureDesiredSize.width,
  292. height: this._mainTextureDesiredSize.height
  293. },
  294. this._scene,
  295. false,
  296. true,
  297. Engine.TEXTURETYPE_UNSIGNED_INT);
  298. this._mainTexture.activeCamera = this._options.camera;
  299. this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  300. this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  301. this._mainTexture.anisotropicFilteringLevel = 1;
  302. this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  303. this._mainTexture.renderParticles = false;
  304. this._mainTexture.renderList = null;
  305. this._mainTexture.ignoreCameraViewport = true;
  306. this._blurTexture = new RenderTargetTexture("HighlightLayerBlurRTT",
  307. {
  308. width: blurTextureWidth,
  309. height: blurTextureHeight
  310. },
  311. this._scene,
  312. false,
  313. true,
  314. Engine.TEXTURETYPE_UNSIGNED_INT);
  315. this._blurTexture.wrapU = Texture.CLAMP_ADDRESSMODE;
  316. this._blurTexture.wrapV = Texture.CLAMP_ADDRESSMODE;
  317. this._blurTexture.anisotropicFilteringLevel = 16;
  318. this._blurTexture.updateSamplingMode(Texture.TRILINEAR_SAMPLINGMODE);
  319. this._blurTexture.renderParticles = false;
  320. this._blurTexture.ignoreCameraViewport = true;
  321. this._downSamplePostprocess = new PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio,
  322. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  323. this._downSamplePostprocess.onApplyObservable.add(effect => {
  324. effect.setTexture("textureSampler", this._mainTexture);
  325. });
  326. if (this._options.alphaBlendingMode === Engine.ALPHA_COMBINE) {
  327. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  328. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  329. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  330. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  331. });
  332. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  333. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  334. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  335. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  336. });
  337. }
  338. else {
  339. this._horizontalBlurPostprocess = new BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1,
  340. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  341. this._horizontalBlurPostprocess.onApplyObservable.add(effect => {
  342. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  343. });
  344. this._verticalBlurPostprocess = new BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1,
  345. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  346. this._verticalBlurPostprocess.onApplyObservable.add(effect => {
  347. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  348. });
  349. }
  350. this._mainTexture.onAfterUnbindObservable.add(() => {
  351. this.onBeforeBlurObservable.notifyObservers(this);
  352. let internalTexture = this._blurTexture.getInternalTexture();
  353. if (internalTexture) {
  354. this._scene.postProcessManager.directRender(
  355. [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess],
  356. internalTexture, true);
  357. }
  358. this.onAfterBlurObservable.notifyObservers(this);
  359. });
  360. // Custom render function
  361. var renderSubMesh = (subMesh: SubMesh): void => {
  362. if (!this._meshes) {
  363. return;
  364. }
  365. var material = subMesh.getMaterial();
  366. var mesh = subMesh.getRenderingMesh();
  367. var scene = this._scene;
  368. var engine = scene.getEngine();
  369. if (!material) {
  370. return;
  371. }
  372. // Culling
  373. engine.setState(material.backFaceCulling);
  374. // Managing instances
  375. var batch = mesh._getInstancesRenderList(subMesh._id);
  376. if (batch.mustReturn) {
  377. return;
  378. }
  379. // Excluded Mesh
  380. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  381. return;
  382. };
  383. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  384. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  385. var emissiveTexture: Nullable<Texture> = null;
  386. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  387. emissiveTexture = (<any>material).emissiveTexture;
  388. }
  389. if (this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  390. engine.enableEffect(this._glowMapGenerationEffect);
  391. mesh._bind(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode);
  392. this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  393. if (highlightLayerMesh) {
  394. this._glowMapGenerationEffect.setFloat4("color",
  395. highlightLayerMesh.color.r,
  396. highlightLayerMesh.color.g,
  397. highlightLayerMesh.color.b,
  398. 1.0);
  399. }
  400. else {
  401. this._glowMapGenerationEffect.setFloat4("color",
  402. HighlightLayer.neutralColor.r,
  403. HighlightLayer.neutralColor.g,
  404. HighlightLayer.neutralColor.b,
  405. HighlightLayer.neutralColor.a);
  406. }
  407. // Alpha test
  408. if (material && material.needAlphaTesting()) {
  409. var alphaTexture = material.getAlphaTestTexture();
  410. if (alphaTexture) {
  411. this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  412. let textureMatrix = alphaTexture.getTextureMatrix();
  413. if (textureMatrix) {
  414. this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  415. }
  416. }
  417. }
  418. // Glow emissive only
  419. if (emissiveTexture) {
  420. this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  421. this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  422. }
  423. // Bones
  424. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  425. this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  426. }
  427. // Draw
  428. mesh._processRendering(subMesh, this._glowMapGenerationEffect, Material.TriangleFillMode, batch, hardwareInstancedRendering,
  429. (isInstance, world) => this._glowMapGenerationEffect.setMatrix("world", world));
  430. } else {
  431. // Need to reset refresh rate of the shadowMap
  432. this._mainTexture.resetRefreshCounter();
  433. }
  434. };
  435. this._mainTexture.customRenderFunction = (opaqueSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>): void => {
  436. this.onBeforeRenderMainTextureObservable.notifyObservers(this);
  437. var index: number;
  438. let engine = this._scene.getEngine();
  439. if (depthOnlySubMeshes.length) {
  440. engine.setColorWrite(false);
  441. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  442. renderSubMesh(depthOnlySubMeshes.data[index]);
  443. }
  444. engine.setColorWrite(true);
  445. }
  446. for (index = 0; index < opaqueSubMeshes.length; index++) {
  447. renderSubMesh(opaqueSubMeshes.data[index]);
  448. }
  449. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  450. renderSubMesh(alphaTestSubMeshes.data[index]);
  451. }
  452. for (index = 0; index < transparentSubMeshes.length; index++) {
  453. renderSubMesh(transparentSubMeshes.data[index]);
  454. }
  455. };
  456. this._mainTexture.onClearObservable.add((engine: Engine) => {
  457. engine.clear(HighlightLayer.neutralColor, true, true, true);
  458. });
  459. }
  460. /**
  461. * Checks for the readiness of the element composing the layer.
  462. * @param subMesh the mesh to check for
  463. * @param useInstances specify wether or not to use instances to render the mesh
  464. * @param emissiveTexture the associated emissive texture used to generate the glow
  465. * @return true if ready otherwise, false
  466. */
  467. private isReady(subMesh: SubMesh, useInstances: boolean, emissiveTexture: Nullable<Texture>): boolean {
  468. let material = subMesh.getMaterial();
  469. if (!material) {
  470. return false;
  471. }
  472. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  473. return false;
  474. }
  475. var defines = [];
  476. var attribs = [VertexBuffer.PositionKind];
  477. var mesh = subMesh.getMesh();
  478. var uv1 = false;
  479. var uv2 = false;
  480. // Alpha test
  481. if (material && material.needAlphaTesting()) {
  482. var alphaTexture = material.getAlphaTestTexture();
  483. if (alphaTexture) {
  484. defines.push("#define ALPHATEST");
  485. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  486. alphaTexture.coordinatesIndex === 1) {
  487. defines.push("#define DIFFUSEUV2");
  488. uv2 = true;
  489. }
  490. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  491. defines.push("#define DIFFUSEUV1");
  492. uv1 = true;
  493. }
  494. }
  495. }
  496. // Emissive
  497. if (emissiveTexture) {
  498. defines.push("#define EMISSIVE");
  499. if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) &&
  500. emissiveTexture.coordinatesIndex === 1) {
  501. defines.push("#define EMISSIVEUV2");
  502. uv2 = true;
  503. }
  504. else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) {
  505. defines.push("#define EMISSIVEUV1");
  506. uv1 = true;
  507. }
  508. }
  509. if (uv1) {
  510. attribs.push(VertexBuffer.UVKind);
  511. defines.push("#define UV1");
  512. }
  513. if (uv2) {
  514. attribs.push(VertexBuffer.UV2Kind);
  515. defines.push("#define UV2");
  516. }
  517. // Bones
  518. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  519. attribs.push(VertexBuffer.MatricesIndicesKind);
  520. attribs.push(VertexBuffer.MatricesWeightsKind);
  521. if (mesh.numBoneInfluencers > 4) {
  522. attribs.push(VertexBuffer.MatricesIndicesExtraKind);
  523. attribs.push(VertexBuffer.MatricesWeightsExtraKind);
  524. }
  525. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  526. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  527. } else {
  528. defines.push("#define NUM_BONE_INFLUENCERS 0");
  529. }
  530. // Instances
  531. if (useInstances) {
  532. defines.push("#define INSTANCES");
  533. attribs.push("world0");
  534. attribs.push("world1");
  535. attribs.push("world2");
  536. attribs.push("world3");
  537. }
  538. // Get correct effect
  539. var join = defines.join("\n");
  540. if (this._cachedDefines !== join) {
  541. this._cachedDefines = join;
  542. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration",
  543. attribs,
  544. ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"],
  545. ["diffuseSampler", "emissiveSampler"], join);
  546. }
  547. return this._glowMapGenerationEffect.isReady();
  548. }
  549. /**
  550. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  551. */
  552. public render(): void {
  553. var currentEffect = this._glowMapMergeEffect;
  554. // Check
  555. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  556. return;
  557. var engine = this._scene.getEngine();
  558. this.onBeforeComposeObservable.notifyObservers(this);
  559. // Render
  560. engine.enableEffect(currentEffect);
  561. engine.setState(false);
  562. // Cache
  563. var previousStencilBuffer = engine.getStencilBuffer();
  564. var previousStencilFunction = engine.getStencilFunction();
  565. var previousStencilMask = engine.getStencilMask();
  566. var previousStencilOperationPass = engine.getStencilOperationPass();
  567. var previousStencilOperationFail = engine.getStencilOperationFail();
  568. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  569. var previousAlphaMode = engine.getAlphaMode();
  570. // Texture
  571. currentEffect.setTexture("textureSampler", this._blurTexture);
  572. // VBOs
  573. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  574. // Stencil operations
  575. engine.setStencilOperationPass(Engine.REPLACE);
  576. engine.setStencilOperationFail(Engine.KEEP);
  577. engine.setStencilOperationDepthFail(Engine.KEEP);
  578. // Draw order
  579. engine.setAlphaMode(this._options.alphaBlendingMode);
  580. engine.setStencilMask(0x00);
  581. engine.setStencilBuffer(true);
  582. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  583. if (this.outerGlow) {
  584. currentEffect.setFloat("offset", 0);
  585. engine.setStencilFunction(Engine.NOTEQUAL);
  586. engine.draw(true, 0, 6);
  587. }
  588. if (this.innerGlow) {
  589. currentEffect.setFloat("offset", 1);
  590. engine.setStencilFunction(Engine.EQUAL);
  591. engine.draw(true, 0, 6);
  592. }
  593. // Restore Cache
  594. engine.setStencilFunction(previousStencilFunction);
  595. engine.setStencilMask(previousStencilMask);
  596. engine.setAlphaMode(previousAlphaMode);
  597. engine.setStencilBuffer(previousStencilBuffer);
  598. engine.setStencilOperationPass(previousStencilOperationPass);
  599. engine.setStencilOperationFail(previousStencilOperationFail);
  600. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  601. (<any>engine)._stencilState.reset();
  602. this.onAfterComposeObservable.notifyObservers(this);
  603. // Handle size changes.
  604. var size = this._mainTexture.getSize();
  605. this.setMainTextureSize();
  606. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  607. // Recreate RTT and post processes on size change.
  608. this.onSizeChangedObservable.notifyObservers(this);
  609. this.disposeTextureAndPostProcesses();
  610. this.createTextureAndPostProcesses();
  611. }
  612. }
  613. /**
  614. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  615. * @param mesh The mesh to exclude from the highlight layer
  616. */
  617. public addExcludedMesh(mesh: Mesh) {
  618. if (!this._excludedMeshes) {
  619. return;
  620. }
  621. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  622. if (!meshExcluded) {
  623. this._excludedMeshes[mesh.uniqueId] = {
  624. mesh: mesh,
  625. beforeRender: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  626. mesh.getEngine().setStencilBuffer(false);
  627. }),
  628. afterRender: mesh.onAfterRenderObservable.add((mesh: Mesh) => {
  629. mesh.getEngine().setStencilBuffer(true);
  630. }),
  631. }
  632. }
  633. }
  634. /**
  635. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  636. * @param mesh The mesh to highlight
  637. */
  638. public removeExcludedMesh(mesh: Mesh) {
  639. if (!this._excludedMeshes) {
  640. return;
  641. }
  642. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  643. if (meshExcluded) {
  644. if (meshExcluded.beforeRender) {
  645. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  646. }
  647. if (meshExcluded.afterRender) {
  648. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  649. }
  650. }
  651. this._excludedMeshes[mesh.uniqueId] = null;
  652. }
  653. /**
  654. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  655. * @param mesh The mesh to highlight
  656. * @param color The color of the highlight
  657. * @param glowEmissiveOnly Extract the glow from the emissive texture
  658. */
  659. public addMesh(mesh: Mesh, color: Color3, glowEmissiveOnly = false) {
  660. if (!this._meshes) {
  661. return;
  662. }
  663. var meshHighlight = this._meshes[mesh.uniqueId];
  664. if (meshHighlight) {
  665. meshHighlight.color = color;
  666. }
  667. else {
  668. this._meshes[mesh.uniqueId] = {
  669. mesh: mesh,
  670. color: color,
  671. // Lambda required for capture due to Observable this context
  672. observerHighlight: mesh.onBeforeRenderObservable.add((mesh: Mesh) => {
  673. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  674. this.defaultStencilReference(mesh);
  675. }
  676. else {
  677. mesh.getScene().getEngine().setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  678. }
  679. }),
  680. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  681. glowEmissiveOnly: glowEmissiveOnly
  682. };
  683. }
  684. this._shouldRender = true;
  685. }
  686. /**
  687. * Remove a mesh from the highlight layer in order to make it stop glowing.
  688. * @param mesh The mesh to highlight
  689. */
  690. public removeMesh(mesh: Mesh) {
  691. if (!this._meshes) {
  692. return;
  693. }
  694. var meshHighlight = this._meshes[mesh.uniqueId];
  695. if (meshHighlight) {
  696. if (meshHighlight.observerHighlight) {
  697. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  698. }
  699. if (meshHighlight.observerDefault) {
  700. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  701. }
  702. }
  703. this._meshes[mesh.uniqueId] = null;
  704. this._shouldRender = false;
  705. for (var meshHighlightToCheck in this._meshes) {
  706. if (this._meshes[meshHighlightToCheck]) {
  707. this._shouldRender = true;
  708. break;
  709. }
  710. }
  711. }
  712. /**
  713. * Returns true if the layer contains information to display, otherwise false.
  714. */
  715. public shouldRender(): boolean {
  716. return this.isEnabled && this._shouldRender;
  717. }
  718. /**
  719. * Sets the main texture desired size which is the closest power of two
  720. * of the engine canvas size.
  721. */
  722. private setMainTextureSize(): void {
  723. if (this._options.mainTextureFixedSize) {
  724. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  725. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  726. }
  727. else {
  728. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  729. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  730. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  731. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  732. }
  733. }
  734. /**
  735. * Force the stencil to the normal expected value for none glowing parts
  736. */
  737. private defaultStencilReference(mesh: Mesh) {
  738. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  739. }
  740. /**
  741. * Dispose only the render target textures and post process.
  742. */
  743. private disposeTextureAndPostProcesses(): void {
  744. this._blurTexture.dispose();
  745. this._mainTexture.dispose();
  746. this._downSamplePostprocess.dispose();
  747. this._horizontalBlurPostprocess.dispose();
  748. this._verticalBlurPostprocess.dispose();
  749. }
  750. /**
  751. * Dispose the highlight layer and free resources.
  752. */
  753. public dispose(): void {
  754. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  755. if (vertexBuffer) {
  756. vertexBuffer.dispose();
  757. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  758. }
  759. if (this._indexBuffer) {
  760. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  761. this._indexBuffer = null;
  762. }
  763. // Clean textures and post processes
  764. this.disposeTextureAndPostProcesses();
  765. if (this._meshes) {
  766. // Clean mesh references
  767. for (let id in this._meshes) {
  768. let meshHighlight = this._meshes[id];
  769. if (meshHighlight && meshHighlight.mesh) {
  770. if (meshHighlight.observerHighlight) {
  771. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  772. }
  773. if (meshHighlight.observerDefault) {
  774. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  775. }
  776. }
  777. }
  778. this._meshes = null;
  779. }
  780. if (this._excludedMeshes) {
  781. for (let id in this._excludedMeshes) {
  782. let meshHighlight = this._excludedMeshes[id];
  783. if (meshHighlight) {
  784. if (meshHighlight.beforeRender) {
  785. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  786. }
  787. if (meshHighlight.afterRender) {
  788. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  789. }
  790. }
  791. }
  792. this._excludedMeshes = null;
  793. }
  794. // Remove from scene
  795. var index = this._scene.highlightLayers.indexOf(this, 0);
  796. if (index > -1) {
  797. this._scene.highlightLayers.splice(index, 1);
  798. }
  799. // Callback
  800. this.onDisposeObservable.notifyObservers(this);
  801. this.onDisposeObservable.clear();
  802. this.onBeforeRenderMainTextureObservable.clear();
  803. this.onBeforeBlurObservable.clear();
  804. this.onBeforeComposeObservable.clear();
  805. this.onAfterComposeObservable.clear();
  806. this.onSizeChangedObservable.clear();
  807. }
  808. }
  809. }