glowLayer.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import { serialize, Tools, SerializationHelper } from "Tools";
  2. import { Nullable } from "types";
  3. import { Camera } from "Cameras";
  4. import { Scene } from "scene";
  5. import { Vector2, Color4 } from "Math";
  6. import { Engine } from "Engine";
  7. import { Mesh, AbstractMesh, VertexBuffer, SubMesh } from "Mesh";
  8. import { RenderTargetTexture, Material, Texture, Effect } from "Materials";
  9. import { PostProcess, BlurPostProcess } from "PostProcess";
  10. import { EffectLayer } from "Layer";
  11. import { AbstractScene } from "abstractScene";
  12. export interface AbstractScene {
  13. /**
  14. * Return a the first highlight layer of the scene with a given name.
  15. * @param name The name of the highlight layer to look for.
  16. * @return The highlight layer if found otherwise null.
  17. */
  18. getGlowLayerByName(name: string): Nullable<GlowLayer>;
  19. }
  20. AbstractScene.prototype.getGlowLayerByName = function(name: string): Nullable<GlowLayer> {
  21. for (var index = 0; index < this.effectLayers.length; index++) {
  22. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  23. return (<any>this.effectLayers[index]) as GlowLayer;
  24. }
  25. }
  26. return null;
  27. };
  28. /**
  29. * Glow layer options. This helps customizing the behaviour
  30. * of the glow layer.
  31. */
  32. export interface IGlowLayerOptions {
  33. /**
  34. * Multiplication factor apply to the canvas size to compute the render target size
  35. * used to generated the glowing objects (the smaller the faster).
  36. */
  37. mainTextureRatio: number;
  38. /**
  39. * Enforces a fixed size texture to ensure resize independant blur.
  40. */
  41. mainTextureFixedSize?: number;
  42. /**
  43. * How big is the kernel of the blur texture.
  44. */
  45. blurKernelSize: number;
  46. /**
  47. * The camera attached to the layer.
  48. */
  49. camera: Nullable<Camera>;
  50. /**
  51. * Enable MSAA by chosing the number of samples.
  52. */
  53. mainTextureSamples?: number;
  54. /**
  55. * The rendering group to draw the layer in.
  56. */
  57. renderingGroupId: number;
  58. }
  59. /**
  60. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  61. *
  62. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  63. * glowy meshes to your scene.
  64. *
  65. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  66. */
  67. export class GlowLayer extends EffectLayer {
  68. /**
  69. * Effect Name of the layer.
  70. */
  71. public static readonly EffectName = "GlowLayer";
  72. /**
  73. * The default blur kernel size used for the glow.
  74. */
  75. public static DefaultBlurKernelSize = 32;
  76. /**
  77. * The default texture size ratio used for the glow.
  78. */
  79. public static DefaultTextureRatio = 0.5;
  80. /**
  81. * Sets the kernel size of the blur.
  82. */
  83. public set blurKernelSize(value: number) {
  84. this._horizontalBlurPostprocess1.kernel = value;
  85. this._verticalBlurPostprocess1.kernel = value;
  86. this._horizontalBlurPostprocess2.kernel = value;
  87. this._verticalBlurPostprocess2.kernel = value;
  88. }
  89. /**
  90. * Gets the kernel size of the blur.
  91. */
  92. @serialize()
  93. public get blurKernelSize(): number {
  94. return this._horizontalBlurPostprocess1.kernel;
  95. }
  96. /**
  97. * Sets the glow intensity.
  98. */
  99. public set intensity(value: number) {
  100. this._intensity = value;
  101. }
  102. /**
  103. * Gets the glow intensity.
  104. */
  105. @serialize()
  106. public get intensity(): number {
  107. return this._intensity;
  108. }
  109. @serialize("options")
  110. private _options: IGlowLayerOptions;
  111. private _intensity: number = 1.0;
  112. private _horizontalBlurPostprocess1: BlurPostProcess;
  113. private _verticalBlurPostprocess1: BlurPostProcess;
  114. private _horizontalBlurPostprocess2: BlurPostProcess;
  115. private _verticalBlurPostprocess2: BlurPostProcess;
  116. private _blurTexture1: RenderTargetTexture;
  117. private _blurTexture2: RenderTargetTexture;
  118. private _postProcesses1: PostProcess[];
  119. private _postProcesses2: PostProcess[];
  120. private _includedOnlyMeshes: number[] = [];
  121. private _excludedMeshes: number[] = [];
  122. /**
  123. * Callback used to let the user override the color selection on a per mesh basis
  124. */
  125. public customEmissiveColorSelector: (mesh: Mesh, subMesh: SubMesh, material: Material, result: Color4) => void;
  126. /**
  127. * Callback used to let the user override the texture selection on a per mesh basis
  128. */
  129. public customEmissiveTextureSelector: (mesh: Mesh, subMesh: SubMesh, material: Material) => Texture;
  130. /**
  131. * Instantiates a new glow Layer and references it to the scene.
  132. * @param name The name of the layer
  133. * @param scene The scene to use the layer in
  134. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  135. */
  136. constructor(name: string, scene: Scene, options?: Partial<IGlowLayerOptions>) {
  137. super(name, scene);
  138. this.neutralColor = new Color4(0, 0, 0, 1);
  139. // Adapt options
  140. this._options = {
  141. mainTextureRatio: GlowLayer.DefaultTextureRatio,
  142. blurKernelSize: 32,
  143. mainTextureFixedSize: undefined,
  144. camera: null,
  145. mainTextureSamples: 1,
  146. renderingGroupId: -1,
  147. ...options,
  148. };
  149. // Initialize the layer
  150. this._init({
  151. alphaBlendingMode: Engine.ALPHA_ADD,
  152. camera: this._options.camera,
  153. mainTextureFixedSize: this._options.mainTextureFixedSize,
  154. mainTextureRatio: this._options.mainTextureRatio,
  155. renderingGroupId: this._options.renderingGroupId
  156. });
  157. }
  158. /**
  159. * Get the effect name of the layer.
  160. * @return The effect name
  161. */
  162. public getEffectName(): string {
  163. return GlowLayer.EffectName;
  164. }
  165. /**
  166. * Create the merge effect. This is the shader use to blit the information back
  167. * to the main canvas at the end of the scene rendering.
  168. */
  169. protected _createMergeEffect(): Effect {
  170. // Effect
  171. return this._engine.createEffect("glowMapMerge",
  172. [VertexBuffer.PositionKind],
  173. ["offset"],
  174. ["textureSampler", "textureSampler2"],
  175. "#define EMISSIVE \n");
  176. }
  177. /**
  178. * Creates the render target textures and post processes used in the glow layer.
  179. */
  180. protected _createTextureAndPostProcesses(): void {
  181. var blurTextureWidth = this._mainTextureDesiredSize.width;
  182. var blurTextureHeight = this._mainTextureDesiredSize.height;
  183. blurTextureWidth = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  184. blurTextureHeight = this._engine.needPOTTextures ? Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  185. var textureType = 0;
  186. if (this._engine.getCaps().textureHalfFloatRender) {
  187. textureType = Engine.TEXTURETYPE_HALF_FLOAT;
  188. }
  189. else {
  190. textureType = Engine.TEXTURETYPE_UNSIGNED_INT;
  191. }
  192. this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT",
  193. {
  194. width: blurTextureWidth,
  195. height: blurTextureHeight
  196. },
  197. this._scene,
  198. false,
  199. true,
  200. textureType);
  201. this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE;
  202. this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE;
  203. this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  204. this._blurTexture1.renderParticles = false;
  205. this._blurTexture1.ignoreCameraViewport = true;
  206. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  207. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  208. this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2",
  209. {
  210. width: blurTextureWidth2,
  211. height: blurTextureHeight2
  212. },
  213. this._scene,
  214. false,
  215. true,
  216. textureType);
  217. this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE;
  218. this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE;
  219. this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE);
  220. this._blurTexture2.renderParticles = false;
  221. this._blurTexture2.ignoreCameraViewport = true;
  222. this._textures = [this._blurTexture1, this._blurTexture2];
  223. this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1", new Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  224. width: blurTextureWidth,
  225. height: blurTextureHeight
  226. },
  227. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  228. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  229. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  230. this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => {
  231. effect.setTexture("textureSampler", this._mainTexture);
  232. });
  233. this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1", new Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  234. width: blurTextureWidth,
  235. height: blurTextureHeight
  236. },
  237. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  238. this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2", new Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  239. width: blurTextureWidth2,
  240. height: blurTextureHeight2
  241. },
  242. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  243. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  244. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  245. this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => {
  246. effect.setTexture("textureSampler", this._blurTexture1);
  247. });
  248. this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2", new Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  249. width: blurTextureWidth2,
  250. height: blurTextureHeight2
  251. },
  252. null, Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  253. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  254. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  255. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  256. this._mainTexture.samples = this._options.mainTextureSamples!;
  257. this._mainTexture.onAfterUnbindObservable.add(() => {
  258. let internalTexture = this._blurTexture1.getInternalTexture();
  259. if (internalTexture) {
  260. this._scene.postProcessManager.directRender(
  261. this._postProcesses1,
  262. internalTexture,
  263. true);
  264. internalTexture = this._blurTexture2.getInternalTexture();
  265. if (internalTexture) {
  266. this._scene.postProcessManager.directRender(
  267. this._postProcesses2,
  268. internalTexture,
  269. true);
  270. }
  271. }
  272. });
  273. // Prevent autoClear.
  274. this._postProcesses.map((pp) => { pp.autoClear = false; });
  275. }
  276. /**
  277. * Checks for the readiness of the element composing the layer.
  278. * @param subMesh the mesh to check for
  279. * @param useInstances specify wether or not to use instances to render the mesh
  280. * @param emissiveTexture the associated emissive texture used to generate the glow
  281. * @return true if ready otherwise, false
  282. */
  283. public isReady(subMesh: SubMesh, useInstances: boolean): boolean {
  284. let material = subMesh.getMaterial();
  285. let mesh = subMesh.getRenderingMesh();
  286. if (!material || !mesh) {
  287. return false;
  288. }
  289. let emissiveTexture = (<any>material).emissiveTexture;
  290. return super._isReady(subMesh, useInstances, emissiveTexture);
  291. }
  292. /**
  293. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  294. */
  295. public needStencil(): boolean {
  296. return false;
  297. }
  298. /**
  299. * Implementation specific of rendering the generating effect on the main canvas.
  300. * @param effect The effect used to render through
  301. */
  302. protected _internalRender(effect: Effect): void {
  303. // Texture
  304. effect.setTexture("textureSampler", this._blurTexture1);
  305. effect.setTexture("textureSampler2", this._blurTexture2);
  306. effect.setFloat("offset", this._intensity);
  307. // Cache
  308. var engine = this._engine;
  309. var previousStencilBuffer = engine.getStencilBuffer();
  310. // Draw order
  311. engine.setStencilBuffer(false);
  312. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  313. // Draw order
  314. engine.setStencilBuffer(previousStencilBuffer);
  315. }
  316. /**
  317. * Sets the required values for both the emissive texture and and the main color.
  318. */
  319. protected _setEmissiveTextureAndColor(mesh: Mesh, subMesh: SubMesh, material: Material): void {
  320. var textureLevel = 1.0;
  321. if (this.customEmissiveTextureSelector) {
  322. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  323. } else {
  324. if (material) {
  325. this._emissiveTextureAndColor.texture = (<any>material).emissiveTexture;
  326. if (this._emissiveTextureAndColor.texture) {
  327. textureLevel = this._emissiveTextureAndColor.texture.level;
  328. }
  329. }
  330. else {
  331. this._emissiveTextureAndColor.texture = null;
  332. }
  333. }
  334. if (this.customEmissiveColorSelector) {
  335. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  336. } else {
  337. if ((<any>material).emissiveColor) {
  338. this._emissiveTextureAndColor.color.set(
  339. (<any>material).emissiveColor.r * textureLevel,
  340. (<any>material).emissiveColor.g * textureLevel,
  341. (<any>material).emissiveColor.b * textureLevel,
  342. 1.0);
  343. }
  344. else {
  345. this._emissiveTextureAndColor.color.set(
  346. this.neutralColor.r,
  347. this.neutralColor.g,
  348. this.neutralColor.b,
  349. this.neutralColor.a);
  350. }
  351. }
  352. }
  353. /**
  354. * Returns true if the mesh should render, otherwise false.
  355. * @param mesh The mesh to render
  356. * @returns true if it should render otherwise false
  357. */
  358. protected _shouldRenderMesh(mesh: Mesh): boolean {
  359. return this.hasMesh(mesh);
  360. }
  361. /**
  362. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  363. * @param mesh The mesh to exclude from the glow layer
  364. */
  365. public addExcludedMesh(mesh: Mesh): void {
  366. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  367. this._excludedMeshes.push(mesh.uniqueId);
  368. }
  369. }
  370. /**
  371. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  372. * @param mesh The mesh to remove
  373. */
  374. public removeExcludedMesh(mesh: Mesh): void {
  375. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  376. if (index !== -1) {
  377. this._excludedMeshes.splice(index, 1);
  378. }
  379. }
  380. /**
  381. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  382. * @param mesh The mesh to include in the glow layer
  383. */
  384. public addIncludedOnlyMesh(mesh: Mesh): void {
  385. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  386. this._includedOnlyMeshes.push(mesh.uniqueId);
  387. }
  388. }
  389. /**
  390. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  391. * @param mesh The mesh to remove
  392. */
  393. public removeIncludedOnlyMesh(mesh: Mesh): void {
  394. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  395. if (index !== -1) {
  396. this._includedOnlyMeshes.splice(index, 1);
  397. }
  398. }
  399. /**
  400. * Determine if a given mesh will be used in the glow layer
  401. * @param mesh The mesh to test
  402. * @returns true if the mesh will be highlighted by the current glow layer
  403. */
  404. public hasMesh(mesh: AbstractMesh): boolean {
  405. if (!super.hasMesh(mesh)) {
  406. return false;
  407. }
  408. // Included Mesh
  409. if (this._includedOnlyMeshes.length) {
  410. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  411. }
  412. // Excluded Mesh
  413. if (this._excludedMeshes.length) {
  414. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  415. }
  416. return true;
  417. }
  418. /**
  419. * Free any resources and references associated to a mesh.
  420. * Internal use
  421. * @param mesh The mesh to free.
  422. * @hidden
  423. */
  424. public _disposeMesh(mesh: Mesh): void {
  425. this.removeIncludedOnlyMesh(mesh);
  426. this.removeExcludedMesh(mesh);
  427. }
  428. /**
  429. * Gets the class name of the effect layer
  430. * @returns the string with the class name of the effect layer
  431. */
  432. public getClassName(): string {
  433. return "GlowLayer";
  434. }
  435. /**
  436. * Serializes this glow layer
  437. * @returns a serialized glow layer object
  438. */
  439. public serialize(): any {
  440. var serializationObject = SerializationHelper.Serialize(this);
  441. serializationObject.customType = "BABYLON.GlowLayer";
  442. var index;
  443. // Included meshes
  444. serializationObject.includedMeshes = [];
  445. if (this._includedOnlyMeshes.length) {
  446. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  447. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  448. if (mesh) {
  449. serializationObject.includedMeshes.push(mesh.id);
  450. }
  451. }
  452. }
  453. // Excluded meshes
  454. serializationObject.excludedMeshes = [];
  455. if (this._excludedMeshes.length) {
  456. for (index = 0; index < this._excludedMeshes.length; index++) {
  457. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  458. if (mesh) {
  459. serializationObject.excludedMeshes.push(mesh.id);
  460. }
  461. }
  462. }
  463. return serializationObject;
  464. }
  465. /**
  466. * Creates a Glow Layer from parsed glow layer data
  467. * @param parsedGlowLayer defines glow layer data
  468. * @param scene defines the current scene
  469. * @param rootUrl defines the root URL containing the glow layer information
  470. * @returns a parsed Glow Layer
  471. */
  472. public static Parse(parsedGlowLayer: any, scene: Scene, rootUrl: string): GlowLayer {
  473. var gl = SerializationHelper.Parse(() => new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl);
  474. var index;
  475. // Excluded meshes
  476. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  477. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  478. if (mesh) {
  479. gl.addExcludedMesh(<Mesh>mesh);
  480. }
  481. }
  482. // Included meshes
  483. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  484. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  485. if (mesh) {
  486. gl.addIncludedOnlyMesh(<Mesh>mesh);
  487. }
  488. }
  489. return gl;
  490. }
  491. }