KHR_lights_punctual.ts 11 KB

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