@needle-tools/engine 5.1.9 → 5.1.11

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 (105) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/SKILL.md +64 -4
  3. package/components.needle.json +1 -1
  4. package/dist/{needle-engine.bundle-CHq9xqXv.min.js → needle-engine.bundle-d-dLyN3s.min.js} +137 -136
  5. package/dist/{needle-engine.bundle-DYPk7VZg.umd.cjs → needle-engine.bundle-n5YALNtc.umd.cjs} +140 -139
  6. package/dist/{needle-engine.bundle-XZ6cKssu.js → needle-engine.bundle-ue2Lw4bF.js} +5267 -5101
  7. package/dist/needle-engine.d.ts +138 -26
  8. package/dist/needle-engine.js +522 -518
  9. package/dist/needle-engine.min.js +1 -1
  10. package/dist/needle-engine.umd.cjs +1 -1
  11. package/dist/three-examples.js +727 -781
  12. package/dist/three-examples.min.js +12 -12
  13. package/dist/three-examples.umd.cjs +9 -9
  14. package/lib/engine/api.d.ts +1 -1
  15. package/lib/engine/api.js +1 -1
  16. package/lib/engine/api.js.map +1 -1
  17. package/lib/engine/engine_init.js +2 -2
  18. package/lib/engine/engine_init.js.map +1 -1
  19. package/lib/engine/engine_license.d.ts +7 -7
  20. package/lib/engine/engine_license.js +71 -71
  21. package/lib/engine/engine_license.js.map +1 -1
  22. package/lib/engine/engine_materialpropertyblock.d.ts +13 -4
  23. package/lib/engine/engine_materialpropertyblock.js +16 -5
  24. package/lib/engine/engine_materialpropertyblock.js.map +1 -1
  25. package/lib/engine/engine_math.d.ts +13 -0
  26. package/lib/engine/engine_math.js +17 -0
  27. package/lib/engine/engine_math.js.map +1 -1
  28. package/lib/engine/engine_networking_blob.js +3 -3
  29. package/lib/engine/engine_networking_blob.js.map +1 -1
  30. package/lib/engine/engine_utils_qrcode.js +2 -2
  31. package/lib/engine/engine_utils_qrcode.js.map +1 -1
  32. package/lib/engine/postprocessing/postprocessing.d.ts +18 -0
  33. package/lib/engine/postprocessing/postprocessing.js +31 -2
  34. package/lib/engine/postprocessing/postprocessing.js.map +1 -1
  35. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js +2 -2
  36. package/lib/engine/webcomponents/needle menu/needle-menu-spatial.js.map +1 -1
  37. package/lib/engine/webcomponents/needle menu/needle-menu.js +5 -5
  38. package/lib/engine/webcomponents/needle menu/needle-menu.js.map +1 -1
  39. package/lib/engine/webcomponents/needle-engine.js +2 -2
  40. package/lib/engine/webcomponents/needle-engine.js.map +1 -1
  41. package/lib/engine/webcomponents/needle-engine.loading.js +2 -2
  42. package/lib/engine/webcomponents/needle-engine.loading.js.map +1 -1
  43. package/lib/engine/xr/TempXRContext.js +2 -2
  44. package/lib/engine/xr/TempXRContext.js.map +1 -1
  45. package/lib/engine/xr/XRHandMeshModel.d.ts +31 -0
  46. package/lib/engine/xr/XRHandMeshModel.js +153 -0
  47. package/lib/engine/xr/XRHandMeshModel.js.map +1 -0
  48. package/lib/engine-components/DragControls.d.ts +0 -5
  49. package/lib/engine-components/DragControls.js +0 -8
  50. package/lib/engine-components/DragControls.js.map +1 -1
  51. package/lib/engine-components/ReflectionProbe.js +3 -3
  52. package/lib/engine-components/ReflectionProbe.js.map +1 -1
  53. package/lib/engine-components/RendererInstancing.d.ts +34 -3
  54. package/lib/engine-components/RendererInstancing.js +92 -11
  55. package/lib/engine-components/RendererInstancing.js.map +1 -1
  56. package/lib/engine-components/RendererLightmap.js +1 -1
  57. package/lib/engine-components/RendererLightmap.js.map +1 -1
  58. package/lib/engine-components/SyncedRoom.js +5 -0
  59. package/lib/engine-components/SyncedRoom.js.map +1 -1
  60. package/lib/engine-components/export/usdz/USDZExporter.js +4 -4
  61. package/lib/engine-components/export/usdz/USDZExporter.js.map +1 -1
  62. package/lib/engine-components/postprocessing/Effects/DepthOfField.js +10 -2
  63. package/lib/engine-components/postprocessing/Effects/DepthOfField.js.map +1 -1
  64. package/lib/engine-components/postprocessing/index.d.ts +4 -0
  65. package/lib/engine-components/postprocessing/index.js +7 -0
  66. package/lib/engine-components/postprocessing/index.js.map +1 -1
  67. package/lib/engine-components/splines/SplineWalker.js +9 -3
  68. package/lib/engine-components/splines/SplineWalker.js.map +1 -1
  69. package/lib/engine-components/utils/LookAt.d.ts +13 -4
  70. package/lib/engine-components/utils/LookAt.js +13 -4
  71. package/lib/engine-components/utils/LookAt.js.map +1 -1
  72. package/lib/engine-components/webxr/WebXR.js +1 -1
  73. package/lib/engine-components/webxr/WebXR.js.map +1 -1
  74. package/lib/engine-components/webxr/controllers/XRControllerModel.d.ts +1 -1
  75. package/lib/engine-components/webxr/controllers/XRControllerModel.js +12 -7
  76. package/lib/engine-components/webxr/controllers/XRControllerModel.js.map +1 -1
  77. package/package.json +2 -2
  78. package/plugins/common/license.js +4 -4
  79. package/plugins/vite/license.js +4 -4
  80. package/src/engine/api.ts +1 -1
  81. package/src/engine/engine_init.ts +2 -2
  82. package/src/engine/engine_license.ts +68 -68
  83. package/src/engine/engine_materialpropertyblock.ts +17 -5
  84. package/src/engine/engine_math.ts +17 -0
  85. package/src/engine/engine_networking_blob.ts +3 -3
  86. package/src/engine/engine_utils_qrcode.ts +2 -2
  87. package/src/engine/postprocessing/postprocessing.ts +32 -2
  88. package/src/engine/webcomponents/needle menu/needle-menu-spatial.ts +2 -2
  89. package/src/engine/webcomponents/needle menu/needle-menu.ts +5 -5
  90. package/src/engine/webcomponents/needle-engine.loading.ts +6 -6
  91. package/src/engine/webcomponents/needle-engine.ts +2 -2
  92. package/src/engine/xr/TempXRContext.ts +2 -2
  93. package/src/engine/xr/XRHandMeshModel.ts +179 -0
  94. package/src/engine-components/DragControls.ts +0 -7
  95. package/src/engine-components/ReflectionProbe.ts +3 -3
  96. package/src/engine-components/RendererInstancing.ts +92 -11
  97. package/src/engine-components/RendererLightmap.ts +1 -1
  98. package/src/engine-components/SyncedRoom.ts +5 -0
  99. package/src/engine-components/export/usdz/USDZExporter.ts +4 -4
  100. package/src/engine-components/postprocessing/Effects/DepthOfField.ts +10 -2
  101. package/src/engine-components/postprocessing/index.ts +7 -0
  102. package/src/engine-components/splines/SplineWalker.ts +9 -3
  103. package/src/engine-components/utils/LookAt.ts +13 -4
  104. package/src/engine-components/webxr/WebXR.ts +1 -1
  105. package/src/engine-components/webxr/controllers/XRControllerModel.ts +13 -7
@@ -3,7 +3,7 @@ import type { Texture } from "three";
3
3
  import { isDevEnvironment, showBalloonWarning } from "../debug/index.js";
4
4
  import { PUBLIC_KEY, VERSION } from "../engine_constants.js";
5
5
  import { ContextEvent, ContextRegistry } from "../engine_context_registry.js";
6
- import { _$qxlHFE, Telemetry } from "../engine_license.js";
6
+ import { __zrAx, Telemetry } from "../engine_license.js";
7
7
  import { onStart } from "../engine_lifecycle_api.js";
8
8
  import { setDracoDecoderPath, setDracoDecoderType, setKtx2TranscoderPath } from "../engine_loaders.gltf.js";
9
9
  import { Context, ContextCreateArgs } from "../engine_setup.js";
@@ -579,7 +579,7 @@ export class NeedleEngineWebComponent extends HTMLElementBase implements INeedle
579
579
 
580
580
 
581
581
  // Loading start events
582
- const allowOverridingDefaultLoading = _$qxlHFE();
582
+ const allowOverridingDefaultLoading = __zrAx();
583
583
  // default loading can be overriden by calling preventDefault in the onload start event
584
584
  this.ensureLoadStartIsRegistered();
585
585
  let useDefaultLoading = this.dispatchEvent(new CustomEvent("loadstart", {
@@ -3,7 +3,7 @@ import { ArrayCamera, AxesHelper, Camera, Color, DirectionalLight, Fog, GridHelp
3
3
  import { needleLogoOnlySVG } from "../assets/index.js";
4
4
  import { isDevEnvironment } from "../debug/index.js";
5
5
  import { ObjectUtils, PrimitiveType } from "../engine_create_objects.js";
6
- import { _$qxlHFE } from "../engine_license.js";
6
+ import { __zrAx } from "../engine_license.js";
7
7
  import { Mathf } from "../engine_math.js";
8
8
  import { delay, DeviceUtilities } from "../engine_utils.js";
9
9
 
@@ -215,7 +215,7 @@ export class TemporaryXRContext {
215
215
  this._scene.background = new Color(0x000000);
216
216
 
217
217
  let logoSrc = needleLogoOnlySVG;
218
- if (_$qxlHFE()) {
218
+ if (__zrAx()) {
219
219
  const htmlComponent = document.querySelector("needle-engine");
220
220
  if (htmlComponent) {
221
221
  const licenseLogo = htmlComponent.getAttribute("logo-src");
@@ -0,0 +1,179 @@
1
+ import { type Bone, type Object3D, type XRHandSpace } from "three";
2
+ import type { GLTF } from "three/examples/jsm/loaders/GLTFLoader.js";
3
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
4
+
5
+ /**
6
+ * Vendored from three's `examples/jsm/webxr/XRHandMeshModel.js` (r185).
7
+ *
8
+ * WHY THIS IS OWNED BY THE ENGINE AND NOT PATCHED IN THE THREE FORK
9
+ * -----------------------------------------------------------------
10
+ * three addons carry no API stability guarantee and this one changed under us twice:
11
+ *
12
+ * - r184 replaced `const object = gltf.scene.children[0]` with
13
+ * `const object = clone(gltf.scene.children[0])`. That single word broke every custom
14
+ * (Unity-exported) hand model, silently: `SkeletonUtils.clone` runs `Object3D.copy`,
15
+ * which deep-copies userData via `JSON.parse(JSON.stringify(...))`. Needle stores live
16
+ * component instances in `userData.components`, and components hold a `gameObject`
17
+ * back-reference, so that throws "Converting circular structure to JSON" — swallowed by
18
+ * GLTFLoader into an onError nobody had set, leaving an empty, invisible hand.
19
+ * - The clone also broke component creation: `XRControllerModel` creates the glTF's builtin
20
+ * components after load, but the parser's node -> object associations point at the parsed
21
+ * original while the clone is what gets displayed.
22
+ *
23
+ * DELIBERATE DIFFERENCES FROM UPSTREAM
24
+ * ------------------------------------
25
+ * 1. No clone. Upstream needs it only because of `customCache`, where several hands share
26
+ * one parsed gltf. We never pass a cache and build a fresh GLTFLoader per hand load, so
27
+ * nothing is shared and the clone was pure overhead. Using the parsed object directly
28
+ * restores the pre-r184 contract the engine is written against: `handModel.add(object)`
29
+ * reparents it out of `gltf.scene` (Object3D.add calls removeFromParent), object identity
30
+ * is preserved so the parser's node map stays valid, and components created during parse
31
+ * live on the object that is actually rendered.
32
+ * 2. `customCache` is dropped entirely rather than left unused — sharing a parsed hand
33
+ * between models would reintroduce the aliasing the clone existed to prevent.
34
+ * 3. The hand mesh inherits the layer mask of the object it is added to (the engine puts
35
+ * hands on the ignore-raycast layer).
36
+ * 4. Load failures are reported instead of vanishing.
37
+ * 5. A missing SkinnedMesh or missing joints no longer throw / spam per joint.
38
+ *
39
+ * When bumping three, diff this against the upstream file and fold in real fixes by hand.
40
+ */
41
+
42
+ const DEFAULT_HAND_PROFILE_PATH = "https://cdn.jsdelivr.net/npm/@webxr-input-profiles/assets@1.0/dist/profiles/generic-hand/";
43
+
44
+ /** The joints of a WebXR hand, in the order three's hand models declare them. */
45
+ const JOINT_NAMES = [
46
+ "wrist",
47
+ "thumb-metacarpal",
48
+ "thumb-phalanx-proximal",
49
+ "thumb-phalanx-distal",
50
+ "thumb-tip",
51
+ "index-finger-metacarpal",
52
+ "index-finger-phalanx-proximal",
53
+ "index-finger-phalanx-intermediate",
54
+ "index-finger-phalanx-distal",
55
+ "index-finger-tip",
56
+ "middle-finger-metacarpal",
57
+ "middle-finger-phalanx-proximal",
58
+ "middle-finger-phalanx-intermediate",
59
+ "middle-finger-phalanx-distal",
60
+ "middle-finger-tip",
61
+ "ring-finger-metacarpal",
62
+ "ring-finger-phalanx-proximal",
63
+ "ring-finger-phalanx-intermediate",
64
+ "ring-finger-phalanx-distal",
65
+ "ring-finger-tip",
66
+ "pinky-finger-metacarpal",
67
+ "pinky-finger-phalanx-proximal",
68
+ "pinky-finger-phalanx-intermediate",
69
+ "pinky-finger-phalanx-distal",
70
+ "pinky-finger-tip",
71
+ ] as const;
72
+
73
+ type JointBone = Bone & { jointName?: string };
74
+
75
+ /**
76
+ * Renders a skinned hand mesh and drives its bones from the tracked WebXR joint poses.
77
+ *
78
+ * @see {@link XRControllerModel} which creates one per tracked hand.
79
+ */
80
+ export class XRHandMeshModel {
81
+
82
+ /** The three XRHandSpace whose `joints` drive this mesh. */
83
+ readonly controller: XRHandSpace;
84
+ /** The object the loaded hand mesh is added to. */
85
+ readonly handModel: Object3D;
86
+ /** The bones driven by {@link updateMesh}, in {@link JOINT_NAMES} order. Sparse if the model lacks joints. */
87
+ readonly bones: Array<JointBone | undefined> = [];
88
+
89
+ /**
90
+ * @param handModel the object the loaded mesh is parented to
91
+ * @param controller the hand space providing joint poses
92
+ * @param path base path for the model (defaults to the generic hand profile CDN)
93
+ * @param handedness file name to load (without extension) — either "left"/"right" for the
94
+ * default profile, or a full path for a custom hand model
95
+ * @param loader loader to use; a plain GLTFLoader is created when omitted
96
+ * @param onLoad invoked with the loaded hand object once it has been added
97
+ */
98
+ constructor(
99
+ handModel: Object3D,
100
+ controller: XRHandSpace,
101
+ path: string | null,
102
+ handedness: string,
103
+ loader: GLTFLoader | null = null,
104
+ onLoad: ((object: Object3D) => void) | null = null,
105
+ ) {
106
+ this.controller = controller;
107
+ this.handModel = handModel;
108
+
109
+ const pathToUse = path || DEFAULT_HAND_PROFILE_PATH;
110
+
111
+ if (loader === null) {
112
+ loader = new GLTFLoader();
113
+ loader.setPath(pathToUse);
114
+ }
115
+
116
+ const url = `${handedness}.glb`;
117
+ loader.load(url,
118
+ (gltf: GLTF) => {
119
+ const object = gltf.scene.children[0];
120
+ if (!object) {
121
+ console.error(`XRHandMeshModel: "${pathToUse}${url}" contains no hand object.`);
122
+ return;
123
+ }
124
+
125
+ // NOTE: adding reparents `object` out of `gltf.scene` (Object3D.add calls
126
+ // removeFromParent), which is what lets the caller detect that the hand has
127
+ // been taken over and create the glTF's builtin components on it.
128
+ this.handModel.add(object);
129
+ // the hand mesh inherits the layers of whatever it was added to
130
+ object.layers.mask = this.handModel.layers.mask;
131
+
132
+ const mesh = object.getObjectByProperty("type", "SkinnedMesh");
133
+ if (mesh) {
134
+ mesh.frustumCulled = false;
135
+ mesh.castShadow = true;
136
+ mesh.receiveShadow = true;
137
+ }
138
+ else {
139
+ console.warn(`XRHandMeshModel: no SkinnedMesh in the ${handedness} hand model — it will not deform.`);
140
+ }
141
+
142
+ const missing: string[] = [];
143
+ for (const jointName of JOINT_NAMES) {
144
+ const bone = object.getObjectByName(jointName) as JointBone | undefined;
145
+ if (bone) bone.jointName = jointName;
146
+ else missing.push(jointName);
147
+ this.bones.push(bone);
148
+ }
149
+ // one warning instead of one per joint — a model with the wrong rig misses all 25
150
+ if (missing.length) {
151
+ console.warn(`XRHandMeshModel: the ${handedness} hand model is missing ${missing.length} of ${JOINT_NAMES.length} joints (${missing.join(", ")}).`);
152
+ }
153
+
154
+ onLoad?.(object);
155
+ },
156
+ undefined,
157
+ (err: unknown) => {
158
+ // Upstream passes no error handler, so a failed hand model silently leaves an
159
+ // empty object and no hand is ever visible. Surface it instead.
160
+ console.error(`XRHandMeshModel: failed to load the ${handedness} hand model from "${pathToUse}${url}" — the hand will not be visible.`, err);
161
+ });
162
+ }
163
+
164
+ /** Copies the current tracked joint poses onto the mesh bones. Called every XR frame. */
165
+ updateMesh() {
166
+ const XRJoints = this.controller.joints;
167
+
168
+ for (let i = 0; i < this.bones.length; i++) {
169
+ const bone = this.bones[i];
170
+ if (!bone?.jointName) continue;
171
+
172
+ const XRJoint = XRJoints[bone.jointName];
173
+ if (XRJoint?.visible) {
174
+ bone.position.copy(XRJoint.position);
175
+ bone.quaternion.copy(XRJoint.quaternion);
176
+ }
177
+ }
178
+ }
179
+ }
@@ -197,13 +197,6 @@ export class DragControls extends Behaviour implements IPointerEventHandler {
197
197
  @serializable()
198
198
  public xrDistanceDragFactor: number = 1;
199
199
 
200
- /**
201
- * When enabled, draws a visual line from the dragged object downwards to the next raycast hit,
202
- * providing visual feedback about the object's position relative to surfaces below it.
203
- */
204
- @serializable()
205
- public showGizmo: boolean = false;
206
-
207
200
  /** Drag profile for screen / touch / mouse input. Reads live from the flat serialized fields. */
208
201
  readonly screenProfile: DragProfile = new DragProfile(this, false);
209
202
  /** Drag profile for XR tracked-pointer and transient-pointer input. Reads live from the flat `xr*` serialized fields. */
@@ -289,9 +289,9 @@ export class ReflectionProbe extends Behaviour {
289
289
  if (block) {
290
290
  const current = block.getOverride("envMap")?.value;
291
291
  if (current === this.texture) {
292
- block.removeOveride("envMap");
293
- block.removeOveride("envMapRotation");
294
- block.removeOveride("envMapIntensity");
292
+ block.removeOverride("envMap");
293
+ block.removeOverride("envMapRotation");
294
+ block.removeOverride("envMapIntensity");
295
295
  }
296
296
  }
297
297
  }
@@ -1,5 +1,5 @@
1
1
  import { calculateMeshLODLevel, getLODColor } from "@needle-tools/gltf-progressive";
2
- import { BatchedMesh, BufferGeometry, Color, Material, Matrix4, Mesh, MeshStandardMaterial, Object3D, RawShaderMaterial, Vector3 } from "three";
2
+ import { BatchedMesh, BufferGeometry, Color, Material, Matrix4, Mesh, MeshStandardMaterial, Object3D, RawShaderMaterial, Sphere, Vector3 } from "three";
3
3
 
4
4
  import { isDevEnvironment, showBalloonError } from "../engine/debug/index.js";
5
5
  import { Gizmos } from "../engine/engine_gizmos.js";
@@ -25,6 +25,11 @@ function trackProgressiveLOD<T>(context: Context, type: "mesh" | "texture", obje
25
25
  return promise;
26
26
  }
27
27
 
28
+ /** Mirrored = negative determinant, which reverses triangle winding. */
29
+ function isMirrored(matrix: Matrix4): boolean {
30
+ return matrix.determinant() < 0;
31
+ }
32
+
28
33
  /**
29
34
  * Handles instancing for Needle Engine.
30
35
  */
@@ -108,8 +113,12 @@ export class InstancingHandler {
108
113
  const mat = mesh.material as Material | Material[];
109
114
  if (Array.isArray(mat)) return null;
110
115
 
116
+ // mirrored objects need their own batch, see InstancedMeshRenderer
117
+ mesh.updateWorldMatrix(true, false);
118
+ const mirrored = isMirrored(mesh.matrixWorld);
119
+
111
120
  for (const i of this.objs) {
112
- if (!i.canAdd(geometry, mat)) continue;
121
+ if (!i.canAdd(geometry, mat, mirrored)) continue;
113
122
  const handle = i.addInstance(mesh, geometry);
114
123
  return handle;
115
124
  }
@@ -119,7 +128,7 @@ export class InstancingHandler {
119
128
  }
120
129
  let name = obj.name;
121
130
  if (!name?.length) name = makeIdFromRandomWords();
122
- const i = new InstancedMeshRenderer(name, geometry, mat, maxInstances, context);
131
+ const i = new InstancedMeshRenderer(name, geometry, mat, maxInstances, context, mirrored);
123
132
  this.objs.push(i);
124
133
  const handle = i.addInstance(mesh, geometry);
125
134
  return handle;
@@ -240,8 +249,18 @@ export class InstanceHandle {
240
249
  updateInstanceMatrix(updateChildren: boolean = false, updateMatrix: boolean = true) {
241
250
  if (this.__instanceIndex < 0) return;
242
251
  if (updateMatrix) this.object.updateWorldMatrix(true, updateChildren);
252
+ this.assertMirroringUnchanged();
243
253
  this.renderer.updateInstance(this.object.matrixWorld, this.__instanceIndex);
244
254
  }
255
+
256
+ private _didWarnAboutMirroringChange = false;
257
+ /** Batches are bucketed by mirroring at setup time and an instance can not move between them. */
258
+ private assertMirroringUnchanged() {
259
+ if (this._didWarnAboutMirroringChange) return;
260
+ if (isMirrored(this.object.matrixWorld) === this.renderer.mirrored) return;
261
+ this._didWarnAboutMirroringChange = true;
262
+ console.warn(`[Instancing] "${this.name}" changed its mirroring at runtime (world matrix determinant flipped sign). Instanced objects can not change mirroring - this object will render its backfaces. Disable instancing for it via Renderer.setInstanced(obj, false).`);
263
+ }
245
264
  /** Updates the matrix of the instance */
246
265
  setMatrix(matrix: Matrix4) {
247
266
  if (this.__instanceIndex < 0) return;
@@ -320,6 +339,23 @@ export class InstanceHandle {
320
339
  }
321
340
  }
322
341
 
342
+ /**
343
+ * Renders one geometry+material combination for many objects using a
344
+ * {@link https://threejs.org/docs/#api/en/objects/BatchedMesh | BatchedMesh}.
345
+ *
346
+ * The BatchedMesh belongs to this class: it is created here, parented directly to the untransformed
347
+ * `context.scene` and never moved, so its transform is whatever {@link applyBatchTransform} puts
348
+ * there and nothing else.
349
+ *
350
+ * **Mirroring:** three flips the winding for a mirrored transform per *draw call*, from
351
+ * `object.matrixWorld.determinant()` - and for a batch that object is the BatchedMesh, not the
352
+ * instance. So mirrored instances get their own batch, which carries the mirror on its own
353
+ * transform (`scale.z = -1`); otherwise their front faces would be culled.
354
+ *
355
+ * That mirror is the one transform the shader's `modelMatrix * batchingMatrix` would otherwise apply
356
+ * twice, so a mirrored batch stores its instance matrices with it undone. Every other batch is
357
+ * untransformed and stores world matrices as they are.
358
+ */
323
359
  class InstancedMeshRenderer {
324
360
  /** The three instanced mesh
325
361
  * @link https://threejs.org/docs/#api/en/objects/InstancedMesh
@@ -327,6 +363,11 @@ class InstancedMeshRenderer {
327
363
  get batchedMesh() {
328
364
  return this._batchedMesh;
329
365
  }
366
+
367
+ /** True if this batch renders mirrored objects. A batch only holds one or the other. */
368
+ get mirrored() {
369
+ return this._mirrored;
370
+ }
330
371
  get visible(): boolean {
331
372
  return this._batchedMesh.visible;
332
373
  }
@@ -369,15 +410,17 @@ class InstancedMeshRenderer {
369
410
  if (sphere)
370
411
  this._batchedMesh.computeBoundingSphere();
371
412
  if (debugInstancing && this._batchedMesh.boundingSphere) {
372
- const sphere = this._batchedMesh.boundingSphere;
373
- // const worldPos = this._batchedMesh.worldPosition.add(sphere.center);
374
- // const worldRadius = sphere!.radius;
413
+ // the bounding sphere is in the batch's local space, the gizmo expects world space
414
+ const sphere = InstancedMeshRenderer.debugBoundsSphere
415
+ .copy(this._batchedMesh.boundingSphere)
416
+ .applyMatrix4(this._batchedMesh.matrixWorld);
375
417
  Gizmos.DrawWireSphere(sphere.center, sphere.radius, 0x00ff00);
376
418
  }
377
419
  }
378
420
 
379
421
  private _context: Context;
380
422
  private _batchedMesh: BatchedMesh;
423
+ private readonly _mirrored: boolean;
381
424
  private _handles: (InstanceHandle | null)[] = [];
382
425
  private _geometryIds = new WeakMap<BufferGeometry, number>();
383
426
  private _maxInstanceCount: number;
@@ -389,8 +432,9 @@ class InstancedMeshRenderer {
389
432
  private _maxVertexCount: number;
390
433
  private _maxIndexCount: number;
391
434
 
392
- private static nullMatrix: Matrix4 = new Matrix4();
435
+ private static instanceMatrix: Matrix4 = new Matrix4();
393
436
  private static lodProjectionScreenMatrix: Matrix4 = new Matrix4();
437
+ private static debugBoundsSphere: Sphere = new Sphere();
394
438
  private static debugLODColor = new Color();
395
439
  private static lodSelectionResult = {
396
440
  level: -1,
@@ -403,12 +447,15 @@ class InstancedMeshRenderer {
403
447
  /** Check if the geometry can be added to this instancer
404
448
  * @param geometry The geometry to check
405
449
  * @param material The material of the geometry
450
+ * @param mirrored Whether the object's world matrix has a negative determinant
406
451
  * @returns true if the geometry can be added
407
452
  */
408
- canAdd(geometry: BufferGeometry, material: Material): boolean {
453
+ canAdd(geometry: BufferGeometry, material: Material, mirrored: boolean): boolean {
409
454
 
410
455
  if (this._maxVertexCount > 10_000_000) return false;
411
456
 
457
+ if (this._mirrored !== mirrored) return false;
458
+
412
459
  // The material instance must match
413
460
  // perhaps at some point later we *could* check if it's the same shader and properties but this would be risky
414
461
  if (material !== this.material) {
@@ -482,11 +529,12 @@ class InstancedMeshRenderer {
482
529
  return this.name ? `${this.name} (BatchedMesh)` : "BatchedMesh";
483
530
  }
484
531
 
485
- constructor(name: string, geo: BufferGeometry, material: Material, initialMaxCount: number, context: Context) {
532
+ constructor(name: string, geo: BufferGeometry, material: Material, initialMaxCount: number, context: Context, mirrored: boolean = false) {
486
533
  this.name = name;
487
534
  this.geometry = geo;
488
535
  this.material = material;
489
536
  this._context = context;
537
+ this._mirrored = mirrored;
490
538
  this._maxInstanceCount = Math.max(2, initialMaxCount);
491
539
  if (debugInstancing) {
492
540
  this._debugMaterial = createDebugMaterial(debugLODColors);
@@ -496,6 +544,7 @@ class InstancedMeshRenderer {
496
544
  this._maxIndexCount = estimate.indexCount;
497
545
  this._batchedMesh = new BatchedMesh(this._maxInstanceCount, this._maxVertexCount, this._maxIndexCount, this._debugMaterial ?? this.material);
498
546
  this._batchedMesh.name = this.getBatchedMeshName();
547
+ this.applyBatchTransform(this._batchedMesh);
499
548
  // this.inst = new InstancedMesh(geo, material, count);
500
549
  this._batchedMesh[$instancingAutoUpdateBounds] = true;
501
550
  // this.inst.count = 0;
@@ -614,10 +663,39 @@ class InstancedMeshRenderer {
614
663
  }
615
664
 
616
665
  updateInstance(mat: Matrix4, index: number) {
617
- this._batchedMesh.setMatrixAt(index, mat);
666
+ this.setInstanceMatrix(index, mat);
618
667
  this.markNeedsUpdate();
619
668
  }
620
669
 
670
+ /** The batch's own transform. This class owns it: the mirror is the only thing that ever goes
671
+ * here, and the batch is never reparented away from the untransformed scene root. */
672
+ private applyBatchTransform(batch: BatchedMesh) {
673
+ // every other batch keeps the identity a fresh BatchedMesh is constructed with
674
+ if (!this._mirrored) return;
675
+ if (batch.scale.z === -1) return;
676
+ // negative determinant on the batch itself -> three flips the winding for the whole draw call
677
+ batch.scale.z = -1;
678
+ // three composes the TRS into matrix/matrixWorld no earlier than the render, which would leave
679
+ // those identity for a frame - and updateBounds() reads matrixWorld from a pre-render callback
680
+ batch.updateMatrixWorld();
681
+ }
682
+
683
+ /** Writes a *world* matrix to an instance slot, converted into the batch's local space.
684
+ * All instance matrix writes go through here. */
685
+ private setInstanceMatrix(index: number, worldMatrix: Matrix4) {
686
+ if (!this._mirrored) {
687
+ // an untransformed batch: local space *is* world space
688
+ this._batchedMesh.setMatrixAt(index, worldMatrix);
689
+ return;
690
+ }
691
+ // undo the batch's mirror, so the shader's modelMatrix * batchingMatrix composes back to the world matrix.
692
+ // a pure z flip only negates row 2 (column-major indices 2/6/10/14), so it's cheaper than a full multiply
693
+ const local = InstancedMeshRenderer.instanceMatrix.copy(worldMatrix);
694
+ const e = local.elements;
695
+ e[2] = -e[2]; e[6] = -e[6]; e[10] = -e[10]; e[14] = -e[14];
696
+ this._batchedMesh.setMatrixAt(index, local);
697
+ }
698
+
621
699
  updateGeometry(geo: BufferGeometry, geometryIndex: number): boolean {
622
700
  if (!this.validateGeometry(geo)) {
623
701
  return false;
@@ -815,11 +893,14 @@ class InstancedMeshRenderer {
815
893
  newInst.receiveShadow = this._batchedMesh.receiveShadow;
816
894
  newInst.visible = this._batchedMesh.visible;
817
895
  newInst[$instancingAutoUpdateBounds] = this._batchedMesh[$instancingAutoUpdateBounds];
896
+
818
897
  newInst.matrixAutoUpdate = this._batchedMesh.matrixAutoUpdate;
819
898
  newInst.matrixWorldNeedsUpdate = this._batchedMesh.matrixWorldNeedsUpdate;
820
899
  newInst.matrixAutoUpdate = this._batchedMesh.matrixAutoUpdate;
821
900
  newInst.matrixWorld.copy(this._batchedMesh.matrixWorld);
822
901
  newInst.matrix.copy(this._batchedMesh.matrix);
902
+ // the replacement must carry the mirror too, otherwise every instance in it ends up culled
903
+ this.applyBatchTransform(newInst);
823
904
 
824
905
  // dispose the old batched mesh
825
906
  this._batchedMesh.dispose();
@@ -942,7 +1023,7 @@ class InstancedMeshRenderer {
942
1023
  handle.__instanceIndex = i;
943
1024
  handle.__reservedVertexRange = handle.maxVertexCount;
944
1025
  handle.__reservedIndexRange = handle.maxIndexCount;
945
- this._batchedMesh.setMatrixAt(i, handle.object.matrixWorld);
1026
+ this.setInstanceMatrix(i, handle.object.matrixWorld);
946
1027
  this.updateDebugLODColor(handle);
947
1028
  if (debugInstancing)
948
1029
  console.debug(`[Instancing] > ADDED INSTANCE \"${handle.name}\"\nGEOMETRY_ID=${geometryId}\n${this._currentInstanceCount} instances\nIndex: ${handle.__instanceIndex}\nVertices: ${this._currentVertexCount.toLocaleString()}/${this._maxVertexCount.toLocaleString()},\nIndices: ${this._currentIndexCount.toLocaleString()}/${this._maxIndexCount.toLocaleString()}`);
@@ -146,7 +146,7 @@ export class RendererLightmap {
146
146
  }
147
147
  const block = MaterialPropertyBlock.get(this.gameObject);
148
148
  if (block) {
149
- block.removeOveride("lightMap");
149
+ block.removeOverride("lightMap");
150
150
  }
151
151
  }
152
152
 
@@ -190,6 +190,11 @@ export class SyncedRoom extends Behaviour {
190
190
  if (val && (typeof val === "string" || typeof val === "number")) {
191
191
  hasRoomParameter = true;
192
192
  const roomNameParam = utils.sanitizeString(val.toString());
193
+ // The URL parameter takes precedence over the configured roomName. That is
194
+ // easy to miss when a room name was set deliberately, so say so in dev.
195
+ if ((debug || isDevEnvironment()) && this.roomName?.length > 0 && this.roomName !== roomNameParam) {
196
+ console.warn(`[SyncedRoom] Joining "${roomNameParam}" from the "${this.urlParameterName}" URL parameter — the roomName set on the component ("${this.roomName}") is ignored.\nThe URL parameter always wins. To use the component's room name instead, clear "urlParameterName".`);
197
+ }
193
198
  this.roomName = roomNameParam;
194
199
  }
195
200
  else if (this.joinRandomRoom) {
@@ -3,7 +3,7 @@ import { Euler, Material, Matrix4, Mesh, Object3D, Quaternion, Vector3 } from "t
3
3
 
4
4
  import { isDevEnvironment, showBalloonMessage, showBalloonWarning } from "../../../engine/debug/index.js";
5
5
  import { findObjectOfType } from "../../../engine/engine_components.js";
6
- import { _iXmRJVD } from "../../../engine/engine_license.js";
6
+ import { oMxKl } from "../../../engine/engine_license.js";
7
7
  import { serializable } from "../../../engine/engine_serialization.js";
8
8
  import { getFormattedDate, Progress } from "../../../engine/engine_time_utils.js";
9
9
  import { DeviceUtilities, getParam } from "../../../engine/engine_utils.js";
@@ -277,7 +277,7 @@ export class USDZExporter extends Behaviour {
277
277
  let name = this.exportFileName ?? this.objectToExport?.name ?? this.name;
278
278
  name += "-" + getFormattedDate(); // seems iOS caches the file in some cases, this ensures we always have a fresh file
279
279
 
280
- if (!_iXmRJVD()) {
280
+ if (!oMxKl()) {
281
281
  if (name !== "") name += "-";
282
282
  name += "MadeWithNeedle";
283
283
  }
@@ -682,7 +682,7 @@ export class USDZExporter extends Behaviour {
682
682
  if (debug)
683
683
  showBalloonMessage("Quicklook url: " + callToActionURL);
684
684
  if (callToActionURL) {
685
- if (!_iXmRJVD()) {
685
+ if (!oMxKl()) {
686
686
  console.warn("Quicklook closed: custom redirects require a Needle Engine Pro license: https://needle.tools/pricing", callToActionURL)
687
687
  }
688
688
  else {
@@ -697,7 +697,7 @@ export class USDZExporter extends Behaviour {
697
697
  private buildQuicklookOverlay(): CustomBranding {
698
698
  const obj: CustomBranding = {};
699
699
  if (this.customBranding) Object.assign(obj, this.customBranding);
700
- if (!_iXmRJVD()) {
700
+ if (!oMxKl()) {
701
701
  console.log("Custom Quicklook banner text requires pro license: https://needle.tools/pricing");
702
702
  obj.callToAction = "Close";
703
703
  obj.checkoutTitle = "🌵 Made with Needle";
@@ -83,12 +83,20 @@ export class DepthOfField extends PostProcessingEffect {
83
83
  // inverted: true,
84
84
  // // blendFunction: BlendFunction.SET,
85
85
  // });
86
+ // Seed from the parameters, the same way BloomEffect does. The
87
+ // onValueChanged handlers below only fire on a LATER assignment, so
88
+ // hardcoding defaults here discarded anything set before the effect
89
+ // was created — which is the usual case, since components are
90
+ // configured right after addComponent but the effect is built when
91
+ // the composer asks for it. Values applied in awake/start were lost
92
+ // and only took hold if the same value was assigned a second time.
86
93
  const dof = new MODULES.POSTPROCESSING.MODULE.DepthOfFieldEffect(this.context.mainCamera!, {
87
- worldFocusRange: .2,
94
+ worldFocusRange: this.focalLength.value,
88
95
  focalLength: 1,
89
- bokehScale: 20,
96
+ bokehScale: this.aperture.value,
90
97
  resolutionScale: this.resolutionScale.value,
91
98
  });
99
+ dof.cocMaterial.worldFocusDistance = this.focusDistance.value;
92
100
 
93
101
  this.focusDistance.onValueChanged = v => {
94
102
  dof.cocMaterial.worldFocusDistance = v;
@@ -1,6 +1,13 @@
1
1
  export * from "./PostProcessingEffect.js";
2
2
  export * from "./PostProcessingHandler.js"
3
3
  export { PostProcessingEffectOrder } from "./utils.js";
4
+ /* Effect option enums. The effect components themselves are exported from
5
+ codegen/components.ts, but these were unreachable: `DepthOfField.mode`
6
+ could not be set to a named value from outside the package. */
7
+ export { DepthOfFieldMode } from "./Effects/DepthOfField.js";
8
+ export { QualityLevel } from "./Effects/Antialiasing.js";
9
+ export { ScreenSpaceAmbientOcclusionN8QualityMode } from "./Effects/ScreenspaceAmbientOcclusionN8.js";
10
+ export { NEToneMappingMode } from "./Effects/Tonemapping.utils.js";
4
11
  export { PostProcessingManager } from "./Volume.js"
5
12
  export { Volume } from "./Volume.js"
6
13
  export * from "./VolumeParameter.js"
@@ -74,7 +74,11 @@ export class SplineWalker extends Behaviour {
74
74
  return this._position01;
75
75
  }
76
76
  set position01(v: number) {
77
- this._position01 = v;
77
+ // Normalize on assignment so reading the value back is predictable and never out of range.
78
+ // Doing this only in updateFromPosition() made it depend on a spline + curve + object being
79
+ // ready and a frame having run — until then this property reported e.g. 1.5.
80
+ // Note this is destructive (as clamping always is): setting 1.5 while clamped stores 1.
81
+ this._position01 = this.clamp ? Mathf.clamp01(v) : Mathf.repeat(v);
78
82
  this._needsUpdate = true;
79
83
  }
80
84
 
@@ -156,10 +160,12 @@ export class SplineWalker extends Behaviour {
156
160
  if (!this.spline || !this.spline.curve) return;
157
161
  if (!this.object) return;
158
162
 
163
+ // Still normalized here as well: autoRun accumulates into _position01 directly (bypassing the
164
+ // setter), and `clamp` may change after a value was assigned.
159
165
  if (this.clamp) this._position01 = Mathf.clamp01(this._position01);
160
- else this._position01 = this._position01 % 1;
166
+ else this._position01 = Mathf.repeat(this._position01);
161
167
 
162
- const t = this._position01 >= 1 ? 1 : this._position01 % 1;
168
+ const t = this._position01 >= 1 ? 1 : Mathf.repeat(this._position01);
163
169
  const pt = this.spline.getPointAt(t);
164
170
 
165
171
  if (this.pullStrength >= 1) {
@@ -20,25 +20,34 @@ import { Behaviour } from "../Component.js";
20
20
  export class LookAt extends Behaviour implements UsdzBehaviour {
21
21
 
22
22
  /**
23
- * The target object to look at. If not set, the main camera will be used.
23
+ * The target object to look at.
24
+ * @default undefined — when no target is set the main camera is used
24
25
  */
25
26
  @serializable(Object3D)
26
27
  target?: Object3D;
27
28
 
28
29
  /**
29
- * Inverts the forward direction.
30
+ * Inverts the forward direction, so the object turns its back to the target
31
+ * instead of facing it. Useful for models authored facing -Z.
32
+ * @default false
30
33
  */
31
34
  @serializable()
32
35
  invertForward: boolean = false;
33
36
 
34
37
  /**
35
- * Keep the up direction.
38
+ * Keeps the object upright while turning, so it only rotates around the up
39
+ * axis rather than tilting to point directly at a target above or below it.
40
+ * @default true
36
41
  */
37
42
  @serializable()
38
43
  keepUpDirection: boolean = true;
39
44
 
40
45
  /**
41
- * Copy the target rotation.
46
+ * Copies the target's rotation instead of aiming at its position. Use this to
47
+ * match a target's orientation, for example to align with the camera.
48
+ *
49
+ * Ignored during a VR or AR session.
50
+ * @default false
42
51
  */
43
52
  @serializable()
44
53
  copyTargetRotation: boolean = false;
@@ -520,7 +520,7 @@ export class WebXR extends Behaviour {
520
520
  models = this.gameObject.addComponent(XRControllerModel)!;
521
521
  this._createdComponentsInSession.push(models);
522
522
  models.createControllerModel = this.showControllerModels;
523
- models.createHandModel == this.showHandModels;
523
+ models.createHandModel = this.showHandModels;
524
524
  }
525
525
  if (models) models.enabled = enabled;
526
526
  return models;