babylon.highlightlayer.ts 36 KB

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