light.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. import { serialize, SerializationHelper, serializeAsColor3, expandToProperty } from "../Misc/decorators";
  2. import { Nullable } from "../types";
  3. import { Scene } from "../scene";
  4. import { Vector3 } from "../Maths/math.vector";
  5. import { Color3, TmpColors } from "../Maths/math.color";
  6. import { Node } from "../node";
  7. import { AbstractMesh } from "../Meshes/abstractMesh";
  8. import { Effect } from "../Materials/effect";
  9. import { UniformBuffer } from "../Materials/uniformBuffer";
  10. import { IShadowGenerator } from "./Shadows/shadowGenerator";
  11. import { _TypeStore } from '../Misc/typeStore';
  12. /**
  13. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  14. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  15. * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
  16. */
  17. export abstract class Light extends Node {
  18. /**
  19. * Falloff Default: light is falling off following the material specification:
  20. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  21. */
  22. public static readonly FALLOFF_DEFAULT = 0;
  23. /**
  24. * Falloff Physical: light is falling off following the inverse squared distance law.
  25. */
  26. public static readonly FALLOFF_PHYSICAL = 1;
  27. /**
  28. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  29. * to enhance interoperability with other engines.
  30. */
  31. public static readonly FALLOFF_GLTF = 2;
  32. /**
  33. * Falloff Standard: light is falling off like in the standard material
  34. * to enhance interoperability with other materials.
  35. */
  36. public static readonly FALLOFF_STANDARD = 3;
  37. //lightmapMode Consts
  38. /**
  39. * If every light affecting the material is in this lightmapMode,
  40. * material.lightmapTexture adds or multiplies
  41. * (depends on material.useLightmapAsShadowmap)
  42. * after every other light calculations.
  43. */
  44. public static readonly LIGHTMAP_DEFAULT = 0;
  45. /**
  46. * material.lightmapTexture as only diffuse lighting from this light
  47. * adds only specular lighting from this light
  48. * adds dynamic shadows
  49. */
  50. public static readonly LIGHTMAP_SPECULAR = 1;
  51. /**
  52. * material.lightmapTexture as only lighting
  53. * no light calculation from this light
  54. * only adds dynamic shadows from this light
  55. */
  56. public static readonly LIGHTMAP_SHADOWSONLY = 2;
  57. // Intensity Mode Consts
  58. /**
  59. * Each light type uses the default quantity according to its type:
  60. * point/spot lights use luminous intensity
  61. * directional lights use illuminance
  62. */
  63. public static readonly INTENSITYMODE_AUTOMATIC = 0;
  64. /**
  65. * lumen (lm)
  66. */
  67. public static readonly INTENSITYMODE_LUMINOUSPOWER = 1;
  68. /**
  69. * candela (lm/sr)
  70. */
  71. public static readonly INTENSITYMODE_LUMINOUSINTENSITY = 2;
  72. /**
  73. * lux (lm/m^2)
  74. */
  75. public static readonly INTENSITYMODE_ILLUMINANCE = 3;
  76. /**
  77. * nit (cd/m^2)
  78. */
  79. public static readonly INTENSITYMODE_LUMINANCE = 4;
  80. // Light types ids const.
  81. /**
  82. * Light type const id of the point light.
  83. */
  84. public static readonly LIGHTTYPEID_POINTLIGHT = 0;
  85. /**
  86. * Light type const id of the directional light.
  87. */
  88. public static readonly LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  89. /**
  90. * Light type const id of the spot light.
  91. */
  92. public static readonly LIGHTTYPEID_SPOTLIGHT = 2;
  93. /**
  94. * Light type const id of the hemispheric light.
  95. */
  96. public static readonly LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  97. /**
  98. * Diffuse gives the basic color to an object.
  99. */
  100. @serializeAsColor3()
  101. public diffuse = new Color3(1.0, 1.0, 1.0);
  102. /**
  103. * Specular produces a highlight color on an object.
  104. * Note: This is note affecting PBR materials.
  105. */
  106. @serializeAsColor3()
  107. public specular = new Color3(1.0, 1.0, 1.0);
  108. /**
  109. * Defines the falloff type for this light. This lets overrriding how punctual light are
  110. * falling off base on range or angle.
  111. * This can be set to any values in Light.FALLOFF_x.
  112. *
  113. * Note: This is only useful for PBR Materials at the moment. This could be extended if required to
  114. * other types of materials.
  115. */
  116. @serialize()
  117. public falloffType = Light.FALLOFF_DEFAULT;
  118. /**
  119. * Strength of the light.
  120. * Note: By default it is define in the framework own unit.
  121. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  122. */
  123. @serialize()
  124. public intensity = 1.0;
  125. private _range = Number.MAX_VALUE;
  126. protected _inverseSquaredRange = 0;
  127. /**
  128. * Defines how far from the source the light is impacting in scene units.
  129. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  130. */
  131. @serialize()
  132. public get range(): number {
  133. return this._range;
  134. }
  135. /**
  136. * Defines how far from the source the light is impacting in scene units.
  137. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  138. */
  139. public set range(value: number) {
  140. this._range = value;
  141. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  142. }
  143. /**
  144. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  145. * of light.
  146. */
  147. private _photometricScale = 1.0;
  148. private _intensityMode: number = Light.INTENSITYMODE_AUTOMATIC;
  149. /**
  150. * Gets the photometric scale used to interpret the intensity.
  151. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  152. */
  153. @serialize()
  154. public get intensityMode(): number {
  155. return this._intensityMode;
  156. }
  157. /**
  158. * Sets the photometric scale used to interpret the intensity.
  159. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  160. */
  161. public set intensityMode(value: number) {
  162. this._intensityMode = value;
  163. this._computePhotometricScale();
  164. }
  165. private _radius = 0.00001;
  166. /**
  167. * Gets the light radius used by PBR Materials to simulate soft area lights.
  168. */
  169. @serialize()
  170. public get radius(): number {
  171. return this._radius;
  172. }
  173. /**
  174. * sets the light radius used by PBR Materials to simulate soft area lights.
  175. */
  176. public set radius(value: number) {
  177. this._radius = value;
  178. this._computePhotometricScale();
  179. }
  180. @serialize()
  181. private _renderPriority: number;
  182. /**
  183. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  184. * exceeding the number allowed of the materials.
  185. */
  186. @expandToProperty("_reorderLightsInScene")
  187. public renderPriority: number = 0;
  188. @serialize("shadowEnabled")
  189. private _shadowEnabled: boolean = true;
  190. /**
  191. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  192. * the current shadow generator.
  193. */
  194. public get shadowEnabled(): boolean {
  195. return this._shadowEnabled;
  196. }
  197. /**
  198. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  199. * the current shadow generator.
  200. */
  201. public set shadowEnabled(value: boolean) {
  202. if (this._shadowEnabled === value) {
  203. return;
  204. }
  205. this._shadowEnabled = value;
  206. this._markMeshesAsLightDirty();
  207. }
  208. private _includedOnlyMeshes: AbstractMesh[];
  209. /**
  210. * Gets the only meshes impacted by this light.
  211. */
  212. public get includedOnlyMeshes(): AbstractMesh[] {
  213. return this._includedOnlyMeshes;
  214. }
  215. /**
  216. * Sets the only meshes impacted by this light.
  217. */
  218. public set includedOnlyMeshes(value: AbstractMesh[]) {
  219. this._includedOnlyMeshes = value;
  220. this._hookArrayForIncludedOnly(value);
  221. }
  222. private _excludedMeshes: AbstractMesh[];
  223. /**
  224. * Gets the meshes not impacted by this light.
  225. */
  226. public get excludedMeshes(): AbstractMesh[] {
  227. return this._excludedMeshes;
  228. }
  229. /**
  230. * Sets the meshes not impacted by this light.
  231. */
  232. public set excludedMeshes(value: AbstractMesh[]) {
  233. this._excludedMeshes = value;
  234. this._hookArrayForExcluded(value);
  235. }
  236. @serialize("excludeWithLayerMask")
  237. private _excludeWithLayerMask = 0;
  238. /**
  239. * Gets the layer id use to find what meshes are not impacted by the light.
  240. * Inactive if 0
  241. */
  242. public get excludeWithLayerMask(): number {
  243. return this._excludeWithLayerMask;
  244. }
  245. /**
  246. * Sets the layer id use to find what meshes are not impacted by the light.
  247. * Inactive if 0
  248. */
  249. public set excludeWithLayerMask(value: number) {
  250. this._excludeWithLayerMask = value;
  251. this._resyncMeshes();
  252. }
  253. @serialize("includeOnlyWithLayerMask")
  254. private _includeOnlyWithLayerMask = 0;
  255. /**
  256. * Gets the layer id use to find what meshes are impacted by the light.
  257. * Inactive if 0
  258. */
  259. public get includeOnlyWithLayerMask(): number {
  260. return this._includeOnlyWithLayerMask;
  261. }
  262. /**
  263. * Sets the layer id use to find what meshes are impacted by the light.
  264. * Inactive if 0
  265. */
  266. public set includeOnlyWithLayerMask(value: number) {
  267. this._includeOnlyWithLayerMask = value;
  268. this._resyncMeshes();
  269. }
  270. @serialize("lightmapMode")
  271. private _lightmapMode = 0;
  272. /**
  273. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  274. */
  275. public get lightmapMode(): number {
  276. return this._lightmapMode;
  277. }
  278. /**
  279. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  280. */
  281. public set lightmapMode(value: number) {
  282. if (this._lightmapMode === value) {
  283. return;
  284. }
  285. this._lightmapMode = value;
  286. this._markMeshesAsLightDirty();
  287. }
  288. /**
  289. * Shadow generator associted to the light.
  290. * @hidden Internal use only.
  291. */
  292. public _shadowGenerator: Nullable<IShadowGenerator>;
  293. /**
  294. * @hidden Internal use only.
  295. */
  296. public _excludedMeshesIds = new Array<string>();
  297. /**
  298. * @hidden Internal use only.
  299. */
  300. public _includedOnlyMeshesIds = new Array<string>();
  301. /**
  302. * The current light unifom buffer.
  303. * @hidden Internal use only.
  304. */
  305. public _uniformBuffer: UniformBuffer;
  306. /** @hidden */
  307. public _renderId: number;
  308. /**
  309. * Creates a Light object in the scene.
  310. * Documentation : https://doc.babylonjs.com/babylon101/lights
  311. * @param name The firendly name of the light
  312. * @param scene The scene the light belongs too
  313. */
  314. constructor(name: string, scene: Scene) {
  315. super(name, scene);
  316. this.getScene().addLight(this);
  317. this._uniformBuffer = new UniformBuffer(this.getScene().getEngine());
  318. this._buildUniformLayout();
  319. this.includedOnlyMeshes = new Array<AbstractMesh>();
  320. this.excludedMeshes = new Array<AbstractMesh>();
  321. this._resyncMeshes();
  322. }
  323. protected abstract _buildUniformLayout(): void;
  324. /**
  325. * Sets the passed Effect "effect" with the Light information.
  326. * @param effect The effect to update
  327. * @param lightIndex The index of the light in the effect to update
  328. * @returns The light
  329. */
  330. public abstract transferToEffect(effect: Effect, lightIndex: string): Light;
  331. /**
  332. * Sets the passed Effect "effect" with the Light textures.
  333. * @param effect The effect to update
  334. * @param lightIndex The index of the light in the effect to update
  335. * @returns The light
  336. */
  337. public transferTexturesToEffect(effect: Effect, lightIndex: string): Light {
  338. // Do nothing by default.
  339. return this;
  340. }
  341. /**
  342. * Binds the lights information from the scene to the effect for the given mesh.
  343. * @param lightIndex Light index
  344. * @param scene The scene where the light belongs to
  345. * @param effect The effect we are binding the data to
  346. * @param useSpecular Defines if specular is supported
  347. * @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
  348. */
  349. public _bindLight(lightIndex: number, scene: Scene, effect: Effect, useSpecular: boolean, rebuildInParallel = false): void {
  350. let iAsString = lightIndex.toString();
  351. let needUpdate = false;
  352. if (rebuildInParallel && this._uniformBuffer._alreadyBound) {
  353. return;
  354. }
  355. this._uniformBuffer.bindToEffect(effect, "Light" + iAsString);
  356. if (this._renderId !== scene.getRenderId() || !this._uniformBuffer.useUbo) {
  357. this._renderId = scene.getRenderId();
  358. let scaledIntensity = this.getScaledIntensity();
  359. this.transferToEffect(effect, iAsString);
  360. this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]);
  361. this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString);
  362. if (useSpecular) {
  363. this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]);
  364. this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString);
  365. }
  366. needUpdate = true;
  367. }
  368. // Textures might still need to be rebound.
  369. this.transferTexturesToEffect(effect, iAsString);
  370. // Shadows
  371. if (scene.shadowsEnabled && this.shadowEnabled) {
  372. var shadowGenerator = this.getShadowGenerator();
  373. if (shadowGenerator) {
  374. shadowGenerator.bindShadowLight(iAsString, effect);
  375. needUpdate = true;
  376. }
  377. }
  378. if (needUpdate) {
  379. this._uniformBuffer.update();
  380. }
  381. }
  382. /**
  383. * Sets the passed Effect "effect" with the Light information.
  384. * @param effect The effect to update
  385. * @param lightDataUniformName The uniform used to store light data (position or direction)
  386. * @returns The light
  387. */
  388. public abstract transferToNodeMaterialEffect(effect: Effect, lightDataUniformName: string): Light;
  389. /**
  390. * Returns the string "Light".
  391. * @returns the class name
  392. */
  393. public getClassName(): string {
  394. return "Light";
  395. }
  396. /** @hidden */
  397. public readonly _isLight = true;
  398. /**
  399. * Converts the light information to a readable string for debug purpose.
  400. * @param fullDetails Supports for multiple levels of logging within scene loading
  401. * @returns the human readable light info
  402. */
  403. public toString(fullDetails?: boolean): string {
  404. var ret = "Name: " + this.name;
  405. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  406. if (this.animations) {
  407. for (var i = 0; i < this.animations.length; i++) {
  408. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  409. }
  410. }
  411. if (fullDetails) {
  412. }
  413. return ret;
  414. }
  415. /** @hidden */
  416. protected _syncParentEnabledState() {
  417. super._syncParentEnabledState();
  418. if (!this.isDisposed()) {
  419. this._resyncMeshes();
  420. }
  421. }
  422. /**
  423. * Set the enabled state of this node.
  424. * @param value - the new enabled state
  425. */
  426. public setEnabled(value: boolean): void {
  427. super.setEnabled(value);
  428. this._resyncMeshes();
  429. }
  430. /**
  431. * Returns the Light associated shadow generator if any.
  432. * @return the associated shadow generator.
  433. */
  434. public getShadowGenerator(): Nullable<IShadowGenerator> {
  435. return this._shadowGenerator;
  436. }
  437. /**
  438. * Returns a Vector3, the absolute light position in the World.
  439. * @returns the world space position of the light
  440. */
  441. public getAbsolutePosition(): Vector3 {
  442. return Vector3.Zero();
  443. }
  444. /**
  445. * Specifies if the light will affect the passed mesh.
  446. * @param mesh The mesh to test against the light
  447. * @return true the mesh is affected otherwise, false.
  448. */
  449. public canAffectMesh(mesh: AbstractMesh): boolean {
  450. if (!mesh) {
  451. return true;
  452. }
  453. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  454. return false;
  455. }
  456. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  457. return false;
  458. }
  459. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  460. return false;
  461. }
  462. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  463. return false;
  464. }
  465. return true;
  466. }
  467. /**
  468. * Sort function to order lights for rendering.
  469. * @param a First Light object to compare to second.
  470. * @param b Second Light object to compare first.
  471. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  472. */
  473. public static CompareLightsPriority(a: Light, b: Light): number {
  474. //shadow-casting lights have priority over non-shadow-casting lights
  475. //the renderPrioirty is a secondary sort criterion
  476. if (a.shadowEnabled !== b.shadowEnabled) {
  477. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  478. }
  479. return b.renderPriority - a.renderPriority;
  480. }
  481. /**
  482. * Releases resources associated with this node.
  483. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  484. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  485. */
  486. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  487. if (this._shadowGenerator) {
  488. this._shadowGenerator.dispose();
  489. this._shadowGenerator = null;
  490. }
  491. // Animations
  492. this.getScene().stopAnimation(this);
  493. // Remove from meshes
  494. for (var mesh of this.getScene().meshes) {
  495. mesh._removeLightSource(this, true);
  496. }
  497. this._uniformBuffer.dispose();
  498. // Remove from scene
  499. this.getScene().removeLight(this);
  500. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  501. }
  502. /**
  503. * Returns the light type ID (integer).
  504. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  505. */
  506. public getTypeID(): number {
  507. return 0;
  508. }
  509. /**
  510. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  511. * @returns the scaled intensity in intensity mode unit
  512. */
  513. public getScaledIntensity() {
  514. return this._photometricScale * this.intensity;
  515. }
  516. /**
  517. * Returns a new Light object, named "name", from the current one.
  518. * @param name The name of the cloned light
  519. * @returns the new created light
  520. */
  521. public clone(name: string): Nullable<Light> {
  522. let constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  523. if (!constructor) {
  524. return null;
  525. }
  526. return SerializationHelper.Clone(constructor, this);
  527. }
  528. /**
  529. * Serializes the current light into a Serialization object.
  530. * @returns the serialized object.
  531. */
  532. public serialize(): any {
  533. var serializationObject = SerializationHelper.Serialize(this);
  534. // Type
  535. serializationObject.type = this.getTypeID();
  536. // Parent
  537. if (this.parent) {
  538. serializationObject.parentId = this.parent.id;
  539. }
  540. // Inclusion / exclusions
  541. if (this.excludedMeshes.length > 0) {
  542. serializationObject.excludedMeshesIds = [];
  543. this.excludedMeshes.forEach((mesh: AbstractMesh) => {
  544. serializationObject.excludedMeshesIds.push(mesh.id);
  545. });
  546. }
  547. if (this.includedOnlyMeshes.length > 0) {
  548. serializationObject.includedOnlyMeshesIds = [];
  549. this.includedOnlyMeshes.forEach((mesh: AbstractMesh) => {
  550. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  551. });
  552. }
  553. // Animations
  554. SerializationHelper.AppendSerializedAnimations(this, serializationObject);
  555. serializationObject.ranges = this.serializeAnimationRanges();
  556. return serializationObject;
  557. }
  558. /**
  559. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  560. * This new light is named "name" and added to the passed scene.
  561. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  562. * @param name The friendly name of the light
  563. * @param scene The scene the new light will belong to
  564. * @returns the constructor function
  565. */
  566. static GetConstructorFromName(type: number, name: string, scene: Scene): Nullable<() => Light> {
  567. let constructorFunc = Node.Construct("Light_Type_" + type, name, scene);
  568. if (constructorFunc) {
  569. return <() => Light>constructorFunc;
  570. }
  571. // Default to no light for none present once.
  572. return null;
  573. }
  574. /**
  575. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  576. * @param parsedLight The JSON representation of the light
  577. * @param scene The scene to create the parsed light in
  578. * @returns the created light after parsing
  579. */
  580. public static Parse(parsedLight: any, scene: Scene): Nullable<Light> {
  581. let constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  582. if (!constructor) {
  583. return null;
  584. }
  585. var light = SerializationHelper.Parse(constructor, parsedLight, scene);
  586. // Inclusion / exclusions
  587. if (parsedLight.excludedMeshesIds) {
  588. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  589. }
  590. if (parsedLight.includedOnlyMeshesIds) {
  591. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  592. }
  593. // Parent
  594. if (parsedLight.parentId) {
  595. light._waitingParentId = parsedLight.parentId;
  596. }
  597. // Falloff
  598. if (parsedLight.falloffType !== undefined) {
  599. light.falloffType = parsedLight.falloffType;
  600. }
  601. // Lightmaps
  602. if (parsedLight.lightmapMode !== undefined) {
  603. light.lightmapMode = parsedLight.lightmapMode;
  604. }
  605. // Animations
  606. if (parsedLight.animations) {
  607. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  608. var parsedAnimation = parsedLight.animations[animationIndex];
  609. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  610. if (internalClass) {
  611. light.animations.push(internalClass.Parse(parsedAnimation));
  612. }
  613. }
  614. Node.ParseAnimationRanges(light, parsedLight, scene);
  615. }
  616. if (parsedLight.autoAnimate) {
  617. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  618. }
  619. return light;
  620. }
  621. private _hookArrayForExcluded(array: AbstractMesh[]): void {
  622. var oldPush = array.push;
  623. array.push = (...items: AbstractMesh[]) => {
  624. var result = oldPush.apply(array, items);
  625. for (var item of items) {
  626. item._resyncLightSource(this);
  627. }
  628. return result;
  629. };
  630. var oldSplice = array.splice;
  631. array.splice = (index: number, deleteCount?: number) => {
  632. var deleted = oldSplice.apply(array, [index, deleteCount]);
  633. for (var item of deleted) {
  634. item._resyncLightSource(this);
  635. }
  636. return deleted;
  637. };
  638. for (var item of array) {
  639. item._resyncLightSource(this);
  640. }
  641. }
  642. private _hookArrayForIncludedOnly(array: AbstractMesh[]): void {
  643. var oldPush = array.push;
  644. array.push = (...items: AbstractMesh[]) => {
  645. var result = oldPush.apply(array, items);
  646. this._resyncMeshes();
  647. return result;
  648. };
  649. var oldSplice = array.splice;
  650. array.splice = (index: number, deleteCount?: number) => {
  651. var deleted = oldSplice.apply(array, [index, deleteCount]);
  652. this._resyncMeshes();
  653. return deleted;
  654. };
  655. this._resyncMeshes();
  656. }
  657. private _resyncMeshes() {
  658. for (var mesh of this.getScene().meshes) {
  659. mesh._resyncLightSource(this);
  660. }
  661. }
  662. /**
  663. * Forces the meshes to update their light related information in their rendering used effects
  664. * @hidden Internal Use Only
  665. */
  666. public _markMeshesAsLightDirty() {
  667. for (var mesh of this.getScene().meshes) {
  668. if (mesh.lightSources.indexOf(this) !== -1) {
  669. mesh._markSubMeshesAsLightDirty();
  670. }
  671. }
  672. }
  673. /**
  674. * Recomputes the cached photometric scale if needed.
  675. */
  676. private _computePhotometricScale(): void {
  677. this._photometricScale = this._getPhotometricScale();
  678. this.getScene().resetCachedMaterial();
  679. }
  680. /**
  681. * Returns the Photometric Scale according to the light type and intensity mode.
  682. */
  683. private _getPhotometricScale() {
  684. let photometricScale = 0.0;
  685. let lightTypeID = this.getTypeID();
  686. //get photometric mode
  687. let photometricMode = this.intensityMode;
  688. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  689. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  690. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  691. } else {
  692. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  693. }
  694. }
  695. //compute photometric scale
  696. switch (lightTypeID) {
  697. case Light.LIGHTTYPEID_POINTLIGHT:
  698. case Light.LIGHTTYPEID_SPOTLIGHT:
  699. switch (photometricMode) {
  700. case Light.INTENSITYMODE_LUMINOUSPOWER:
  701. photometricScale = 1.0 / (4.0 * Math.PI);
  702. break;
  703. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  704. photometricScale = 1.0;
  705. break;
  706. case Light.INTENSITYMODE_LUMINANCE:
  707. photometricScale = this.radius * this.radius;
  708. break;
  709. }
  710. break;
  711. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  712. switch (photometricMode) {
  713. case Light.INTENSITYMODE_ILLUMINANCE:
  714. photometricScale = 1.0;
  715. break;
  716. case Light.INTENSITYMODE_LUMINANCE:
  717. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  718. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  719. let apexAngleRadians = this.radius;
  720. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  721. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  722. let solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  723. photometricScale = solidAngle;
  724. break;
  725. }
  726. break;
  727. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  728. // No fall off in hemisperic light.
  729. photometricScale = 1.0;
  730. break;
  731. }
  732. return photometricScale;
  733. }
  734. /**
  735. * Reorder the light in the scene according to their defined priority.
  736. * @hidden Internal Use Only
  737. */
  738. public _reorderLightsInScene(): void {
  739. var scene = this.getScene();
  740. if (this._renderPriority != 0) {
  741. scene.requireLightSorting = true;
  742. }
  743. this.getScene().sortLightsByPriority();
  744. }
  745. /**
  746. * Prepares the list of defines specific to the light type.
  747. * @param defines the list of defines
  748. * @param lightIndex defines the index of the light for the effect
  749. */
  750. public abstract prepareLightSpecificDefines(defines: any, lightIndex: number): void;
  751. }