@ignifx/core 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/{color-CpvebMIh.js → color-DrR6GFTd.js} +3 -276
  2. package/dist/color-DrR6GFTd.js.map +1 -0
  3. package/dist/{environment-CTM7BAyb.js → environment-mr5wp69e.js} +3 -2
  4. package/dist/{environment-CTM7BAyb.js.map → environment-mr5wp69e.js.map} +1 -1
  5. package/dist/index.d.ts +140 -88
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +1353 -2797
  8. package/dist/index.js.map +1 -1
  9. package/dist/{instanced-mesh-instance-Cgx1H87p.js → instanced-mesh-instance-DYwH0vLi.js} +74 -10
  10. package/dist/instanced-mesh-instance-DYwH0vLi.js.map +1 -0
  11. package/dist/{material-plugin-Cfw_h_Mg.js → material-plugin-BRnhfw7K.js} +2 -2
  12. package/dist/material-plugin-BRnhfw7K.js.map +1 -0
  13. package/dist/math-utils-BcDnL-gi.js +277 -0
  14. package/dist/math-utils-BcDnL-gi.js.map +1 -0
  15. package/dist/shader-declaration-5q__jycG.js.map +1 -1
  16. package/dist/{shader-material-CJxMJEUO.js → shader-material-BIG3UDyu.js} +3 -3
  17. package/dist/{shader-material-CJxMJEUO.js.map → shader-material-BIG3UDyu.js.map} +1 -1
  18. package/dist/{shader-material-F-CL4D70.js → shader-material-U6BKZ8D1.js} +2 -2
  19. package/dist/{shader-material-F-CL4D70.js.map → shader-material-U6BKZ8D1.js.map} +1 -1
  20. package/dist/{shader-pragma-D4HKC9vP.js → shader-pragma-tw6AKaQD.js} +24 -3
  21. package/dist/shader-pragma-tw6AKaQD.js.map +1 -0
  22. package/dist/{surface-shader-Chs7wOAE.js → surface-shader-Br17yysO.js} +7 -5
  23. package/dist/{surface-shader-Chs7wOAE.js.map → surface-shader-Br17yysO.js.map} +1 -1
  24. package/dist/vec3-T2PasQZv.js +2458 -0
  25. package/dist/vec3-T2PasQZv.js.map +1 -0
  26. package/package.json +2 -2
  27. package/dist/color-CpvebMIh.js.map +0 -1
  28. package/dist/instanced-mesh-instance-Cgx1H87p.js.map +0 -1
  29. package/dist/material-plugin-Cfw_h_Mg.js.map +0 -1
  30. package/dist/mesh-CnK_PX46.js +0 -811
  31. package/dist/mesh-CnK_PX46.js.map +0 -1
  32. package/dist/shader-pragma-D4HKC9vP.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { a as CORE_ERROR_MESSAGES, c as THIRD_PARTY_ERROR_PREFIX, i as isIgnifxError, l as isValidErrorCode, n as assertNever, o as CoreErrorCode, r as formatErrorMessage, s as ErrorRange, t as IgnifxError } from "./ignifx-error-CRh89KUJ.js";
2
- import { _ as sign, a as approximately, c as degToRad, d as lerp, f as lerpAngleDegrees, g as repeat, h as radToDeg, i as RAD_TO_DEG, l as deltaAngleDegrees, m as pingPong, n as DEG_TO_RAD, o as clamp, p as moveTowards, r as EPSILON, s as clamp01, t as Color, u as inverseLerp, v as smoothStep, y as wrapAngleDegrees } from "./color-CpvebMIh.js";
3
- import { A as linkParent, B as tagNode, C as setMeshSubtreeVisible, D as updateMeshUvs$1, E as updateMeshPositions$1, F as readNodeTag, I as readWorldMatrix, L as reparentKeepingWorld, M as localRotation, N as localScale, O as createNode, P as parentNode, R as setNodeName, S as setMeshRenderOrder, T as updateMeshNormals$1, V as worldMatrixVersion, a as createCapsuleMesh, b as setMeshPickable, c as createMeshFromGeometry, d as createTorusMesh, g as removeMeshFromScene, h as recomputeMeshBounds, i as createBoxMesh, j as localPosition, k as disposeNode, l as createPlaneMesh, m as overrideSubtreeMaterials, n as cloneMeshUnderNode, o as createCylinderMesh, p as disposeMeshTemplate, r as collectSubtreeMeshes, s as createGroundMesh, t as addMeshToScene, u as createSphereMesh, v as setMeshId, w as updateMeshColors$1, x as setMeshReceiveShadows, y as setMeshMaterial, z as setNodeSelfVisible } from "./mesh-CnK_PX46.js";
4
- import { a as readSceneImageProcessing, c as setSceneEnvironmentRotation, l as setSceneFog, n as installSceneEnvironment, o as setSceneClearColor, r as loadSceneEnvironment, s as setSceneEnvironmentBlur, t as TONE_MAPPING_NAMES, u as setSceneImageProcessingOptions } from "./environment-CTM7BAyb.js";
5
- import { a as defineMaterialPlugin, c as MATERIAL_ALPHA_MODES, d as createStandardMaterialFromProps, f as markMaterialDirty, g as setPbrMetallicRoughness, h as setPbrBaseColor, i as MATERIAL_PLUGIN_SAMPLER_BUDGET, l as createDefaultMaterial, m as setMaterialAlpha, n as MATERIAL_PLUGIN_DEFAULT_PRIORITY, o as isLiteMaterialPluginPoint, r as MATERIAL_PLUGIN_RESERVED_NAMES, t as LITE_MATERIAL_PLUGIN_POINTS, u as createPbrMaterialFromProps } from "./material-plugin-Cfw_h_Mg.js";
2
+ import { _ as smoothStep, a as clamp, c as deltaAngleDegrees, d as lerpAngleDegrees, f as moveTowards, g as sign, h as repeat, i as approximately, l as inverseLerp, m as radToDeg, n as EPSILON, o as clamp01, p as pingPong, r as RAD_TO_DEG, s as degToRad, t as DEG_TO_RAD, u as lerp, v as wrapAngleDegrees } from "./math-utils-BcDnL-gi.js";
3
+ import { $ as basisToQuatToRef, A as setMeshReceiveShadows, B as localPosition, C as overrideSubtreeMaterials, D as setMeshId, E as setMeshBounds, F as updateMeshPositions$1, G as readWorldMatrix, H as localScale, I as updateMeshUvs$1, J as setNodeSelfVisible, K as reparentKeepingWorld, L as createNode, M as setMeshSubtreeVisible, N as updateMeshColors$1, O as setMeshMaterial, P as updateMeshNormals$1, Q as Mat4, R as disposeNode, S as disposeMeshTemplate, T as removeMeshFromScene, U as parentNode, V as localRotation, W as readNodeTag, X as worldMatrixVersion, Y as tagNode, Z as MAT4_IDENTITY, _ as createMeshFromGeometry, a as VEC3_ONE, b as createTorusMesh, c as VEC3_ZERO, d as cloneMeshUnderNode, f as collectSubtreeMeshes, g as createGroundMesh, h as createCylinderMesh, i as VEC3_LEFT, j as setMeshRenderOrder, k as setMeshPickable, l as Vec3, m as createCapsuleMesh, n as VEC3_DOWN, o as VEC3_RIGHT, p as createBoxMesh, q as setNodeName, r as VEC3_FORWARD, s as VEC3_UP, t as VEC3_BACKWARD, u as addMeshToScene, v as createPlaneMesh, w as recomputeMeshBounds, x as detachMeshBounds, y as createSphereMesh, z as linkParent } from "./vec3-T2PasQZv.js";
4
+ import { t as Color } from "./color-DrR6GFTd.js";
5
+ import { a as readSceneImageProcessing, c as setSceneEnvironmentRotation, l as setSceneFog, n as installSceneEnvironment, o as setSceneClearColor, r as loadSceneEnvironment, s as setSceneEnvironmentBlur, t as TONE_MAPPING_NAMES, u as setSceneImageProcessingOptions } from "./environment-mr5wp69e.js";
6
+ import { a as defineMaterialPlugin, c as MATERIAL_ALPHA_MODES, d as createStandardMaterialFromProps, f as markMaterialDirty, g as setPbrMetallicRoughness, h as setPbrBaseColor, i as MATERIAL_PLUGIN_SAMPLER_BUDGET, l as createDefaultMaterial, m as setMaterialAlpha, n as MATERIAL_PLUGIN_DEFAULT_PRIORITY, o as isLiteMaterialPluginPoint, r as MATERIAL_PLUGIN_RESERVED_NAMES, t as LITE_MATERIAL_PLUGIN_POINTS, u as createPbrMaterialFromProps } from "./material-plugin-BRnhfw7K.js";
6
7
  import { a as postEffectValuesCodec, i as declaredTextureBinding, n as POST_EFFECT_FUNCTION, o as asJsonArray, r as customEffect, s as asJsonObject, t as POST_EFFECT_BUILTIN_UNIFORMS } from "./post-effect-C42XJFmo.js";
7
8
  import { a as SHADER_BLEND_MODES, c as SHADER_KINDS, d as SURFACE_HOOK_NAMES, f as SURFACE_UNIFORM_BLOCK, i as SHADER_ATTRIBUTE_NAMES, l as SHADER_TEXTURE_FALLBACKS, o as SHADER_CULL_MODES, r as LITE_SYSTEM_UNIFORM_NAMES, s as SHADER_INSTANCING_MODES, t as IGNIFX_UNIFORM_NAMES, u as SHADER_UNIFORM_TYPES } from "./shader-declaration-5q__jycG.js";
8
9
  import { acquireTexture, addTask, addToScene, buildFrameGraphTask, captureScreenshot, cloneTransformNode, createBloomPostProcessTask, createCopyToTextureTask, createCsmDirectionalShadowGenerator, createDirectionalLight, createEngine, createEsmDirectionalShadowGenerator, createFontFromBuffer, createFreeCamera, createGpuPicker, createHemisphericLight, createImageProcessingTask, createMeshFromData, createNullEngine, createPcfDirectionalShadowGenerator, createPcfSpotlightShadowGenerator, createPointLight, createRenderTarget, createRenderTask, createSceneContext, createSmaaPostProcessTask, createSpotLight, createStorageBuffer, createTexture2DFromPixels, disableOrthographicCamera, disposeEngine, disposePicker, disposeScene, disposeStorageBuffer, enableBoneControl, enableDeviceLostSceneRecovery, enableMaterialPlugins, enableMaterialStencil, enableOrthographicCamera, enablePbrLightmap, enableSkeletonShadows, enableStandardSkeleton, forceWebGpuDeviceLossForTesting, getEffectiveAspectRatio, getFrameGraph, getProjectionMatrix, getRenderTaskGpuTimings, getViewMatrix, getViewProjectionMatrix, isPbrMaterial, isShaderMaterial, loadTexture2D, onBeforeRender, pickAsync, pickWithRay, rebuildSceneRenderables, registerScene, registerSceneWithShadowSupport, releaseTexture, removeFromScene, resizeEngine, resolveCameraViewport, setGpuTimingEnabled, setShadowTaskCasterMeshes, setSubtreeVisible, setSurfaceSize, startEngine, stopEngine, updateStorageBuffer, updateTexture2DFromPixels } from "@babylonjs/lite";
@@ -4751,1563 +4752,618 @@ function entityInternals(entity) {
4751
4752
  return entity[ENTITY_INTERNALS];
4752
4753
  }
4753
4754
  //#endregion
4754
- //#region src/math/mat4.ts
4755
+ //#region src/lite/camera.ts
4756
+ /** Scratch inverse view-projection matrix, created on first use (coding standards §4). */
4757
+ let inverseViewProjection = null;
4758
+ /**
4759
+ * Creates the Lite camera an ignifx `Camera` component owns and parents it under the entity's
4760
+ * transform node.
4761
+ *
4762
+ * @remarks
4763
+ * The camera is created at the local origin looking down local `+Z`, ignifx's forward axis
4764
+ * (ADR-0011). Its own position and target are never touched again: the entity's node supplies the
4765
+ * transform, so the component has no follow logic (`docs/architecture/07-rendering.md` §2.1).
4766
+ *
4767
+ * @param parent - The entity's transform node, or `null` for a camera in world space.
4768
+ * @returns The camera. It is not attached to any scene; call {@link setSceneCamera} for that.
4769
+ *
4770
+ * @example
4771
+ * ```ts
4772
+ * const camera = createCameraUnderNode(entityNode);
4773
+ * setCameraPerspective(camera, 60);
4774
+ * setSceneCamera(scene, camera);
4775
+ * ```
4776
+ *
4777
+ * @internal
4778
+ */
4779
+ function createCameraUnderNode(parent) {
4780
+ const camera = createFreeCamera({
4781
+ x: 0,
4782
+ y: 0,
4783
+ z: 0
4784
+ }, {
4785
+ x: 0,
4786
+ y: 0,
4787
+ z: 1
4788
+ });
4789
+ camera.parent = parent;
4790
+ return camera;
4791
+ }
4755
4792
  /**
4756
- * Allocates the 16-element column-major storage a matrix owns, pre-filled with zeroes.
4793
+ * Re-parents a camera, keeping its local position and target — the entity's node defines the view.
4794
+ *
4795
+ * @remarks
4796
+ * Unlike `linkParent` in `./node.ts` this does not maintain the parent's `children` array. Lite
4797
+ * types `SceneNode.children` as `SceneNode[]` and a camera is not a scene node; nothing in Lite
4798
+ * walks an ignifx transform node's children either, because ignifx transform nodes are never added
4799
+ * to a scene (`docs/architecture/02-scene-graph.md` §5.1). The `parent` link alone is what
4800
+ * `worldMatrix` reads.
4801
+ *
4802
+ * @param camera - The camera to move.
4803
+ * @param parent - The new parent node, or `null` to detach the camera to world space.
4757
4804
  *
4758
- * @returns Fresh, zeroed storage.
4805
+ * @internal
4759
4806
  */
4760
- function allocateElements() {
4761
- return /* @__PURE__ */ new Float32Array(16);
4807
+ function setCameraParent(camera, parent) {
4808
+ camera.parent = parent;
4762
4809
  }
4763
4810
  /**
4764
- * The determinant of the upper-left 3×3 basis. Its sign says whether the matrix mirrors, which is
4765
- * how Babylon Lite decides the sign of the decomposed Y scale (`lib/math/mat4-decompose.js`).
4811
+ * Switches a camera to a perspective projection with the given vertical field of view.
4766
4812
  *
4767
- * @param m - The matrix to measure.
4768
- * @returns The 3×3 determinant.
4813
+ * @param camera - The camera to configure.
4814
+ * @param fovDegrees - The vertical field of view, in degrees.
4815
+ *
4816
+ * @internal
4769
4817
  */
4770
- function basisDeterminant(m) {
4771
- const m0 = m[0] ?? 0;
4772
- const m1 = m[1] ?? 0;
4773
- const m2 = m[2] ?? 0;
4774
- const m4 = m[4] ?? 0;
4775
- const m5 = m[5] ?? 0;
4776
- const m6 = m[6] ?? 0;
4777
- const m8 = m[8] ?? 0;
4778
- const m9 = m[9] ?? 0;
4779
- const m10 = m[10] ?? 0;
4780
- return m0 * (m5 * m10 - m6 * m9) + m1 * (m6 * m8 - m4 * m10) + m2 * (m4 * m9 - m5 * m8);
4818
+ function setCameraPerspective(camera, fovDegrees) {
4819
+ camera.fov = degToRad(fovDegrees);
4820
+ if (camera.ortho !== null && camera.ortho !== void 0) disableOrthographicCamera(camera);
4781
4821
  }
4782
4822
  /**
4783
- * Writes the unit quaternion of an orthonormal basis into `out`. Arguments are named row-major
4784
- * (`b<row><column>`), matching Babylon Lite's `_quatFromRotationBasis`
4785
- * (`lib/math/quat-from-rotation-matrix.js`), which this reproduces branch for branch.
4823
+ * Switches a camera to an orthographic projection of the given half-height.
4786
4824
  *
4787
- * Shared with the quaternion module; not part of the public API.
4825
+ * @remarks
4826
+ * Only `halfHeight` is set; the four clip planes are left `null` so Lite derives them from the
4827
+ * half-height and the render target's aspect ratio (`OrthographicBounds`, `index.d.ts` 7803),
4828
+ * which is the behaviour `Camera.orthographicSize` promises. Calling this twice replaces the
4829
+ * bounds object, so the adapter keeps the returned handle and mutates it through
4830
+ * {@link setCameraOrthographicSize} instead.
4788
4831
  *
4789
- * @param b00 - Row 0, column 0.
4790
- * @param b01 - Row 0, column 1.
4791
- * @param b02 - Row 0, column 2.
4792
- * @param b10 - Row 1, column 0.
4793
- * @param b11 - Row 1, column 1.
4794
- * @param b12 - Row 1, column 2.
4795
- * @param b20 - Row 2, column 0.
4796
- * @param b21 - Row 2, column 1.
4797
- * @param b22 - Row 2, column 2.
4798
- * @param out - The quaternion to write.
4832
+ * @param camera - The camera to configure.
4833
+ * @param halfHeight - Half of the visible height, in metres.
4834
+ * @returns The live bounds object; assigning to its fields takes effect on the next frame.
4799
4835
  *
4800
4836
  * @internal
4801
4837
  */
4802
- function basisToQuatToRef(b00, b01, b02, b10, b11, b12, b20, b21, b22, out) {
4803
- const trace = b00 + b11 + b22;
4804
- if (trace > 0) {
4805
- const s = .5 / Math.sqrt(trace + 1);
4806
- out.set((b21 - b12) * s, (b02 - b20) * s, (b10 - b01) * s, .25 / s);
4807
- return;
4808
- }
4809
- if (b00 > b11 && b00 > b22) {
4810
- const s = 2 * Math.sqrt(1 + b00 - b11 - b22);
4811
- out.set(.25 * s, (b01 + b10) / s, (b02 + b20) / s, (b21 - b12) / s);
4812
- return;
4838
+ function setCameraOrthographic(camera, halfHeight) {
4839
+ const existing = camera.ortho;
4840
+ if (existing !== null && existing !== void 0) {
4841
+ existing.halfHeight = halfHeight;
4842
+ return existing;
4813
4843
  }
4814
- if (b11 > b22) {
4815
- const s = 2 * Math.sqrt(1 + b11 - b00 - b22);
4816
- out.set((b01 + b10) / s, .25 * s, (b12 + b21) / s, (b02 - b20) / s);
4844
+ return enableOrthographicCamera(camera, { halfHeight });
4845
+ }
4846
+ /**
4847
+ * Changes the half-height of an orthographic camera. Halving it doubles the zoom.
4848
+ *
4849
+ * @param bounds - The bounds {@link setCameraOrthographic} returned.
4850
+ * @param halfHeight - The new half-height, in metres.
4851
+ *
4852
+ * @internal
4853
+ */
4854
+ function setCameraOrthographicSize(bounds, halfHeight) {
4855
+ bounds.halfHeight = halfHeight;
4856
+ }
4857
+ /**
4858
+ * Sets the near and far clip planes.
4859
+ *
4860
+ * @param camera - The camera to configure.
4861
+ * @param near - The near plane distance, in metres.
4862
+ * @param far - The far plane distance, in metres.
4863
+ *
4864
+ * @internal
4865
+ */
4866
+ function setCameraClipPlanes(camera, near, far) {
4867
+ camera.nearPlane = near;
4868
+ camera.farPlane = far;
4869
+ }
4870
+ /**
4871
+ * Sets the camera's normalized viewport, in Babylon's convention: the origin is the **bottom** left
4872
+ * of the render target.
4873
+ *
4874
+ * @remarks
4875
+ * The viewport object is reused when one is already installed, so a per-frame viewport animation
4876
+ * allocates nothing (coding standards §7).
4877
+ *
4878
+ * @param camera - The camera to configure.
4879
+ * @param x - The left edge, 0 to 1.
4880
+ * @param y - The bottom edge, 0 to 1.
4881
+ * @param width - The width, 0 to 1.
4882
+ * @param height - The height, 0 to 1.
4883
+ *
4884
+ * @internal
4885
+ */
4886
+ function setCameraViewport(camera, x, y, width, height) {
4887
+ const existing = camera.viewport;
4888
+ if (existing === void 0) {
4889
+ camera.viewport = {
4890
+ x,
4891
+ y,
4892
+ width,
4893
+ height
4894
+ };
4817
4895
  return;
4818
4896
  }
4819
- const s = 2 * Math.sqrt(1 + b22 - b00 - b11);
4820
- out.set((b02 + b20) / s, (b12 + b21) / s, .25 * s, (b10 - b01) / s);
4897
+ existing.x = x;
4898
+ existing.y = y;
4899
+ existing.width = width;
4900
+ existing.height = height;
4901
+ }
4902
+ /**
4903
+ * Resolves a camera's normalized viewport to integer render-target pixels.
4904
+ *
4905
+ * @remarks
4906
+ * Lite flips the y axis here: the normalized viewport measures `y` from the bottom (Babylon), the
4907
+ * pixel viewport measures it from the top (WebGPU). Verified in `lib/camera/viewport.js`, which
4908
+ * computes `y = floor(clamp01(1 - v.y - v.height) * targetHeight)`.
4909
+ *
4910
+ * @param camera - The camera, or `null` for the full target.
4911
+ * @param targetWidth - The render target width, in pixels.
4912
+ * @param targetHeight - The render target height, in pixels.
4913
+ * @returns A fresh pixel viewport. **Allocates** — Lite builds the object; do not call per frame.
4914
+ *
4915
+ * @internal
4916
+ */
4917
+ function resolveViewportPixels(camera, targetWidth, targetHeight) {
4918
+ return resolveCameraViewport(camera, targetWidth, targetHeight);
4919
+ }
4920
+ /**
4921
+ * The aspect ratio Lite projects with: the render target's ratio scaled by the camera's viewport.
4922
+ *
4923
+ * @param camera - The camera, or `null` for an unrestricted viewport.
4924
+ * @param targetWidth - The render target width, in pixels.
4925
+ * @param targetHeight - The render target height, in pixels.
4926
+ * @returns Width divided by height.
4927
+ *
4928
+ * @internal
4929
+ */
4930
+ function cameraAspectRatio(camera, targetWidth, targetHeight) {
4931
+ return getEffectiveAspectRatio(camera, targetWidth, targetHeight);
4932
+ }
4933
+ /**
4934
+ * Copies the camera's view matrix (the inverse of its world matrix) into `out`.
4935
+ *
4936
+ * @param camera - The camera to read.
4937
+ * @param out - A sink of at least 16 elements, written column-major.
4938
+ * @returns `out`, for chaining.
4939
+ *
4940
+ * @internal
4941
+ */
4942
+ function readViewMatrix(camera, out) {
4943
+ return copyMatrix(getViewMatrix(camera), out);
4944
+ }
4945
+ /**
4946
+ * Copies the camera's projection matrix into `out`.
4947
+ *
4948
+ * @param camera - The camera to read.
4949
+ * @param aspectRatio - Width divided by height, from {@link cameraAspectRatio}.
4950
+ * @param out - A sink of at least 16 elements, written column-major.
4951
+ * @returns `out`, for chaining.
4952
+ *
4953
+ * @internal
4954
+ */
4955
+ function readProjectionMatrix(camera, aspectRatio, out) {
4956
+ return copyMatrix(getProjectionMatrix(camera, aspectRatio), out);
4957
+ }
4958
+ /**
4959
+ * Makes a camera the one a scene renders through, or clears it.
4960
+ *
4961
+ * @remarks
4962
+ * Lite renders through exactly one camera per scene (`SceneContext.camera`, `index.d.ts` 10072);
4963
+ * a scene with no camera draws nothing. Choosing between several enabled ignifx cameras by
4964
+ * `priority` is the component layer's job.
4965
+ *
4966
+ * @param scene - The render scene.
4967
+ * @param camera - The camera to render through, or `null` for none.
4968
+ *
4969
+ * @internal
4970
+ */
4971
+ function setSceneCamera(scene, camera) {
4972
+ scene.camera = camera;
4821
4973
  }
4822
4974
  /**
4823
- * A 4×4 transformation matrix stored column-major in a `Float32Array`, byte-compatible with WGSL's
4824
- * `mat4x4<f32>` and with Babylon Lite's `Mat4` (translation in slots 12/13/14).
4975
+ * Builds a world-space ray through a point on the render target.
4976
+ *
4977
+ * @remarks
4978
+ * This reproduces Lite's own `createPickingRay` (`lib/picking/ray.js`), which is not exported from
4979
+ * the package, and the coordinate handling of `pickAsync` (`lib/picking/gpu-picker.js` lines
4980
+ * 176–193): the pixel is made relative to the camera's **pixel** viewport, the projection uses that
4981
+ * viewport's aspect ratio, and the normalized device coordinates are
4982
+ * `(2x/w - 1, 1 - 2y/h)`. Because the projection is reverse-depth, clip depth `1` unprojects to the
4983
+ * near plane and `0` to the far plane.
4825
4984
  *
4826
- * ignifx is left-handed, Y up, +Z forward (ADR-0011), so the projection helpers are the `LH`
4827
- * family and they use Lite's **reverse depth** convention: the near plane maps to 1 and the far
4828
- * plane to 0.
4985
+ * The ray is written into `out`, so a picking loop allocates nothing.
4829
4986
  *
4830
- * Instance methods mutate the matrix and return `this`; `ToRef` statics write into their `out`
4831
- * matrix and allocate nothing, and are safe when `out` aliases an input. The remaining statics
4832
- * allocate a fresh matrix and say so.
4987
+ * @param camera - The camera to look through.
4988
+ * @param x - The pixel x inside the viewport, measured from its left edge.
4989
+ * @param y - The pixel y inside the viewport, measured from its top edge.
4990
+ * @param viewportWidth - The viewport width, in pixels.
4991
+ * @param viewportHeight - The viewport height, in pixels.
4992
+ * @param out - The ray to fill.
4993
+ * @returns `out` when the ray could be built, or `null` when the view-projection matrix is
4994
+ * singular (a zero-sized viewport, or a degenerate projection).
4833
4995
  *
4834
4996
  * @example
4835
4997
  * ```ts
4836
- * const world = new Mat4();
4837
- * Mat4.composeToRef(position, rotation, scale, world);
4838
- *
4839
- * const inverse = new Mat4();
4840
- * if (Mat4.invertToRef(world, inverse)) {
4841
- * Mat4.transformPointToRef(inverse, worldPoint, localPoint);
4842
- * }
4998
+ * const ray: MutableRay = { origin: [0, 0, 0], direction: [0, 0, 1], length: 1 };
4999
+ * const viewport = resolveViewportPixels(camera, canvas.width, canvas.height);
5000
+ * screenToRay(camera, px - viewport.x, py - viewport.y, viewport.width, viewport.height, ray);
4843
5001
  * ```
4844
5002
  *
4845
- * @public
5003
+ * @internal
4846
5004
  */
4847
- var Mat4 = class Mat4 {
4848
- /**
4849
- * The 16 elements, column-major (`elements[column * 4 + row]`). This is the object to hand to
4850
- * anything that wants a {@link Mat4Like} — including Babylon Lite — and the buffer to upload to
4851
- * the GPU. It is never reallocated, so a reference to it stays valid for the matrix's lifetime.
4852
- */
4853
- elements;
4854
- /**
4855
- * Creates an identity matrix.
4856
- */
4857
- constructor() {
4858
- const e = allocateElements();
4859
- e[0] = 1;
4860
- e[5] = 1;
4861
- e[10] = 1;
4862
- e[15] = 1;
4863
- this.elements = e;
4864
- }
4865
- /**
4866
- * Resets this matrix to the identity.
4867
- *
4868
- * @returns This matrix.
4869
- */
4870
- identity() {
4871
- const e = this.elements;
4872
- e[0] = 1;
4873
- e[1] = 0;
4874
- e[2] = 0;
4875
- e[3] = 0;
4876
- e[4] = 0;
4877
- e[5] = 1;
4878
- e[6] = 0;
4879
- e[7] = 0;
4880
- e[8] = 0;
4881
- e[9] = 0;
4882
- e[10] = 1;
4883
- e[11] = 0;
4884
- e[12] = 0;
4885
- e[13] = 0;
4886
- e[14] = 0;
4887
- e[15] = 1;
4888
- return this;
4889
- }
4890
- /**
4891
- * Copies every element from another matrix.
4892
- *
4893
- * @param m - The matrix to read.
4894
- * @returns This matrix.
4895
- */
4896
- copyFrom(m) {
4897
- const e = this.elements;
4898
- for (let i = 0; i < 16; i++) e[i] = m[i] ?? 0;
4899
- return this;
4900
- }
4901
- /**
4902
- * Copies this matrix into a new one.
4903
- *
4904
- * @returns A new matrix. **Allocates.**
4905
- */
4906
- clone() {
4907
- return new Mat4().copyFrom(this.elements);
4908
- }
4909
- /**
4910
- * Post-multiplies this matrix by another (`this = this * m`), so `m`'s transform is applied first
4911
- * when the product acts on a column vector.
4912
- *
4913
- * @param m - The right-hand matrix.
4914
- * @returns This matrix.
4915
- */
4916
- multiply(m) {
4917
- Mat4.multiplyToRef(this.elements, m, this);
4918
- return this;
4919
- }
4920
- /**
4921
- * Inverts this matrix in place.
4922
- *
4923
- * @returns `true` on success. When the matrix is singular this returns `false` and leaves the
4924
- * matrix untouched.
4925
- */
4926
- invert() {
4927
- return Mat4.invertToRef(this.elements, this);
4928
- }
4929
- /**
4930
- * Transposes this matrix in place, swapping rows and columns.
4931
- *
4932
- * @returns This matrix.
4933
- */
4934
- transpose() {
4935
- Mat4.transposeToRef(this.elements, this);
4936
- return this;
4937
- }
4938
- /**
4939
- * The full 4×4 determinant of this matrix.
4940
- *
4941
- * @returns The determinant; zero means the matrix cannot be inverted.
4942
- */
4943
- determinant() {
4944
- return Mat4.determinant(this.elements);
4945
- }
4946
- /**
4947
- * Compares this matrix with another element by element, with a tolerance.
4948
- *
4949
- * @param m - The matrix to compare against.
4950
- * @param epsilon - The largest per-element difference still considered equal.
4951
- * @returns `true` when every element matches within `epsilon`.
4952
- */
4953
- equalsWithEpsilon(m, epsilon = EPSILON) {
4954
- return Mat4.equalsWithEpsilon(this.elements, m, epsilon);
4955
- }
4956
- /**
4957
- * Creates an identity matrix.
4958
- *
4959
- * @returns A new identity matrix. **Allocates.**
4960
- */
4961
- static identity() {
4962
- return new Mat4();
4963
- }
4964
- /**
4965
- * Creates a matrix holding a copy of another matrix's elements.
4966
- *
4967
- * @param m - The matrix to copy.
4968
- * @returns A new matrix. **Allocates.**
4969
- */
4970
- static from(m) {
4971
- return new Mat4().copyFrom(m);
4972
- }
4973
- /**
4974
- * Builds a translation-rotation-scale matrix, the same composition order Babylon Lite's
4975
- * `mat4Compose` uses (`translation * rotation * scale`).
4976
- *
4977
- * @param position - The translation, in metres.
4978
- * @param rotation - The rotation; assumed to be a unit quaternion.
4979
- * @param scale - The per-axis scale.
4980
- * @returns A new matrix. **Allocates.**
4981
- */
4982
- static compose(position, rotation, scale) {
4983
- return Mat4.composeToRef(position, rotation, scale, new Mat4());
4984
- }
4985
- /**
4986
- * Writes a translation-rotation-scale matrix into `out`.
4987
- *
4988
- * @param position - The translation, in metres.
4989
- * @param rotation - The rotation; assumed to be a unit quaternion.
4990
- * @param scale - The per-axis scale.
4991
- * @param out - The matrix to write.
4992
- * @returns `out`.
4993
- *
4994
- * @example
4995
- * ```ts
4996
- * Mat4.composeToRef(transform.localPosition, transform.localRotation, transform.localScale, local);
4997
- * ```
4998
- */
4999
- static composeToRef(position, rotation, scale, out) {
5000
- const qx = rotation.x;
5001
- const qy = rotation.y;
5002
- const qz = rotation.z;
5003
- const qw = rotation.w;
5004
- const sx = scale.x;
5005
- const sy = scale.y;
5006
- const sz = scale.z;
5007
- const xx = qx * qx;
5008
- const yy = qy * qy;
5009
- const zz = qz * qz;
5010
- const xy = qx * qy;
5011
- const xz = qx * qz;
5012
- const yz = qy * qz;
5013
- const wx = qw * qx;
5014
- const wy = qw * qy;
5015
- const wz = qw * qz;
5016
- const e = out.elements;
5017
- e[0] = (1 - 2 * (yy + zz)) * sx;
5018
- e[1] = 2 * (xy + wz) * sx;
5019
- e[2] = 2 * (xz - wy) * sx;
5020
- e[3] = 0;
5021
- e[4] = 2 * (xy - wz) * sy;
5022
- e[5] = (1 - 2 * (xx + zz)) * sy;
5023
- e[6] = 2 * (yz + wx) * sy;
5024
- e[7] = 0;
5025
- e[8] = 2 * (xz + wy) * sz;
5026
- e[9] = 2 * (yz - wx) * sz;
5027
- e[10] = (1 - 2 * (xx + yy)) * sz;
5028
- e[11] = 0;
5029
- e[12] = position.x;
5030
- e[13] = position.y;
5031
- e[14] = position.z;
5032
- e[15] = 1;
5033
- return out;
5034
- }
5035
- /**
5036
- * Splits an affine transformation-rotation-scale matrix back into its parts, using Babylon Lite's
5037
- * convention (`lib/math/mat4-decompose.js`): scales are the lengths of the basis columns, and a
5038
- * mirrored matrix (negative basis determinant) reports a **negative Y scale** rather than
5039
- * silently dropping the reflection. Shear is not detected.
5040
- *
5041
- * @param m - The matrix to split.
5042
- * @param outPosition - Receives the translation.
5043
- * @param outRotation - Receives the rotation as a unit quaternion.
5044
- * @param outScale - Receives the per-axis scale.
5045
- * @returns `true` on success; `false` when a basis column has (near) zero length, in which case
5046
- * the outputs are left untouched.
5047
- *
5048
- * @example
5049
- * ```ts
5050
- * Mat4.decomposeToRef(node.worldMatrix, position, rotation, scale);
5051
- * ```
5052
- */
5053
- static decomposeToRef(m, outPosition, outRotation, outScale) {
5054
- const m0 = m[0] ?? 0;
5055
- const m1 = m[1] ?? 0;
5056
- const m2 = m[2] ?? 0;
5057
- const m4 = m[4] ?? 0;
5058
- const m5 = m[5] ?? 0;
5059
- const m6 = m[6] ?? 0;
5060
- const m8 = m[8] ?? 0;
5061
- const m9 = m[9] ?? 0;
5062
- const m10 = m[10] ?? 0;
5063
- const sx = Math.hypot(m0, m1, m2);
5064
- const syAbs = Math.hypot(m4, m5, m6);
5065
- const sz = Math.hypot(m8, m9, m10);
5066
- if (sx <= 1e-8 || syAbs <= 1e-8 || sz <= 1e-8) return false;
5067
- const sy = basisDeterminant(m) < 0 ? -syAbs : syAbs;
5068
- const invSx = 1 / sx;
5069
- const invSy = 1 / sy;
5070
- const invSz = 1 / sz;
5071
- const tx = m[12] ?? 0;
5072
- const ty = m[13] ?? 0;
5073
- const tz = m[14] ?? 0;
5074
- basisToQuatToRef(m0 * invSx, m4 * invSy, m8 * invSz, m1 * invSx, m5 * invSy, m9 * invSz, m2 * invSx, m6 * invSy, m10 * invSz, outRotation);
5075
- const qx = outRotation.x;
5076
- const qy = outRotation.y;
5077
- const qz = outRotation.z;
5078
- const qw = outRotation.w;
5079
- const invLength = 1 / Math.hypot(qx, qy, qz, qw);
5080
- outRotation.set(qx * invLength, qy * invLength, qz * invLength, qw * invLength);
5081
- outPosition.set(tx, ty, tz);
5082
- outScale.set(sx, sy, sz);
5083
- return true;
5084
- }
5085
- /**
5086
- * Multiplies two matrices.
5087
- *
5088
- * @param a - The left-hand matrix.
5089
- * @param b - The right-hand matrix.
5090
- * @returns A new matrix holding `a * b`. **Allocates.**
5091
- */
5092
- static multiply(a, b) {
5093
- return Mat4.multiplyToRef(a, b, new Mat4());
5094
- }
5095
- /**
5096
- * Writes `a * b` into `out`. Acting on a column vector, `b` is applied first.
5097
- *
5098
- * @param a - The left-hand matrix.
5099
- * @param b - The right-hand matrix.
5100
- * @param out - The matrix to write; may alias `a` or `b`.
5101
- * @returns `out`.
5102
- */
5103
- static multiplyToRef(a, b, out) {
5104
- const a0 = a[0] ?? 0;
5105
- const a1 = a[1] ?? 0;
5106
- const a2 = a[2] ?? 0;
5107
- const a3 = a[3] ?? 0;
5108
- const a4 = a[4] ?? 0;
5109
- const a5 = a[5] ?? 0;
5110
- const a6 = a[6] ?? 0;
5111
- const a7 = a[7] ?? 0;
5112
- const a8 = a[8] ?? 0;
5113
- const a9 = a[9] ?? 0;
5114
- const a10 = a[10] ?? 0;
5115
- const a11 = a[11] ?? 0;
5116
- const a12 = a[12] ?? 0;
5117
- const a13 = a[13] ?? 0;
5118
- const a14 = a[14] ?? 0;
5119
- const a15 = a[15] ?? 0;
5120
- const b0 = b[0] ?? 0;
5121
- const b1 = b[1] ?? 0;
5122
- const b2 = b[2] ?? 0;
5123
- const b3 = b[3] ?? 0;
5124
- const b4 = b[4] ?? 0;
5125
- const b5 = b[5] ?? 0;
5126
- const b6 = b[6] ?? 0;
5127
- const b7 = b[7] ?? 0;
5128
- const b8 = b[8] ?? 0;
5129
- const b9 = b[9] ?? 0;
5130
- const b10 = b[10] ?? 0;
5131
- const b11 = b[11] ?? 0;
5132
- const b12 = b[12] ?? 0;
5133
- const b13 = b[13] ?? 0;
5134
- const b14 = b[14] ?? 0;
5135
- const b15 = b[15] ?? 0;
5136
- const e = out.elements;
5137
- e[0] = a0 * b0 + a4 * b1 + a8 * b2 + a12 * b3;
5138
- e[1] = a1 * b0 + a5 * b1 + a9 * b2 + a13 * b3;
5139
- e[2] = a2 * b0 + a6 * b1 + a10 * b2 + a14 * b3;
5140
- e[3] = a3 * b0 + a7 * b1 + a11 * b2 + a15 * b3;
5141
- e[4] = a0 * b4 + a4 * b5 + a8 * b6 + a12 * b7;
5142
- e[5] = a1 * b4 + a5 * b5 + a9 * b6 + a13 * b7;
5143
- e[6] = a2 * b4 + a6 * b5 + a10 * b6 + a14 * b7;
5144
- e[7] = a3 * b4 + a7 * b5 + a11 * b6 + a15 * b7;
5145
- e[8] = a0 * b8 + a4 * b9 + a8 * b10 + a12 * b11;
5146
- e[9] = a1 * b8 + a5 * b9 + a9 * b10 + a13 * b11;
5147
- e[10] = a2 * b8 + a6 * b9 + a10 * b10 + a14 * b11;
5148
- e[11] = a3 * b8 + a7 * b9 + a11 * b10 + a15 * b11;
5149
- e[12] = a0 * b12 + a4 * b13 + a8 * b14 + a12 * b15;
5150
- e[13] = a1 * b12 + a5 * b13 + a9 * b14 + a13 * b15;
5151
- e[14] = a2 * b12 + a6 * b13 + a10 * b14 + a14 * b15;
5152
- e[15] = a3 * b12 + a7 * b13 + a11 * b14 + a15 * b15;
5153
- return out;
5154
- }
5155
- /**
5156
- * Writes the inverse of `m` into `out`.
5157
- *
5158
- * @param m - The matrix to invert.
5159
- * @param out - The matrix to write; may alias `m`. Left untouched when the inverse does not exist.
5160
- * @returns `true` on success, `false` when `m` is singular. Returning a status rather than `null`
5161
- * keeps the call allocation-free (coding standards §7).
5162
- *
5163
- * @example
5164
- * ```ts
5165
- * if (!Mat4.invertToRef(world, worldToLocal)) {
5166
- * // degenerate scale — skip this entity
5167
- * }
5168
- * ```
5169
- */
5170
- static invertToRef(m, out) {
5171
- const a00 = m[0] ?? 0;
5172
- const a01 = m[1] ?? 0;
5173
- const a02 = m[2] ?? 0;
5174
- const a03 = m[3] ?? 0;
5175
- const a10 = m[4] ?? 0;
5176
- const a11 = m[5] ?? 0;
5177
- const a12 = m[6] ?? 0;
5178
- const a13 = m[7] ?? 0;
5179
- const a20 = m[8] ?? 0;
5180
- const a21 = m[9] ?? 0;
5181
- const a22 = m[10] ?? 0;
5182
- const a23 = m[11] ?? 0;
5183
- const a30 = m[12] ?? 0;
5184
- const a31 = m[13] ?? 0;
5185
- const a32 = m[14] ?? 0;
5186
- const a33 = m[15] ?? 0;
5187
- const b00 = a00 * a11 - a01 * a10;
5188
- const b01 = a00 * a12 - a02 * a10;
5189
- const b02 = a00 * a13 - a03 * a10;
5190
- const b03 = a01 * a12 - a02 * a11;
5191
- const b04 = a01 * a13 - a03 * a11;
5192
- const b05 = a02 * a13 - a03 * a12;
5193
- const b06 = a20 * a31 - a21 * a30;
5194
- const b07 = a20 * a32 - a22 * a30;
5195
- const b08 = a20 * a33 - a23 * a30;
5196
- const b09 = a21 * a32 - a22 * a31;
5197
- const b10 = a21 * a33 - a23 * a31;
5198
- const b11 = a22 * a33 - a23 * a32;
5199
- const determinant = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
5200
- if (Math.abs(determinant) < 1e-10) return false;
5201
- const inv = 1 / determinant;
5202
- const e = out.elements;
5203
- e[0] = (a11 * b11 - a12 * b10 + a13 * b09) * inv;
5204
- e[1] = (a02 * b10 - a01 * b11 - a03 * b09) * inv;
5205
- e[2] = (a31 * b05 - a32 * b04 + a33 * b03) * inv;
5206
- e[3] = (a22 * b04 - a21 * b05 - a23 * b03) * inv;
5207
- e[4] = (a12 * b08 - a10 * b11 - a13 * b07) * inv;
5208
- e[5] = (a00 * b11 - a02 * b08 + a03 * b07) * inv;
5209
- e[6] = (a32 * b02 - a30 * b05 - a33 * b01) * inv;
5210
- e[7] = (a20 * b05 - a22 * b02 + a23 * b01) * inv;
5211
- e[8] = (a10 * b10 - a11 * b08 + a13 * b06) * inv;
5212
- e[9] = (a01 * b08 - a00 * b10 - a03 * b06) * inv;
5213
- e[10] = (a30 * b04 - a31 * b02 + a33 * b00) * inv;
5214
- e[11] = (a21 * b02 - a20 * b04 - a23 * b00) * inv;
5215
- e[12] = (a11 * b07 - a10 * b09 - a12 * b06) * inv;
5216
- e[13] = (a00 * b09 - a01 * b07 + a02 * b06) * inv;
5217
- e[14] = (a31 * b01 - a30 * b03 - a32 * b00) * inv;
5218
- e[15] = (a20 * b03 - a21 * b01 + a22 * b00) * inv;
5219
- return true;
5220
- }
5221
- /**
5222
- * Writes the transpose of `m` into `out`.
5223
- *
5224
- * @param m - The matrix to transpose.
5225
- * @param out - The matrix to write; may alias `m`.
5226
- * @returns `out`.
5227
- */
5228
- static transposeToRef(m, out) {
5229
- const m0 = m[0] ?? 0;
5230
- const m1 = m[1] ?? 0;
5231
- const m2 = m[2] ?? 0;
5232
- const m3 = m[3] ?? 0;
5233
- const m4 = m[4] ?? 0;
5234
- const m5 = m[5] ?? 0;
5235
- const m6 = m[6] ?? 0;
5236
- const m7 = m[7] ?? 0;
5237
- const m8 = m[8] ?? 0;
5238
- const m9 = m[9] ?? 0;
5239
- const m10 = m[10] ?? 0;
5240
- const m11 = m[11] ?? 0;
5241
- const m12 = m[12] ?? 0;
5242
- const m13 = m[13] ?? 0;
5243
- const m14 = m[14] ?? 0;
5244
- const m15 = m[15] ?? 0;
5245
- const e = out.elements;
5246
- e[0] = m0;
5247
- e[1] = m4;
5248
- e[2] = m8;
5249
- e[3] = m12;
5250
- e[4] = m1;
5251
- e[5] = m5;
5252
- e[6] = m9;
5253
- e[7] = m13;
5254
- e[8] = m2;
5255
- e[9] = m6;
5256
- e[10] = m10;
5257
- e[11] = m14;
5258
- e[12] = m3;
5259
- e[13] = m7;
5260
- e[14] = m11;
5261
- e[15] = m15;
5262
- return out;
5263
- }
5264
- /**
5265
- * The full 4×4 determinant.
5266
- *
5267
- * @param m - The matrix to measure.
5268
- * @returns The determinant; zero means the matrix cannot be inverted.
5269
- */
5270
- static determinant(m) {
5271
- const a00 = m[0] ?? 0;
5272
- const a01 = m[1] ?? 0;
5273
- const a02 = m[2] ?? 0;
5274
- const a03 = m[3] ?? 0;
5275
- const a10 = m[4] ?? 0;
5276
- const a11 = m[5] ?? 0;
5277
- const a12 = m[6] ?? 0;
5278
- const a13 = m[7] ?? 0;
5279
- const a20 = m[8] ?? 0;
5280
- const a21 = m[9] ?? 0;
5281
- const a22 = m[10] ?? 0;
5282
- const a23 = m[11] ?? 0;
5283
- const a30 = m[12] ?? 0;
5284
- const a31 = m[13] ?? 0;
5285
- const a32 = m[14] ?? 0;
5286
- const a33 = m[15] ?? 0;
5287
- const b00 = a00 * a11 - a01 * a10;
5288
- const b01 = a00 * a12 - a02 * a10;
5289
- const b02 = a00 * a13 - a03 * a10;
5290
- const b03 = a01 * a12 - a02 * a11;
5291
- const b04 = a01 * a13 - a03 * a11;
5292
- const b05 = a02 * a13 - a03 * a12;
5293
- const b06 = a20 * a31 - a21 * a30;
5294
- const b07 = a20 * a32 - a22 * a30;
5295
- const b08 = a20 * a33 - a23 * a30;
5296
- const b09 = a21 * a32 - a22 * a31;
5297
- const b10 = a21 * a33 - a23 * a31;
5298
- return b00 * (a22 * a33 - a23 * a32) - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
5299
- }
5300
- /**
5301
- * Builds a pure translation matrix.
5302
- *
5303
- * @param x - Translation along X, in metres.
5304
- * @param y - Translation along Y, in metres.
5305
- * @param z - Translation along Z, in metres.
5306
- * @returns A new matrix. **Allocates.**
5307
- */
5308
- static translation(x, y, z) {
5309
- return Mat4.translationToRef(x, y, z, new Mat4());
5310
- }
5311
- /**
5312
- * Writes a pure translation matrix into `out`.
5313
- *
5314
- * @param x - Translation along X, in metres.
5315
- * @param y - Translation along Y, in metres.
5316
- * @param z - Translation along Z, in metres.
5317
- * @param out - The matrix to write.
5318
- * @returns `out`.
5319
- */
5320
- static translationToRef(x, y, z, out) {
5321
- const e = out.identity().elements;
5322
- e[12] = x;
5323
- e[13] = y;
5324
- e[14] = z;
5325
- return out;
5326
- }
5327
- /**
5328
- * Builds a pure scaling matrix.
5329
- *
5330
- * @param x - Scale along X.
5331
- * @param y - Scale along Y.
5332
- * @param z - Scale along Z.
5333
- * @returns A new matrix. **Allocates.**
5334
- */
5335
- static scaling(x, y, z) {
5336
- return Mat4.scalingToRef(x, y, z, new Mat4());
5337
- }
5338
- /**
5339
- * Writes a pure scaling matrix into `out`.
5340
- *
5341
- * @param x - Scale along X.
5342
- * @param y - Scale along Y.
5343
- * @param z - Scale along Z.
5344
- * @param out - The matrix to write.
5345
- * @returns `out`.
5346
- */
5347
- static scalingToRef(x, y, z, out) {
5348
- const e = out.identity().elements;
5349
- e[0] = x;
5350
- e[5] = y;
5351
- e[10] = z;
5352
- return out;
5353
- }
5354
- /**
5355
- * Builds a pure rotation matrix from a quaternion.
5356
- *
5357
- * @param q - The rotation; assumed to be a unit quaternion.
5358
- * @returns A new matrix. **Allocates.**
5359
- */
5360
- static fromQuat(q) {
5361
- return Mat4.fromQuatToRef(q, new Mat4());
5362
- }
5363
- /**
5364
- * Writes a pure rotation matrix into `out`.
5365
- *
5366
- * @param q - The rotation; assumed to be a unit quaternion.
5367
- * @param out - The matrix to write.
5368
- * @returns `out`.
5369
- */
5370
- static fromQuatToRef(q, out) {
5371
- return Mat4.composeToRef(ZERO_TRANSLATION, q, UNIT_SCALE, out);
5372
- }
5373
- /**
5374
- * Builds a left-handed view matrix that places the camera at `eye` looking at `target`.
5375
- *
5376
- * @param eye - The camera position, in metres.
5377
- * @param target - The point to look at, in metres.
5378
- * @param up - The camera's up direction.
5379
- * @returns A new matrix. **Allocates.**
5380
- */
5381
- static lookAtLH(eye, target, up) {
5382
- return Mat4.lookAtLHToRef(eye, target, up, new Mat4());
5383
- }
5384
- /**
5385
- * Writes a left-handed view matrix into `out`. Reproduces Babylon Lite's `mat4LookAtLHToRef`,
5386
- * including its degenerate-input behaviour: when `eye` and `target` coincide, or when `up` is
5387
- * parallel to the view direction, `out` becomes the identity.
5388
- *
5389
- * @param eye - The camera position, in metres.
5390
- * @param target - The point to look at, in metres.
5391
- * @param up - The camera's up direction.
5392
- * @param out - The matrix to write.
5393
- * @returns `out`.
5394
- */
5395
- static lookAtLHToRef(eye, target, up, out) {
5396
- const ex = eye.x;
5397
- const ey = eye.y;
5398
- const ez = eye.z;
5399
- let zx = target.x - ex;
5400
- let zy = target.y - ey;
5401
- let zz = target.z - ez;
5402
- const zLength = Math.hypot(zx, zy, zz);
5403
- if (zLength < 1e-10) return out.identity();
5404
- const invZ = 1 / zLength;
5405
- zx *= invZ;
5406
- zy *= invZ;
5407
- zz *= invZ;
5408
- let xx = up.y * zz - up.z * zy;
5409
- let xy = up.z * zx - up.x * zz;
5410
- let xz = up.x * zy - up.y * zx;
5411
- const xLength = Math.hypot(xx, xy, xz);
5412
- if (xLength < 1e-10) return out.identity();
5413
- const invX = 1 / xLength;
5414
- xx *= invX;
5415
- xy *= invX;
5416
- xz *= invX;
5417
- const yx = zy * xz - zz * xy;
5418
- const yy = zz * xx - zx * xz;
5419
- const yz = zx * xy - zy * xx;
5420
- const e = out.elements;
5421
- e[0] = xx;
5422
- e[1] = yx;
5423
- e[2] = zx;
5424
- e[3] = 0;
5425
- e[4] = xy;
5426
- e[5] = yy;
5427
- e[6] = zy;
5428
- e[7] = 0;
5429
- e[8] = xz;
5430
- e[9] = yz;
5431
- e[10] = zz;
5432
- e[11] = 0;
5433
- e[12] = -(xx * ex + xy * ey + xz * ez);
5434
- e[13] = -(yx * ex + yy * ey + yz * ez);
5435
- e[14] = -(zx * ex + zy * ey + zz * ez);
5436
- e[15] = 1;
5437
- return out;
5438
- }
5439
- /**
5440
- * Builds a left-handed perspective projection.
5441
- *
5442
- * @param fovDegrees - The vertical field of view, in degrees.
5443
- * @param aspect - The viewport's width divided by its height.
5444
- * @param near - The near plane distance, in metres.
5445
- * @param far - The far plane distance, in metres.
5446
- * @returns A new matrix. **Allocates.**
5447
- */
5448
- static perspectiveLH(fovDegrees, aspect, near, far) {
5449
- return Mat4.perspectiveLHToRef(fovDegrees, aspect, near, far, new Mat4());
5450
- }
5451
- /**
5452
- * Writes a left-handed perspective projection into `out`, matching Babylon Lite's
5453
- * `mat4PerspectiveLHToRef` — which is a **reverse-depth** projection: the near plane maps to
5454
- * clip-space depth 1 and the far plane to 0, the arrangement that keeps float depth precise.
5455
- *
5456
- * @param fovDegrees - The vertical field of view, in degrees.
5457
- * @param aspect - The viewport's width divided by its height.
5458
- * @param near - The near plane distance, in metres.
5459
- * @param far - The far plane distance, in metres.
5460
- * @param out - The matrix to write.
5461
- * @returns `out`.
5462
- */
5463
- static perspectiveLHToRef(fovDegrees, aspect, near, far, out) {
5464
- const cot = 1 / Math.tan(degToRad(fovDegrees) * .5);
5465
- const range = far - near;
5466
- const e = out.elements;
5467
- e[0] = cot / aspect;
5468
- e[1] = 0;
5469
- e[2] = 0;
5470
- e[3] = 0;
5471
- e[4] = 0;
5472
- e[5] = cot;
5473
- e[6] = 0;
5474
- e[7] = 0;
5475
- e[8] = 0;
5476
- e[9] = 0;
5477
- e[10] = -near / range;
5478
- e[11] = 1;
5479
- e[12] = 0;
5480
- e[13] = 0;
5481
- e[14] = far * near / range;
5482
- e[15] = 0;
5483
- return out;
5484
- }
5485
- /**
5486
- * Builds a centred left-handed orthographic projection.
5487
- *
5488
- * @param width - The view width, in metres.
5489
- * @param height - The view height, in metres.
5490
- * @param near - The near plane distance, in metres.
5491
- * @param far - The far plane distance, in metres.
5492
- * @returns A new matrix. **Allocates.**
5493
- */
5494
- static orthoLH(width, height, near, far) {
5495
- return Mat4.orthoLHToRef(width, height, near, far, new Mat4());
5496
- }
5497
- /**
5498
- * Writes a centred left-handed orthographic projection into `out`, with the same reverse-depth
5499
- * convention as {@link Mat4.perspectiveLHToRef}.
5500
- *
5501
- * @param width - The view width, in metres.
5502
- * @param height - The view height, in metres.
5503
- * @param near - The near plane distance, in metres.
5504
- * @param far - The far plane distance, in metres.
5505
- * @param out - The matrix to write.
5506
- * @returns `out`.
5507
- */
5508
- static orthoLHToRef(width, height, near, far, out) {
5509
- const halfWidth = width * .5;
5510
- const halfHeight = height * .5;
5511
- return Mat4.orthoOffCenterLHToRef(-halfWidth, halfWidth, -halfHeight, halfHeight, near, far, out);
5512
- }
5513
- /**
5514
- * Writes an off-centre left-handed orthographic projection into `out`, reproducing Babylon Lite's
5515
- * `mat4OrthoOffCenterLHToRef` (reverse depth).
5516
- *
5517
- * @param left - The left clip plane, in metres.
5518
- * @param right - The right clip plane, in metres.
5519
- * @param bottom - The bottom clip plane, in metres.
5520
- * @param top - The top clip plane, in metres.
5521
- * @param near - The near plane distance, in metres.
5522
- * @param far - The far plane distance, in metres.
5523
- * @param out - The matrix to write.
5524
- * @returns `out`.
5525
- */
5526
- static orthoOffCenterLHToRef(left, right, bottom, top, near, far, out) {
5527
- const range = far - near;
5528
- const e = out.elements;
5529
- e[0] = 2 / (right - left);
5530
- e[1] = 0;
5531
- e[2] = 0;
5532
- e[3] = 0;
5533
- e[4] = 0;
5534
- e[5] = 2 / (top - bottom);
5535
- e[6] = 0;
5536
- e[7] = 0;
5537
- e[8] = 0;
5538
- e[9] = 0;
5539
- e[10] = -1 / range;
5540
- e[11] = 0;
5541
- e[12] = (left + right) / (left - right);
5542
- e[13] = (top + bottom) / (bottom - top);
5543
- e[14] = far / range;
5544
- e[15] = 1;
5545
- return out;
5546
- }
5547
- /**
5548
- * Reads a matrix's translation.
5549
- *
5550
- * @param m - The matrix to read.
5551
- * @param out - The vector to write.
5552
- * @returns `out`.
5553
- */
5554
- static getTranslationToRef(m, out) {
5555
- out.set(m[12] ?? 0, m[13] ?? 0, m[14] ?? 0);
5556
- return out;
5557
- }
5558
- /**
5559
- * Reads a matrix's per-axis scale as the lengths of its basis columns, negating Y for a mirrored
5560
- * matrix exactly as {@link Mat4.decomposeToRef} does.
5561
- *
5562
- * @param m - The matrix to read.
5563
- * @param out - The vector to write.
5564
- * @returns `out`.
5565
- */
5566
- static getScaleToRef(m, out) {
5567
- const sx = Math.hypot(m[0] ?? 0, m[1] ?? 0, m[2] ?? 0);
5568
- const syAbs = Math.hypot(m[4] ?? 0, m[5] ?? 0, m[6] ?? 0);
5569
- const sz = Math.hypot(m[8] ?? 0, m[9] ?? 0, m[10] ?? 0);
5570
- out.set(sx, basisDeterminant(m) < 0 ? -syAbs : syAbs, sz);
5571
- return out;
5572
- }
5573
- /**
5574
- * Reads a matrix's rotation, dividing the scale out of the basis first.
5575
- *
5576
- * @param m - The matrix to read.
5577
- * @param out - The quaternion to write. Left untouched when a basis column has zero length.
5578
- * @returns `out`.
5579
- */
5580
- static getRotationToRef(m, out) {
5581
- const m0 = m[0] ?? 0;
5582
- const m1 = m[1] ?? 0;
5583
- const m2 = m[2] ?? 0;
5584
- const m4 = m[4] ?? 0;
5585
- const m5 = m[5] ?? 0;
5586
- const m6 = m[6] ?? 0;
5587
- const m8 = m[8] ?? 0;
5588
- const m9 = m[9] ?? 0;
5589
- const m10 = m[10] ?? 0;
5590
- const sx = Math.hypot(m0, m1, m2);
5591
- const syAbs = Math.hypot(m4, m5, m6);
5592
- const sz = Math.hypot(m8, m9, m10);
5593
- if (sx <= 1e-8 || syAbs <= 1e-8 || sz <= 1e-8) return out;
5594
- const invSx = 1 / sx;
5595
- const invSy = 1 / (basisDeterminant(m) < 0 ? -syAbs : syAbs);
5596
- const invSz = 1 / sz;
5597
- basisToQuatToRef(m0 * invSx, m4 * invSy, m8 * invSz, m1 * invSx, m5 * invSy, m9 * invSz, m2 * invSx, m6 * invSy, m10 * invSz, out);
5598
- const invLength = 1 / Math.hypot(out.x, out.y, out.z, out.w);
5599
- out.set(out.x * invLength, out.y * invLength, out.z * invLength, out.w * invLength);
5600
- return out;
5601
- }
5602
- /**
5603
- * Transforms a point by a matrix, applying translation and the perspective divide.
5604
- *
5605
- * @param m - The transformation.
5606
- * @param point - The point to transform, in metres.
5607
- * @param out - The vector to write; may alias `point`.
5608
- * @returns `out`.
5609
- */
5610
- static transformPointToRef(m, point, out) {
5611
- const x = point.x;
5612
- const y = point.y;
5613
- const z = point.z;
5614
- const rx = x * (m[0] ?? 0) + y * (m[4] ?? 0) + z * (m[8] ?? 0) + (m[12] ?? 0);
5615
- const ry = x * (m[1] ?? 0) + y * (m[5] ?? 0) + z * (m[9] ?? 0) + (m[13] ?? 0);
5616
- const rz = x * (m[2] ?? 0) + y * (m[6] ?? 0) + z * (m[10] ?? 0) + (m[14] ?? 0);
5617
- const invW = 1 / (x * (m[3] ?? 0) + y * (m[7] ?? 0) + z * (m[11] ?? 0) + (m[15] ?? 0));
5618
- out.set(rx * invW, ry * invW, rz * invW);
5619
- return out;
5620
- }
5621
- /**
5622
- * Transforms a direction by a matrix, ignoring translation. Note that this is the plain basis
5623
- * transform: a non-uniformly scaled matrix needs its inverse-transpose to keep normals correct.
5624
- *
5625
- * @param m - The transformation.
5626
- * @param direction - The direction to transform.
5627
- * @param out - The vector to write; may alias `direction`.
5628
- * @returns `out`.
5629
- */
5630
- static transformDirectionToRef(m, direction, out) {
5631
- const x = direction.x;
5632
- const y = direction.y;
5633
- const z = direction.z;
5634
- out.set(x * (m[0] ?? 0) + y * (m[4] ?? 0) + z * (m[8] ?? 0), x * (m[1] ?? 0) + y * (m[5] ?? 0) + z * (m[9] ?? 0), x * (m[2] ?? 0) + y * (m[6] ?? 0) + z * (m[10] ?? 0));
5635
- return out;
5636
- }
5637
- /**
5638
- * Compares two matrices element by element, with a tolerance.
5639
- *
5640
- * @param a - The first matrix.
5641
- * @param b - The second matrix.
5642
- * @param epsilon - The largest per-element difference still considered equal.
5643
- * @returns `true` when every element matches within `epsilon`.
5644
- */
5645
- static equalsWithEpsilon(a, b, epsilon = EPSILON) {
5646
- for (let i = 0; i < 16; i++) if (Math.abs((a[i] ?? 0) - (b[i] ?? 0)) > epsilon) return false;
5647
- return true;
5648
- }
5649
- };
5650
- /**
5651
- * The zero translation {@link Mat4.fromQuatToRef} composes with. Module-scope constant, frozen so it
5652
- * can never be written through.
5653
- */
5654
- const ZERO_TRANSLATION = Object.freeze({
5655
- x: 0,
5656
- y: 0,
5657
- z: 0
5658
- });
5659
- /**
5660
- * The unit scale {@link Mat4.fromQuatToRef} composes with.
5661
- */
5662
- const UNIT_SCALE = Object.freeze({
5663
- x: 1,
5664
- y: 1,
5665
- z: 1
5666
- });
5667
- /**
5668
- * A frozen identity matrix, for the common case of "no transform". It is a plain {@link Mat4Like}
5669
- * rather than a {@link Mat4} because a `Float32Array` cannot be frozen — pass it to anything that
5670
- * reads a matrix, and use `new Mat4()` when you need one you can write to.
5671
- *
5672
- * @example
5673
- * ```ts
5674
- * Mat4.transformPointToRef(MAT4_IDENTITY, point, out); // copies the point
5675
- * ```
5676
- *
5677
- * @public
5678
- */
5679
- const MAT4_IDENTITY = Object.freeze({
5680
- length: 16,
5681
- 0: 1,
5682
- 1: 0,
5683
- 2: 0,
5684
- 3: 0,
5685
- 4: 0,
5686
- 5: 1,
5687
- 6: 0,
5688
- 7: 0,
5689
- 8: 0,
5690
- 9: 0,
5691
- 10: 1,
5692
- 11: 0,
5693
- 12: 0,
5694
- 13: 0,
5695
- 14: 0,
5696
- 15: 1
5697
- });
5698
- //#endregion
5699
- //#region src/lite/camera.ts
5700
- /** Scratch inverse view-projection matrix, created on first use (coding standards §4). */
5701
- let inverseViewProjection = null;
5005
+ function screenToRay(camera, x, y, viewportWidth, viewportHeight, out) {
5006
+ if (viewportWidth <= 0 || viewportHeight <= 0) return null;
5007
+ const inverse = inverseViewProjection ??= new Mat4();
5008
+ const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);
5009
+ if (!Mat4.invertToRef(viewProjection, inverse)) return null;
5010
+ const ndcX = 2 * x / viewportWidth - 1;
5011
+ const ndcY = 1 - 2 * y / viewportHeight;
5012
+ const origin = out.origin;
5013
+ const direction = out.direction;
5014
+ unproject(inverse, ndcX, ndcY, 1, origin);
5015
+ unproject(inverse, ndcX, ndcY, 0, direction);
5016
+ const dx = direction[0] - origin[0];
5017
+ const dy = direction[1] - origin[1];
5018
+ const dz = direction[2] - origin[2];
5019
+ const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
5020
+ if (!(length > 0)) return null;
5021
+ const inverseLength = 1 / length;
5022
+ direction[0] = dx * inverseLength;
5023
+ direction[1] = dy * inverseLength;
5024
+ direction[2] = dz * inverseLength;
5025
+ out.length = length;
5026
+ return out;
5027
+ }
5702
5028
  /**
5703
- * Creates the Lite camera an ignifx `Camera` component owns and parents it under the entity's
5704
- * transform node.
5029
+ * Projects a world-space point onto the render target.
5705
5030
  *
5706
5031
  * @remarks
5707
- * The camera is created at the local origin looking down local `+Z`, ignifx's forward axis
5708
- * (ADR-0011). Its own position and target are never touched again: the entity's node supplies the
5709
- * transform, so the component has no follow logic (`docs/architecture/07-rendering.md` §2.1).
5710
- *
5711
- * @param parent - The entity's transform node, or `null` for a camera in world space.
5712
- * @returns The camera. It is not attached to any scene; call {@link setSceneCamera} for that.
5032
+ * `out.x`/`out.y` are pixels inside the camera's viewport, measured from its **top** left, matching
5033
+ * {@link screenToRay}'s input; `out.z` is the clip-space depth, which is `1` at the near plane and
5034
+ * `0` at the far plane because Lite's projection is reverse-depth.
5713
5035
  *
5714
- * @example
5715
- * ```ts
5716
- * const camera = createCameraUnderNode(entityNode);
5717
- * setCameraPerspective(camera, 60);
5718
- * setSceneCamera(scene, camera);
5719
- * ```
5036
+ * @param camera - The camera to look through.
5037
+ * @param point - The world-space point.
5038
+ * @param viewportWidth - The viewport width, in pixels.
5039
+ * @param viewportHeight - The viewport height, in pixels.
5040
+ * @param out - Receives the pixel position and the clip depth.
5041
+ * @returns `true` when the point is in front of the camera; `false` when it is behind it, in which
5042
+ * case `out` holds the mirrored projection and should be ignored.
5720
5043
  *
5721
5044
  * @internal
5722
5045
  */
5723
- function createCameraUnderNode(parent) {
5724
- const camera = createFreeCamera({
5725
- x: 0,
5726
- y: 0,
5727
- z: 0
5728
- }, {
5729
- x: 0,
5730
- y: 0,
5731
- z: 1
5732
- });
5733
- camera.parent = parent;
5734
- return camera;
5046
+ function worldToScreen(camera, point, viewportWidth, viewportHeight, out) {
5047
+ const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);
5048
+ const x = point.x;
5049
+ const y = point.y;
5050
+ const z = point.z;
5051
+ const clipX = element(viewProjection, 0) * x + element(viewProjection, 4) * y + element(viewProjection, 8) * z + element(viewProjection, 12);
5052
+ const clipY = element(viewProjection, 1) * x + element(viewProjection, 5) * y + element(viewProjection, 9) * z + element(viewProjection, 13);
5053
+ const clipZ = element(viewProjection, 2) * x + element(viewProjection, 6) * y + element(viewProjection, 10) * z + element(viewProjection, 14);
5054
+ const clipW = element(viewProjection, 3) * x + element(viewProjection, 7) * y + element(viewProjection, 11) * z + element(viewProjection, 15);
5055
+ if (clipW === 0) {
5056
+ out.x = 0;
5057
+ out.y = 0;
5058
+ out.z = 0;
5059
+ return false;
5060
+ }
5061
+ const inverseW = 1 / clipW;
5062
+ out.x = (clipX * inverseW + 1) * .5 * viewportWidth;
5063
+ out.y = (1 - clipY * inverseW) * .5 * viewportHeight;
5064
+ out.z = clipZ * inverseW;
5065
+ return clipW > 0;
5735
5066
  }
5736
5067
  /**
5737
- * Re-parents a camera, keeping its local position and target — the entity's node defines the view.
5068
+ * Reads one element of a matrix-like value.
5738
5069
  *
5739
5070
  * @remarks
5740
- * Unlike `linkParent` in `./node.ts` this does not maintain the parent's `children` array. Lite
5741
- * types `SceneNode.children` as `SceneNode[]` and a camera is not a scene node; nothing in Lite
5742
- * walks an ignifx transform node's children either, because ignifx transform nodes are never added
5743
- * to a scene (`docs/architecture/02-scene-graph.md` §5.1). The `parent` link alone is what
5744
- * `worldMatrix` reads.
5745
- *
5746
- * @param camera - The camera to move.
5747
- * @param parent - The new parent node, or `null` to detach the camera to world space.
5071
+ * `noUncheckedIndexedAccess` widens every index read to `number | undefined`, and a matrix has no
5072
+ * holes, so the fallback is unreachable. Funnelling every read through one function keeps that
5073
+ * single dead branch in one place instead of scattering thirty of them through the hot paths.
5748
5074
  *
5749
- * @internal
5075
+ * @param matrix - The matrix to read.
5076
+ * @param index - The column-major element index, 0 to 15.
5077
+ * @returns The element.
5750
5078
  */
5751
- function setCameraParent(camera, parent) {
5752
- camera.parent = parent;
5079
+ function element(matrix, index) {
5080
+ return matrix[index] ?? 0;
5753
5081
  }
5754
5082
  /**
5755
- * Switches a camera to a perspective projection with the given vertical field of view.
5756
- *
5757
- * @param camera - The camera to configure.
5758
- * @param fovDegrees - The vertical field of view, in degrees.
5083
+ * Unprojects one normalized device coordinate through an inverse view-projection matrix.
5759
5084
  *
5760
- * @internal
5085
+ * @param inverse - The inverted view-projection matrix.
5086
+ * @param ndcX - The device x, -1 to 1.
5087
+ * @param ndcY - The device y, -1 to 1.
5088
+ * @param depth - The clip depth: `1` for the near plane, `0` for the far plane.
5089
+ * @param out - Receives the world-space point.
5761
5090
  */
5762
- function setCameraPerspective(camera, fovDegrees) {
5763
- camera.fov = degToRad(fovDegrees);
5764
- if (camera.ortho !== null && camera.ortho !== void 0) disableOrthographicCamera(camera);
5091
+ function unproject(inverse, ndcX, ndcY, depth, out) {
5092
+ const e = inverse.elements;
5093
+ const x = element(e, 0) * ndcX + element(e, 4) * ndcY + element(e, 8) * depth + element(e, 12);
5094
+ const y = element(e, 1) * ndcX + element(e, 5) * ndcY + element(e, 9) * depth + element(e, 13);
5095
+ const z = element(e, 2) * ndcX + element(e, 6) * ndcY + element(e, 10) * depth + element(e, 14);
5096
+ const w = element(e, 3) * ndcX + element(e, 7) * ndcY + element(e, 11) * depth + element(e, 15);
5097
+ const inverseW = w === 0 ? 0 : 1 / w;
5098
+ out[0] = x * inverseW;
5099
+ out[1] = y * inverseW;
5100
+ out[2] = z * inverseW;
5765
5101
  }
5766
5102
  /**
5767
- * Switches a camera to an orthographic projection of the given half-height.
5768
- *
5769
- * @remarks
5770
- * Only `halfHeight` is set; the four clip planes are left `null` so Lite derives them from the
5771
- * half-height and the render target's aspect ratio (`OrthographicBounds`, `index.d.ts` 7803),
5772
- * which is the behaviour `Camera.orthographicSize` promises. Calling this twice replaces the
5773
- * bounds object, so the adapter keeps the returned handle and mutates it through
5774
- * {@link setCameraOrthographicSize} instead.
5775
- *
5776
- * @param camera - The camera to configure.
5777
- * @param halfHeight - Half of the visible height, in metres.
5778
- * @returns The live bounds object; assigning to its fields takes effect on the next frame.
5103
+ * Copies 16 matrix elements into an output sink.
5779
5104
  *
5780
- * @internal
5105
+ * @param source - The matrix to read.
5106
+ * @param out - The sink to write.
5107
+ * @returns `out`.
5781
5108
  */
5782
- function setCameraOrthographic(camera, halfHeight) {
5783
- const existing = camera.ortho;
5784
- if (existing !== null && existing !== void 0) {
5785
- existing.halfHeight = halfHeight;
5786
- return existing;
5787
- }
5788
- return enableOrthographicCamera(camera, { halfHeight });
5109
+ function copyMatrix(source, out) {
5110
+ for (let i = 0; i < 16; i++) out[i] = element(source, i);
5111
+ return out;
5789
5112
  }
5113
+ //#endregion
5114
+ //#region src/lite/picking.ts
5790
5115
  /**
5791
- * Changes the half-height of an orthographic camera. Halving it doubles the zoom.
5116
+ * Creates a reusable ray, pointing along `+Z` from the origin.
5792
5117
  *
5793
- * @param bounds - The bounds {@link setCameraOrthographic} returned.
5794
- * @param halfHeight - The new half-height, in metres.
5118
+ * @returns A fresh ray. **Allocates** — create one per picking site, not per pick.
5119
+ *
5120
+ * @example
5121
+ * ```ts
5122
+ * const ray = createPickRay();
5123
+ * screenToRay(camera, x, y, width, height, ray);
5124
+ * const hit = raycastScene(scene, ray);
5125
+ * ```
5795
5126
  *
5796
5127
  * @internal
5797
5128
  */
5798
- function setCameraOrthographicSize(bounds, halfHeight) {
5799
- bounds.halfHeight = halfHeight;
5129
+ function createPickRay() {
5130
+ return {
5131
+ origin: [
5132
+ 0,
5133
+ 0,
5134
+ 0
5135
+ ],
5136
+ direction: [
5137
+ 0,
5138
+ 0,
5139
+ 1
5140
+ ],
5141
+ length: Number.MAX_VALUE
5142
+ };
5800
5143
  }
5801
5144
  /**
5802
- * Sets the near and far clip planes.
5145
+ * Points a ray at a world-space origin and direction, in place.
5803
5146
  *
5804
- * @param camera - The camera to configure.
5805
- * @param near - The near plane distance, in metres.
5806
- * @param far - The far plane distance, in metres.
5147
+ * @param ray - The ray to rewrite.
5148
+ * @param originX - The world-space origin x.
5149
+ * @param originY - The world-space origin y.
5150
+ * @param originZ - The world-space origin z.
5151
+ * @param directionX - The direction x; it need not be normalized.
5152
+ * @param directionY - The direction y.
5153
+ * @param directionZ - The direction z.
5154
+ * @param length - How far the ray reaches, in metres.
5807
5155
  *
5808
5156
  * @internal
5809
5157
  */
5810
- function setCameraClipPlanes(camera, near, far) {
5811
- camera.nearPlane = near;
5812
- camera.farPlane = far;
5158
+ function setPickRay(ray, originX, originY, originZ, directionX, directionY, directionZ, length) {
5159
+ const origin = ray.origin;
5160
+ origin[0] = originX;
5161
+ origin[1] = originY;
5162
+ origin[2] = originZ;
5163
+ const magnitude = Math.hypot(directionX, directionY, directionZ);
5164
+ const scale = magnitude > 0 ? 1 / magnitude : 0;
5165
+ const direction = ray.direction;
5166
+ direction[0] = directionX * scale;
5167
+ direction[1] = directionY * scale;
5168
+ direction[2] = directionZ * scale;
5169
+ ray.length = length;
5813
5170
  }
5814
5171
  /**
5815
- * Sets the camera's normalized viewport, in Babylon's convention: the origin is the **bottom** left
5816
- * of the render target.
5172
+ * Casts a ray against every renderable mesh in a scene, on the CPU.
5817
5173
  *
5818
5174
  * @remarks
5819
- * The viewport object is reused when one is already installed, so a per-frame viewport animation
5820
- * allocates nothing (coding standards §7).
5175
+ * This is `world.raycastRender`. It is distinct from a physics raycast
5176
+ * (`docs/architecture/09-physics.md` §5): it hits render geometry, including meshes that carry no
5177
+ * collider.
5821
5178
  *
5822
- * @param camera - The camera to configure.
5823
- * @param x - The left edge, 0 to 1.
5824
- * @param y - The bottom edge, 0 to 1.
5825
- * @param width - The width, 0 to 1.
5826
- * @param height - The height, 0 to 1.
5179
+ * @param scene - The render scene.
5180
+ * @param ray - The ray to cast.
5181
+ * @param options - An optional mesh predicate.
5182
+ * @returns Lite's picking info. Check `hit` before reading anything else. **Allocates** one result
5183
+ * object per call — Lite builds it.
5827
5184
  *
5828
5185
  * @internal
5829
5186
  */
5830
- function setCameraViewport(camera, x, y, width, height) {
5831
- const existing = camera.viewport;
5832
- if (existing === void 0) {
5833
- camera.viewport = {
5834
- x,
5835
- y,
5836
- width,
5837
- height
5838
- };
5839
- return;
5840
- }
5841
- existing.x = x;
5842
- existing.y = y;
5843
- existing.width = width;
5844
- existing.height = height;
5187
+ function raycastScene(scene, ray, options) {
5188
+ return pickWithRay(scene, ray, options);
5845
5189
  }
5846
5190
  /**
5847
- * Resolves a camera's normalized viewport to integer render-target pixels.
5191
+ * Casts a ray against a scene's renderable meshes, considering only the meshes whose ignifx tag a
5192
+ * predicate accepts.
5848
5193
  *
5849
5194
  * @remarks
5850
- * Lite flips the y axis here: the normalized viewport measures `y` from the bottom (Babylon), the
5851
- * pixel viewport measures it from the top (WebGPU). Verified in `lib/camera/viewport.js`, which
5852
- * computes `y = floor(clamp01(1 - v.y - v.height) * targetHeight)`.
5853
- *
5854
- * @param camera - The camera, or `null` for the full target.
5855
- * @param targetWidth - The render target width, in pixels.
5856
- * @param targetHeight - The render target height, in pixels.
5857
- * @returns A fresh pixel viewport. **Allocates** — Lite builds the object; do not call per frame.
5858
- *
5859
- * @internal
5860
- */
5861
- function resolveViewportPixels(camera, targetWidth, targetHeight) {
5862
- return resolveCameraViewport(camera, targetWidth, targetHeight);
5863
- }
5864
- /**
5865
- * The aspect ratio Lite projects with: the render target's ratio scaled by the camera's viewport.
5195
+ * The predicate is stated over the *tag* rather than over Lite's `Mesh` so the component layer can
5196
+ * filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). Lite's own
5197
+ * `pickable === false` exclusion still runs first.
5866
5198
  *
5867
- * @param camera - The camera, or `null` for an unrestricted viewport.
5868
- * @param targetWidth - The render target width, in pixels.
5869
- * @param targetHeight - The render target height, in pixels.
5870
- * @returns Width divided by height.
5199
+ * @param scene - The render scene.
5200
+ * @param ray - The ray to cast.
5201
+ * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.
5202
+ * @returns Lite's picking info.
5871
5203
  *
5872
5204
  * @internal
5873
5205
  */
5874
- function cameraAspectRatio(camera, targetWidth, targetHeight) {
5875
- return getEffectiveAspectRatio(camera, targetWidth, targetHeight);
5206
+ function raycastSceneWhere(scene, ray, accept) {
5207
+ return pickWithRay(scene, ray, { predicate: (mesh) => accept(readNodeTag(mesh)) });
5876
5208
  }
5877
5209
  /**
5878
- * Copies the camera's view matrix (the inverse of its world matrix) into `out`.
5210
+ * Resolves a hit back to the ignifx entity and component that own the mesh.
5879
5211
  *
5880
- * @param camera - The camera to read.
5881
- * @param out - A sink of at least 16 elements, written column-major.
5882
- * @returns `out`, for chaining.
5212
+ * @param info - A result from {@link raycastScene}, {@link raycastMeshes}, or the GPU picker.
5213
+ * @returns The owning entity's tag, or `null` when the ray missed or the mesh is not one ignifx
5214
+ * created (a glTF child node inside a `Model`, for instance, whose tag lives on the model's root).
5883
5215
  *
5884
5216
  * @internal
5885
5217
  */
5886
- function readViewMatrix(camera, out) {
5887
- return copyMatrix(getViewMatrix(camera), out);
5218
+ function readPickedTag(info) {
5219
+ const mesh = info.pickedMesh;
5220
+ if (mesh === null) return null;
5221
+ return readNodeTag(mesh);
5888
5222
  }
5223
+ //#endregion
5224
+ //#region src/schema/types.ts
5889
5225
  /**
5890
- * Copies the camera's projection matrix into `out`.
5891
- *
5892
- * @param camera - The camera to read.
5893
- * @param aspectRatio - Width divided by height, from {@link cameraAspectRatio}.
5894
- * @param out - A sink of at least 16 elements, written column-major.
5895
- * @returns `out`, for chaining.
5226
+ * Field kinds supported by component schemas.
5896
5227
  *
5897
- * @internal
5228
+ * @public
5898
5229
  */
5899
- function readProjectionMatrix(camera, aspectRatio, out) {
5900
- return copyMatrix(getProjectionMatrix(camera, aspectRatio), out);
5901
- }
5230
+ const FieldKind = {
5231
+ /** A 32-bit-ranged floating point number. */
5232
+ f32: "f32",
5233
+ /** A double-precision floating point number. */
5234
+ f64: "f64",
5235
+ /** A signed 32-bit integer. */
5236
+ i32: "i32",
5237
+ /** An unsigned 32-bit integer. */
5238
+ u32: "u32",
5239
+ /** A boolean toggle. */
5240
+ bool: "bool",
5241
+ /** A UTF-8 string. */
5242
+ str: "str",
5243
+ /** A 2D vector. */
5244
+ vec2: "vec2",
5245
+ /** A 3D vector. */
5246
+ vec3: "vec3",
5247
+ /** A 4D vector. */
5248
+ vec4: "vec4",
5249
+ /** A rotation quaternion. */
5250
+ quat: "quat",
5251
+ /** An RGBA color. */
5252
+ color: "color",
5253
+ /** One of a fixed set of string values. */
5254
+ enum: "enum",
5255
+ /** A reference to another entity in the same scene file. */
5256
+ entityRef: "entityRef",
5257
+ /** A reference to a component on an entity in the same scene file. */
5258
+ componentRef: "componentRef",
5259
+ /** A reference to an addressable asset. */
5260
+ asset: "asset",
5261
+ /** A list of values of one kind. */
5262
+ array: "array",
5263
+ /** A fixed group of named sub-fields. */
5264
+ record: "record",
5265
+ /** A string-keyed dictionary of values of one kind. */
5266
+ map: "map",
5267
+ /** A value that may also be `null`. */
5268
+ optional: "optional",
5269
+ /** A set of layer names. */
5270
+ layerMask: "layerMask",
5271
+ /** An animation curve. */
5272
+ curve: "curve",
5273
+ /** A value with a hand-written encoder and decoder. */
5274
+ custom: "custom"
5275
+ };
5276
+ //#endregion
5277
+ //#region src/schema/field-kinds.ts
5902
5278
  /**
5903
- * Makes a camera the one a scene renders through, or clears it.
5904
- *
5905
- * @remarks
5906
- * Lite renders through exactly one camera per scene (`SceneContext.camera`, `index.d.ts` 10072);
5907
- * a scene with no camera draws nothing. Choosing between several enabled ignifx cameras by
5908
- * `priority` is the component layer's job.
5909
- *
5910
- * @param scene - The render scene.
5911
- * @param camera - The camera to render through, or `null` for none.
5279
+ * The default a `vec2()` field takes when none is given.
5912
5280
  *
5913
5281
  * @internal
5914
5282
  */
5915
- function setSceneCamera(scene, camera) {
5916
- scene.camera = camera;
5917
- }
5283
+ const ZERO2 = {
5284
+ x: 0,
5285
+ y: 0
5286
+ };
5918
5287
  /**
5919
- * Builds a world-space ray through a point on the render target.
5920
- *
5921
- * @remarks
5922
- * This reproduces Lite's own `createPickingRay` (`lib/picking/ray.js`), which is not exported from
5923
- * the package, and the coordinate handling of `pickAsync` (`lib/picking/gpu-picker.js` lines
5924
- * 176–193): the pixel is made relative to the camera's **pixel** viewport, the projection uses that
5925
- * viewport's aspect ratio, and the normalized device coordinates are
5926
- * `(2x/w - 1, 1 - 2y/h)`. Because the projection is reverse-depth, clip depth `1` unprojects to the
5927
- * near plane and `0` to the far plane.
5928
- *
5929
- * The ray is written into `out`, so a picking loop allocates nothing.
5930
- *
5931
- * @param camera - The camera to look through.
5932
- * @param x - The pixel x inside the viewport, measured from its left edge.
5933
- * @param y - The pixel y inside the viewport, measured from its top edge.
5934
- * @param viewportWidth - The viewport width, in pixels.
5935
- * @param viewportHeight - The viewport height, in pixels.
5936
- * @param out - The ray to fill.
5937
- * @returns `out` when the ray could be built, or `null` when the view-projection matrix is
5938
- * singular (a zero-sized viewport, or a degenerate projection).
5939
- *
5940
- * @example
5941
- * ```ts
5942
- * const ray: MutableRay = { origin: [0, 0, 0], direction: [0, 0, 1], length: 1 };
5943
- * const viewport = resolveViewportPixels(camera, canvas.width, canvas.height);
5944
- * screenToRay(camera, px - viewport.x, py - viewport.y, viewport.width, viewport.height, ray);
5945
- * ```
5288
+ * The default a `vec3()` field takes when none is given.
5946
5289
  *
5947
5290
  * @internal
5948
5291
  */
5949
- function screenToRay(camera, x, y, viewportWidth, viewportHeight, out) {
5950
- if (viewportWidth <= 0 || viewportHeight <= 0) return null;
5951
- const inverse = inverseViewProjection ??= new Mat4();
5952
- const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);
5953
- if (!Mat4.invertToRef(viewProjection, inverse)) return null;
5954
- const ndcX = 2 * x / viewportWidth - 1;
5955
- const ndcY = 1 - 2 * y / viewportHeight;
5956
- const origin = out.origin;
5957
- const direction = out.direction;
5958
- unproject(inverse, ndcX, ndcY, 1, origin);
5959
- unproject(inverse, ndcX, ndcY, 0, direction);
5960
- const dx = direction[0] - origin[0];
5961
- const dy = direction[1] - origin[1];
5962
- const dz = direction[2] - origin[2];
5963
- const length = Math.sqrt(dx * dx + dy * dy + dz * dz);
5964
- if (!(length > 0)) return null;
5965
- const inverseLength = 1 / length;
5966
- direction[0] = dx * inverseLength;
5967
- direction[1] = dy * inverseLength;
5968
- direction[2] = dz * inverseLength;
5969
- out.length = length;
5970
- return out;
5971
- }
5292
+ const ZERO3 = {
5293
+ x: 0,
5294
+ y: 0,
5295
+ z: 0
5296
+ };
5972
5297
  /**
5973
- * Projects a world-space point onto the render target.
5974
- *
5975
- * @remarks
5976
- * `out.x`/`out.y` are pixels inside the camera's viewport, measured from its **top** left, matching
5977
- * {@link screenToRay}'s input; `out.z` is the clip-space depth, which is `1` at the near plane and
5978
- * `0` at the far plane because Lite's projection is reverse-depth.
5298
+ * The default a `vec4()` field takes when none is given.
5979
5299
  *
5980
- * @param camera - The camera to look through.
5981
- * @param point - The world-space point.
5982
- * @param viewportWidth - The viewport width, in pixels.
5983
- * @param viewportHeight - The viewport height, in pixels.
5984
- * @param out - Receives the pixel position and the clip depth.
5985
- * @returns `true` when the point is in front of the camera; `false` when it is behind it, in which
5986
- * case `out` holds the mirrored projection and should be ignored.
5300
+ * @internal
5301
+ */
5302
+ const ZERO4 = {
5303
+ x: 0,
5304
+ y: 0,
5305
+ z: 0,
5306
+ w: 0
5307
+ };
5308
+ /**
5309
+ * The identity rotation, the default a `quat()` field takes when none is given.
5987
5310
  *
5988
5311
  * @internal
5989
5312
  */
5990
- function worldToScreen(camera, point, viewportWidth, viewportHeight, out) {
5991
- const viewProjection = getViewProjectionMatrix(camera, viewportWidth / viewportHeight);
5992
- const x = point.x;
5993
- const y = point.y;
5994
- const z = point.z;
5995
- const clipX = element(viewProjection, 0) * x + element(viewProjection, 4) * y + element(viewProjection, 8) * z + element(viewProjection, 12);
5996
- const clipY = element(viewProjection, 1) * x + element(viewProjection, 5) * y + element(viewProjection, 9) * z + element(viewProjection, 13);
5997
- const clipZ = element(viewProjection, 2) * x + element(viewProjection, 6) * y + element(viewProjection, 10) * z + element(viewProjection, 14);
5998
- const clipW = element(viewProjection, 3) * x + element(viewProjection, 7) * y + element(viewProjection, 11) * z + element(viewProjection, 15);
5999
- if (clipW === 0) {
6000
- out.x = 0;
6001
- out.y = 0;
6002
- out.z = 0;
6003
- return false;
6004
- }
6005
- const inverseW = 1 / clipW;
6006
- out.x = (clipX * inverseW + 1) * .5 * viewportWidth;
6007
- out.y = (1 - clipY * inverseW) * .5 * viewportHeight;
6008
- out.z = clipZ * inverseW;
6009
- return clipW > 0;
6010
- }
5313
+ const IDENTITY_QUAT = {
5314
+ x: 0,
5315
+ y: 0,
5316
+ z: 0,
5317
+ w: 1
5318
+ };
6011
5319
  /**
6012
- * Reads one element of a matrix-like value.
5320
+ * Opaque white, the default a `color()` field takes when none is given.
6013
5321
  *
6014
- * @remarks
6015
- * `noUncheckedIndexedAccess` widens every index read to `number | undefined`, and a matrix has no
6016
- * holes, so the fallback is unreachable. Funnelling every read through one function keeps that
6017
- * single dead branch in one place instead of scattering thirty of them through the hot paths.
5322
+ * @internal
5323
+ */
5324
+ const WHITE = {
5325
+ r: 1,
5326
+ g: 1,
5327
+ b: 1,
5328
+ a: 1
5329
+ };
5330
+ /**
5331
+ * The default a `curve()` field takes when none is given.
6018
5332
  *
6019
- * @param matrix - The matrix to read.
6020
- * @param index - The column-major element index, 0 to 15.
6021
- * @returns The element.
5333
+ * @internal
6022
5334
  */
6023
- function element(matrix, index) {
6024
- return matrix[index] ?? 0;
6025
- }
5335
+ const EMPTY_CURVE = { keys: [] };
6026
5336
  /**
6027
- * Unprojects one normalized device coordinate through an inverse view-projection matrix.
5337
+ * Matches `#rgb`, `#rgba`, `#rrggbb`, and `#rrggbbaa`.
6028
5338
  *
6029
- * @param inverse - The inverted view-projection matrix.
6030
- * @param ndcX - The device x, -1 to 1.
6031
- * @param ndcY - The device y, -1 to 1.
6032
- * @param depth - The clip depth: `1` for the near plane, `0` for the far plane.
6033
- * @param out - Receives the world-space point.
5339
+ * @internal
6034
5340
  */
6035
- function unproject(inverse, ndcX, ndcY, depth, out) {
6036
- const e = inverse.elements;
6037
- const x = element(e, 0) * ndcX + element(e, 4) * ndcY + element(e, 8) * depth + element(e, 12);
6038
- const y = element(e, 1) * ndcX + element(e, 5) * ndcY + element(e, 9) * depth + element(e, 13);
6039
- const z = element(e, 2) * ndcX + element(e, 6) * ndcY + element(e, 10) * depth + element(e, 14);
6040
- const w = element(e, 3) * ndcX + element(e, 7) * ndcY + element(e, 11) * depth + element(e, 15);
6041
- const inverseW = w === 0 ? 0 : 1 / w;
6042
- out[0] = x * inverseW;
6043
- out[1] = y * inverseW;
6044
- out[2] = z * inverseW;
6045
- }
5341
+ const HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/u;
6046
5342
  /**
6047
- * Copies 16 matrix elements into an output sink.
5343
+ * Assembles a field definition. Centralising construction keeps `kind` and `spec.kind` in step and
5344
+ * keeps every field a plain, frozen-by-convention data object.
6048
5345
  *
6049
- * @param source - The matrix to read.
6050
- * @param out - The sink to write.
6051
- * @returns `out`.
5346
+ * @param spec - The kind-specific data, which also supplies the discriminant.
5347
+ * @param options - Inspector and serializer metadata, if any.
5348
+ * @param createDefault - Factory for a fresh default value.
5349
+ * @returns The field definition.
5350
+ *
5351
+ * @internal
6052
5352
  */
6053
- function copyMatrix(source, out) {
6054
- for (let i = 0; i < 16; i++) out[i] = element(source, i);
6055
- return out;
5353
+ function field(spec, options, createDefault) {
5354
+ return {
5355
+ kind: spec.kind,
5356
+ spec,
5357
+ options: options ?? {},
5358
+ createDefault
5359
+ };
6056
5360
  }
6057
- //#endregion
6058
- //#region src/lite/picking.ts
6059
5361
  /**
6060
- * Creates a reusable ray, pointing along `+Z` from the origin.
6061
- *
6062
- * @returns A fresh ray. **Allocates** — create one per picking site, not per pick.
5362
+ * Parses a CSS-style hexadecimal color into normalized sRGB channels.
6063
5363
  *
6064
- * @example
6065
- * ```ts
6066
- * const ray = createPickRay();
6067
- * screenToRay(camera, x, y, width, height, ray);
6068
- * const hit = raycastScene(scene, ray);
6069
- * ```
6070
- *
6071
- * @internal
6072
- */
6073
- function createPickRay() {
6074
- return {
6075
- origin: [
6076
- 0,
6077
- 0,
6078
- 0
6079
- ],
6080
- direction: [
6081
- 0,
6082
- 0,
6083
- 1
6084
- ],
6085
- length: Number.MAX_VALUE
6086
- };
6087
- }
6088
- /**
6089
- * Points a ray at a world-space origin and direction, in place.
6090
- *
6091
- * @param ray - The ray to rewrite.
6092
- * @param originX - The world-space origin x.
6093
- * @param originY - The world-space origin y.
6094
- * @param originZ - The world-space origin z.
6095
- * @param directionX - The direction x; it need not be normalized.
6096
- * @param directionY - The direction y.
6097
- * @param directionZ - The direction z.
6098
- * @param length - How far the ray reaches, in metres.
6099
- *
6100
- * @internal
6101
- */
6102
- function setPickRay(ray, originX, originY, originZ, directionX, directionY, directionZ, length) {
6103
- const origin = ray.origin;
6104
- origin[0] = originX;
6105
- origin[1] = originY;
6106
- origin[2] = originZ;
6107
- const magnitude = Math.hypot(directionX, directionY, directionZ);
6108
- const scale = magnitude > 0 ? 1 / magnitude : 0;
6109
- const direction = ray.direction;
6110
- direction[0] = directionX * scale;
6111
- direction[1] = directionY * scale;
6112
- direction[2] = directionZ * scale;
6113
- ray.length = length;
6114
- }
6115
- /**
6116
- * Casts a ray against every renderable mesh in a scene, on the CPU.
6117
- *
6118
- * @remarks
6119
- * This is `world.raycastRender`. It is distinct from a physics raycast
6120
- * (`docs/architecture/09-physics.md` §5): it hits render geometry, including meshes that carry no
6121
- * collider.
6122
- *
6123
- * @param scene - The render scene.
6124
- * @param ray - The ray to cast.
6125
- * @param options - An optional mesh predicate.
6126
- * @returns Lite's picking info. Check `hit` before reading anything else. **Allocates** one result
6127
- * object per call — Lite builds it.
6128
- *
6129
- * @internal
6130
- */
6131
- function raycastScene(scene, ray, options) {
6132
- return pickWithRay(scene, ray, options);
6133
- }
6134
- /**
6135
- * Casts a ray against a scene's renderable meshes, considering only the meshes whose ignifx tag a
6136
- * predicate accepts.
6137
- *
6138
- * @remarks
6139
- * The predicate is stated over the *tag* rather than over Lite's `Mesh` so the component layer can
6140
- * filter by entity without naming a Lite type (`CONSTITUTION.md` §3.4). Lite's own
6141
- * `pickable === false` exclusion still runs first.
6142
- *
6143
- * @param scene - The render scene.
6144
- * @param ray - The ray to cast.
6145
- * @param accept - Decides whether a mesh may be picked, from the ignifx tag its node carries.
6146
- * @returns Lite's picking info.
6147
- *
6148
- * @internal
6149
- */
6150
- function raycastSceneWhere(scene, ray, accept) {
6151
- return pickWithRay(scene, ray, { predicate: (mesh) => accept(readNodeTag(mesh)) });
6152
- }
6153
- /**
6154
- * Resolves a hit back to the ignifx entity and component that own the mesh.
6155
- *
6156
- * @param info - A result from {@link raycastScene}, {@link raycastMeshes}, or the GPU picker.
6157
- * @returns The owning entity's tag, or `null` when the ray missed or the mesh is not one ignifx
6158
- * created (a glTF child node inside a `Model`, for instance, whose tag lives on the model's root).
6159
- *
6160
- * @internal
6161
- */
6162
- function readPickedTag(info) {
6163
- const mesh = info.pickedMesh;
6164
- if (mesh === null) return null;
6165
- return readNodeTag(mesh);
6166
- }
6167
- //#endregion
6168
- //#region src/schema/types.ts
6169
- /**
6170
- * Field kinds supported by component schemas.
6171
- *
6172
- * @public
6173
- */
6174
- const FieldKind = {
6175
- /** A 32-bit-ranged floating point number. */
6176
- f32: "f32",
6177
- /** A double-precision floating point number. */
6178
- f64: "f64",
6179
- /** A signed 32-bit integer. */
6180
- i32: "i32",
6181
- /** An unsigned 32-bit integer. */
6182
- u32: "u32",
6183
- /** A boolean toggle. */
6184
- bool: "bool",
6185
- /** A UTF-8 string. */
6186
- str: "str",
6187
- /** A 2D vector. */
6188
- vec2: "vec2",
6189
- /** A 3D vector. */
6190
- vec3: "vec3",
6191
- /** A 4D vector. */
6192
- vec4: "vec4",
6193
- /** A rotation quaternion. */
6194
- quat: "quat",
6195
- /** An RGBA color. */
6196
- color: "color",
6197
- /** One of a fixed set of string values. */
6198
- enum: "enum",
6199
- /** A reference to another entity in the same scene file. */
6200
- entityRef: "entityRef",
6201
- /** A reference to a component on an entity in the same scene file. */
6202
- componentRef: "componentRef",
6203
- /** A reference to an addressable asset. */
6204
- asset: "asset",
6205
- /** A list of values of one kind. */
6206
- array: "array",
6207
- /** A fixed group of named sub-fields. */
6208
- record: "record",
6209
- /** A string-keyed dictionary of values of one kind. */
6210
- map: "map",
6211
- /** A value that may also be `null`. */
6212
- optional: "optional",
6213
- /** A set of layer names. */
6214
- layerMask: "layerMask",
6215
- /** An animation curve. */
6216
- curve: "curve",
6217
- /** A value with a hand-written encoder and decoder. */
6218
- custom: "custom"
6219
- };
6220
- //#endregion
6221
- //#region src/schema/field-kinds.ts
6222
- /**
6223
- * The default a `vec2()` field takes when none is given.
6224
- *
6225
- * @internal
6226
- */
6227
- const ZERO2 = {
6228
- x: 0,
6229
- y: 0
6230
- };
6231
- /**
6232
- * The default a `vec3()` field takes when none is given.
6233
- *
6234
- * @internal
6235
- */
6236
- const ZERO3 = {
6237
- x: 0,
6238
- y: 0,
6239
- z: 0
6240
- };
6241
- /**
6242
- * The default a `vec4()` field takes when none is given.
6243
- *
6244
- * @internal
6245
- */
6246
- const ZERO4 = {
6247
- x: 0,
6248
- y: 0,
6249
- z: 0,
6250
- w: 0
6251
- };
6252
- /**
6253
- * The identity rotation, the default a `quat()` field takes when none is given.
6254
- *
6255
- * @internal
6256
- */
6257
- const IDENTITY_QUAT = {
6258
- x: 0,
6259
- y: 0,
6260
- z: 0,
6261
- w: 1
6262
- };
6263
- /**
6264
- * Opaque white, the default a `color()` field takes when none is given.
6265
- *
6266
- * @internal
6267
- */
6268
- const WHITE = {
6269
- r: 1,
6270
- g: 1,
6271
- b: 1,
6272
- a: 1
6273
- };
6274
- /**
6275
- * The default a `curve()` field takes when none is given.
6276
- *
6277
- * @internal
6278
- */
6279
- const EMPTY_CURVE = { keys: [] };
6280
- /**
6281
- * Matches `#rgb`, `#rgba`, `#rrggbb`, and `#rrggbbaa`.
6282
- *
6283
- * @internal
6284
- */
6285
- const HEX_COLOR_PATTERN = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/u;
6286
- /**
6287
- * Assembles a field definition. Centralising construction keeps `kind` and `spec.kind` in step and
6288
- * keeps every field a plain, frozen-by-convention data object.
6289
- *
6290
- * @param spec - The kind-specific data, which also supplies the discriminant.
6291
- * @param options - Inspector and serializer metadata, if any.
6292
- * @param createDefault - Factory for a fresh default value.
6293
- * @returns The field definition.
6294
- *
6295
- * @internal
6296
- */
6297
- function field(spec, options, createDefault) {
6298
- return {
6299
- kind: spec.kind,
6300
- spec,
6301
- options: options ?? {},
6302
- createDefault
6303
- };
6304
- }
6305
- /**
6306
- * Parses a CSS-style hexadecimal color into normalized sRGB channels.
6307
- *
6308
- * @param hex - `#rgb`, `#rgba`, `#rrggbb`, or `#rrggbbaa`.
6309
- * @returns The parsed color with channels in the 0–1 range.
6310
- * @throws A `TypeError` when the string is not one of the accepted forms.
5364
+ * @param hex - `#rgb`, `#rgba`, `#rrggbb`, or `#rrggbbaa`.
5365
+ * @returns The parsed color with channels in the 0–1 range.
5366
+ * @throws A `TypeError` when the string is not one of the accepted forms.
6311
5367
  *
6312
5368
  * @internal
6313
5369
  */
@@ -7844,7 +6900,7 @@ let layer = null;
7844
6900
  * @internal
7845
6901
  */
7846
6902
  async function loadInstancedMeshSupport() {
7847
- const loaded = layer ?? await import("./instanced-mesh-instance-Cgx1H87p.js");
6903
+ const loaded = layer ?? await import("./instanced-mesh-instance-DYwH0vLi.js");
7848
6904
  layer = loaded;
7849
6905
  return loaded;
7850
6906
  }
@@ -7872,7 +6928,7 @@ let surfaceLayer = null;
7872
6928
  * @internal
7873
6929
  */
7874
6930
  async function loadShaderSupport() {
7875
- const loaded = shaderLayer ?? await import("./shader-material-CJxMJEUO.js").then((n) => n.n);
6931
+ const loaded = shaderLayer ?? await import("./shader-material-BIG3UDyu.js").then((n) => n.n);
7876
6932
  shaderLayer = loaded;
7877
6933
  await loaded.loadShaderMaterialAdapter();
7878
6934
  return loaded;
@@ -7895,7 +6951,7 @@ function shaderSupport() {
7895
6951
  * @internal
7896
6952
  */
7897
6953
  async function loadSurfaceShaderSupport() {
7898
- const loaded = surfaceLayer ?? await import("./surface-shader-Chs7wOAE.js");
6954
+ const loaded = surfaceLayer ?? await import("./surface-shader-Br17yysO.js");
7899
6955
  surfaceLayer = loaded;
7900
6956
  return loaded;
7901
6957
  }
@@ -8115,6 +7171,28 @@ var MaterialAsset = class {
8115
7171
  return surfaceShaderSupport()?.surfaceShaders(this) ?? [];
8116
7172
  }
8117
7173
  /**
7174
+ * How far, in world metres, drawing with this material may move a vertex: the shader's
7175
+ * `// @ignifx displace`, or the sum over the enabled surface shaders. Renderers widen their
7176
+ * bounds by it.
7177
+ *
7178
+ * @returns The distance; `0` for a material whose vertex stage moves nothing.
7179
+ *
7180
+ * @internal
7181
+ */
7182
+ get displacement() {
7183
+ const shader = this.#shader;
7184
+ if (shader !== null) return shader.shader.declaration.displace;
7185
+ const support = surfaceShaderSupport();
7186
+ if (support === null) return 0;
7187
+ const bindings = support.surfaceShaders(this);
7188
+ let total = 0;
7189
+ for (let index = 0; index < bindings.length; index += 1) {
7190
+ const binding = bindings[index];
7191
+ if (binding?.enabled === true) total += binding.shader.declaration.displace;
7192
+ }
7193
+ return total;
7194
+ }
7195
+ /**
8118
7196
  * One attached surface shader, by the name it answers to — the `.surface.wgsl` basename unless the
8119
7197
  * material renamed it.
8120
7198
  *
@@ -9805,25 +8883,26 @@ function canWarmUp(material) {
9805
8883
  *
9806
8884
  * Everything here is `@internal`.
9807
8885
  *
9808
- * ## Why the render layer has to know (verified against `@babylonjs/lite@1.27.0`)
8886
+ * ## Why the render layer has to know (verified against `@babylonjs/lite@1.34.0`)
9809
8887
  *
9810
8888
  * Lite registers the PBR skinning and morph-target shader fragments only inside a full build of
9811
8889
  * the PBR group, and only when that build contains a skinned or morphed mesh (`buildPbrRenderables`,
9812
- * `lib/material/pbr/pbr-renderable.js` 114-117). A mesh added after `registerScene` to a PBR group
8890
+ * `lib/material/pbr/pbr-renderable.js` 112). A mesh added after `registerScene` to a PBR group
9813
8891
  * that already exists is built at once by the group's `rebuildSingle` instead
9814
- * (`processMaterialSwaps`, `lib/scene/scene-material-swap.js` 22-45), and that never registers
8892
+ * (`processMaterialSwaps`, `lib/scene/scene-material-swap.js` 4-45), and that never registers
9815
8893
  * them. ignifx's warm-up builds the PBR group at start whenever the scene has a light (ADR-0014).
9816
8894
  *
9817
8895
  * So the first skinned model a page adds after `app.start()` is composed without its skinning
9818
8896
  * fragment, and Lite caches that bind-group layout under a key that does not say which fragments
9819
- * were registered (`getOrCreatePbrBindings`, `lib/material/pbr/pbr-pipeline.js` 33-36). The next
8897
+ * were registered (`getOrCreatePbrBindings`, `lib/material/pbr/pbr-pipeline.js` 59-63). The next
9820
8898
  * renderable rebuild registers the fragment, reuses the cached layout, and builds a bind group with
9821
8899
  * one more entry than it: WebGPU rejects every frame from then on ("Binding entry sampler not set",
9822
8900
  * group 1, entries[3]) and the canvas stays black. The fragments are registered process-wide, so
9823
8901
  * every later app in the page was fine.
9824
8902
  *
9825
8903
  * The render sync system compares what this reports with what a full build has already composed,
9826
- * and clears Lite's layout caches before the rebuild that first sees a new kind. Until that
8904
+ * and clears Lite's layout caches (`forgetMaterialBindingLayouts`, `./shadow.ts`) before the
8905
+ * rebuild that first sees a new kind. Until that
9827
8906
  * rebuild, one frame after the mesh arrives, a skinned mesh draws in its bind pose; a morphed one
9828
8907
  * gets a shader that does not compile, so WebGPU rejects that frame or two.
9829
8908
  */
@@ -10215,13 +9294,317 @@ function disposeSceneOnly(scene) {
10215
9294
  disposeScene(scene);
10216
9295
  }
10217
9296
  //#endregion
10218
- //#region src/render/gpu/renderer-gpu.ts
9297
+ //#region src/lite/shadow.ts
10219
9298
  /**
10220
- * The device-only half of `app.renderer` (`docs/architecture/07-rendering.md` §1, §3, §5).
9299
+ * The shadow techniques Lite offers, in the order `docs/architecture/07-rendering.md` §2.2 lists them.
10221
9300
  *
10222
- * Everything here fails or answers nothing under the null engine — a picker needs a device and a
10223
- * rendered frame, a warm-up probe needs vertex buffers, GPU timing needs `timestamp-query`, and a
10224
- * surface's backing store needs a canvas — so it lives under `src/render/gpu/`, which the root
9301
+ * @public
9302
+ */
9303
+ const SHADOW_TECHNIQUES = [
9304
+ "esm",
9305
+ "pcf",
9306
+ "csm"
9307
+ ];
9308
+ /**
9309
+ * Refuses to build a shadow generator for a light kind Lite cannot shadow.
9310
+ *
9311
+ * @remarks
9312
+ * Lite has no point-light (cube) shadow generator and no area lights
9313
+ * (`docs/architecture/07-rendering.md` §8). Hemispheric lights have no position or frustum at all.
9314
+ *
9315
+ * @param lightType - The Lite `lightType` discriminant of the light.
9316
+ * @throws IgnifxError with code `IGX-0703` for any light kind other than `directional` or `spot`.
9317
+ *
9318
+ * @example
9319
+ * ```ts
9320
+ * assertShadowsSupported(light.lightType); // throws IGX-0703 for "point"
9321
+ * ```
9322
+ *
9323
+ * @internal
9324
+ */
9325
+ function assertShadowsSupported(lightType) {
9326
+ if (lightType === "directional" || lightType === "spot") return;
9327
+ throw new IgnifxError(CoreErrorCode.shadowsUnsupportedForLight, `Babylon Lite has no shadow generator for a ${lightType} light.`, {
9328
+ context: { lightType },
9329
+ hint: "Cast shadows from a directional or spot light instead."
9330
+ });
9331
+ }
9332
+ /**
9333
+ * Turns shadows on for a light by attaching its generator.
9334
+ *
9335
+ * @param light - The light that should cast shadows.
9336
+ * @param generator - A generator built for that light by `./gpu/shadow-generator.ts`.
9337
+ *
9338
+ * @internal
9339
+ */
9340
+ function attachShadowGenerator(light, generator) {
9341
+ light.shadowGenerator = generator;
9342
+ }
9343
+ /**
9344
+ * Turns shadows off for a light.
9345
+ *
9346
+ * @remarks
9347
+ * This only breaks the link. The generator's GPU resources are released when the scene disposes it
9348
+ * through {@link disposeShadowGenerator}.
9349
+ *
9350
+ * @param light - The light that should stop casting shadows.
9351
+ *
9352
+ * @internal
9353
+ */
9354
+ function detachShadowGenerator(light) {
9355
+ delete light.shadowGenerator;
9356
+ }
9357
+ /**
9358
+ * Replaces the list of meshes a generator renders into its shadow map.
9359
+ *
9360
+ * @remarks
9361
+ * Lite keys the list by array identity and re-preloads the shadow pipeline every time a **new**
9362
+ * array arrives, skipping the generator until that finishes. Callers therefore build the list once
9363
+ * per change, never per frame.
9364
+ *
9365
+ * @param generator - The shadow generator.
9366
+ * @param casters - The meshes that cast into it.
9367
+ *
9368
+ * @internal
9369
+ */
9370
+ function setShadowCasters(generator, casters) {
9371
+ setShadowTaskCasterMeshes(generator, casters);
9372
+ }
9373
+ /**
9374
+ * Creates an empty record of a scene's material cache resets.
9375
+ *
9376
+ * @returns The record; install it with {@link trackMaterialCacheResets}.
9377
+ *
9378
+ * @internal
9379
+ */
9380
+ function createMaterialCacheResets() {
9381
+ return {
9382
+ found: /* @__PURE__ */ new Set(),
9383
+ seen: /* @__PURE__ */ new WeakSet(),
9384
+ unconfirmed: false
9385
+ };
9386
+ }
9387
+ /**
9388
+ * Starts recording what the scene's disposer list is handed, for the scene's lifetime.
9389
+ *
9390
+ * @remarks
9391
+ * Call it before the scene is registered, so the builds `registerScene` runs are seen too. It is
9392
+ * idempotent. An own `push` shadows `Array.prototype.push` on that one array; Lite only ever appends
9393
+ * to it with `push`.
9394
+ *
9395
+ * @param scene - The scene.
9396
+ * @param resets - Where to record.
9397
+ *
9398
+ * @internal
9399
+ */
9400
+ function trackMaterialCacheResets(scene, resets) {
9401
+ const disposables = scene._disposables;
9402
+ if (disposables === void 0 || Object.hasOwn(disposables, "push")) return;
9403
+ Object.defineProperty(disposables, "push", {
9404
+ configurable: true,
9405
+ writable: true,
9406
+ value: (...items) => {
9407
+ for (const item of items) if (disposables.includes(item)) resets.found.add(item);
9408
+ else if (!resets.seen.has(item)) {
9409
+ resets.seen.add(item);
9410
+ resets.unconfirmed = true;
9411
+ }
9412
+ return Array.prototype.push.apply(disposables, items);
9413
+ }
9414
+ });
9415
+ }
9416
+ /**
9417
+ * Rebuilds every material group of a registered scene so renderables pick up the current light and
9418
+ * shadow topology.
9419
+ *
9420
+ * @remarks
9421
+ * Renderables bake the per-mesh light index list, the single- versus multi-light shader
9422
+ * permutation, and each generator's shadow bind group at build time; none of that follows a light
9423
+ * being added, removed, or given a generator (`rebuildSceneRenderables`, `index.d.ts` 11165). The
9424
+ * call is a no-op before the scene's first build, and it is expensive, so the component layer
9425
+ * coalesces every topology change in a frame into one call.
9426
+ *
9427
+ * With `resets`, a rebuild that built a material family for the first time rebuilds once more
9428
+ * straight away, so the family's cache reset is known before anything needs it; see
9429
+ * {@link MaterialCacheResets}.
9430
+ *
9431
+ * @param scene - The scene to rebuild.
9432
+ * @param resets - The scene's record of cache resets.
9433
+ * @returns A promise that resolves when the rebuild has finished.
9434
+ *
9435
+ * @internal
9436
+ */
9437
+ async function rebuildRenderables(scene, resets) {
9438
+ if (resets === void 0) {
9439
+ await rebuildSceneRenderables(scene);
9440
+ return;
9441
+ }
9442
+ trackMaterialCacheResets(scene, resets);
9443
+ takeUnconfirmed(resets);
9444
+ await rebuildSceneRenderables(scene);
9445
+ if (takeUnconfirmed(resets)) await rebuildSceneRenderables(scene);
9446
+ }
9447
+ /**
9448
+ * Reads and clears {@link MaterialCacheResets.unconfirmed}.
9449
+ *
9450
+ * @param resets - The record.
9451
+ * @returns Whether a never-seen function was pushed since the flag was last cleared.
9452
+ */
9453
+ function takeUnconfirmed(resets) {
9454
+ const unconfirmed = resets.unconfirmed;
9455
+ resets.unconfirmed = false;
9456
+ return unconfirmed;
9457
+ }
9458
+ /**
9459
+ * Rebuilds a freshly registered scene once when its registration built anything, so Lite pushes
9460
+ * its cache resets again and {@link forgetMaterialBindingLayouts} can call them from the first
9461
+ * frame on.
9462
+ *
9463
+ * @remarks
9464
+ * Nothing has changed since registration, so every pipeline and layout comes from Lite's caches and
9465
+ * the rebuild only re-creates uniform buffers and bind groups.
9466
+ *
9467
+ * @param scene - The registered scene.
9468
+ * @param resets - The scene's record, installed with {@link trackMaterialCacheResets} before
9469
+ * registration.
9470
+ * @returns A promise that resolves when the rebuild has finished.
9471
+ *
9472
+ * @internal
9473
+ */
9474
+ async function learnMaterialCacheResets(scene, resets) {
9475
+ if (resets.unconfirmed) await rebuildRenderables(scene, resets);
9476
+ }
9477
+ /**
9478
+ * How many times the scene's materials have been rebuilt.
9479
+ *
9480
+ * @remarks
9481
+ * An ESM generator keeps the caster views it built for a caster array until it is handed a
9482
+ * different array, whatever happens to the materials (`ensureEsmShadowTaskState`,
9483
+ * `lib/shadow/esm-directional-shadow-generator.js` 121-126; PCF and CSM compare each material's
9484
+ * `_csmGen` instead). So a surface shader switched on or off went on drawing the old shape into an
9485
+ * ESM map. The render sync system re-supplies the caster lists whenever this moves.
9486
+ *
9487
+ * @param scene - The scene.
9488
+ * @returns The counter; `0` before anything was built.
9489
+ *
9490
+ * @internal
9491
+ */
9492
+ function readMaterialEpoch(scene) {
9493
+ return scene._materialEpoch ?? 0;
9494
+ }
9495
+ /**
9496
+ * Makes the next renderable rebuild create fresh bind-group layouts for every material.
9497
+ *
9498
+ * @remarks
9499
+ * Call it before {@link rebuildRenderables} whenever a light gained or lost a shadow generator,
9500
+ * and when the scene gained its first skinned or morphed PBR mesh (`./pbr-deformers.ts`).
9501
+ * Lite caches a PBR material's bindings, shadow bind-group layout included, under a key that does
9502
+ * not name the shadow maps (`getOrCreatePbrBindings`, `lib/material/pbr/pbr-pipeline.js` 59-63).
9503
+ * So after the number of shadow-casting lights changes, a rebuild reuses a layout sized for the old
9504
+ * number and builds a bind group for the new one, and WebGPU rejects every frame ("Number of
9505
+ * entries (3) did not match the expected number of entries (6)"). Clearing the caches costs one
9506
+ * pipeline rebuild per material, only on a frame whose shadow casters changed.
9507
+ *
9508
+ * @param resets - The resets the scene's rebuilds identified; see {@link MaterialCacheResets}.
9509
+ *
9510
+ * @internal
9511
+ */
9512
+ function forgetMaterialBindingLayouts(resets) {
9513
+ for (const reset of resets.found) reset();
9514
+ }
9515
+ /**
9516
+ * Releases a shadow generator's GPU resources and unlinks it from its light.
9517
+ *
9518
+ * @remarks
9519
+ * `removeFromScene` recognises a shadow generator by its private `_shadowType`/`_light` fields
9520
+ * (`lib/scene/scene-remove.js`), clears `light.shadowGenerator`, marks the scene's light topology
9521
+ * dirty, and queues the generator's task for disposal after the GPU has drained.
9522
+ *
9523
+ * @param scene - The scene the generator was rendering into.
9524
+ * @param generator - The generator to release.
9525
+ *
9526
+ * @internal
9527
+ */
9528
+ function disposeShadowGenerator(scene, generator) {
9529
+ removeFromScene(scene, generator);
9530
+ }
9531
+ /**
9532
+ * Maps the shared settings onto an exponential shadow map's configuration.
9533
+ *
9534
+ * @param settings - The declared settings.
9535
+ * @returns Lite's configuration, with every field the caller left out omitted.
9536
+ *
9537
+ * @internal
9538
+ */
9539
+ function toEsmConfig(settings) {
9540
+ const config = {};
9541
+ if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
9542
+ if (settings.bias !== void 0) config.bias = settings.bias;
9543
+ if (settings.darkness !== void 0) config.darkness = settings.darkness;
9544
+ return config;
9545
+ }
9546
+ /**
9547
+ * Maps the shared settings onto a percentage-closer-filtered directional shadow map's configuration.
9548
+ *
9549
+ * @param settings - The declared settings.
9550
+ * @returns Lite's configuration.
9551
+ *
9552
+ * @internal
9553
+ */
9554
+ function toPcfConfig(settings) {
9555
+ const config = {};
9556
+ if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
9557
+ if (settings.bias !== void 0) config.bias = settings.bias;
9558
+ if (settings.normalBias !== void 0) config.normalBias = settings.normalBias;
9559
+ if (settings.darkness !== void 0) config.darkness = settings.darkness;
9560
+ return config;
9561
+ }
9562
+ /**
9563
+ * Maps the shared settings onto a cascaded shadow map's configuration.
9564
+ *
9565
+ * @remarks
9566
+ * `cascades` becomes `numCascades` and `maxDistance` becomes `shadowMaxZ`; Lite clamps the cascade
9567
+ * count to four (`index.d.ts` 3515).
9568
+ *
9569
+ * @param settings - The declared settings.
9570
+ * @returns Lite's configuration.
9571
+ *
9572
+ * @internal
9573
+ */
9574
+ function toCsmConfig(settings) {
9575
+ const config = {};
9576
+ if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
9577
+ if (settings.bias !== void 0) config.bias = settings.bias;
9578
+ if (settings.darkness !== void 0) config.darkness = settings.darkness;
9579
+ if (settings.cascades !== void 0) config.numCascades = settings.cascades;
9580
+ if (settings.maxDistance !== void 0) config.shadowMaxZ = settings.maxDistance;
9581
+ return config;
9582
+ }
9583
+ /**
9584
+ * Maps the shared settings onto a spot light's shadow configuration.
9585
+ *
9586
+ * @param settings - The declared settings.
9587
+ * @returns Lite's configuration.
9588
+ *
9589
+ * @internal
9590
+ */
9591
+ function toSpotConfig(settings) {
9592
+ const config = {};
9593
+ if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
9594
+ if (settings.bias !== void 0) config.bias = settings.bias;
9595
+ if (settings.normalBias !== void 0) config.normalBias = settings.normalBias;
9596
+ if (settings.darkness !== void 0) config.darkness = settings.darkness;
9597
+ if (settings.maxDistance !== void 0) config.far = settings.maxDistance;
9598
+ return config;
9599
+ }
9600
+ //#endregion
9601
+ //#region src/render/gpu/renderer-gpu.ts
9602
+ /**
9603
+ * The device-only half of `app.renderer` (`docs/architecture/07-rendering.md` §1, §3, §5).
9604
+ *
9605
+ * Everything here fails or answers nothing under the null engine — a picker needs a device and a
9606
+ * rendered frame, a warm-up probe needs vertex buffers, GPU timing needs `timestamp-query`, and a
9607
+ * surface's backing store needs a canvas — so it lives under `src/render/gpu/`, which the root
10225
9608
  * Vitest coverage config excludes for the same reason it excludes `src/lite/gpu/`. `RendererImpl`
10226
9609
  * keeps every headless guard, and the browser project measures these lines.
10227
9610
  */
@@ -10775,6 +10158,8 @@ var RendererImpl = class {
10775
10158
  * this engine. A kind missing from it gets fresh layouts on its first rebuild (`../lite/pbr-deformers.ts`).
10776
10159
  */
10777
10160
  builtPbrDeformers = 0;
10161
+ /** Lite's material cache resets, as this scene's rebuilds identified them (`../lite/shadow.ts`). */
10162
+ materialCacheResets = createMaterialCacheResets();
10778
10163
  /** `true` once a camera was added, removed, enabled, disabled, or re-prioritised. */
10779
10164
  needsCameraSelect = true;
10780
10165
  /** `true` once the world has been told it has no enabled camera, so `IGX-0706` is logged once. */
@@ -11684,6 +11069,7 @@ var InstancedMeshRenderer = class InstancedMeshRenderer extends Component {
11684
11069
  this.#hasAppliedSettings = true;
11685
11070
  const instance = this.#instance;
11686
11071
  if (instance === null) return changed;
11072
+ instance.applyDisplacement(this.#upload, this.#displacement(), this.entity.transform);
11687
11073
  const uploaded = instance.sync(this.#upload, this.#material(renderer), this.receiveShadows, this.renderOrder, this.pickable, this.lod, this.#matrices ?? noMatrices(), this.#count, this.#colors, this.castShadows, this.isEnabledInHierarchy);
11688
11074
  return changed || uploaded;
11689
11075
  }
@@ -11824,6 +11210,15 @@ var InstancedMeshRenderer = class InstancedMeshRenderer extends Component {
11824
11210
  return declared?.state === "loaded" ? declared.value.lite.material : renderer.defaultMaterial().lite.material;
11825
11211
  }
11826
11212
  /**
11213
+ * How far the material's vertex stage may move a vertex: its shaders' `// @ignifx displace`.
11214
+ *
11215
+ * @returns The distance in world metres; `0` for the default material or one still loading.
11216
+ */
11217
+ #displacement() {
11218
+ const declared = this.materials[0];
11219
+ return declared?.state === "loaded" ? declared.value.displacement : 0;
11220
+ }
11221
+ /**
11827
11222
  * Removes the meshes from the scene, when there are any.
11828
11223
  *
11829
11224
  * @param renderer - The rendering service, for the scene.
@@ -12008,10 +11403,10 @@ function createHemisphericLightInWorld(intensity) {
12008
11403
  * from, in the one place every consumer reads them.
12009
11404
  *
12010
11405
  * @remarks
12011
- * The light's world matrix is its local matrix (there is no parent), so `worldMatrix[8..10]` — what
12012
- * the shader reads as the direction — is exactly what was written to `direction`,
12013
- * `worldMatrix[12..14]` — what a spot light reports as its position — is exactly `position`, and
12014
- * `computeDirectionalLightMatrix` fits the shadow frustum from the same two vectors.
11406
+ * The light has no parent and an identity rotation, so its world matrix is a pure translation:
11407
+ * the world direction Lite derives from `direction` is `direction` itself, and `worldMatrix[12..14]`
11408
+ * — where a point or spot light shines from, and where the shadow frustum is fitted from — is
11409
+ * exactly `position`.
12015
11410
  *
12016
11411
  * Each kind is written only what it uses, and each kind reads a different axis of the entity:
12017
11412
  *
@@ -12021,8 +11416,8 @@ function createHemisphericLightInWorld(intensity) {
12021
11416
  * | `point` | — | yes |
12022
11417
  * | `hemispheric` | the entity's world **up**: it is a sky direction, not a beam | — |
12023
11418
  *
12024
- * Both writes fire `ObservableVec3`'s dirty hook, so the lights uniform buffer re-uploads without a
12025
- * separate {@link markLightTransformDirty}.
11419
+ * Both writes bump the light's `_lightVersion`, so the lights uniform buffer re-uploads and a
11420
+ * shadow refits without a separate {@link markLightTransformDirty}.
12026
11421
  *
12027
11422
  * @param light - The light to pose.
12028
11423
  * @param forwardX - The entity's world-space forward x.
@@ -12163,7 +11558,7 @@ function setSpotExponent(light, exponent) {
12163
11558
  *
12164
11559
  * @remarks
12165
11560
  * Lite matches on `Mesh.id`, a string a loader or the adapter assigns; the include list wins over
12166
- * the exclude list when both are present (`lib/render/lights-ubo.js`, `affectsMesh`).
11561
+ * the exclude list when both are present (`lib/render/mesh-light-selection.js`, `affectsMesh`).
12167
11562
  *
12168
11563
  * @param light - The light to restrict.
12169
11564
  * @param meshIds - The mesh ids that may be lit, or `null` to light everything.
@@ -12236,230 +11631,9 @@ function markLightDirty(light) {
12236
11631
  }
12237
11632
  }
12238
11633
  //#endregion
12239
- //#region src/lite/shadow.ts
11634
+ //#region src/lite/shadow-caster-shapes.ts
12240
11635
  /**
12241
- * The shadow techniques Lite offers, in the order `docs/architecture/07-rendering.md` §2.2 lists them.
12242
- *
12243
- * @public
12244
- */
12245
- const SHADOW_TECHNIQUES = [
12246
- "esm",
12247
- "pcf",
12248
- "csm"
12249
- ];
12250
- /**
12251
- * Refuses to build a shadow generator for a light kind Lite cannot shadow.
12252
- *
12253
- * @remarks
12254
- * Lite has no point-light (cube) shadow generator and no area lights
12255
- * (`docs/architecture/07-rendering.md` §8). Hemispheric lights have no position or frustum at all.
12256
- *
12257
- * @param lightType - The Lite `lightType` discriminant of the light.
12258
- * @throws IgnifxError with code `IGX-0703` for any light kind other than `directional` or `spot`.
12259
- *
12260
- * @example
12261
- * ```ts
12262
- * assertShadowsSupported(light.lightType); // throws IGX-0703 for "point"
12263
- * ```
12264
- *
12265
- * @internal
12266
- */
12267
- function assertShadowsSupported(lightType) {
12268
- if (lightType === "directional" || lightType === "spot") return;
12269
- throw new IgnifxError(CoreErrorCode.shadowsUnsupportedForLight, `Babylon Lite has no shadow generator for a ${lightType} light.`, {
12270
- context: { lightType },
12271
- hint: "Cast shadows from a directional or spot light instead."
12272
- });
12273
- }
12274
- /**
12275
- * Turns shadows on for a light by attaching its generator.
12276
- *
12277
- * @param light - The light that should cast shadows.
12278
- * @param generator - A generator built for that light by `./gpu/shadow-generator.ts`.
12279
- *
12280
- * @internal
12281
- */
12282
- function attachShadowGenerator(light, generator) {
12283
- light.shadowGenerator = generator;
12284
- }
12285
- /**
12286
- * Turns shadows off for a light.
12287
- *
12288
- * @remarks
12289
- * This only breaks the link. The generator's GPU resources are released when the scene disposes it
12290
- * through {@link disposeShadowGenerator}.
12291
- *
12292
- * @param light - The light that should stop casting shadows.
12293
- *
12294
- * @internal
12295
- */
12296
- function detachShadowGenerator(light) {
12297
- delete light.shadowGenerator;
12298
- }
12299
- /**
12300
- * Replaces the list of meshes a generator renders into its shadow map.
12301
- *
12302
- * @remarks
12303
- * Lite keys the list by array identity and re-preloads the shadow pipeline every time a **new**
12304
- * array arrives, skipping the generator until that finishes. Callers therefore build the list once
12305
- * per change, never per frame.
12306
- *
12307
- * @param generator - The shadow generator.
12308
- * @param casters - The meshes that cast into it.
12309
- *
12310
- * @internal
12311
- */
12312
- function setShadowCasters(generator, casters) {
12313
- setShadowTaskCasterMeshes(generator, casters);
12314
- }
12315
- /**
12316
- * Rebuilds every material group of a registered scene so renderables pick up the current light and
12317
- * shadow topology.
12318
- *
12319
- * @remarks
12320
- * Renderables bake the per-mesh light index list, the single- versus multi-light shader
12321
- * permutation, and each generator's shadow bind group at build time; none of that follows a light
12322
- * being added, removed, or given a generator (`index.d.ts` 9465). The call is a no-op before the
12323
- * scene's first build, and it is expensive, so the component layer coalesces every topology change
12324
- * in a frame into one call.
12325
- *
12326
- * @param scene - The scene to rebuild.
12327
- * @returns A promise that resolves when the rebuild has finished.
12328
- *
12329
- * @internal
12330
- */
12331
- function rebuildRenderables(scene) {
12332
- return rebuildSceneRenderables(scene);
12333
- }
12334
- /**
12335
- * How many times the scene's materials have been rebuilt.
12336
- *
12337
- * @remarks
12338
- * An ESM generator keeps the caster views it built for a caster array until it is handed a
12339
- * different array, whatever happens to the materials (`ensureEsmShadowTaskState`,
12340
- * `lib/shadow/esm-directional-shadow-generator.js` 121-126; PCF and CSM compare each material's
12341
- * `_csmGen` instead). So a surface shader switched on or off went on drawing the old shape into an
12342
- * ESM map. The render sync system re-supplies the caster lists whenever this moves.
12343
- *
12344
- * @param scene - The scene.
12345
- * @returns The counter; `0` before anything was built.
12346
- *
12347
- * @internal
12348
- */
12349
- function readMaterialEpoch(scene) {
12350
- return scene._materialEpoch ?? 0;
12351
- }
12352
- /**
12353
- * Makes the next renderable rebuild create fresh bind-group layouts for every material.
12354
- *
12355
- * @remarks
12356
- * Call it before {@link rebuildRenderables} whenever a light gained or lost a shadow generator,
12357
- * and when the scene gained its first skinned or morphed PBR mesh (`./pbr-deformers.ts`).
12358
- * Lite caches a material's bindings, shadow bind-group layout included, under a key that does not
12359
- * name the shadow maps (`getOrCreatePbrBindings`, `lib/material/pbr/pbr-pipeline.js` 36). So after
12360
- * the number of shadow-casting lights changes, a rebuild reuses a layout sized for the old number
12361
- * and builds a bind group for the new one, and WebGPU rejects every frame ("Number of entries (3)
12362
- * did not match the expected number of entries (6)"). Clearing the cache costs one pipeline
12363
- * rebuild per material, only on a frame whose shadow casters changed.
12364
- *
12365
- * @param engine - The engine whose caches to clear.
12366
- *
12367
- * @internal
12368
- */
12369
- function forgetMaterialBindingLayouts(engine) {
12370
- const resets = engine;
12371
- resets._pbrCleanup?.();
12372
- resets._standardCleanup?.();
12373
- }
12374
- /**
12375
- * Releases a shadow generator's GPU resources and unlinks it from its light.
12376
- *
12377
- * @remarks
12378
- * `removeFromScene` recognises a shadow generator by its private `_shadowType`/`_light` fields
12379
- * (`lib/scene/scene-remove.js`), clears `light.shadowGenerator`, marks the scene's light topology
12380
- * dirty, and queues the generator's task for disposal after the GPU has drained.
12381
- *
12382
- * @param scene - The scene the generator was rendering into.
12383
- * @param generator - The generator to release.
12384
- *
12385
- * @internal
12386
- */
12387
- function disposeShadowGenerator(scene, generator) {
12388
- removeFromScene(scene, generator);
12389
- }
12390
- /**
12391
- * Maps the shared settings onto an exponential shadow map's configuration.
12392
- *
12393
- * @param settings - The declared settings.
12394
- * @returns Lite's configuration, with every field the caller left out omitted.
12395
- *
12396
- * @internal
12397
- */
12398
- function toEsmConfig(settings) {
12399
- const config = {};
12400
- if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
12401
- if (settings.bias !== void 0) config.bias = settings.bias;
12402
- if (settings.darkness !== void 0) config.darkness = settings.darkness;
12403
- return config;
12404
- }
12405
- /**
12406
- * Maps the shared settings onto a percentage-closer-filtered directional shadow map's configuration.
12407
- *
12408
- * @param settings - The declared settings.
12409
- * @returns Lite's configuration.
12410
- *
12411
- * @internal
12412
- */
12413
- function toPcfConfig(settings) {
12414
- const config = {};
12415
- if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
12416
- if (settings.bias !== void 0) config.bias = settings.bias;
12417
- if (settings.normalBias !== void 0) config.normalBias = settings.normalBias;
12418
- if (settings.darkness !== void 0) config.darkness = settings.darkness;
12419
- return config;
12420
- }
12421
- /**
12422
- * Maps the shared settings onto a cascaded shadow map's configuration.
12423
- *
12424
- * @remarks
12425
- * `cascades` becomes `numCascades` and `maxDistance` becomes `shadowMaxZ`; Lite clamps the cascade
12426
- * count to four (`index.d.ts` 3515).
12427
- *
12428
- * @param settings - The declared settings.
12429
- * @returns Lite's configuration.
12430
- *
12431
- * @internal
12432
- */
12433
- function toCsmConfig(settings) {
12434
- const config = {};
12435
- if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
12436
- if (settings.bias !== void 0) config.bias = settings.bias;
12437
- if (settings.darkness !== void 0) config.darkness = settings.darkness;
12438
- if (settings.cascades !== void 0) config.numCascades = settings.cascades;
12439
- if (settings.maxDistance !== void 0) config.shadowMaxZ = settings.maxDistance;
12440
- return config;
12441
- }
12442
- /**
12443
- * Maps the shared settings onto a spot light's shadow configuration.
12444
- *
12445
- * @param settings - The declared settings.
12446
- * @returns Lite's configuration.
12447
- *
12448
- * @internal
12449
- */
12450
- function toSpotConfig(settings) {
12451
- const config = {};
12452
- if (settings.mapSize !== void 0) config.mapSize = settings.mapSize;
12453
- if (settings.bias !== void 0) config.bias = settings.bias;
12454
- if (settings.normalBias !== void 0) config.normalBias = settings.normalBias;
12455
- if (settings.darkness !== void 0) config.darkness = settings.darkness;
12456
- if (settings.maxDistance !== void 0) config.far = settings.maxDistance;
12457
- return config;
12458
- }
12459
- //#endregion
12460
- //#region src/lite/shadow-caster-shapes.ts
12461
- /**
12462
- * Tracks the bone poses and shader uniforms of one shadow generator's casters.
11636
+ * Tracks the bone poses and shader uniforms of one shadow generator's casters.
12463
11637
  *
12464
11638
  * @remarks
12465
11639
  * Call {@link ShadowCasterShapes.watch} whenever the generator starts drawing a new caster list,
@@ -14605,7 +13779,7 @@ function createShaderLoader() {
14605
13779
  type: SHADER_ASSET_TYPE,
14606
13780
  extensions: SHADER_FILE_EXTENSIONS,
14607
13781
  async load(ctx) {
14608
- const [source, pragma] = await Promise.all([ctx.fetchText(), import("./shader-pragma-D4HKC9vP.js")]);
13782
+ const [source, pragma] = await Promise.all([ctx.fetchText(), import("./shader-pragma-tw6AKaQD.js")]);
14609
13783
  const declaration = pragma.parseShaderDeclaration(source, ctx.address);
14610
13784
  await loadShaderSupport();
14611
13785
  if (declaration.kind === "surface") await loadSurfaceShaderSupport();
@@ -15252,6 +14426,12 @@ var MeshInstance = class {
15252
14426
  #renderOrder = NaN;
15253
14427
  #pickable = null;
15254
14428
  #visible = false;
14429
+ /** The template's own box, which a displacement margin widens; `null` until one is first applied. */
14430
+ #ownBox = null;
14431
+ /** The object-space margins last written, per axis. */
14432
+ #margin = new Vec3();
14433
+ /** Scratch for the entity's world scale. */
14434
+ #scale = new Vec3();
15255
14435
  /**
15256
14436
  * Clones a template under an entity's node, tags it, and adds it to the scene.
15257
14437
  *
@@ -15325,6 +14505,36 @@ var MeshInstance = class {
15325
14505
  }
15326
14506
  }
15327
14507
  /**
14508
+ * Widens the clone's bounds by how far its material's vertex stage may move a vertex, so a
14509
+ * directional shadow map fitted to them still covers the moved shape.
14510
+ *
14511
+ * @remarks
14512
+ * The margin is in world metres and the bounds are object-local, so each axis is divided by the
14513
+ * entity's world scale along it. Only the clone is widened: it gets bound arrays of its own first,
14514
+ * because a fresh clone shares the template's with every other renderer of the asset.
14515
+ *
14516
+ * @param margin - The material's displacement, in world metres; `0` restores the template's box.
14517
+ * @param transform - The entity's transform, whose world scale the clone inherits.
14518
+ */
14519
+ applyDisplacement(margin, transform) {
14520
+ const scale = this.#scale;
14521
+ if (margin > 0) transform.lossyScaleToRef(scale);
14522
+ const x = objectMargin(margin, scale.x);
14523
+ const y = objectMargin(margin, scale.y);
14524
+ const z = objectMargin(margin, scale.z);
14525
+ const applied = this.#margin;
14526
+ if (x === applied.x && y === applied.y && z === applied.z) return;
14527
+ applied.set(x, y, z);
14528
+ const mesh = this.mesh;
14529
+ let box = this.#ownBox;
14530
+ if (box === null) {
14531
+ box = readBox(mesh);
14532
+ detachMeshBounds(mesh);
14533
+ this.#ownBox = box;
14534
+ }
14535
+ setMeshBounds(mesh, (box[0] ?? 0) - x, (box[1] ?? 0) - y, (box[2] ?? 0) - z, (box[3] ?? 0) + x, (box[4] ?? 0) + y, (box[5] ?? 0) + z);
14536
+ }
14537
+ /**
15328
14538
  * Shows or hides the clone, when the state changed.
15329
14539
  *
15330
14540
  * @param visible - `entity.activeInHierarchy && component.enabled`.
@@ -15344,6 +14554,39 @@ var MeshInstance = class {
15344
14554
  }
15345
14555
  };
15346
14556
  /**
14557
+ * Converts a world-space margin into the object-space margin along one axis.
14558
+ *
14559
+ * @param margin - The margin, in world metres.
14560
+ * @param scale - The entity's world scale along the axis.
14561
+ * @returns The margin in object units; `0` for no margin or a collapsed axis.
14562
+ */
14563
+ function objectMargin(margin, scale) {
14564
+ return margin > 0 && scale > 1e-9 ? margin / scale : 0;
14565
+ }
14566
+ /**
14567
+ * Reads a mesh's object-local box into six numbers.
14568
+ *
14569
+ * @remarks
14570
+ * A mesh without bounds falls back to the half-metre cube `computeDirectionalLightMatrix` assumes
14571
+ * for one (`lib/shadow/shadow-base.js` 62).
14572
+ *
14573
+ * @param mesh - The mesh to read.
14574
+ * @returns `minX, minY, minZ, maxX, maxY, maxZ`.
14575
+ */
14576
+ function readBox(mesh) {
14577
+ const min = mesh.boundMin ?? [
14578
+ -.5,
14579
+ -.5,
14580
+ -.5
14581
+ ];
14582
+ const max = mesh.boundMax ?? [
14583
+ .5,
14584
+ .5,
14585
+ .5
14586
+ ];
14587
+ return Float64Array.of(min[0], min[1], min[2], max[0], max[1], max[2]);
14588
+ }
14589
+ /**
15347
14590
  * Narrows a cloned subtree root to a mesh.
15348
14591
  *
15349
14592
  * @remarks
@@ -15462,6 +14705,7 @@ var MeshRenderer = class MeshRenderer extends Component {
15462
14705
  const instance = this.#instance;
15463
14706
  if (instance === null) return changed;
15464
14707
  instance.applyMaterial(this.#material(renderer));
14708
+ instance.applyDisplacement(this.#displacement(), this.entity.transform);
15465
14709
  instance.applyFlags(this.receiveShadows, this.renderOrder, this.pickable);
15466
14710
  instance.applyVisible(this.isEnabledInHierarchy);
15467
14711
  return changed;
@@ -15537,6 +14781,15 @@ var MeshRenderer = class MeshRenderer extends Component {
15537
14781
  return declared?.state === "loaded" ? declared.value.lite.material : renderer.defaultMaterial().lite.material;
15538
14782
  }
15539
14783
  /**
14784
+ * How far the material's vertex stage may move a vertex: its shaders' `// @ignifx displace`.
14785
+ *
14786
+ * @returns The distance in world metres; `0` for the default material or one still loading.
14787
+ */
14788
+ #displacement() {
14789
+ const declared = this.materials[0];
14790
+ return declared?.state === "loaded" ? declared.value.displacement : 0;
14791
+ }
14792
+ /**
15540
14793
  * Removes the clone from the scene, when there is one.
15541
14794
  *
15542
14795
  * @param renderer - The rendering service, for the scene.
@@ -17156,6 +16409,7 @@ var RenderSyncSystem = class {
17156
16409
  renderer.refreshClearColor();
17157
16410
  this.#applyStacks(world);
17158
16411
  this.#areCastersDirty = this.#areCastersDirty || castersChanged;
16412
+ if (renderer.materialCacheResets.unconfirmed && !this.#isRebuildDue && !this.#isRebuildInFlight) this.#rebuildRenderables();
17159
16413
  if (this.#isRebuildDue && !topologyChanged) {
17160
16414
  this.#isRebuildDue = false;
17161
16415
  this.#rebuildRenderables();
@@ -17408,9 +16662,9 @@ var RenderSyncSystem = class {
17408
16662
  const deformers = readPbrDeformers(renderer.scene);
17409
16663
  if (renderer.needsShadowLayoutReset || (deformers & ~renderer.builtPbrDeformers) !== 0) {
17410
16664
  renderer.needsShadowLayoutReset = false;
17411
- forgetMaterialBindingLayouts(renderer.engine);
16665
+ forgetMaterialBindingLayouts(renderer.materialCacheResets);
17412
16666
  }
17413
- await rebuildRenderables(renderer.scene);
16667
+ await rebuildRenderables(renderer.scene, renderer.materialCacheResets);
17414
16668
  renderer.builtPbrDeformers |= deformers;
17415
16669
  } catch (error) {
17416
16670
  renderer.app.onError.emit({
@@ -19142,1144 +18396,443 @@ function validateSceneFile(value) {
19142
18396
  }
19143
18397
  if (file["format"] !== "ignifx.scene") issues.push({
19144
18398
  path: "format",
19145
- message: `expected "${SCENE_FILE_FORMAT}".`
19146
- });
19147
- if (file["formatVersion"] !== 1) issues.push({
19148
- path: "formatVersion",
19149
- message: `expected ${String(1)}.`
19150
- });
19151
- if (typeof file["name"] !== "string") issues.push({
19152
- path: "name",
19153
- message: "expected a string."
19154
- });
19155
- const settings = file["settings"];
19156
- if (settings !== void 0 && asRecord(settings) === null) issues.push({
19157
- path: "settings",
19158
- message: "expected an object."
19159
- });
19160
- const entities = file["entities"];
19161
- if (!Array.isArray(entities)) {
19162
- issues.push({
19163
- path: "entities",
19164
- message: "expected an array."
19165
- });
19166
- return issues;
19167
- }
19168
- const uids = /* @__PURE__ */ new Set();
19169
- for (let index = 0; index < entities.length; index += 1) validateEntity(entities[index], `entities/${String(index)}`, uids, issues);
19170
- return issues;
19171
- }
19172
- /**
19173
- * Narrows a value to a scene file after {@link validateSceneFile} has passed.
19174
- *
19175
- * @param value - The validated JSON.
19176
- * @returns The same value, typed as a scene file.
19177
- *
19178
- * @internal
19179
- */
19180
- function asSceneFile(value) {
19181
- return value;
19182
- }
19183
- /**
19184
- * Validates one entity entry.
19185
- *
19186
- * @param value - The entry.
19187
- * @param path - Its path, for issue messages.
19188
- * @param uids - Uids already seen in the file, for the uniqueness check.
19189
- * @param issues - Where problems are appended.
19190
- */
19191
- function validateEntity(value, path, uids, issues) {
19192
- const entity = asRecord(value);
19193
- if (entity === null) {
19194
- issues.push({
19195
- path,
19196
- message: "expected an object."
19197
- });
19198
- return;
19199
- }
19200
- requireUid(entity["uid"], `${path}/uid`, uids, issues);
19201
- if (typeof entity["name"] !== "string") issues.push({
19202
- path: `${path}/name`,
19203
- message: "expected a string."
19204
- });
19205
- const parent = entity["parent"];
19206
- if (parent !== null && typeof parent !== "string") issues.push({
19207
- path: `${path}/parent`,
19208
- message: "expected a uid string or null."
19209
- });
19210
- requireBoolean(entity["active"], `${path}/active`, issues);
19211
- requireBoolean(entity["static"], `${path}/static`, issues);
19212
- if (entity["layer"] !== void 0 && typeof entity["layer"] !== "string") issues.push({
19213
- path: `${path}/layer`,
19214
- message: "expected a layer name string."
19215
- });
19216
- validateTags(entity["tags"], `${path}/tags`, issues);
19217
- validateTransform(entity["transform"], `${path}/transform`, issues);
19218
- validateInstance(entity["instance"], `${path}/instance`, issues);
19219
- const components = entity["components"];
19220
- if (components === void 0) return;
19221
- if (!Array.isArray(components)) {
19222
- issues.push({
19223
- path: `${path}/components`,
19224
- message: "expected an array."
19225
- });
19226
- return;
19227
- }
19228
- for (let index = 0; index < components.length; index += 1) validateComponent(components[index], `${path}/components/${String(index)}`, uids, issues);
19229
- }
19230
- /**
19231
- * Validates one component entry.
19232
- *
19233
- * @param value - The entry.
19234
- * @param path - Its path.
19235
- * @param uids - Uids already seen.
19236
- * @param issues - Where problems are appended.
19237
- */
19238
- function validateComponent(value, path, uids, issues) {
19239
- const component = asRecord(value);
19240
- if (component === null) {
19241
- issues.push({
19242
- path,
19243
- message: "expected an object."
19244
- });
19245
- return;
19246
- }
19247
- requireUid(component["uid"], `${path}/uid`, uids, issues);
19248
- const type = component["type"];
19249
- if (typeof type !== "string" || type === "") issues.push({
19250
- path: `${path}/type`,
19251
- message: "expected a registered component type id."
19252
- });
19253
- requireBoolean(component["enabled"], `${path}/enabled`, issues);
19254
- const version = component["schemaVersion"];
19255
- if (version !== void 0 && (typeof version !== "number" || !Number.isInteger(version) || version < 1)) issues.push({
19256
- path: `${path}/schemaVersion`,
19257
- message: "expected a positive integer."
19258
- });
19259
- const props = component["props"];
19260
- if (props !== void 0 && asRecord(props) === null) issues.push({
19261
- path: `${path}/props`,
19262
- message: "expected an object."
19263
- });
19264
- }
19265
- /**
19266
- * Validates an `instance` entry.
19267
- *
19268
- * @param value - The entry, or `undefined`.
19269
- * @param path - Its path.
19270
- * @param issues - Where problems are appended.
19271
- */
19272
- function validateInstance(value, path, issues) {
19273
- if (value === void 0) return;
19274
- const instance = asRecord(value);
19275
- if (instance === null) {
19276
- issues.push({
19277
- path,
19278
- message: "expected an object."
19279
- });
19280
- return;
19281
- }
19282
- const scene = asRecord(instance["scene"]);
19283
- if (scene === null || typeof scene["$asset"] !== "string") issues.push({
19284
- path: `${path}/scene`,
19285
- message: "expected { \"$asset\": \"<address>\" }."
19286
- });
19287
- if (instance["hash"] !== void 0 && typeof instance["hash"] !== "string") issues.push({
19288
- path: `${path}/hash`,
19289
- message: "expected a string."
19290
- });
19291
- const overrides = instance["overrides"];
19292
- if (overrides === void 0) return;
19293
- if (!Array.isArray(overrides)) {
19294
- issues.push({
19295
- path: `${path}/overrides`,
19296
- message: "expected an array."
19297
- });
19298
- return;
19299
- }
19300
- for (let index = 0; index < overrides.length; index += 1) {
19301
- const at = `${path}/overrides/${String(index)}`;
19302
- const override = asRecord(overrides[index]);
19303
- if (override === null || typeof override["path"] !== "string" || override["path"] === "") {
19304
- issues.push({
19305
- path: at,
19306
- message: "expected an object with a non-empty path."
19307
- });
19308
- continue;
19309
- }
19310
- const op = override["op"];
19311
- if (op !== void 0 && op !== "replace" && op !== "remove" && op !== "add") issues.push({
19312
- path: `${at}/op`,
19313
- message: "expected \"replace\", \"remove\", or \"add\"."
19314
- });
19315
- }
19316
- }
19317
- /**
19318
- * Validates a `transform` entry.
19319
- *
19320
- * @param value - The entry.
19321
- * @param path - Its path.
19322
- * @param issues - Where problems are appended.
19323
- */
19324
- function validateTransform(value, path, issues) {
19325
- const transform = asRecord(value);
19326
- if (transform === null) {
19327
- issues.push({
19328
- path,
19329
- message: "expected an object with position, rotation, and scale."
19330
- });
19331
- return;
19332
- }
19333
- requireNumbers(transform["position"], `${path}/position`, 3, issues);
19334
- requireNumbers(transform["rotation"], `${path}/rotation`, 4, issues);
19335
- requireNumbers(transform["scale"], `${path}/scale`, 3, issues);
19336
- }
19337
- /**
19338
- * Validates a `tags` array.
19339
- *
19340
- * @param value - The array, or `undefined`.
19341
- * @param path - Its path.
19342
- * @param issues - Where problems are appended.
19343
- */
19344
- function validateTags(value, path, issues) {
19345
- if (value === void 0) return;
19346
- if (!Array.isArray(value)) {
19347
- issues.push({
19348
- path,
19349
- message: "expected an array of strings."
19350
- });
19351
- return;
19352
- }
19353
- for (let index = 0; index < value.length; index += 1) if (typeof value[index] !== "string") issues.push({
19354
- path: `${path}/${String(index)}`,
19355
- message: "expected a string."
19356
- });
19357
- }
19358
- /**
19359
- * Checks a uid: a non-empty string, unique within the file.
19360
- *
19361
- * @param value - The candidate.
19362
- * @param path - Its path.
19363
- * @param uids - Uids already seen.
19364
- * @param issues - Where problems are appended.
19365
- */
19366
- function requireUid(value, path, uids, issues) {
19367
- if (typeof value !== "string" || value === "") {
19368
- issues.push({
19369
- path,
19370
- message: "expected a non-empty uid string."
19371
- });
19372
- return;
19373
- }
19374
- if (uids.has(value)) {
19375
- issues.push({
19376
- path,
19377
- message: `the uid ${value} is used twice; uids are unique within a file.`
19378
- });
19379
- return;
19380
- }
19381
- uids.add(value);
19382
- }
19383
- /**
19384
- * Checks an optional boolean.
19385
- *
19386
- * @param value - The candidate.
19387
- * @param path - Its path.
19388
- * @param issues - Where problems are appended.
19389
- */
19390
- function requireBoolean(value, path, issues) {
19391
- if (value !== void 0 && typeof value !== "boolean") issues.push({
19392
- path,
19393
- message: "expected a boolean."
19394
- });
19395
- }
19396
- /**
19397
- * Checks a fixed-length array of finite numbers.
19398
- *
19399
- * @param value - The candidate.
19400
- * @param path - Its path.
19401
- * @param length - How many entries are required.
19402
- * @param issues - Where problems are appended.
19403
- */
19404
- function requireNumbers(value, path, length, issues) {
19405
- if (!Array.isArray(value) || value.length !== length) {
19406
- issues.push({
19407
- path,
19408
- message: `expected an array of ${String(length)} numbers.`
19409
- });
19410
- return;
19411
- }
19412
- for (let index = 0; index < value.length; index += 1) {
19413
- const entry = value[index];
19414
- if (typeof entry !== "number" || !Number.isFinite(entry)) issues.push({
19415
- path: `${path}/${String(index)}`,
19416
- message: "expected a finite number."
19417
- });
19418
- }
19419
- }
19420
- /**
19421
- * Narrows a value to a string-keyed object.
19422
- *
19423
- * @param value - The candidate.
19424
- * @returns The record, or `null` when the value is not a plain object.
19425
- */
19426
- function asRecord(value) {
19427
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
19428
- return value;
19429
- }
19430
- //#endregion
19431
- //#region src/serialization/scene-loader.ts
19432
- /**
19433
- * The `AssetLoader` for `*.scene.json` and `*.prefab.json`
19434
- * (`docs/architecture/06-serialization-and-scene-format.md` §4 steps 1 and 2, ADR-0005 — one
19435
- * loader for levels and prefabs).
19436
- *
19437
- * @remarks
19438
- * The loader does everything the file needs *before* the world sees it: parse, check the header and
19439
- * the format version, validate the structure, then resolve every `$asset` it can find — in
19440
- * `settings`, in every component's `props`, and in every `instance.scene`, recursively through the
19441
- * scene assets those pull in. The resulting `SceneAsset` therefore carries a fully loaded
19442
- * dependency set, which is what makes `world.instantiate` synchronous
19443
- * (`02-scene-graph.md` §2).
19444
- *
19445
- * @param options - Whether to validate.
19446
- * @returns The loader to register with `ctx.registerAssetLoader`.
19447
- *
19448
- * @example
19449
- * ```ts
19450
- * ctx.registerAssetLoader(createSceneLoader());
19451
- * const level = await app.assets.loadAsync<SceneAsset>("levels/level01.scene.json");
19452
- * ```
19453
- *
19454
- * @public
19455
- */
19456
- function createSceneLoader(options) {
19457
- const validate = options?.validate ?? true;
19458
- return {
19459
- type: SCENE_ASSET_TYPE,
19460
- extensions: SCENE_FILE_EXTENSIONS,
19461
- async load(ctx) {
19462
- const file = readSceneFile(await ctx.fetchJson(), ctx.address, validate);
19463
- const dependencies = await loadDependencies(file, ctx);
19464
- return {
19465
- address: ctx.address,
19466
- file,
19467
- dependencies,
19468
- hash: await computeSceneHash(file)
19469
- };
19470
- }
19471
- };
19472
- }
19473
- /**
19474
- * Checks a parsed file's header, version, and structure.
19475
- *
19476
- * @param parsed - The parsed JSON.
19477
- * @param address - The address, for diagnostics.
19478
- * @param validate - `true` runs the structural validation.
19479
- * @returns The file.
19480
- * @throws IgnifxError with code `IGX-0308` when the header is missing, `IGX-0603` when the format
19481
- * version is not readable, and `IGX-0608` when the structure does not match.
19482
- *
19483
- * @internal
19484
- */
19485
- function readSceneFile(parsed, address, validate) {
19486
- if (!isSceneFileHeader(parsed)) throw new IgnifxError(CoreErrorCode.notASceneFile, `${address} is not an ignifx scene file.`, {
19487
- context: { file: address },
19488
- hint: "A scene file carries { \"format\": \"ignifx.scene\", \"formatVersion\": 1 }."
19489
- });
19490
- const version = parsed["formatVersion"];
19491
- if (version !== 1) throw new IgnifxError(CoreErrorCode.unsupportedFormatVersion, `${address} declares format version ${String(version)}, which this build cannot read.`, {
19492
- context: {
19493
- file: address,
19494
- version: String(version)
19495
- },
19496
- hint: `This build reads ignifx.scene version ${String(1)}.`
19497
- });
19498
- if (validate) {
19499
- const issues = validateSceneFile(parsed);
19500
- const first = issues[0];
19501
- if (first !== void 0) throw new IgnifxError(CoreErrorCode.sceneFileInvalid, `${address} does not match the scene file schema: ${issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`, { context: {
19502
- file: address,
19503
- issues: issues.length,
19504
- first: first.path
19505
- } });
19506
- }
19507
- return asSceneFile(parsed);
19508
- }
19509
- /**
19510
- * Loads every asset the file references, in a stable order: `settings` first, then each entity's
19511
- * `instance.scene`, then each component's `props`
19512
- * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 2).
19513
- *
19514
- * @param file - The parsed file.
19515
- * @param ctx - The loader context.
19516
- * @returns The loaded handles, deduplicated by address, in discovery order.
19517
- */
19518
- async function loadDependencies(file, ctx) {
19519
- const requests = [];
19520
- const seen = /* @__PURE__ */ new Set();
19521
- const add = (address, type) => {
19522
- if (address === "" || seen.has(address)) return;
19523
- seen.add(address);
19524
- requests.push({
19525
- address,
19526
- type
19527
- });
19528
- };
19529
- const settings = file.settings;
19530
- if (settings !== void 0) collectAssetRefs(settings, add);
19531
- for (let index = 0; index < file.entities.length; index += 1) {
19532
- const entity = file.entities[index];
19533
- if (entity !== void 0) collectEntityRefs(entity, add);
19534
- }
19535
- return Promise.all(requests.map(async (request) => ctx.loadDependency(request.address, request.type === null ? void 0 : { type: request.type })));
19536
- }
19537
- /**
19538
- * Collects the asset references of one entity: its `instance.scene` first, so a nested scene is
19539
- * loaded before the props that may name sub-assets of it, then every component's props.
19540
- *
19541
- * @param entity - The entity record.
19542
- * @param add - Called with each address and its declared type.
19543
- */
19544
- function collectEntityRefs(entity, add) {
19545
- const instance = entity.instance;
19546
- if (instance !== void 0) {
19547
- add(instance.scene.$asset, instance.scene.type ?? "scene");
19548
- const overrides = instance.overrides ?? [];
19549
- for (let index = 0; index < overrides.length; index += 1) {
19550
- const value = overrides[index]?.value;
19551
- if (value !== void 0) collectAssetRefs(value, add);
19552
- }
19553
- }
19554
- const components = entity.components ?? [];
19555
- for (let index = 0; index < components.length; index += 1) {
19556
- const props = components[index]?.props;
19557
- if (props !== void 0) collectAssetRefs(props, add);
19558
- }
19559
- }
19560
- /**
19561
- * Walks any JSON and reports every `{ "$asset": … }` it finds, at any depth.
19562
- *
19563
- * @param value - The JSON to walk.
19564
- * @param add - Called with each address and its declared type.
19565
- */
19566
- function collectAssetRefs(value, add) {
19567
- const items = asJsonArray(value);
19568
- if (items !== null) {
19569
- for (let index = 0; index < items.length; index += 1) collectAssetRefs(items[index] ?? null, add);
19570
- return;
19571
- }
19572
- const object = asJsonObject(value);
19573
- if (object === null) return;
19574
- const address = object["$asset"];
19575
- if (typeof address === "string") {
19576
- const type = object["type"];
19577
- add(address, typeof type === "string" ? type : null);
19578
- return;
19579
- }
19580
- for (const key of Object.keys(object)) collectAssetRefs(object[key] ?? null, add);
19581
- }
19582
- //#endregion
19583
- //#region src/math/vec3.ts
19584
- /**
19585
- * A 3-component vector: a position or a direction in metres, or a per-axis scale. ignifx is
19586
- * left-handed with Y up and +Z forward (ADR-0011), so {@link Vec3.forward} is `(0, 0, 1)` and
19587
- * {@link Vec3.right} is `(1, 0, 0)`.
19588
- *
19589
- * The fields are plain mutable numbers, which is what makes a `Vec3` interchangeable with Babylon
19590
- * Lite's `{ x, y, z }` vectors and with the live {@link MutableVec3} views a `Transform` exposes.
19591
- *
19592
- * Three families of operations, and the names say which is which:
19593
- *
19594
- * - instance methods mutate the receiver and return `this` (`a.add(b)` means `a += b`);
19595
- * - `ToRef` statics write into a final `out` argument, allocate nothing, and are safe when `out`
19596
- * aliases an input — these are what per-frame code uses (coding standards section 7);
19597
- * - the remaining statics return a fresh vector and are documented as allocating.
19598
- *
19599
- * @example
19600
- * ```ts
19601
- * // convenience code
19602
- * const offset = Vec3.add(position, Vec3.scale(direction, distance));
19603
- *
19604
- * // per-frame code: no allocation
19605
- * Vec3.scaleToRef(direction, distance, scratch);
19606
- * Vec3.addToRef(position, scratch, position);
19607
- * ```
19608
- *
19609
- * @public
19610
- */
19611
- var Vec3 = class Vec3 {
19612
- /** The X component; positive is right. */
19613
- x;
19614
- /** The Y component; positive is up. */
19615
- y;
19616
- /** The Z component; positive is forward. */
19617
- z;
19618
- /**
19619
- * Creates a vector.
19620
- *
19621
- * @param x - The X component. Defaults to 0.
19622
- * @param y - The Y component. Defaults to 0.
19623
- * @param z - The Z component. Defaults to 0.
19624
- */
19625
- constructor(x = 0, y = 0, z = 0) {
19626
- this.x = x;
19627
- this.y = y;
19628
- this.z = z;
19629
- }
19630
- /**
19631
- * Assigns every component at once.
19632
- *
19633
- * @param x - The new X component.
19634
- * @param y - The new Y component.
19635
- * @param z - The new Z component.
19636
- * @returns This vector.
19637
- */
19638
- set(x, y, z) {
19639
- this.x = x;
19640
- this.y = y;
19641
- this.z = z;
19642
- return this;
19643
- }
19644
- /**
19645
- * Copies every component from another vector.
19646
- *
19647
- * @param v - The vector to read.
19648
- * @returns This vector.
19649
- */
19650
- copyFrom(v) {
19651
- this.x = v.x;
19652
- this.y = v.y;
19653
- this.z = v.z;
19654
- return this;
19655
- }
19656
- /**
19657
- * Copies this vector into a new one.
19658
- *
19659
- * @returns A new vector. **Allocates.**
19660
- */
19661
- clone() {
19662
- return new Vec3(this.x, this.y, this.z);
19663
- }
19664
- /**
19665
- * Adds another vector to this one.
19666
- *
19667
- * @param v - The vector to add.
19668
- * @returns This vector.
19669
- */
19670
- add(v) {
19671
- this.x += v.x;
19672
- this.y += v.y;
19673
- this.z += v.z;
19674
- return this;
19675
- }
19676
- /**
19677
- * Adds a scaled vector to this one — the "move by velocity times delta time" step, without a
19678
- * temporary.
19679
- *
19680
- * @param v - The vector to add.
19681
- * @param scale - The factor to multiply `v` by first.
19682
- * @returns This vector.
19683
- *
19684
- * @example
19685
- * ```ts
19686
- * position.addScaled(velocity, time.deltaTime);
19687
- * ```
19688
- */
19689
- addScaled(v, scale) {
19690
- this.x += v.x * scale;
19691
- this.y += v.y * scale;
19692
- this.z += v.z * scale;
19693
- return this;
19694
- }
19695
- /**
19696
- * Subtracts another vector from this one.
19697
- *
19698
- * @param v - The vector to subtract.
19699
- * @returns This vector.
19700
- */
19701
- subtract(v) {
19702
- this.x -= v.x;
19703
- this.y -= v.y;
19704
- this.z -= v.z;
19705
- return this;
19706
- }
19707
- /**
19708
- * Multiplies this vector by another component by component.
19709
- *
19710
- * @param v - The vector to multiply by.
19711
- * @returns This vector.
19712
- */
19713
- multiply(v) {
19714
- this.x *= v.x;
19715
- this.y *= v.y;
19716
- this.z *= v.z;
19717
- return this;
19718
- }
19719
- /**
19720
- * Multiplies every component by a number.
19721
- *
19722
- * @param scale - The factor.
19723
- * @returns This vector.
19724
- */
19725
- scale(scale) {
19726
- this.x *= scale;
19727
- this.y *= scale;
19728
- this.z *= scale;
19729
- return this;
19730
- }
19731
- /**
19732
- * Flips this vector to point the other way.
19733
- *
19734
- * @returns This vector.
19735
- */
19736
- negate() {
19737
- this.x = -this.x;
19738
- this.y = -this.y;
19739
- this.z = -this.z;
19740
- return this;
19741
- }
19742
- /**
19743
- * Scales this vector to unit length. A zero-length vector is left at zero rather than becoming
19744
- * `NaN`, so callers can normalize an unchecked direction safely.
19745
- *
19746
- * @returns This vector.
19747
- */
19748
- normalize() {
19749
- const length = Math.hypot(this.x, this.y, this.z);
19750
- if (length === 0) return this;
19751
- return this.scale(1 / length);
19752
- }
19753
- /**
19754
- * Replaces this vector with its cross product with another (`this = this x v`).
19755
- *
19756
- * @param v - The right-hand vector.
19757
- * @returns This vector.
19758
- */
19759
- cross(v) {
19760
- return Vec3.crossToRef(this, v, this);
19761
- }
19762
- /**
19763
- * Moves this vector towards a target by an interpolant.
19764
- *
19765
- * @param target - The vector reached at `t === 1`.
19766
- * @param t - The interpolant; not clamped.
19767
- * @returns This vector.
19768
- */
19769
- lerp(target, t) {
19770
- return Vec3.lerpToRef(this, target, t, this);
19771
- }
19772
- /**
19773
- * The dot product of this vector with another.
19774
- *
19775
- * @param v - The other vector.
19776
- * @returns The dot product.
19777
- */
19778
- dot(v) {
19779
- return this.x * v.x + this.y * v.y + this.z * v.z;
19780
- }
19781
- /**
19782
- * The length of this vector, in metres.
19783
- *
19784
- * @returns The length.
19785
- */
19786
- length() {
19787
- return Math.hypot(this.x, this.y, this.z);
19788
- }
19789
- /**
19790
- * The squared length of this vector. Prefer it over `length()` when comparing distances:
19791
- * it skips the square root.
19792
- *
19793
- * @returns The squared length.
19794
- */
19795
- lengthSquared() {
19796
- return this.x * this.x + this.y * this.y + this.z * this.z;
19797
- }
19798
- /**
19799
- * The distance from this vector to another, in metres.
19800
- *
19801
- * @param v - The other position.
19802
- * @returns The distance.
19803
- */
19804
- distance(v) {
19805
- return Math.hypot(this.x - v.x, this.y - v.y, this.z - v.z);
19806
- }
19807
- /**
19808
- * The squared distance from this vector to another.
19809
- *
19810
- * @param v - The other position.
19811
- * @returns The squared distance.
19812
- */
19813
- distanceSquared(v) {
19814
- return Vec3.distanceSquared(this, v);
19815
- }
19816
- /**
19817
- * Compares this vector with another, component by component, with a tolerance.
19818
- *
19819
- * @param v - The vector to compare against.
19820
- * @param epsilon - The largest per-component difference still considered equal.
19821
- * @returns `true` when every component matches within `epsilon`.
19822
- */
19823
- equalsWithEpsilon(v, epsilon = EPSILON) {
19824
- return Vec3.equalsWithEpsilon(this, v, epsilon);
19825
- }
19826
- /**
19827
- * Writes this vector into a `Float32Array`, for GPU upload. The output comes first to mirror
19828
- * Babylon Lite's `ObservableVec3.toArray`, the shape the adapter has to interoperate with.
19829
- *
19830
- * @param out - The array to write into.
19831
- * @param offset - The index of the X component. Defaults to 0.
19832
- * @returns `out`.
19833
- */
19834
- toArray(out, offset = 0) {
19835
- out[offset] = this.x;
19836
- out[offset + 1] = this.y;
19837
- out[offset + 2] = this.z;
19838
- return out;
19839
- }
19840
- /**
19841
- * The zero vector.
19842
- *
19843
- * @returns A new `(0, 0, 0)`. **Allocates**; use {@link VEC3_ZERO} when a read-only value will do.
19844
- */
19845
- static zero() {
19846
- return new Vec3(0, 0, 0);
19847
- }
19848
- /**
19849
- * The vector whose components are all one.
19850
- *
19851
- * @returns A new `(1, 1, 1)`. **Allocates.**
19852
- */
19853
- static one() {
19854
- return new Vec3(1, 1, 1);
19855
- }
19856
- /**
19857
- * The world up direction.
19858
- *
19859
- * @returns A new `(0, 1, 0)`. **Allocates**; see {@link VEC3_UP}.
19860
- */
19861
- static up() {
19862
- return new Vec3(0, 1, 0);
19863
- }
19864
- /**
19865
- * The world down direction.
19866
- *
19867
- * @returns A new `(0, -1, 0)`. **Allocates.**
19868
- */
19869
- static down() {
19870
- return new Vec3(0, -1, 0);
19871
- }
19872
- /**
19873
- * The world right direction.
19874
- *
19875
- * @returns A new `(1, 0, 0)`. **Allocates**; see {@link VEC3_RIGHT}.
19876
- */
19877
- static right() {
19878
- return new Vec3(1, 0, 0);
19879
- }
19880
- /**
19881
- * The world left direction.
19882
- *
19883
- * @returns A new `(-1, 0, 0)`. **Allocates.**
19884
- */
19885
- static left() {
19886
- return new Vec3(-1, 0, 0);
19887
- }
19888
- /**
19889
- * The world forward direction. ignifx is left-handed, so forward is **+Z** (ADR-0011).
19890
- *
19891
- * @returns A new `(0, 0, 1)`. **Allocates**; see {@link VEC3_FORWARD}.
19892
- */
19893
- static forward() {
19894
- return new Vec3(0, 0, 1);
19895
- }
19896
- /**
19897
- * The world backward direction.
19898
- *
19899
- * @returns A new `(0, 0, -1)`. **Allocates.**
19900
- */
19901
- static backward() {
19902
- return new Vec3(0, 0, -1);
19903
- }
19904
- /**
19905
- * Copies any vector-shaped value into a `Vec3`.
19906
- *
19907
- * @param v - The vector to copy.
19908
- * @returns A new vector. **Allocates.**
19909
- *
19910
- * @example
19911
- * ```ts
19912
- * const position = Vec3.from(node.position); // snapshot of a live Lite view
19913
- * ```
19914
- */
19915
- static from(v) {
19916
- return new Vec3(v.x, v.y, v.z);
19917
- }
19918
- /**
19919
- * Adds two vectors.
19920
- *
19921
- * @param a - The first vector.
19922
- * @param b - The second vector.
19923
- * @returns A new vector. **Allocates**; use {@link Vec3.addToRef} in per-frame code.
19924
- */
19925
- static add(a, b) {
19926
- return Vec3.addToRef(a, b, new Vec3());
19927
- }
19928
- /**
19929
- * Subtracts one vector from another.
19930
- *
19931
- * @param a - The vector to subtract from.
19932
- * @param b - The vector to subtract.
19933
- * @returns A new vector holding `a - b`. **Allocates.**
19934
- */
19935
- static subtract(a, b) {
19936
- return Vec3.subtractToRef(a, b, new Vec3());
19937
- }
19938
- /**
19939
- * Multiplies a vector by a number.
19940
- *
19941
- * @param v - The vector to scale.
19942
- * @param scale - The factor.
19943
- * @returns A new vector. **Allocates.**
19944
- */
19945
- static scale(v, scale) {
19946
- return Vec3.scaleToRef(v, scale, new Vec3());
19947
- }
19948
- /**
19949
- * The cross product of two vectors.
19950
- *
19951
- * @param a - The left-hand vector.
19952
- * @param b - The right-hand vector.
19953
- * @returns A new vector holding `a x b`. **Allocates.**
19954
- */
19955
- static cross(a, b) {
19956
- return Vec3.crossToRef(a, b, new Vec3());
19957
- }
19958
- /**
19959
- * A unit-length copy of a vector.
19960
- *
19961
- * @param v - The vector to normalize.
19962
- * @returns A new vector. **Allocates.**
19963
- */
19964
- static normalize(v) {
19965
- return Vec3.normalizeToRef(v, new Vec3());
19966
- }
19967
- /**
19968
- * Linearly interpolates between two vectors.
19969
- *
19970
- * @param a - The vector returned at `t === 0`.
19971
- * @param b - The vector returned at `t === 1`.
19972
- * @param t - The interpolant; not clamped.
19973
- * @returns A new vector. **Allocates.**
19974
- */
19975
- static lerp(a, b, t) {
19976
- return Vec3.lerpToRef(a, b, t, new Vec3());
19977
- }
19978
- /**
19979
- * Writes `a + b` into `out`.
19980
- *
19981
- * @param a - The first vector.
19982
- * @param b - The second vector.
19983
- * @param out - The vector to write; may alias `a` or `b`.
19984
- * @returns `out`.
19985
- */
19986
- static addToRef(a, b, out) {
19987
- out.set(a.x + b.x, a.y + b.y, a.z + b.z);
19988
- return out;
19989
- }
19990
- /**
19991
- * Writes `a - b` into `out`.
19992
- *
19993
- * @param a - The vector to subtract from.
19994
- * @param b - The vector to subtract.
19995
- * @param out - The vector to write; may alias `a` or `b`.
19996
- * @returns `out`.
19997
- */
19998
- static subtractToRef(a, b, out) {
19999
- out.set(a.x - b.x, a.y - b.y, a.z - b.z);
20000
- return out;
20001
- }
20002
- /**
20003
- * Writes the component-wise product `a * b` into `out`.
20004
- *
20005
- * @param a - The first vector.
20006
- * @param b - The second vector.
20007
- * @param out - The vector to write; may alias `a` or `b`.
20008
- * @returns `out`.
20009
- */
20010
- static multiplyToRef(a, b, out) {
20011
- out.set(a.x * b.x, a.y * b.y, a.z * b.z);
20012
- return out;
20013
- }
20014
- /**
20015
- * Writes `v * scale` into `out`.
20016
- *
20017
- * @param v - The vector to scale.
20018
- * @param scale - The factor.
20019
- * @param out - The vector to write; may alias `v`.
20020
- * @returns `out`.
20021
- */
20022
- static scaleToRef(v, scale, out) {
20023
- out.set(v.x * scale, v.y * scale, v.z * scale);
20024
- return out;
20025
- }
20026
- /**
20027
- * Writes `-v` into `out`.
20028
- *
20029
- * @param v - The vector to flip.
20030
- * @param out - The vector to write; may alias `v`.
20031
- * @returns `out`.
20032
- */
20033
- static negateToRef(v, out) {
20034
- out.set(-v.x, -v.y, -v.z);
20035
- return out;
20036
- }
20037
- /**
20038
- * Writes a unit-length copy of `v` into `out`. A zero-length input is written as zero rather than
20039
- * `NaN`.
20040
- *
20041
- * @param v - The vector to normalize.
20042
- * @param out - The vector to write; may alias `v`.
20043
- * @returns `out`.
20044
- */
20045
- static normalizeToRef(v, out) {
20046
- const length = Math.hypot(v.x, v.y, v.z);
20047
- if (length === 0) {
20048
- out.set(0, 0, 0);
20049
- return out;
20050
- }
20051
- const inv = 1 / length;
20052
- out.set(v.x * inv, v.y * inv, v.z * inv);
20053
- return out;
20054
- }
20055
- /**
20056
- * Writes `a x b` into `out`.
20057
- *
20058
- * @param a - The left-hand vector.
20059
- * @param b - The right-hand vector.
20060
- * @param out - The vector to write; may alias `a` or `b`.
20061
- * @returns `out`.
20062
- */
20063
- static crossToRef(a, b, out) {
20064
- const ax = a.x;
20065
- const ay = a.y;
20066
- const az = a.z;
20067
- const bx = b.x;
20068
- const by = b.y;
20069
- const bz = b.z;
20070
- out.set(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx);
20071
- return out;
20072
- }
20073
- /**
20074
- * Writes the interpolation of `a` and `b` into `out`.
20075
- *
20076
- * @param a - The vector written at `t === 0`.
20077
- * @param b - The vector written at `t === 1`.
20078
- * @param t - The interpolant; not clamped.
20079
- * @param out - The vector to write; may alias `a` or `b`.
20080
- * @returns `out`.
20081
- */
20082
- static lerpToRef(a, b, t, out) {
20083
- out.set(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t));
20084
- return out;
18399
+ message: `expected "${SCENE_FILE_FORMAT}".`
18400
+ });
18401
+ if (file["formatVersion"] !== 1) issues.push({
18402
+ path: "formatVersion",
18403
+ message: `expected ${String(1)}.`
18404
+ });
18405
+ if (typeof file["name"] !== "string") issues.push({
18406
+ path: "name",
18407
+ message: "expected a string."
18408
+ });
18409
+ const settings = file["settings"];
18410
+ if (settings !== void 0 && asRecord(settings) === null) issues.push({
18411
+ path: "settings",
18412
+ message: "expected an object."
18413
+ });
18414
+ const entities = file["entities"];
18415
+ if (!Array.isArray(entities)) {
18416
+ issues.push({
18417
+ path: "entities",
18418
+ message: "expected an array."
18419
+ });
18420
+ return issues;
20085
18421
  }
20086
- /**
20087
- * Writes the component-wise minimum of two vectors into `out`.
20088
- *
20089
- * @param a - The first vector.
20090
- * @param b - The second vector.
20091
- * @param out - The vector to write; may alias `a` or `b`.
20092
- * @returns `out`.
20093
- */
20094
- static minToRef(a, b, out) {
20095
- out.set(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));
20096
- return out;
18422
+ const uids = /* @__PURE__ */ new Set();
18423
+ for (let index = 0; index < entities.length; index += 1) validateEntity(entities[index], `entities/${String(index)}`, uids, issues);
18424
+ return issues;
18425
+ }
18426
+ /**
18427
+ * Narrows a value to a scene file after {@link validateSceneFile} has passed.
18428
+ *
18429
+ * @param value - The validated JSON.
18430
+ * @returns The same value, typed as a scene file.
18431
+ *
18432
+ * @internal
18433
+ */
18434
+ function asSceneFile(value) {
18435
+ return value;
18436
+ }
18437
+ /**
18438
+ * Validates one entity entry.
18439
+ *
18440
+ * @param value - The entry.
18441
+ * @param path - Its path, for issue messages.
18442
+ * @param uids - Uids already seen in the file, for the uniqueness check.
18443
+ * @param issues - Where problems are appended.
18444
+ */
18445
+ function validateEntity(value, path, uids, issues) {
18446
+ const entity = asRecord(value);
18447
+ if (entity === null) {
18448
+ issues.push({
18449
+ path,
18450
+ message: "expected an object."
18451
+ });
18452
+ return;
20097
18453
  }
20098
- /**
20099
- * Writes the component-wise maximum of two vectors into `out`.
20100
- *
20101
- * @param a - The first vector.
20102
- * @param b - The second vector.
20103
- * @param out - The vector to write; may alias `a` or `b`.
20104
- * @returns `out`.
20105
- */
20106
- static maxToRef(a, b, out) {
20107
- out.set(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));
20108
- return out;
18454
+ requireUid(entity["uid"], `${path}/uid`, uids, issues);
18455
+ if (typeof entity["name"] !== "string") issues.push({
18456
+ path: `${path}/name`,
18457
+ message: "expected a string."
18458
+ });
18459
+ const parent = entity["parent"];
18460
+ if (parent !== null && typeof parent !== "string") issues.push({
18461
+ path: `${path}/parent`,
18462
+ message: "expected a uid string or null."
18463
+ });
18464
+ requireBoolean(entity["active"], `${path}/active`, issues);
18465
+ requireBoolean(entity["static"], `${path}/static`, issues);
18466
+ if (entity["layer"] !== void 0 && typeof entity["layer"] !== "string") issues.push({
18467
+ path: `${path}/layer`,
18468
+ message: "expected a layer name string."
18469
+ });
18470
+ validateTags(entity["tags"], `${path}/tags`, issues);
18471
+ validateTransform(entity["transform"], `${path}/transform`, issues);
18472
+ validateInstance(entity["instance"], `${path}/instance`, issues);
18473
+ const components = entity["components"];
18474
+ if (components === void 0) return;
18475
+ if (!Array.isArray(components)) {
18476
+ issues.push({
18477
+ path: `${path}/components`,
18478
+ message: "expected an array."
18479
+ });
18480
+ return;
20109
18481
  }
20110
- /**
20111
- * Transforms a **position** by a matrix into `out`: the matrix's translation is applied and the
20112
- * result is divided by w, so a projection matrix gives clip-space coordinates.
20113
- *
20114
- * @param v - The position to transform, in metres.
20115
- * @param m - The transformation, column-major.
20116
- * @param out - The vector to write; may alias `v`.
20117
- * @returns `out`.
20118
- *
20119
- * @example
20120
- * ```ts
20121
- * Vec3.transformCoordinatesToRef(localPoint, node.worldMatrix, worldPoint);
20122
- * ```
20123
- */
20124
- static transformCoordinatesToRef(v, m, out) {
20125
- return Mat4.transformPointToRef(m, v, out);
18482
+ for (let index = 0; index < components.length; index += 1) validateComponent(components[index], `${path}/components/${String(index)}`, uids, issues);
18483
+ }
18484
+ /**
18485
+ * Validates one component entry.
18486
+ *
18487
+ * @param value - The entry.
18488
+ * @param path - Its path.
18489
+ * @param uids - Uids already seen.
18490
+ * @param issues - Where problems are appended.
18491
+ */
18492
+ function validateComponent(value, path, uids, issues) {
18493
+ const component = asRecord(value);
18494
+ if (component === null) {
18495
+ issues.push({
18496
+ path,
18497
+ message: "expected an object."
18498
+ });
18499
+ return;
20126
18500
  }
20127
- /**
20128
- * Transforms a **direction** by a matrix into `out`, ignoring the matrix's translation.
20129
- *
20130
- * @param v - The direction to transform.
20131
- * @param m - The transformation, column-major.
20132
- * @param out - The vector to write; may alias `v`.
20133
- * @returns `out`.
20134
- */
20135
- static transformNormalToRef(v, m, out) {
20136
- return Mat4.transformDirectionToRef(m, v, out);
18501
+ requireUid(component["uid"], `${path}/uid`, uids, issues);
18502
+ const type = component["type"];
18503
+ if (typeof type !== "string" || type === "") issues.push({
18504
+ path: `${path}/type`,
18505
+ message: "expected a registered component type id."
18506
+ });
18507
+ requireBoolean(component["enabled"], `${path}/enabled`, issues);
18508
+ const version = component["schemaVersion"];
18509
+ if (version !== void 0 && (typeof version !== "number" || !Number.isInteger(version) || version < 1)) issues.push({
18510
+ path: `${path}/schemaVersion`,
18511
+ message: "expected a positive integer."
18512
+ });
18513
+ const props = component["props"];
18514
+ if (props !== void 0 && asRecord(props) === null) issues.push({
18515
+ path: `${path}/props`,
18516
+ message: "expected an object."
18517
+ });
18518
+ }
18519
+ /**
18520
+ * Validates an `instance` entry.
18521
+ *
18522
+ * @param value - The entry, or `undefined`.
18523
+ * @param path - Its path.
18524
+ * @param issues - Where problems are appended.
18525
+ */
18526
+ function validateInstance(value, path, issues) {
18527
+ if (value === void 0) return;
18528
+ const instance = asRecord(value);
18529
+ if (instance === null) {
18530
+ issues.push({
18531
+ path,
18532
+ message: "expected an object."
18533
+ });
18534
+ return;
20137
18535
  }
20138
- /**
20139
- * The dot product of two vectors.
20140
- *
20141
- * @param a - The first vector.
20142
- * @param b - The second vector.
20143
- * @returns The dot product.
20144
- */
20145
- static dot(a, b) {
20146
- return a.x * b.x + a.y * b.y + a.z * b.z;
18536
+ const scene = asRecord(instance["scene"]);
18537
+ if (scene === null || typeof scene["$asset"] !== "string") issues.push({
18538
+ path: `${path}/scene`,
18539
+ message: "expected { \"$asset\": \"<address>\" }."
18540
+ });
18541
+ if (instance["hash"] !== void 0 && typeof instance["hash"] !== "string") issues.push({
18542
+ path: `${path}/hash`,
18543
+ message: "expected a string."
18544
+ });
18545
+ const overrides = instance["overrides"];
18546
+ if (overrides === void 0) return;
18547
+ if (!Array.isArray(overrides)) {
18548
+ issues.push({
18549
+ path: `${path}/overrides`,
18550
+ message: "expected an array."
18551
+ });
18552
+ return;
20147
18553
  }
20148
- /**
20149
- * The length of a vector, in metres.
20150
- *
20151
- * @param v - The vector to measure.
20152
- * @returns The length.
20153
- */
20154
- static length(v) {
20155
- return Math.hypot(v.x, v.y, v.z);
18554
+ for (let index = 0; index < overrides.length; index += 1) {
18555
+ const at = `${path}/overrides/${String(index)}`;
18556
+ const override = asRecord(overrides[index]);
18557
+ if (override === null || typeof override["path"] !== "string" || override["path"] === "") {
18558
+ issues.push({
18559
+ path: at,
18560
+ message: "expected an object with a non-empty path."
18561
+ });
18562
+ continue;
18563
+ }
18564
+ const op = override["op"];
18565
+ if (op !== void 0 && op !== "replace" && op !== "remove" && op !== "add") issues.push({
18566
+ path: `${at}/op`,
18567
+ message: "expected \"replace\", \"remove\", or \"add\"."
18568
+ });
20156
18569
  }
20157
- /**
20158
- * The squared length of a vector.
20159
- *
20160
- * @param v - The vector to measure.
20161
- * @returns The squared length.
20162
- */
20163
- static lengthSquared(v) {
20164
- return v.x * v.x + v.y * v.y + v.z * v.z;
18570
+ }
18571
+ /**
18572
+ * Validates a `transform` entry.
18573
+ *
18574
+ * @param value - The entry.
18575
+ * @param path - Its path.
18576
+ * @param issues - Where problems are appended.
18577
+ */
18578
+ function validateTransform(value, path, issues) {
18579
+ const transform = asRecord(value);
18580
+ if (transform === null) {
18581
+ issues.push({
18582
+ path,
18583
+ message: "expected an object with position, rotation, and scale."
18584
+ });
18585
+ return;
20165
18586
  }
20166
- /**
20167
- * The distance between two positions, in metres.
20168
- *
20169
- * @param a - The first position.
20170
- * @param b - The second position.
20171
- * @returns The distance.
20172
- */
20173
- static distance(a, b) {
20174
- return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
18587
+ requireNumbers(transform["position"], `${path}/position`, 3, issues);
18588
+ requireNumbers(transform["rotation"], `${path}/rotation`, 4, issues);
18589
+ requireNumbers(transform["scale"], `${path}/scale`, 3, issues);
18590
+ }
18591
+ /**
18592
+ * Validates a `tags` array.
18593
+ *
18594
+ * @param value - The array, or `undefined`.
18595
+ * @param path - Its path.
18596
+ * @param issues - Where problems are appended.
18597
+ */
18598
+ function validateTags(value, path, issues) {
18599
+ if (value === void 0) return;
18600
+ if (!Array.isArray(value)) {
18601
+ issues.push({
18602
+ path,
18603
+ message: "expected an array of strings."
18604
+ });
18605
+ return;
20175
18606
  }
20176
- /**
20177
- * The squared distance between two positions. Compare squared distances to avoid a square root.
20178
- *
20179
- * @param a - The first position.
20180
- * @param b - The second position.
20181
- * @returns The squared distance.
20182
- */
20183
- static distanceSquared(a, b) {
20184
- const dx = a.x - b.x;
20185
- const dy = a.y - b.y;
20186
- const dz = a.z - b.z;
20187
- return dx * dx + dy * dy + dz * dz;
18607
+ for (let index = 0; index < value.length; index += 1) if (typeof value[index] !== "string") issues.push({
18608
+ path: `${path}/${String(index)}`,
18609
+ message: "expected a string."
18610
+ });
18611
+ }
18612
+ /**
18613
+ * Checks a uid: a non-empty string, unique within the file.
18614
+ *
18615
+ * @param value - The candidate.
18616
+ * @param path - Its path.
18617
+ * @param uids - Uids already seen.
18618
+ * @param issues - Where problems are appended.
18619
+ */
18620
+ function requireUid(value, path, uids, issues) {
18621
+ if (typeof value !== "string" || value === "") {
18622
+ issues.push({
18623
+ path,
18624
+ message: "expected a non-empty uid string."
18625
+ });
18626
+ return;
20188
18627
  }
20189
- /**
20190
- * Compares two vectors component by component, with a tolerance.
20191
- *
20192
- * @param a - The first vector.
20193
- * @param b - The second vector.
20194
- * @param epsilon - The largest per-component difference still considered equal.
20195
- * @returns `true` when every component matches within `epsilon`.
20196
- */
20197
- static equalsWithEpsilon(a, b, epsilon = EPSILON) {
20198
- return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon;
18628
+ if (uids.has(value)) {
18629
+ issues.push({
18630
+ path,
18631
+ message: `the uid ${value} is used twice; uids are unique within a file.`
18632
+ });
18633
+ return;
20199
18634
  }
20200
- };
18635
+ uids.add(value);
18636
+ }
20201
18637
  /**
20202
- * The frozen zero vector, `(0, 0, 0)`. Read-only: pass it anywhere a {@link Vec3Like} is wanted, and
20203
- * call {@link Vec3.zero} when you need a vector you can write to.
18638
+ * Checks an optional boolean.
20204
18639
  *
20205
- * @public
18640
+ * @param value - The candidate.
18641
+ * @param path - Its path.
18642
+ * @param issues - Where problems are appended.
20206
18643
  */
20207
- const VEC3_ZERO = Object.freeze({
20208
- x: 0,
20209
- y: 0,
20210
- z: 0
20211
- });
18644
+ function requireBoolean(value, path, issues) {
18645
+ if (value !== void 0 && typeof value !== "boolean") issues.push({
18646
+ path,
18647
+ message: "expected a boolean."
18648
+ });
18649
+ }
20212
18650
  /**
20213
- * The frozen vector whose components are all one, `(1, 1, 1)` — the identity scale.
18651
+ * Checks a fixed-length array of finite numbers.
20214
18652
  *
20215
- * @public
18653
+ * @param value - The candidate.
18654
+ * @param path - Its path.
18655
+ * @param length - How many entries are required.
18656
+ * @param issues - Where problems are appended.
20216
18657
  */
20217
- const VEC3_ONE = Object.freeze({
20218
- x: 1,
20219
- y: 1,
20220
- z: 1
20221
- });
18658
+ function requireNumbers(value, path, length, issues) {
18659
+ if (!Array.isArray(value) || value.length !== length) {
18660
+ issues.push({
18661
+ path,
18662
+ message: `expected an array of ${String(length)} numbers.`
18663
+ });
18664
+ return;
18665
+ }
18666
+ for (let index = 0; index < value.length; index += 1) {
18667
+ const entry = value[index];
18668
+ if (typeof entry !== "number" || !Number.isFinite(entry)) issues.push({
18669
+ path: `${path}/${String(index)}`,
18670
+ message: "expected a finite number."
18671
+ });
18672
+ }
18673
+ }
20222
18674
  /**
20223
- * The frozen world up direction, `(0, 1, 0)`.
18675
+ * Narrows a value to a string-keyed object.
20224
18676
  *
20225
- * @public
18677
+ * @param value - The candidate.
18678
+ * @returns The record, or `null` when the value is not a plain object.
20226
18679
  */
20227
- const VEC3_UP = Object.freeze({
20228
- x: 0,
20229
- y: 1,
20230
- z: 0
20231
- });
18680
+ function asRecord(value) {
18681
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
18682
+ return value;
18683
+ }
18684
+ //#endregion
18685
+ //#region src/serialization/scene-loader.ts
20232
18686
  /**
20233
- * The frozen world down direction, `(0, -1, 0)`.
18687
+ * The `AssetLoader` for `*.scene.json` and `*.prefab.json`
18688
+ * (`docs/architecture/06-serialization-and-scene-format.md` §4 steps 1 and 2, ADR-0005 — one
18689
+ * loader for levels and prefabs).
18690
+ *
18691
+ * @remarks
18692
+ * The loader does everything the file needs *before* the world sees it: parse, check the header and
18693
+ * the format version, validate the structure, then resolve every `$asset` it can find — in
18694
+ * `settings`, in every component's `props`, and in every `instance.scene`, recursively through the
18695
+ * scene assets those pull in. The resulting `SceneAsset` therefore carries a fully loaded
18696
+ * dependency set, which is what makes `world.instantiate` synchronous
18697
+ * (`02-scene-graph.md` §2).
18698
+ *
18699
+ * @param options - Whether to validate.
18700
+ * @returns The loader to register with `ctx.registerAssetLoader`.
18701
+ *
18702
+ * @example
18703
+ * ```ts
18704
+ * ctx.registerAssetLoader(createSceneLoader());
18705
+ * const level = await app.assets.loadAsync<SceneAsset>("levels/level01.scene.json");
18706
+ * ```
20234
18707
  *
20235
18708
  * @public
20236
18709
  */
20237
- const VEC3_DOWN = Object.freeze({
20238
- x: 0,
20239
- y: -1,
20240
- z: 0
20241
- });
18710
+ function createSceneLoader(options) {
18711
+ const validate = options?.validate ?? true;
18712
+ return {
18713
+ type: SCENE_ASSET_TYPE,
18714
+ extensions: SCENE_FILE_EXTENSIONS,
18715
+ async load(ctx) {
18716
+ const file = readSceneFile(await ctx.fetchJson(), ctx.address, validate);
18717
+ const dependencies = await loadDependencies(file, ctx);
18718
+ return {
18719
+ address: ctx.address,
18720
+ file,
18721
+ dependencies,
18722
+ hash: await computeSceneHash(file)
18723
+ };
18724
+ }
18725
+ };
18726
+ }
20242
18727
  /**
20243
- * The frozen world right direction, `(1, 0, 0)`.
18728
+ * Checks a parsed file's header, version, and structure.
20244
18729
  *
20245
- * @public
18730
+ * @param parsed - The parsed JSON.
18731
+ * @param address - The address, for diagnostics.
18732
+ * @param validate - `true` runs the structural validation.
18733
+ * @returns The file.
18734
+ * @throws IgnifxError with code `IGX-0308` when the header is missing, `IGX-0603` when the format
18735
+ * version is not readable, and `IGX-0608` when the structure does not match.
18736
+ *
18737
+ * @internal
20246
18738
  */
20247
- const VEC3_RIGHT = Object.freeze({
20248
- x: 1,
20249
- y: 0,
20250
- z: 0
20251
- });
18739
+ function readSceneFile(parsed, address, validate) {
18740
+ if (!isSceneFileHeader(parsed)) throw new IgnifxError(CoreErrorCode.notASceneFile, `${address} is not an ignifx scene file.`, {
18741
+ context: { file: address },
18742
+ hint: "A scene file carries { \"format\": \"ignifx.scene\", \"formatVersion\": 1 }."
18743
+ });
18744
+ const version = parsed["formatVersion"];
18745
+ if (version !== 1) throw new IgnifxError(CoreErrorCode.unsupportedFormatVersion, `${address} declares format version ${String(version)}, which this build cannot read.`, {
18746
+ context: {
18747
+ file: address,
18748
+ version: String(version)
18749
+ },
18750
+ hint: `This build reads ignifx.scene version ${String(1)}.`
18751
+ });
18752
+ if (validate) {
18753
+ const issues = validateSceneFile(parsed);
18754
+ const first = issues[0];
18755
+ if (first !== void 0) throw new IgnifxError(CoreErrorCode.sceneFileInvalid, `${address} does not match the scene file schema: ${issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`, { context: {
18756
+ file: address,
18757
+ issues: issues.length,
18758
+ first: first.path
18759
+ } });
18760
+ }
18761
+ return asSceneFile(parsed);
18762
+ }
20252
18763
  /**
20253
- * The frozen world left direction, `(-1, 0, 0)`.
18764
+ * Loads every asset the file references, in a stable order: `settings` first, then each entity's
18765
+ * `instance.scene`, then each component's `props`
18766
+ * (`docs/architecture/06-serialization-and-scene-format.md` §4 step 2).
20254
18767
  *
20255
- * @public
18768
+ * @param file - The parsed file.
18769
+ * @param ctx - The loader context.
18770
+ * @returns The loaded handles, deduplicated by address, in discovery order.
20256
18771
  */
20257
- const VEC3_LEFT = Object.freeze({
20258
- x: -1,
20259
- y: 0,
20260
- z: 0
20261
- });
18772
+ async function loadDependencies(file, ctx) {
18773
+ const requests = [];
18774
+ const seen = /* @__PURE__ */ new Set();
18775
+ const add = (address, type) => {
18776
+ if (address === "" || seen.has(address)) return;
18777
+ seen.add(address);
18778
+ requests.push({
18779
+ address,
18780
+ type
18781
+ });
18782
+ };
18783
+ const settings = file.settings;
18784
+ if (settings !== void 0) collectAssetRefs(settings, add);
18785
+ for (let index = 0; index < file.entities.length; index += 1) {
18786
+ const entity = file.entities[index];
18787
+ if (entity !== void 0) collectEntityRefs(entity, add);
18788
+ }
18789
+ return Promise.all(requests.map(async (request) => ctx.loadDependency(request.address, request.type === null ? void 0 : { type: request.type })));
18790
+ }
20262
18791
  /**
20263
- * The frozen world forward direction, `(0, 0, 1)`. ignifx is left-handed, so forward is +Z
20264
- * (ADR-0011).
18792
+ * Collects the asset references of one entity: its `instance.scene` first, so a nested scene is
18793
+ * loaded before the props that may name sub-assets of it, then every component's props.
20265
18794
  *
20266
- * @public
18795
+ * @param entity - The entity record.
18796
+ * @param add - Called with each address and its declared type.
20267
18797
  */
20268
- const VEC3_FORWARD = Object.freeze({
20269
- x: 0,
20270
- y: 0,
20271
- z: 1
20272
- });
18798
+ function collectEntityRefs(entity, add) {
18799
+ const instance = entity.instance;
18800
+ if (instance !== void 0) {
18801
+ add(instance.scene.$asset, instance.scene.type ?? "scene");
18802
+ const overrides = instance.overrides ?? [];
18803
+ for (let index = 0; index < overrides.length; index += 1) {
18804
+ const value = overrides[index]?.value;
18805
+ if (value !== void 0) collectAssetRefs(value, add);
18806
+ }
18807
+ }
18808
+ const components = entity.components ?? [];
18809
+ for (let index = 0; index < components.length; index += 1) {
18810
+ const props = components[index]?.props;
18811
+ if (props !== void 0) collectAssetRefs(props, add);
18812
+ }
18813
+ }
20273
18814
  /**
20274
- * The frozen world backward direction, `(0, 0, -1)`.
18815
+ * Walks any JSON and reports every `{ "$asset": … }` it finds, at any depth.
20275
18816
  *
20276
- * @public
18817
+ * @param value - The JSON to walk.
18818
+ * @param add - Called with each address and its declared type.
20277
18819
  */
20278
- const VEC3_BACKWARD = Object.freeze({
20279
- x: 0,
20280
- y: 0,
20281
- z: -1
20282
- });
18820
+ function collectAssetRefs(value, add) {
18821
+ const items = asJsonArray(value);
18822
+ if (items !== null) {
18823
+ for (let index = 0; index < items.length; index += 1) collectAssetRefs(items[index] ?? null, add);
18824
+ return;
18825
+ }
18826
+ const object = asJsonObject(value);
18827
+ if (object === null) return;
18828
+ const address = object["$asset"];
18829
+ if (typeof address === "string") {
18830
+ const type = object["type"];
18831
+ add(address, typeof type === "string" ? type : null);
18832
+ return;
18833
+ }
18834
+ for (const key of Object.keys(object)) collectAssetRefs(object[key] ?? null, add);
18835
+ }
20283
18836
  //#endregion
20284
18837
  //#region src/math/quat.ts
20285
18838
  /**
@@ -33471,7 +32024,10 @@ var AppImpl = class {
33471
32024
  const world = this.#world;
33472
32025
  if (world !== null) renderer.syncBeforeRegister(world);
33473
32026
  renderer.warmUpAtStart();
32027
+ trackMaterialCacheResets(handles.scene, renderer.materialCacheResets);
33474
32028
  await registerRenderScene(handles.scene, { shadows: features.shadows });
32029
+ await learnMaterialCacheResets(handles.scene, renderer.materialCacheResets);
32030
+ renderer.needsCasterRebuild = true;
33475
32031
  renderer.markSceneRegistered();
33476
32032
  }
33477
32033
  /** Stops the Lite loop, detaches the browser listeners, and runs `onStop` in reverse order. */