babylon.lensFlareSystem.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. module BABYLON {
  2. /**
  3. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  4. * It is usually composed of several `BABYLON.lensFlare`.
  5. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  6. */
  7. export class LensFlareSystem {
  8. /**
  9. * List of lens flares used in this system.
  10. */
  11. public lensFlares = new Array<LensFlare>();
  12. /**
  13. * Define a limit from the border the lens flare can be visible.
  14. */
  15. public borderLimit = 300;
  16. /**
  17. * Define a viewport border we do not want to see the lens flare in.
  18. */
  19. public viewportBorder = 0;
  20. /**
  21. * Define a predicate which could limit the list of meshes able to occlude the effect.
  22. */
  23. public meshesSelectionPredicate: (mesh: AbstractMesh) => boolean;
  24. /**
  25. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  26. */
  27. public layerMask: number = 0x0FFFFFFF;
  28. /**
  29. * Define the id of the lens flare system in the scene.
  30. * (equal to name by default)
  31. */
  32. public id: string;
  33. private _scene: Scene;
  34. private _emitter: any;
  35. private _vertexBuffers: { [key: string]: Nullable<VertexBuffer> } = {};
  36. private _indexBuffer: Nullable<WebGLBuffer>;
  37. private _effect: Effect;
  38. private _positionX: number;
  39. private _positionY: number;
  40. private _isEnabled = true;
  41. /**
  42. * Instantiates a lens flare system.
  43. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  44. * It is usually composed of several `BABYLON.lensFlare`.
  45. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  46. * @param name Define the name of the lens flare system in the scene
  47. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  48. * @param scene Define the scene the lens flare system belongs to
  49. */
  50. constructor(public name: string, emitter: any, scene: Scene) {
  51. this._scene = scene || Engine.LastCreatedScene;
  52. let component = this._scene._getComponent(SceneComponentConstants.NAME_LENSFLARESYSTEM) as LensFlareSystemSceneComponent;
  53. if (!component) {
  54. component = new LensFlareSystemSceneComponent(this._scene);
  55. scene._addComponent(component);
  56. }
  57. this._emitter = emitter;
  58. this.id = name;
  59. scene.lensFlareSystems.push(this);
  60. this.meshesSelectionPredicate = m => <boolean>(scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0));
  61. var engine = scene.getEngine();
  62. // VBO
  63. var vertices = [];
  64. vertices.push(1, 1);
  65. vertices.push(-1, 1);
  66. vertices.push(-1, -1);
  67. vertices.push(1, -1);
  68. this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2);
  69. // Indices
  70. var indices = [];
  71. indices.push(0);
  72. indices.push(1);
  73. indices.push(2);
  74. indices.push(0);
  75. indices.push(2);
  76. indices.push(3);
  77. this._indexBuffer = engine.createIndexBuffer(indices);
  78. // Effects
  79. this._effect = engine.createEffect("lensFlare",
  80. [VertexBuffer.PositionKind],
  81. ["color", "viewportMatrix"],
  82. ["textureSampler"], "");
  83. }
  84. /**
  85. * Define if the lens flare system is enabled.
  86. */
  87. public get isEnabled(): boolean {
  88. return this._isEnabled;
  89. }
  90. public set isEnabled(value: boolean) {
  91. this._isEnabled = value;
  92. }
  93. /**
  94. * Get the scene the effects belongs to.
  95. * @returns the scene holding the lens flare system
  96. */
  97. public getScene(): Scene {
  98. return this._scene;
  99. }
  100. /**
  101. * Get the emitter of the lens flare system.
  102. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  103. */
  104. public getEmitter(): any {
  105. return this._emitter;
  106. }
  107. /**
  108. * Set the emitter of the lens flare system.
  109. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  110. */
  111. public setEmitter(newEmitter: any): void {
  112. this._emitter = newEmitter;
  113. }
  114. /**
  115. * Get the lens flare system emitter position.
  116. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  117. */
  118. public getEmitterPosition(): Vector3 {
  119. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  120. }
  121. /**
  122. * @hidden
  123. */
  124. public computeEffectivePosition(globalViewport: Viewport): boolean {
  125. var position = this.getEmitterPosition();
  126. position = Vector3.Project(position, Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  127. this._positionX = position.x;
  128. this._positionY = position.y;
  129. position = Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  130. if (this.viewportBorder > 0) {
  131. globalViewport.x -= this.viewportBorder;
  132. globalViewport.y -= this.viewportBorder;
  133. globalViewport.width += this.viewportBorder * 2;
  134. globalViewport.height += this.viewportBorder * 2;
  135. position.x += this.viewportBorder;
  136. position.y += this.viewportBorder;
  137. this._positionX += this.viewportBorder;
  138. this._positionY += this.viewportBorder;
  139. }
  140. if (position.z > 0) {
  141. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  142. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  143. return true;
  144. }
  145. return true;
  146. }
  147. return false;
  148. }
  149. /** @hidden */
  150. public _isVisible(): boolean {
  151. if (!this._isEnabled || !this._scene.activeCamera) {
  152. return false;
  153. }
  154. var emitterPosition = this.getEmitterPosition();
  155. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  156. var distance = direction.length();
  157. direction.normalize();
  158. var ray = new Ray(this._scene.activeCamera.globalPosition, direction);
  159. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  160. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  161. }
  162. /**
  163. * @hidden
  164. */
  165. public render(): boolean {
  166. if (!this._effect.isReady() || !this._scene.activeCamera)
  167. return false;
  168. var engine = this._scene.getEngine();
  169. var viewport = this._scene.activeCamera.viewport;
  170. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  171. // Position
  172. if (!this.computeEffectivePosition(globalViewport)) {
  173. return false;
  174. }
  175. // Visibility
  176. if (!this._isVisible()) {
  177. return false;
  178. }
  179. // Intensity
  180. var awayX;
  181. var awayY;
  182. if (this._positionX < this.borderLimit + globalViewport.x) {
  183. awayX = this.borderLimit + globalViewport.x - this._positionX;
  184. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  185. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  186. } else {
  187. awayX = 0;
  188. }
  189. if (this._positionY < this.borderLimit + globalViewport.y) {
  190. awayY = this.borderLimit + globalViewport.y - this._positionY;
  191. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  192. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  193. } else {
  194. awayY = 0;
  195. }
  196. var away = (awayX > awayY) ? awayX : awayY;
  197. away -= this.viewportBorder;
  198. if (away > this.borderLimit) {
  199. away = this.borderLimit;
  200. }
  201. var intensity = 1.0 - (away / this.borderLimit);
  202. if (intensity < 0) {
  203. return false;
  204. }
  205. if (intensity > 1.0) {
  206. intensity = 1.0;
  207. }
  208. if (this.viewportBorder > 0) {
  209. globalViewport.x += this.viewportBorder;
  210. globalViewport.y += this.viewportBorder;
  211. globalViewport.width -= this.viewportBorder * 2;
  212. globalViewport.height -= this.viewportBorder * 2;
  213. this._positionX -= this.viewportBorder;
  214. this._positionY -= this.viewportBorder;
  215. }
  216. // Position
  217. var centerX = globalViewport.x + globalViewport.width / 2;
  218. var centerY = globalViewport.y + globalViewport.height / 2;
  219. var distX = centerX - this._positionX;
  220. var distY = centerY - this._positionY;
  221. // Effects
  222. engine.enableEffect(this._effect);
  223. engine.setState(false);
  224. engine.setDepthBuffer(false);
  225. // VBOs
  226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  227. // Flares
  228. for (var index = 0; index < this.lensFlares.length; index++) {
  229. var flare = this.lensFlares[index];
  230. engine.setAlphaMode(flare.alphaMode);
  231. var x = centerX - (distX * flare.position);
  232. var y = centerY - (distY * flare.position);
  233. var cw = flare.size;
  234. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  235. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  236. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  237. var viewportMatrix = Matrix.FromValues(
  238. cw / 2, 0, 0, 0,
  239. 0, ch / 2, 0, 0,
  240. 0, 0, 1, 0,
  241. cx, cy, 0, 1);
  242. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  243. // Texture
  244. this._effect.setTexture("textureSampler", flare.texture);
  245. // Color
  246. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  247. // Draw order
  248. engine.drawElementsType(Material.TriangleFillMode, 0, 6);
  249. }
  250. engine.setDepthBuffer(true);
  251. engine.setAlphaMode(Engine.ALPHA_DISABLE);
  252. return true;
  253. }
  254. /**
  255. * Dispose and release the lens flare with its associated resources.
  256. */
  257. public dispose(): void {
  258. var vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind];
  259. if (vertexBuffer) {
  260. vertexBuffer.dispose();
  261. this._vertexBuffers[VertexBuffer.PositionKind] = null;
  262. }
  263. if (this._indexBuffer) {
  264. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  265. this._indexBuffer = null;
  266. }
  267. while (this.lensFlares.length) {
  268. this.lensFlares[0].dispose();
  269. }
  270. // Remove from scene
  271. var index = this._scene.lensFlareSystems.indexOf(this);
  272. this._scene.lensFlareSystems.splice(index, 1);
  273. }
  274. /**
  275. * Parse a lens flare system from a JSON repressentation
  276. * @param parsedLensFlareSystem Define the JSON to parse
  277. * @param scene Define the scene the parsed system should be instantiated in
  278. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  279. * @returns the parsed system
  280. */
  281. public static Parse(parsedLensFlareSystem: any, scene: Scene, rootUrl: string): LensFlareSystem {
  282. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  283. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  284. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  285. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  286. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  287. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  288. var parsedFlare = parsedLensFlareSystem.flares[index];
  289. LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  290. }
  291. return lensFlareSystem;
  292. }
  293. /**
  294. * Serialize the current Lens Flare System into a JSON representation.
  295. * @returns the serialized JSON
  296. */
  297. public serialize(): any {
  298. var serializationObject: any = {};
  299. serializationObject.id = this.id;
  300. serializationObject.name = this.name;
  301. serializationObject.emitterId = this.getEmitter().id;
  302. serializationObject.borderLimit = this.borderLimit;
  303. serializationObject.flares = [];
  304. for (var index = 0; index < this.lensFlares.length; index++) {
  305. var flare = this.lensFlares[index];
  306. serializationObject.flares.push({
  307. size: flare.size,
  308. position: flare.position,
  309. color: flare.color.asArray(),
  310. textureName: Tools.GetFilename(flare.texture ? flare.texture.name : "")
  311. });
  312. }
  313. return serializationObject;
  314. }
  315. }
  316. }