KHR_lights_punctual.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. import { SpotLight } from "babylonjs/Lights/spotLight";
  2. import { Nullable } from "babylonjs/types";
  3. import { Vector3, Color3, Quaternion, Matrix, TmpVectors } from "babylonjs/Maths/math";
  4. import { Light } from "babylonjs/Lights/light";
  5. import { Node } from "babylonjs/node";
  6. import { ShadowLight } from "babylonjs/Lights/shadowLight";
  7. import { IChildRootProperty } from "babylonjs-gltf2interface";
  8. import { INode } from "babylonjs-gltf2interface";
  9. import { IGLTFExporterExtensionV2 } from "../glTFExporterExtension";
  10. import { _Exporter } from "../glTFExporter";
  11. import { Logger } from "babylonjs/Misc/logger";
  12. import { _GLTFUtilities } from "../glTFUtilities";
  13. import { DirectionalLight } from 'babylonjs';
  14. const NAME = "KHR_lights_punctual";
  15. enum LightType {
  16. DIRECTIONAL = "directional",
  17. POINT = "point",
  18. SPOT = "spot"
  19. }
  20. interface ILightReference {
  21. light: number;
  22. }
  23. interface ILight extends IChildRootProperty {
  24. type: LightType;
  25. color?: number[];
  26. intensity?: number;
  27. range?: number;
  28. spot?: {
  29. innerConeAngle?: number;
  30. outerConeAngle?: number;
  31. };
  32. }
  33. interface ILights {
  34. lights: ILight[];
  35. }
  36. /**
  37. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_lights_punctual/README.md)
  38. */
  39. export class KHR_lights_punctual implements IGLTFExporterExtensionV2 {
  40. /** The name of this extension. */
  41. public readonly name = NAME;
  42. /** Defines whether this extension is enabled. */
  43. public enabled = true;
  44. /** Defines whether this extension is required */
  45. public required = false;
  46. /** Reference to the glTF exporter */
  47. private _exporter: _Exporter;
  48. private _lights: ILights;
  49. /** @hidden */
  50. constructor(exporter: _Exporter) {
  51. this._exporter = exporter;
  52. }
  53. /** @hidden */
  54. public dispose() {
  55. delete this._lights;
  56. }
  57. /** @hidden */
  58. public get wasUsed() {
  59. return !!this._lights;
  60. }
  61. /** @hidden */
  62. public onExporting(): void {
  63. this._exporter!._glTF.extensions![NAME] = this._lights;
  64. }
  65. /**
  66. * Define this method to modify the default behavior when exporting a node
  67. * @param context The context when exporting the node
  68. * @param node glTF node
  69. * @param babylonNode BabylonJS node
  70. * @returns nullable INode promise
  71. */
  72. public postExportNodeAsync(context: string, node: Nullable<INode>, babylonNode: Node, nodeMap?: {[key: number]: number}): Promise<Nullable<INode>> {
  73. return new Promise((resolve, reject) => {
  74. if ( node && babylonNode instanceof ShadowLight) {
  75. const babylonLight: ShadowLight = babylonNode;
  76. let light: ILight;
  77. const lightType = (
  78. babylonLight.getTypeID() == Light.LIGHTTYPEID_POINTLIGHT ? LightType.POINT : (
  79. babylonLight.getTypeID() == Light.LIGHTTYPEID_DIRECTIONALLIGHT ? LightType.DIRECTIONAL : (
  80. babylonLight.getTypeID() == Light.LIGHTTYPEID_SPOTLIGHT ? LightType.SPOT : null
  81. )));
  82. if (lightType == null) {
  83. Logger.Warn(`${context}: Light ${babylonLight.name} is not supported in ${NAME}`);
  84. }
  85. else {
  86. const lightPosition = babylonLight.position.clone();
  87. let convertToRightHandedSystem = this._exporter._convertToRightHandedSystemMap[babylonNode.uniqueId];
  88. if (!lightPosition.equals(Vector3.Zero())) {
  89. if (convertToRightHandedSystem) {
  90. _GLTFUtilities._GetRightHandedPositionVector3FromRef(lightPosition);
  91. }
  92. node.translation = lightPosition.asArray();
  93. }
  94. if (lightType !== LightType.POINT) {
  95. const localAxis = babylonLight.direction;
  96. const yaw = -Math.atan2(localAxis.z * (this._exporter._babylonScene.useRightHandedSystem ? -1 : 1), localAxis.x) + Math.PI / 2;
  97. const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
  98. const pitch = -Math.atan2(localAxis.y, len);
  99. const lightRotationQuaternion = Quaternion.RotationYawPitchRoll(yaw, pitch, 0);
  100. if (convertToRightHandedSystem) {
  101. _GLTFUtilities._GetRightHandedQuaternionFromRef(lightRotationQuaternion);
  102. }
  103. if (!lightRotationQuaternion.equals(Quaternion.Identity())) {
  104. node.rotation = lightRotationQuaternion.asArray();
  105. }
  106. }
  107. if (babylonLight.falloffType !== Light.FALLOFF_GLTF) {
  108. Logger.Warn(`${context}: Light falloff for ${babylonLight.name} does not match the ${NAME} specification!`);
  109. }
  110. light = {
  111. type: lightType
  112. };
  113. if (!babylonLight.diffuse.equals(Color3.White())) {
  114. light.color = babylonLight.diffuse.asArray();
  115. }
  116. if (babylonLight.intensity !== 1.0) {
  117. light.intensity = babylonLight.intensity;
  118. }
  119. if (babylonLight.range !== Number.MAX_VALUE) {
  120. light.range = babylonLight.range;
  121. }
  122. if (lightType === LightType.SPOT) {
  123. const babylonSpotLight = babylonLight as SpotLight;
  124. if (babylonSpotLight.angle !== Math.PI / 2.0) {
  125. if (light.spot == null) {
  126. light.spot = {};
  127. }
  128. light.spot.outerConeAngle = babylonSpotLight.angle / 2.0;
  129. }
  130. if (babylonSpotLight.innerAngle !== 0) {
  131. if (light.spot == null) {
  132. light.spot = {};
  133. }
  134. light.spot.innerConeAngle = babylonSpotLight.innerAngle / 2.0;
  135. }
  136. }
  137. if (this._lights == null) {
  138. this._lights = {
  139. lights: []
  140. };
  141. }
  142. this._lights.lights.push(light);
  143. const lightReference: ILightReference = {
  144. light: this._lights.lights.length - 1
  145. };
  146. // Avoid duplicating the Light's parent node if possible.
  147. let parentBabylonNode = babylonNode.parent;
  148. if (parentBabylonNode && parentBabylonNode.getChildren().length == 1) {
  149. let parentNode = this._exporter._nodes[nodeMap![parentBabylonNode.uniqueId]];
  150. if (parentNode) {
  151. let parentNodeLocalMatrix = TmpVectors.Matrix[0];
  152. let parentInvertNodeLocalMatrix = TmpVectors.Matrix[1];
  153. let parentNodeLocalTranslation = parentNode.translation ? new Vector3(parentNode.translation[0], parentNode.translation[1], parentNode.translation[2]) : Vector3.Zero();
  154. let parentNodeLocalRotation = parentNode.rotation ? new Quaternion(parentNode.rotation[0], parentNode.rotation[1], parentNode.rotation[2], parentNode.rotation[3]) : Quaternion.Identity();
  155. let parentNodeLocalScale = parentNode.scale ? new Vector3(parentNode.scale[0], parentNode.scale[1], parentNode.scale[2]) : Vector3.One();
  156. Matrix.ComposeToRef(parentNodeLocalScale, parentNodeLocalRotation, parentNodeLocalTranslation, parentNodeLocalMatrix);
  157. parentNodeLocalMatrix.invertToRef(parentInvertNodeLocalMatrix);
  158. // Convert light local matrix to local matrix relative to grandparent, facing -Z
  159. let lightLocalMatrix = TmpVectors.Matrix[2];
  160. let nodeLocalTranslation = node.translation ? new Vector3(node.translation[0], node.translation[1], node.translation[2]) : Vector3.Zero();
  161. // Undo directional light positional offset
  162. if (babylonLight instanceof DirectionalLight) {
  163. nodeLocalTranslation.subtractInPlace(this._exporter._babylonScene.useRightHandedSystem ? babylonLight.direction : _GLTFUtilities._GetRightHandedPositionVector3(babylonLight.direction));
  164. }
  165. let nodeLocalRotation = this._exporter._babylonScene.useRightHandedSystem ? Quaternion.Identity() : new Quaternion(0, 1, 0, 0);
  166. if (node.rotation) {
  167. nodeLocalRotation.multiplyInPlace(new Quaternion(node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3]));
  168. }
  169. let nodeLocalScale = node.scale ? new Vector3(node.scale[0], node.scale[1], node.scale[2]) : Vector3.One();
  170. Matrix.ComposeToRef(nodeLocalScale, nodeLocalRotation, nodeLocalTranslation, lightLocalMatrix);
  171. lightLocalMatrix.multiplyToRef(parentInvertNodeLocalMatrix, lightLocalMatrix);
  172. let parentNewScale = TmpVectors.Vector3[0];
  173. let parentNewRotationQuaternion = TmpVectors.Quaternion[0];
  174. let parentNewTranslation = TmpVectors.Vector3[1];
  175. lightLocalMatrix.decompose(parentNewScale, parentNewRotationQuaternion, parentNewTranslation);
  176. parentNode.scale = parentNewScale.asArray();
  177. parentNode.rotation = parentNewRotationQuaternion.asArray();
  178. parentNode.translation = parentNewTranslation.asArray();
  179. if (parentNode.extensions == null) {
  180. parentNode.extensions = {};
  181. }
  182. parentNode.extensions[NAME] = lightReference;
  183. // Do not export the original node
  184. resolve(undefined);
  185. return;
  186. }
  187. }
  188. if (node.extensions == null) {
  189. node.extensions = {};
  190. }
  191. node.extensions[NAME] = lightReference;
  192. }
  193. }
  194. resolve(node);
  195. });
  196. }
  197. }
  198. _Exporter.RegisterExtension(NAME, (exporter) => new KHR_lights_punctual(exporter));