layer.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { Observer, Observable } from "../Misc/observable";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Vector2, Color4 } from "../Maths/math";
  5. import { EngineStore } from "../Engines/engineStore";
  6. import { VertexBuffer } from "../Meshes/buffer";
  7. import { Effect } from "../Materials/effect";
  8. import { Material } from "../Materials/material";
  9. import { Texture } from "../Materials/Textures/texture";
  10. import { SceneComponentConstants } from "../sceneComponent";
  11. import { _TimeToken } from "../Instrumentation/timeToken";
  12. import { _DepthCullingState, _StencilState, _AlphaState } from "../States/index";
  13. import { LayerSceneComponent } from "./layerSceneComponent";
  14. import { Constants } from "../Engines/constants";
  15. import { RenderTargetTexture } from "../Materials/Textures/renderTargetTexture";
  16. import "../Shaders/layer.fragment";
  17. import "../Shaders/layer.vertex";
  18. import { DataBuffer } from '../Meshes/dataBuffer';
  19. /**
  20. * This represents a full screen 2d layer.
  21. * This can be useful to display a picture in the background of your scene for instance.
  22. * @see https://www.babylonjs-playground.com/#08A2BS#1
  23. */
  24. export class Layer {
  25. /**
  26. * Define the texture the layer should display.
  27. */
  28. public texture: Nullable<Texture>;
  29. /**
  30. * Is the layer in background or foreground.
  31. */
  32. public isBackground: boolean;
  33. /**
  34. * Define the color of the layer (instead of texture).
  35. */
  36. public color: Color4;
  37. /**
  38. * Define the scale of the layer in order to zoom in out of the texture.
  39. */
  40. public scale = new Vector2(1, 1);
  41. /**
  42. * Define an offset for the layer in order to shift the texture.
  43. */
  44. public offset = new Vector2(0, 0);
  45. /**
  46. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  47. */
  48. public alphaBlendingMode = Constants.ALPHA_COMBINE;
  49. /**
  50. * Define if the layer should alpha test or alpha blend with the rest of the scene.
  51. * Alpha test will not mix with the background color in case of transparency.
  52. * It will either use the texture color or the background depending on the alpha value of the current pixel.
  53. */
  54. public alphaTest: boolean;
  55. /**
  56. * Define a mask to restrict the layer to only some of the scene cameras.
  57. */
  58. public layerMask: number = 0x0FFFFFFF;
  59. /**
  60. * Define the list of render target the layer is visible into.
  61. */
  62. public renderTargetTextures: RenderTargetTexture[] = [];
  63. /**
  64. * Define if the layer is only used in renderTarget or if it also
  65. * renders in the main frame buffer of the canvas.
  66. */
  67. public renderOnlyInRenderTargetTextures = false;
  68. private _scene: Scene;
  69. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  70. private _indexBuffer: Nullable<DataBuffer>;
  71. private _effect: Effect;
  72. private _alphaTestEffect: Effect;
  73. /**
  74. * An event triggered when the layer is disposed.
  75. */
  76. public onDisposeObservable = new Observable<Layer>();
  77. private _onDisposeObserver: Nullable<Observer<Layer>>;
  78. /**
  79. * Back compatibility with callback before the onDisposeObservable existed.
  80. * The set callback will be triggered when the layer has been disposed.
  81. */
  82. public set onDispose(callback: () => void) {
  83. if (this._onDisposeObserver) {
  84. this.onDisposeObservable.remove(this._onDisposeObserver);
  85. }
  86. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  87. }
  88. /**
  89. * An event triggered before rendering the scene
  90. */
  91. public onBeforeRenderObservable = new Observable<Layer>();
  92. private _onBeforeRenderObserver: Nullable<Observer<Layer>>;
  93. /**
  94. * Back compatibility with callback before the onBeforeRenderObservable existed.
  95. * The set callback will be triggered just before rendering the layer.
  96. */
  97. public set onBeforeRender(callback: () => void) {
  98. if (this._onBeforeRenderObserver) {
  99. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  100. }
  101. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  102. }
  103. /**
  104. * An event triggered after rendering the scene
  105. */
  106. public onAfterRenderObservable = new Observable<Layer>();
  107. private _onAfterRenderObserver: Nullable<Observer<Layer>>;
  108. /**
  109. * Back compatibility with callback before the onAfterRenderObservable existed.
  110. * The set callback will be triggered just after rendering the layer.
  111. */
  112. public set onAfterRender(callback: () => void) {
  113. if (this._onAfterRenderObserver) {
  114. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  115. }
  116. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  117. }
  118. /**
  119. * Instantiates a new layer.
  120. * This represents a full screen 2d layer.
  121. * This can be useful to display a picture in the background of your scene for instance.
  122. * @see https://www.babylonjs-playground.com/#08A2BS#1
  123. * @param name Define the name of the layer in the scene
  124. * @param imgUrl Define the url of the texture to display in the layer
  125. * @param scene Define the scene the layer belongs to
  126. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  127. * @param color Defines a color for the layer
  128. */
  129. constructor(
  130. /**
  131. * Define the name of the layer.
  132. */
  133. public name: string,
  134. imgUrl: Nullable<string>,
  135. scene: Nullable<Scene>,
  136. isBackground?: boolean, color?: Color4) {
  137. this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null;
  138. this.isBackground = isBackground === undefined ? true : isBackground;
  139. this.color = color === undefined ? new Color4(1, 1, 1, 1) : color;
  140. this._scene = <Scene>(scene || EngineStore.LastCreatedScene);
  141. let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER) as LayerSceneComponent;
  142. if (!layerComponent) {
  143. layerComponent = new LayerSceneComponent(this._scene);
  144. this._scene._addComponent(layerComponent);
  145. }
  146. this._scene.layers.push(this);
  147. var engine = this._scene.getEngine();
  148. // VBO
  149. var vertices = [];
  150. vertices.push(1, 1);
  151. vertices.push(-1, 1);
  152. vertices.push(-1, -1);
  153. vertices.push(1, -1);
  154. var vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  155. this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer;
  156. this._createIndexBuffer();
  157. // Effects
  158. this._effect = engine.createEffect("layer",
  159. [VertexBuffer.PositionKind],
  160. ["textureMatrix", "color", "scale", "offset"],
  161. ["textureSampler"], "");
  162. this._alphaTestEffect = engine.createEffect("layer",
  163. [VertexBuffer.PositionKind],
  164. ["textureMatrix", "color", "scale", "offset"],
  165. ["textureSampler"], "#define ALPHATEST");
  166. }
  167. private _createIndexBuffer(): void {
  168. var engine = this._scene.getEngine();
  169. // Indices
  170. var indices = [];
  171. indices.push(0);
  172. indices.push(1);
  173. indices.push(2);
  174. indices.push(0);
  175. indices.push(2);
  176. indices.push(3);
  177. this._indexBuffer = engine.createIndexBuffer(indices);
  178. }
  179. /** @hidden */
  180. public _rebuild(): void {
  181. let vb = this._vertexBuffers[VertexBuffer.PositionKind];
  182. if (vb) {
  183. vb._rebuild();
  184. }
  185. this._createIndexBuffer();
  186. }
  187. /**
  188. * Renders the layer in the scene.
  189. */
  190. public render(): void {
  191. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  192. // Check
  193. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
  194. return;
  195. }
  196. var engine = this._scene.getEngine();
  197. this.onBeforeRenderObservable.notifyObservers(this);
  198. // Render
  199. engine.enableEffect(currentEffect);
  200. engine.setState(false);
  201. // Texture
  202. currentEffect.setTexture("textureSampler", this.texture);
  203. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  204. // Color
  205. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  206. // Scale / offset
  207. currentEffect.setVector2("offset", this.offset);
  208. currentEffect.setVector2("scale", this.scale);
  209. // VBOs
  210. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  211. // Draw order
  212. if (!this.alphaTest) {
  213. engine.setAlphaMode(this.alphaBlendingMode);
  214. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  215. engine.setAlphaMode(Constants.ALPHA_DISABLE);
  216. }
  217. else {
  218. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  219. }
  220. this.onAfterRenderObservable.notifyObservers(this);
  221. }
  222. /**
  223. * Disposes and releases the associated ressources.
  224. */
  225. public dispose(): void {
  226. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  227. if (vertexBuffer) {
  228. vertexBuffer.dispose();
  229. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  230. }
  231. if (this._indexBuffer) {
  232. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  233. this._indexBuffer = null;
  234. }
  235. if (this.texture) {
  236. this.texture.dispose();
  237. this.texture = null;
  238. }
  239. // Clean RTT list
  240. this.renderTargetTextures = [];
  241. // Remove from scene
  242. var index = this._scene.layers.indexOf(this);
  243. this._scene.layers.splice(index, 1);
  244. // Callback
  245. this.onDisposeObservable.notifyObservers(this);
  246. this.onDisposeObservable.clear();
  247. this.onAfterRenderObservable.clear();
  248. this.onBeforeRenderObservable.clear();
  249. }
  250. }