babylon.highlightlayer.ts 40 KB

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