babylon.light.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. module BABYLON {
  2. export class Light extends Node {
  3. //lightmapMode Consts
  4. private static _LIGHTMAP_DEFAULT = 0;
  5. private static _LIGHTMAP_SPECULAR = 1;
  6. private static _LIGHTMAP_SHADOWSONLY = 2;
  7. /**
  8. * If every light affecting the material is in this lightmapMode,
  9. * material.lightmapTexture adds or multiplies
  10. * (depends on material.useLightmapAsShadowmap)
  11. * after every other light calculations.
  12. */
  13. public static get LIGHTMAP_DEFAULT(): number {
  14. return Light._LIGHTMAP_DEFAULT;
  15. }
  16. /**
  17. * material.lightmapTexture as only diffuse lighting from this light
  18. * adds pnly specular lighting from this light
  19. * adds dynamic shadows
  20. */
  21. public static get LIGHTMAP_SPECULAR(): number {
  22. return Light._LIGHTMAP_SPECULAR;
  23. }
  24. /**
  25. * material.lightmapTexture as only lighting
  26. * no light calculation from this light
  27. * only adds dynamic shadows from this light
  28. */
  29. public static get LIGHTMAP_SHADOWSONLY(): number {
  30. return Light._LIGHTMAP_SHADOWSONLY;
  31. }
  32. // Intensity Mode Consts
  33. private static _INTENSITYMODE_AUTOMATIC = 0;
  34. private static _INTENSITYMODE_LUMINOUSPOWER = 1;
  35. private static _INTENSITYMODE_LUMINOUSINTENSITY = 2;
  36. private static _INTENSITYMODE_ILLUMINANCE = 3;
  37. private static _INTENSITYMODE_LUMINANCE = 4;
  38. /**
  39. * Each light type uses the default quantity according to its type:
  40. * point/spot lights use luminous intensity
  41. * directional lights use illuminance
  42. */
  43. public static get INTENSITYMODE_AUTOMATIC(): number {
  44. return Light._INTENSITYMODE_AUTOMATIC;
  45. }
  46. /**
  47. * lumen (lm)
  48. */
  49. public static get INTENSITYMODE_LUMINOUSPOWER(): number {
  50. return Light._INTENSITYMODE_LUMINOUSPOWER;
  51. }
  52. /**
  53. * candela (lm/sr)
  54. */
  55. public static get INTENSITYMODE_LUMINOUSINTENSITY(): number {
  56. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  57. }
  58. /**
  59. * lux (lm/m^2)
  60. */
  61. public static get INTENSITYMODE_ILLUMINANCE(): number {
  62. return Light._INTENSITYMODE_ILLUMINANCE;
  63. }
  64. /**
  65. * nit (cd/m^2)
  66. */
  67. public static get INTENSITYMODE_LUMINANCE(): number {
  68. return Light._INTENSITYMODE_LUMINANCE;
  69. }
  70. // Light types ids const.
  71. private static _LIGHTTYPEID_POINTLIGHT = 0;
  72. private static _LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  73. private static _LIGHTTYPEID_SPOTLIGHT = 2;
  74. private static _LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  75. /**
  76. * Light type const id of the point light.
  77. */
  78. public static get LIGHTTYPEID_POINTLIGHT(): number {
  79. return Light._LIGHTTYPEID_POINTLIGHT;
  80. }
  81. /**
  82. * Light type const id of the directional light.
  83. */
  84. public static get LIGHTTYPEID_DIRECTIONALLIGHT(): number {
  85. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  86. }
  87. /**
  88. * Light type const id of the spot light.
  89. */
  90. public static get LIGHTTYPEID_SPOTLIGHT(): number {
  91. return Light._LIGHTTYPEID_SPOTLIGHT;
  92. }
  93. /**
  94. * Light type const id of the hemispheric light.
  95. */
  96. public static get LIGHTTYPEID_HEMISPHERICLIGHT(): number {
  97. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  98. }
  99. @serializeAsColor3()
  100. public diffuse = new Color3(1.0, 1.0, 1.0);
  101. @serializeAsColor3()
  102. public specular = new Color3(1.0, 1.0, 1.0);
  103. @serialize()
  104. public intensity = 1.0;
  105. @serialize()
  106. public range = Number.MAX_VALUE;
  107. /**
  108. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  109. * of light.
  110. */
  111. private _photometricScale = 1.0;
  112. private _intensityMode: number = Light.INTENSITYMODE_AUTOMATIC;
  113. /**
  114. * Gets the photometric scale used to interpret the intensity.
  115. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  116. */
  117. @serialize()
  118. public get intensityMode(): number {
  119. return this._intensityMode;
  120. };
  121. /**
  122. * Sets the photometric scale used to interpret the intensity.
  123. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  124. */
  125. public set intensityMode(value: number) {
  126. this._intensityMode = value;
  127. this._computePhotometricScale();
  128. };
  129. private _radius = 0.00001;
  130. /**
  131. * Gets the light radius used by PBR Materials to simulate soft area lights.
  132. */
  133. @serialize()
  134. public get radius(): number {
  135. return this._radius;
  136. };
  137. /**
  138. * sets the light radius used by PBR Materials to simulate soft area lights.
  139. */
  140. public set radius(value: number) {
  141. this._radius = value;
  142. this._computePhotometricScale();
  143. };
  144. /**
  145. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  146. * exceeding the number allowed of the materials.
  147. */
  148. @serialize()
  149. private _renderPriority: number;
  150. @expandToProperty("_reorderLightsInScene")
  151. public renderPriority: number = 0;
  152. /**
  153. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  154. * the current shadow generator.
  155. */
  156. @serialize()
  157. public shadowEnabled: boolean = true;
  158. private _includedOnlyMeshes: AbstractMesh[];
  159. public get includedOnlyMeshes(): AbstractMesh[] {
  160. return this._includedOnlyMeshes;
  161. }
  162. public set includedOnlyMeshes(value: AbstractMesh[]) {
  163. this._includedOnlyMeshes = value;
  164. this._hookArrayForIncludedOnly(value);
  165. }
  166. private _excludedMeshes: AbstractMesh[];
  167. public get excludedMeshes(): AbstractMesh[] {
  168. return this._excludedMeshes;
  169. }
  170. public set excludedMeshes(value: AbstractMesh[]) {
  171. this._excludedMeshes = value;
  172. this._hookArrayForExcluded(value);
  173. }
  174. @serialize("excludeWithLayerMask")
  175. private _excludeWithLayerMask = 0;
  176. public get excludeWithLayerMask(): number {
  177. return this._excludeWithLayerMask;
  178. }
  179. public set excludeWithLayerMask(value: number) {
  180. this._excludeWithLayerMask = value;
  181. this._resyncMeshes();
  182. }
  183. @serialize("includeOnlyWithLayerMask")
  184. private _includeOnlyWithLayerMask = 0;
  185. public get includeOnlyWithLayerMask(): number {
  186. return this._includeOnlyWithLayerMask;
  187. }
  188. public set includeOnlyWithLayerMask(value: number) {
  189. this._includeOnlyWithLayerMask = value;
  190. this._resyncMeshes();
  191. }
  192. @serialize("lightmapMode")
  193. private _lightmapMode = 0;
  194. public get lightmapMode(): number {
  195. return this._lightmapMode;
  196. }
  197. public set lightmapMode(value: number) {
  198. if (this._lightmapMode === value) {
  199. return;
  200. }
  201. this._lightmapMode = value;
  202. this._markMeshesAsLightDirty();
  203. }
  204. private _parentedWorldMatrix: Matrix;
  205. public _shadowGenerator: IShadowGenerator;
  206. public _excludedMeshesIds = new Array<string>();
  207. public _includedOnlyMeshesIds = new Array<string>();
  208. // Light uniform buffer
  209. public _uniformBuffer: UniformBuffer;
  210. /**
  211. * Creates a Light object in the scene.
  212. * Documentation : http://doc.babylonjs.com/tutorials/lights
  213. */
  214. constructor(name: string, scene: Scene) {
  215. super(name, scene);
  216. this.getScene().addLight(this);
  217. this._uniformBuffer = new UniformBuffer(this.getScene().getEngine());
  218. this._buildUniformLayout();
  219. this.includedOnlyMeshes = new Array<AbstractMesh>();
  220. this.excludedMeshes = new Array<AbstractMesh>();
  221. this._resyncMeshes();
  222. }
  223. protected _buildUniformLayout(): void {
  224. // Overridden
  225. }
  226. /**
  227. * Returns the string "Light".
  228. */
  229. public getClassName(): string {
  230. return "Light";
  231. }
  232. /**
  233. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  234. */
  235. public toString(fullDetails?: boolean): string {
  236. var ret = "Name: " + this.name;
  237. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  238. if (this.animations) {
  239. for (var i = 0; i < this.animations.length; i++) {
  240. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  241. }
  242. }
  243. if (fullDetails) {
  244. }
  245. return ret;
  246. }
  247. /**
  248. * Set the enabled state of this node.
  249. * @param {boolean} value - the new enabled state
  250. * @see isEnabled
  251. */
  252. public setEnabled(value: boolean): void {
  253. super.setEnabled(value);
  254. this._resyncMeshes();
  255. }
  256. /**
  257. * Returns the Light associated shadow generator.
  258. */
  259. public getShadowGenerator(): IShadowGenerator {
  260. return this._shadowGenerator;
  261. }
  262. /**
  263. * Returns a Vector3, the absolute light position in the World.
  264. */
  265. public getAbsolutePosition(): Vector3 {
  266. return Vector3.Zero();
  267. }
  268. public transferToEffect(effect: Effect, lightIndex: string): void {
  269. }
  270. public _getWorldMatrix(): Matrix {
  271. return Matrix.Identity();
  272. }
  273. /**
  274. * Boolean : True if the light will affect the passed mesh.
  275. */
  276. public canAffectMesh(mesh: AbstractMesh): boolean {
  277. if (!mesh) {
  278. return true;
  279. }
  280. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  281. return false;
  282. }
  283. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  284. return false;
  285. }
  286. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  287. return false;
  288. }
  289. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  290. return false;
  291. }
  292. return true;
  293. }
  294. /**
  295. * Returns the light World matrix.
  296. */
  297. public getWorldMatrix(): Matrix {
  298. this._currentRenderId = this.getScene().getRenderId();
  299. var worldMatrix = this._getWorldMatrix();
  300. if (this.parent && this.parent.getWorldMatrix) {
  301. if (!this._parentedWorldMatrix) {
  302. this._parentedWorldMatrix = Matrix.Identity();
  303. }
  304. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  305. this._markSyncedWithParent();
  306. return this._parentedWorldMatrix;
  307. }
  308. return worldMatrix;
  309. }
  310. /**
  311. * Sort function to order lights for rendering.
  312. * @param a First Light object to compare to second.
  313. * @param b Second Light object to compare first.
  314. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  315. */
  316. public static compareLightsPriority(a: Light, b: Light): number {
  317. //shadow-casting lights have priority over non-shadow-casting lights
  318. //the renderPrioirty is a secondary sort criterion
  319. if (a.shadowEnabled !== b.shadowEnabled) {
  320. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  321. }
  322. return b.renderPriority - a.renderPriority;
  323. }
  324. /**
  325. * Disposes the light.
  326. */
  327. public dispose(): void {
  328. if (this._shadowGenerator) {
  329. this._shadowGenerator.dispose();
  330. this._shadowGenerator = null;
  331. }
  332. // Animations
  333. this.getScene().stopAnimation(this);
  334. // Remove from meshes
  335. for (var mesh of this.getScene().meshes) {
  336. mesh._removeLightSource(this);
  337. }
  338. this._uniformBuffer.dispose();
  339. // Remove from scene
  340. this.getScene().removeLight(this);
  341. super.dispose();
  342. }
  343. /**
  344. * Returns the light type ID (integer).
  345. */
  346. public getTypeID(): number {
  347. return 0;
  348. }
  349. /**
  350. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  351. */
  352. public getScaledIntensity() {
  353. return this._photometricScale * this.intensity;
  354. }
  355. /**
  356. * Returns a new Light object, named "name", from the current one.
  357. */
  358. public clone(name: string): Light {
  359. return SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  360. }
  361. /**
  362. * Serializes the current light into a Serialization object.
  363. * Returns the serialized object.
  364. */
  365. public serialize(): any {
  366. var serializationObject = SerializationHelper.Serialize(this);
  367. // Type
  368. serializationObject.type = this.getTypeID();
  369. // Parent
  370. if (this.parent) {
  371. serializationObject.parentId = this.parent.id;
  372. }
  373. // Inclusion / exclusions
  374. if (this.excludedMeshes.length > 0) {
  375. serializationObject.excludedMeshesIds = [];
  376. this.excludedMeshes.forEach((mesh: AbstractMesh) => {
  377. serializationObject.excludedMeshesIds.push(mesh.id);
  378. });
  379. }
  380. if (this.includedOnlyMeshes.length > 0) {
  381. serializationObject.includedOnlyMeshesIds = [];
  382. this.includedOnlyMeshes.forEach((mesh: AbstractMesh) => {
  383. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  384. });
  385. }
  386. // Animations
  387. Animation.AppendSerializedAnimations(this, serializationObject);
  388. serializationObject.ranges = this.serializeAnimationRanges();
  389. return serializationObject;
  390. }
  391. /**
  392. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  393. * This new light is named "name" and added to the passed scene.
  394. */
  395. static GetConstructorFromName(type: number, name: string, scene: Scene): () => Light {
  396. switch (type) {
  397. case 0:
  398. return () => new PointLight(name, Vector3.Zero(), scene);
  399. case 1:
  400. return () => new DirectionalLight(name, Vector3.Zero(), scene);
  401. case 2:
  402. return () => new SpotLight(name, Vector3.Zero(), Vector3.Zero(), 0, 0, scene);
  403. case 3:
  404. return () => new HemisphericLight(name, Vector3.Zero(), scene);
  405. }
  406. }
  407. /**
  408. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  409. */
  410. public static Parse(parsedLight: any, scene: Scene): Light {
  411. var light = SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  412. // Inclusion / exclusions
  413. if (parsedLight.excludedMeshesIds) {
  414. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  415. }
  416. if (parsedLight.includedOnlyMeshesIds) {
  417. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  418. }
  419. // Parent
  420. if (parsedLight.parentId) {
  421. light._waitingParentId = parsedLight.parentId;
  422. }
  423. // Animations
  424. if (parsedLight.animations) {
  425. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  426. var parsedAnimation = parsedLight.animations[animationIndex];
  427. light.animations.push(Animation.Parse(parsedAnimation));
  428. }
  429. Node.ParseAnimationRanges(light, parsedLight, scene);
  430. }
  431. if (parsedLight.autoAnimate) {
  432. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  433. }
  434. return light;
  435. }
  436. private _hookArrayForExcluded(array: AbstractMesh[]): void {
  437. var oldPush = array.push;
  438. array.push = (...items: AbstractMesh[]) => {
  439. var result = oldPush.apply(array, items);
  440. for (var item of items) {
  441. item._resyncLighSource(this);
  442. }
  443. return result;
  444. }
  445. var oldSplice = array.splice;
  446. array.splice = (index: number, deleteCount?: number) => {
  447. var deleted = oldSplice.apply(array, [index, deleteCount]);
  448. for (var item of deleted) {
  449. item._resyncLighSource(this);
  450. }
  451. return deleted;
  452. }
  453. for (var item of array) {
  454. item._resyncLighSource(this);
  455. }
  456. }
  457. private _hookArrayForIncludedOnly(array: AbstractMesh[]): void {
  458. var oldPush = array.push;
  459. array.push = (...items: AbstractMesh[]) => {
  460. var result = oldPush.apply(array, items);
  461. this._resyncMeshes();
  462. return result;
  463. }
  464. var oldSplice = array.splice;
  465. array.splice = (index: number, deleteCount?: number) => {
  466. var deleted = oldSplice.apply(array, [index, deleteCount]);
  467. this._resyncMeshes();
  468. return deleted;
  469. }
  470. this._resyncMeshes();
  471. }
  472. private _resyncMeshes() {
  473. for (var mesh of this.getScene().meshes) {
  474. mesh._resyncLighSource(this);
  475. }
  476. }
  477. public _markMeshesAsLightDirty() {
  478. for (var mesh of this.getScene().meshes) {
  479. if (mesh._lightSources.indexOf(this) !== -1) {
  480. mesh._markSubMeshesAsLightDirty();
  481. }
  482. }
  483. }
  484. /**
  485. * Recomputes the cached photometric scale if needed.
  486. */
  487. private _computePhotometricScale(): void {
  488. this._photometricScale = this._getPhotometricScale();
  489. this.getScene().resetCachedMaterial();
  490. }
  491. /**
  492. * Returns the Photometric Scale according to the light type and intensity mode.
  493. */
  494. private _getPhotometricScale() {
  495. let photometricScale = 0.0;
  496. let lightTypeID = this.getTypeID();
  497. //get photometric mode
  498. let photometricMode = this.intensityMode;
  499. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  500. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  501. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  502. } else {
  503. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  504. }
  505. }
  506. //compute photometric scale
  507. switch (lightTypeID) {
  508. case Light.LIGHTTYPEID_POINTLIGHT:
  509. case Light.LIGHTTYPEID_SPOTLIGHT:
  510. switch (photometricMode) {
  511. case Light.INTENSITYMODE_LUMINOUSPOWER:
  512. photometricScale = 1.0 / (4.0 * Math.PI);
  513. break;
  514. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  515. photometricScale = 1.0;
  516. break;
  517. case Light.INTENSITYMODE_LUMINANCE:
  518. photometricScale = this.radius * this.radius;
  519. break;
  520. }
  521. break;
  522. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  523. switch (photometricMode) {
  524. case Light.INTENSITYMODE_ILLUMINANCE:
  525. photometricScale = 1.0;
  526. break;
  527. case Light.INTENSITYMODE_LUMINANCE:
  528. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  529. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  530. let apexAngleRadians = this.radius;
  531. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  532. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  533. let solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  534. photometricScale = solidAngle;
  535. break;
  536. }
  537. break;
  538. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  539. // No fall off in hemisperic light.
  540. photometricScale = 1.0;
  541. break;
  542. }
  543. return photometricScale;
  544. }
  545. private _reorderLightsInScene(): void {
  546. var scene = this.getScene();
  547. if (this.renderPriority != 0) {
  548. scene.requireLightSorting = true;
  549. }
  550. this.getScene().sortLightsByPriority();
  551. }
  552. }
  553. }