lensFlareSystem.ts 15 KB

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