@khr3/core 0.2.9 → 0.2.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 (76) hide show
  1. package/README.md +5 -175
  2. package/dist/KhrAssembly-CKW8I_2z.js +1667 -0
  3. package/dist/KhrAssembly-CKW8I_2z.js.map +1 -0
  4. package/dist/KhrAssembly.d.ts +46 -8
  5. package/dist/KhrCollider.d.ts +21 -7
  6. package/dist/clone.d.ts +40 -0
  7. package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
  8. package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
  9. package/dist/index.d.ts +10 -10
  10. package/dist/index.js +1548 -343
  11. package/dist/index.js.map +1 -1
  12. package/dist/{khrInertia.d.ts → inertia.d.ts} +22 -8
  13. package/dist/{jointDynamics.d.ts → joints.d.ts} +8 -7
  14. package/dist/loader.d.ts +9 -0
  15. package/dist/types.d.ts +282 -0
  16. package/dist/useKhrGlb.d.ts +6 -1
  17. package/dist/vehicle.d.ts +35 -2
  18. package/dist/vehicle.js +435 -539
  19. package/dist/vehicle.js.map +1 -1
  20. package/dist/wheelLoads.d.ts +5 -4
  21. package/package.json +6 -25
  22. package/AGENTS.md +0 -12
  23. package/CLAUDE.md +0 -8
  24. package/dist/AssemblyRootBody.d.ts +0 -16
  25. package/dist/BundleSceneHost.d.ts +0 -23
  26. package/dist/KhrVehicle.d.ts +0 -20
  27. package/dist/assemblyPlan.d.ts +0 -61
  28. package/dist/curves-Cf8okB-M.js +0 -542
  29. package/dist/curves-Cf8okB-M.js.map +0 -1
  30. package/dist/curves.d.ts +0 -378
  31. package/dist/curves.js +0 -1
  32. package/dist/khrBundleFinalize.d.ts +0 -15
  33. package/dist/khrClone.d.ts +0 -14
  34. package/dist/khrConfigTypes.d.ts +0 -62
  35. package/dist/khrExportEncoders.d.ts +0 -8
  36. package/dist/khrExtras.d.ts +0 -22
  37. package/dist/khrInertia-DgCUCDTx.js +0 -247
  38. package/dist/khrInertia-DgCUCDTx.js.map +0 -1
  39. package/dist/khrJointParser.d.ts +0 -3
  40. package/dist/khrLoader.d.ts +0 -7
  41. package/dist/khrMassProps.d.ts +0 -16
  42. package/dist/khrParsers.d.ts +0 -10
  43. package/dist/khrPlugin.d.ts +0 -8
  44. package/dist/khrPluginHelpers.d.ts +0 -26
  45. package/dist/khrRotorDecoders.d.ts +0 -4
  46. package/dist/khrShapeParser.d.ts +0 -8
  47. package/dist/khrTypes.d.ts +0 -141
  48. package/dist/khrVehicleChassis.d.ts +0 -20
  49. package/dist/khrVehicleJointHelpers.d.ts +0 -37
  50. package/dist/khrVehicleJoints.d.ts +0 -30
  51. package/dist/khrVehicleRotors.d.ts +0 -22
  52. package/dist/khrVehicleSlots.d.ts +0 -41
  53. package/dist/khrVehicleTypes.d.ts +0 -52
  54. package/dist/pacejka.d.ts +0 -22
  55. package/dist/physicsEcs-C00N5zCh.js +0 -914
  56. package/dist/physicsEcs-C00N5zCh.js.map +0 -1
  57. package/dist/physicsEcs.d.ts +0 -25
  58. package/dist/sand3d/sand3dAssemblyHelpers.d.ts +0 -30
  59. package/dist/sand3d/sand3dCavityOps.d.ts +0 -15
  60. package/dist/sand3d/sand3dCompiler.d.ts +0 -121
  61. package/dist/sand3d/sand3dEvaluator.d.ts +0 -80
  62. package/dist/sand3d/sand3dFramesAndEdits.d.ts +0 -30
  63. package/dist/sand3d/sand3dHullAndSweep.d.ts +0 -27
  64. package/dist/sand3d/sand3dParser.d.ts +0 -6
  65. package/dist/sand3d/sand3dPrimitives.d.ts +0 -50
  66. package/dist/sand3d/sand3dProfiles.d.ts +0 -32
  67. package/dist/sand3d/sand3dRecipes.d.ts +0 -5
  68. package/dist/sand3d/sand3dShellOp.d.ts +0 -8
  69. package/dist/sand3d/sand3dSolids.d.ts +0 -32
  70. package/dist/sand3d/sand3dTokenizer.d.ts +0 -8
  71. package/dist/sand3d/sand3dTypes.d.ts +0 -157
  72. package/dist/sand3d-DQ8-OMlo.js +0 -5045
  73. package/dist/sand3d-DQ8-OMlo.js.map +0 -1
  74. package/dist/sand3d.d.ts +0 -23
  75. package/dist/sand3d.js +0 -1
  76. package/docs/api-reference.md +0 -383
package/dist/index.js CHANGED
@@ -1,13 +1,12 @@
1
- import { a as SAND3D_RECIPE_MAP, c as isSand3dFileName, ct as KHR_BUNDLE_USERDATA_KEY, dt as isHeadlessTextureEnv, ft as applyKhrCustomExtractors, i as SAND3D_RECIPES, l as parseSand3dSource, lt as createKhrGltfPlugin, n as exportSand3dGlb, o as buildSand3dRecipe, ot as exportKhrGlb, pt as patchGlbJsonChunk, r as loadSand3dBundle, s as findSand3dRecipe, st as loadKhrGlb, t as compileSand3dAssembly, u as s3d, ut as createHeadlessTexturePlugin } from "./sand3d-DQ8-OMlo.js";
2
- import { _ as releaseBundleMount, a as MountSubtreeSlot, c as planAssembly, f as KhrCollider, h as disposeKhrBundle, i as BundleSceneHost, m as cloneKhrBundle, n as buildJointRuntime, o as captureSubtreeOrigins, p as claimBundleMount, r as createRapierImpulseJoint, t as JointRegistryContext } from "./physicsEcs-C00N5zCh.js";
3
- import { n as assertSceneIdentityWorldScale, r as assertUnitScale, t as assertIdentityWorldScale, u as KhrValidationError } from "./khrInertia-DgCUCDTx.js";
4
- import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
1
+ import { useMemo } from "react";
5
2
  import { useFrame, useLoader } from "@react-three/fiber";
6
- import { Physics, RigidBody, useRapier } from "@react-three/rapier";
3
+ import { Physics, useRapier } from "@react-three/rapier";
7
4
  import { TimeControl } from "@pinkaphant/ecctrl/time";
8
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
- import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
5
+ import { A as computeShapeInertia, B as isObj, C as assertSceneIdentityWorldScale, D as computeBodyInertia, E as computeAssemblyMassAndCom, F as JointRegistryContext, H as optFiniteNum, I as KhrValidationError, L as assignRef, M as readFiniteVec3, N as readUnitQuat, P as COMBINE_MODES, R as isFiniteNum, S as assertIdentityWorldScale, V as isPosNum, _ as cloneKhrBundle, a as DETACHED_PANEL_INTERACTION_GROUPS, b as releaseBundleMount, c as createRapierImpulseJoint, d as openTargetForLimits, f as KhrCollider, g as claimBundleMount, i as ATTACHED_PANEL_INTERACTION_GROUPS, j as extractMeshColliderShape, k as computeRelativePose, l as isJointOpen, n as planAssembly, o as buildJointRuntime, s as configureJointDrive, t as KhrAssembly, u as measureJointCoordinate, v as disposeKhrBundle, w as assertUnitScale, z as isNonNegNum } from "./KhrAssembly-CKW8I_2z.js";
6
+ import { jsx, jsxs } from "react/jsx-runtime";
10
7
  import * as THREE from "three";
8
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
9
+ import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
11
10
  // src/PhysicsWorld.tsx
12
11
  var readVal = (v) => typeof v === "number" ? v : v.current;
13
12
  function TimestepPresync({ paused, timeScale, maxDelta }) {
@@ -15,7 +14,7 @@ function TimestepPresync({ paused, timeScale, maxDelta }) {
15
14
  useFrame((_, delta) => {
16
15
  const md = Math.max(0, readVal(maxDelta));
17
16
  const ts = readVal(timeScale);
18
- world.timestep = !paused && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
17
+ world.timestep = !paused && Number.isFinite(ts) && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
19
18
  });
20
19
  return null;
21
20
  }
@@ -24,390 +23,1596 @@ function PhysicsWorld({ paused = false, timeScale = 1, maxDelta = 1 / 30, gravit
24
23
  -9.81,
25
24
  0
26
25
  ], children, ...physicsProps }) {
27
- return /* @__PURE__ */ jsxs(Physics, {
28
- ...physicsProps,
29
- paused: true,
30
- timeStep: "vary",
31
- gravity,
32
- children: [
33
- /* @__PURE__ */ jsx(TimestepPresync, {
34
- paused,
35
- timeScale,
36
- maxDelta
37
- }),
38
- children,
39
- /* @__PURE__ */ jsx(TimeControl, {
40
- paused,
41
- timeScale,
42
- maxDelta
43
- })
44
- ]
26
+ const jointRegistry = useMemo(() => /* @__PURE__ */ new Set(), []);
27
+ return /* @__PURE__ */ jsx(JointRegistryContext.Provider, {
28
+ value: jointRegistry,
29
+ children: /* @__PURE__ */ jsxs(Physics, {
30
+ ...physicsProps,
31
+ paused: true,
32
+ timeStep: "vary",
33
+ gravity,
34
+ children: [
35
+ /* @__PURE__ */ jsx(TimestepPresync, {
36
+ paused,
37
+ timeScale,
38
+ maxDelta
39
+ }),
40
+ children,
41
+ /* @__PURE__ */ jsx(TimeControl, {
42
+ paused,
43
+ timeScale,
44
+ maxDelta
45
+ })
46
+ ]
47
+ })
45
48
  });
46
49
  }
47
- // src/AssemblyRootBody.tsx
48
- function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef, origin, onBody, onJointReady }) {
49
- const { rapier, world } = useRapier();
50
- const registry = useContext(JointRegistryContext);
51
- const childRef = useRef(null);
52
- const rtRef = useRef(null);
53
- const worldPose = useMemo(() => {
54
- const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
55
- const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
50
+ // src/glb.ts
51
+ /** ASCII "glTF" little-endian fourCC. */
52
+ var GLB_MAGIC = 0x46546c67;
53
+ /** ASCII "JSON" little-endian fourCC. */
54
+ var GLB_JSON_CHUNK = 0x4e4f534a;
55
+ /** ASCII "BIN\0" little-endian fourCC. */
56
+ var GLB_BIN_CHUNK = 5130562;
57
+ function validateGlbHeader(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
58
+ if (byteLength < 20) throw new KhrValidationError("GLB buffer shorter than 20-byte header");
59
+ const view = new DataView(buffer, byteOffset, byteLength);
60
+ if (view.getUint32(0, true) !== 0x46546c67) throw new KhrValidationError("Invalid GLB magic");
61
+ if (view.getUint32(4, true) !== 2) throw new KhrValidationError("Unsupported glTF version");
62
+ const jsonLen = view.getUint32(12, true);
63
+ if (view.getUint32(16, true) !== 0x4e4f534a) throw new KhrValidationError("Missing GLB JSON chunk");
64
+ if (20 + jsonLen > byteLength) throw new KhrValidationError("Truncated GLB JSON chunk");
65
+ return jsonLen;
66
+ }
67
+ function bytesToBase64(bytes) {
68
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
69
+ const CHUNK = 32768;
70
+ const chunks = [];
71
+ for (let i = 0; i < bytes.length; i += CHUNK) chunks.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK)));
72
+ return btoa(chunks.join(""));
73
+ }
74
+ function ensureHeadlessFileReader() {
75
+ if (globalThis.FileReader !== void 0) return;
76
+ class HeadlessFileReader extends EventTarget {
77
+ static EMPTY = 0;
78
+ static LOADING = 1;
79
+ static DONE = 2;
80
+ EMPTY = 0;
81
+ LOADING = 1;
82
+ DONE = 2;
83
+ readyState = 0;
84
+ result = null;
85
+ error = null;
86
+ onload = null;
87
+ onloadend = null;
88
+ onerror = null;
89
+ abort() {
90
+ this.readyState = 2;
91
+ }
92
+ readAsArrayBuffer(blob) {
93
+ this.readyState = 1;
94
+ blob.arrayBuffer().then((buf) => {
95
+ this.result = buf;
96
+ this.readyState = 2;
97
+ this.onload?.({ target: this });
98
+ this.dispatchEvent(new Event("load"));
99
+ this.onloadend?.({ target: this });
100
+ this.dispatchEvent(new Event("loadend"));
101
+ }, (err) => {
102
+ this.error = err;
103
+ this.readyState = 2;
104
+ this.onerror?.(err);
105
+ this.dispatchEvent(new Event("error"));
106
+ this.onloadend?.({ target: this });
107
+ this.dispatchEvent(new Event("loadend"));
108
+ });
109
+ }
110
+ readAsDataURL(blob) {
111
+ this.readyState = 1;
112
+ blob.arrayBuffer().then((buf) => {
113
+ const b64 = bytesToBase64(new Uint8Array(buf));
114
+ this.result = `data:${blob.type || "application/octet-stream"};base64,${b64}`;
115
+ this.readyState = 2;
116
+ this.onload?.({ target: this });
117
+ this.dispatchEvent(new Event("load"));
118
+ this.onloadend?.({ target: this });
119
+ this.dispatchEvent(new Event("loadend"));
120
+ }, (err) => {
121
+ this.error = err;
122
+ this.readyState = 2;
123
+ this.onerror?.(err);
124
+ this.dispatchEvent(new Event("error"));
125
+ this.onloadend?.({ target: this });
126
+ this.dispatchEvent(new Event("loadend"));
127
+ });
128
+ }
129
+ }
130
+ globalThis.FileReader = HeadlessFileReader;
131
+ }
132
+ function packJsonToGlb(gltf) {
133
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
134
+ const paddedJsonLen = jsonBytes.byteLength + 3 & -4;
135
+ const totalLen = 20 + paddedJsonLen;
136
+ const out = new ArrayBuffer(totalLen);
137
+ const dv = new DataView(out);
138
+ const u8 = new Uint8Array(out);
139
+ dv.setUint32(0, GLB_MAGIC, true);
140
+ dv.setUint32(4, 2, true);
141
+ dv.setUint32(8, totalLen, true);
142
+ dv.setUint32(12, paddedJsonLen, true);
143
+ dv.setUint32(16, GLB_JSON_CHUNK, true);
144
+ u8.set(jsonBytes, 20);
145
+ u8.fill(32, 20 + jsonBytes.byteLength, 20 + paddedJsonLen);
146
+ return out;
147
+ }
148
+ function patchGlbJsonChunk(source, mutator) {
149
+ const buf = source instanceof ArrayBuffer ? source : source.buffer;
150
+ const byteOffset = source instanceof ArrayBuffer ? 0 : source.byteOffset;
151
+ const byteLength = source.byteLength;
152
+ const jsonLen = validateGlbHeader(buf, byteOffset, byteLength);
153
+ const dv = new DataView(buf, byteOffset, byteLength);
154
+ let gltf;
155
+ try {
156
+ gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, byteOffset + 20, jsonLen)));
157
+ } catch {
158
+ throw new KhrValidationError("Malformed GLB JSON chunk");
159
+ }
160
+ mutator(gltf);
161
+ const nextJson = new TextEncoder().encode(JSON.stringify(gltf));
162
+ const paddedJsonLen = nextJson.byteLength + 3 & -4;
163
+ const binHeaderOff = 20 + jsonLen;
164
+ const hasBin = binHeaderOff < byteLength;
165
+ let binTag = GLB_BIN_CHUNK;
166
+ let binData = /* @__PURE__ */ new Uint8Array(0);
167
+ if (hasBin) {
168
+ if (binHeaderOff + 8 > byteLength) throw new KhrValidationError("Truncated GLB binary chunk header");
169
+ const binLen = dv.getUint32(binHeaderOff, true);
170
+ binTag = dv.getUint32(binHeaderOff + 4, true);
171
+ if (binHeaderOff + 8 + binLen > byteLength) throw new KhrValidationError("Truncated GLB binary chunk payload");
172
+ binData = new Uint8Array(buf, byteOffset + binHeaderOff + 8, binLen);
173
+ }
174
+ const paddedBinLen = binData.byteLength + 3 & -4;
175
+ const totalLen = 20 + paddedJsonLen + (hasBin ? 8 + paddedBinLen : 0);
176
+ const out = new ArrayBuffer(totalLen);
177
+ const outDv = new DataView(out);
178
+ const outU8 = new Uint8Array(out);
179
+ outDv.setUint32(0, GLB_MAGIC, true);
180
+ outDv.setUint32(4, 2, true);
181
+ outDv.setUint32(8, totalLen, true);
182
+ outDv.setUint32(12, paddedJsonLen, true);
183
+ outDv.setUint32(16, GLB_JSON_CHUNK, true);
184
+ outU8.set(nextJson, 20);
185
+ outU8.fill(32, 20 + nextJson.byteLength, 20 + paddedJsonLen);
186
+ if (hasBin) {
187
+ outDv.setUint32(20 + paddedJsonLen, paddedBinLen, true);
188
+ outDv.setUint32(24 + paddedJsonLen, binTag, true);
189
+ outU8.set(binData, 28 + paddedJsonLen);
190
+ }
191
+ return out;
192
+ }
193
+ // src/loader.ts
194
+ var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
195
+ var HEADLESS_TEXTURE_EXT_NAMES = [
196
+ "EXT_texture_webp",
197
+ "EXT_texture_avif",
198
+ "KHR_texture_basisu"
199
+ ];
200
+ function isHeadlessTextureEnv() {
201
+ return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
202
+ }
203
+ function stubTextureInParser(parser, textureIndex) {
204
+ const tex = new THREE.Texture();
205
+ tex.flipY = false;
206
+ parser.associations.set(tex, { textures: textureIndex });
207
+ return Promise.resolve(tex);
208
+ }
209
+ function patchHeadlessTexturePlugins(parser) {
210
+ const plugins = parser.plugins;
211
+ if (!plugins) return;
212
+ for (const extName of HEADLESS_TEXTURE_EXT_NAMES) {
213
+ const existing = plugins[extName];
214
+ if (!existing) continue;
215
+ existing.loadTexture = (textureIndex) => {
216
+ if (!(parser.json?.textures?.[textureIndex])?.extensions?.[extName]) return null;
217
+ return stubTextureInParser(parser, textureIndex);
218
+ };
219
+ }
220
+ }
221
+ function reqArr(val, label) {
222
+ if (val === void 0) return [];
223
+ if (!Array.isArray(val)) throw new KhrValidationError(`${label} must be an array`);
224
+ return val;
225
+ }
226
+ function decodeShape(raw, idx) {
227
+ if (!isObj(raw)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] must be an object`);
228
+ const type = raw.type;
229
+ if (type === "box") {
230
+ if (raw.box !== void 0 && !isObj(raw.box)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box`);
231
+ const box = isObj(raw.box) ? raw.box : {};
232
+ const size = box.size === void 0 ? [
233
+ 1,
234
+ 1,
235
+ 1
236
+ ] : box.size;
237
+ if (!Array.isArray(size) || size.length !== 3 || !size.every(isPosNum)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box.size`);
56
238
  return {
57
- pos: [
58
- pos.x,
59
- pos.y,
60
- pos.z
61
- ],
62
- quat: [
63
- rq.x,
64
- rq.y,
65
- rq.z,
66
- rq.w
239
+ type: "box",
240
+ size: [
241
+ size[0],
242
+ size[1],
243
+ size[2]
67
244
  ]
68
245
  };
69
- }, [
70
- part.restRelRootPos,
71
- rootPos,
72
- rootQuat
73
- ]);
74
- useEffect(() => {
75
- onBody(part.spec.nodeName, childRef);
76
- return () => onBody(part.spec.nodeName, null);
77
- }, [part.spec.nodeName, onBody]);
78
- useEffect(() => {
79
- const rb = childRef.current;
80
- const pm = part.partMass;
81
- if (rb && pm) {
82
- rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
83
- rb.recomputeMassPropertiesFromColliders();
246
+ }
247
+ if (type === "sphere") {
248
+ if (raw.sphere !== void 0 && !isObj(raw.sphere)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere`);
249
+ const sphere = isObj(raw.sphere) ? raw.sphere : {};
250
+ const radius = sphere.radius === void 0 ? .5 : sphere.radius;
251
+ if (!isPosNum(radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere.radius`);
252
+ return {
253
+ type: "sphere",
254
+ radius
255
+ };
256
+ }
257
+ if (type === "cylinder" || type === "capsule") {
258
+ if (raw[type] !== void 0 && !isObj(raw[type])) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}`);
259
+ const g = isObj(raw[type]) ? raw[type] : {};
260
+ const height = g.height === void 0 ? type === "cylinder" ? 2 : 1 : g.height;
261
+ if (!isPosNum(height)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.height`);
262
+ const radiusTop = g.radiusTop === void 0 ? .5 : g.radiusTop;
263
+ const radiusBottom = g.radiusBottom === void 0 ? .5 : g.radiusBottom;
264
+ if (!isPosNum(radiusTop)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusTop`);
265
+ if (!isPosNum(radiusBottom)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusBottom`);
266
+ if (Math.abs(radiusTop - radiusBottom) > 1e-6) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] tapered ${type} (${radiusTop} !== ${radiusBottom}) is unsupported`);
267
+ return {
268
+ type,
269
+ height,
270
+ radiusTop,
271
+ radiusBottom
272
+ };
273
+ }
274
+ throw new KhrValidationError(`KHR_implicit_shapes[${idx}] unsupported shape type "${String(type)}"`);
275
+ }
276
+ function optCombineMode(v, label) {
277
+ if (v === void 0) return void 0;
278
+ if (typeof v !== "string" || !COMBINE_MODES.has(v)) throw new KhrValidationError(`Invalid ${label}: "${String(v)}"`);
279
+ return v;
280
+ }
281
+ function decodePhysicsMaterial(rawMaterials, idx, ownerName) {
282
+ if (idx === void 0) return {};
283
+ if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || idx >= rawMaterials.length) throw new KhrValidationError(`Node "${ownerName}" references out-of-bounds physicsMaterial ${String(idx)}`);
284
+ const mat = rawMaterials[idx];
285
+ if (!isObj(mat)) throw new KhrValidationError(`Invalid physicsMaterials[${idx}] on "${ownerName}"`);
286
+ const dynF = optFiniteNum(mat.dynamicFriction, `physicsMaterials[${idx}].dynamicFriction`, true);
287
+ const statF = optFiniteNum(mat.staticFriction, `physicsMaterials[${idx}].staticFriction`, true);
288
+ const rest = optFiniteNum(mat.restitution, `physicsMaterials[${idx}].restitution`, true);
289
+ const frictionCombine = optCombineMode(mat.frictionCombine, `physicsMaterials[${idx}].frictionCombine`);
290
+ const restitutionCombine = optCombineMode(mat.restitutionCombine, `physicsMaterials[${idx}].restitutionCombine`);
291
+ return {
292
+ ...dynF !== void 0 || statF !== void 0 ? { friction: dynF ?? statF } : {},
293
+ ...rest === void 0 ? {} : { restitution: rest },
294
+ ...frictionCombine === void 0 ? {} : { frictionCombine },
295
+ ...restitutionCombine === void 0 ? {} : { restitutionCombine }
296
+ };
297
+ }
298
+ function decodeCollisionGroups(rawFilters) {
299
+ const collisionSystemIds = /* @__PURE__ */ new Map([["default", 0]]);
300
+ let nextCollisionBit = 1;
301
+ const bitFor = (sys) => {
302
+ const hit = collisionSystemIds.get(sys);
303
+ if (hit !== void 0) return hit;
304
+ if (nextCollisionBit > 15) throw new KhrValidationError(`Exceeded Rapier 16-group limit for collisionSystem "${sys}"`);
305
+ const b = nextCollisionBit++;
306
+ collisionSystemIds.set(sys, b);
307
+ return b;
308
+ };
309
+ const maskFor = (arr, label) => {
310
+ if (arr === void 0) return 0;
311
+ if (!Array.isArray(arr)) throw new KhrValidationError(`collisionFilter.${label} must be an array`);
312
+ let mask = 0;
313
+ for (const s of arr) {
314
+ if (typeof s !== "string" || s.length === 0) throw new KhrValidationError(`collisionFilter.${label} has invalid system`);
315
+ mask |= 1 << bitFor(s);
84
316
  }
85
- }, [part.partMass]);
86
- useEffect(() => {
87
- const parentBody = parentBodyRef.current;
88
- const childBody = childRef.current;
89
- if (!parentBody || !childBody) return;
90
- const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
317
+ return mask;
318
+ };
319
+ return rawFilters.map((f, idx) => {
320
+ if (!isObj(f)) throw new KhrValidationError(`collisionFilters[${idx}] must be an object`);
321
+ if (f.collideWithSystems !== void 0 && f.notCollideWithSystems !== void 0) throw new KhrValidationError(`collisionFilters[${idx}] cannot specify both collideWithSystems and notCollideWithSystems`);
322
+ const membership = maskFor(f.collisionSystems, "collisionSystems");
323
+ const filter = f.collideWithSystems === void 0 ? 65535 & ~maskFor(f.notCollideWithSystems, "notCollideWithSystems") : maskFor(f.collideWithSystems, "collideWithSystems");
324
+ return (membership & 65535) << 16 | filter & 65535;
325
+ });
326
+ }
327
+ function decodeMotion(motion, hasMotion, name) {
328
+ if (motion.isKinematic !== void 0 && typeof motion.isKinematic !== "boolean") throw new KhrValidationError(`Node "${name}" has non-boolean motion.isKinematic`);
329
+ const isKinematic = !hasMotion || Boolean(motion.isKinematic);
330
+ let mass = 0;
331
+ if (!isKinematic) {
332
+ if (!isPosNum(motion.mass)) throw new KhrValidationError(`Dynamic node "${name}" is missing positive finite motion.mass`);
333
+ mass = motion.mass;
334
+ } else if (motion.mass !== void 0) {
335
+ if (!isNonNegNum(motion.mass)) throw new KhrValidationError(`Kinematic node "${name}" has invalid motion.mass`);
336
+ mass = motion.mass;
337
+ }
338
+ const centerOfMass = motion.centerOfMass === void 0 ? [
339
+ 0,
340
+ 0,
341
+ 0
342
+ ] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
343
+ const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
344
+ 0,
345
+ 0,
346
+ 0,
347
+ 1
348
+ ] : readUnitQuat(motion.inertiaOrientation, `${name}.motion.inertiaOrientation`);
349
+ let inertiaDiagonal = [
350
+ 0,
351
+ 0,
352
+ 0
353
+ ];
354
+ const hasExplicitInertia = motion.inertiaDiagonal !== void 0;
355
+ if (hasExplicitInertia) {
356
+ inertiaDiagonal = readFiniteVec3(motion.inertiaDiagonal, `${name}.motion.inertiaDiagonal`);
357
+ if (inertiaDiagonal.some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`Node "${name}" has invalid motion.inertiaDiagonal`);
358
+ }
359
+ const linearVelocity = motion.linearVelocity === void 0 ? void 0 : readFiniteVec3(motion.linearVelocity, `${name}.motion.linearVelocity`);
360
+ const angularVelocity = motion.angularVelocity === void 0 ? void 0 : readFiniteVec3(motion.angularVelocity, `${name}.motion.angularVelocity`);
361
+ const gravityFactor = optFiniteNum(motion.gravityFactor, `${name}.motion.gravityFactor`);
362
+ return {
363
+ isKinematic,
364
+ hasExplicitMotion: hasMotion,
365
+ mass,
366
+ centerOfMass,
367
+ inertiaDiagonal,
368
+ inertiaOrientation,
369
+ hasExplicitInertia,
370
+ ...linearVelocity ? { linearVelocity } : {},
371
+ ...angularVelocity ? { angularVelocity } : {},
372
+ ...gravityFactor === void 0 ? {} : { gravityFactor }
373
+ };
374
+ }
375
+ var axisVector = (axis) => axis === 0 ? [
376
+ 1,
377
+ 0,
378
+ 0
379
+ ] : axis === 1 ? [
380
+ 0,
381
+ 1,
382
+ 0
383
+ ] : [
384
+ 0,
385
+ 0,
386
+ 1
387
+ ];
388
+ function decodeJointDrives(rawDrives, jointIdx, nodeName) {
389
+ return rawDrives.map((d, i) => {
390
+ const label = `physicsJoints[${jointIdx}].drives[${i}] on "${nodeName}"`;
391
+ if (!isObj(d)) throw new KhrValidationError(`${label} must be an object`);
392
+ if (d.mode !== "force" && d.mode !== "acceleration") throw new KhrValidationError(`${label} missing valid drive.mode`);
393
+ if (d.axis !== 0 && d.axis !== 1 && d.axis !== 2) throw new KhrValidationError(`${label} missing valid drive.axis (0|1|2)`);
394
+ if (d.type !== void 0 && d.type !== "linear" && d.type !== "angular") throw new KhrValidationError(`${label} invalid drive.type`);
395
+ const positionTarget = optFiniteNum(d.positionTarget, `${label} drive.positionTarget`);
396
+ const velocityTarget = optFiniteNum(d.velocityTarget, `${label} drive.velocityTarget`);
397
+ if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`${label} requires finite drive.positionTarget or drive.velocityTarget`);
398
+ const stiffness = optFiniteNum(d.stiffness, `${label} drive.stiffness`, true);
399
+ const damping = optFiniteNum(d.damping, `${label} drive.damping`, true);
400
+ const maxForce = optFiniteNum(d.maxForce, `${label} drive.maxForce`, true);
401
+ return {
402
+ ...d.type ? { type: d.type } : {},
403
+ mode: d.mode,
404
+ axis: d.axis,
405
+ ...positionTarget === void 0 ? {} : { positionTarget },
406
+ ...velocityTarget === void 0 ? {} : { velocityTarget },
407
+ ...stiffness === void 0 ? {} : { stiffness },
408
+ ...damping === void 0 ? {} : { damping },
409
+ ...maxForce === void 0 ? {} : { maxForce }
410
+ };
411
+ });
412
+ }
413
+ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, enableCollision, role, connectedNodeName = connectedNode.name) {
414
+ const raw = rawJoints[jointIdx];
415
+ if (!isObj(raw)) throw new KhrValidationError(`physicsJoints[${jointIdx}] out of bounds for "${nodeName}"`);
416
+ if (raw.limits !== void 0 && !Array.isArray(raw.limits)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must be an array`);
417
+ if (raw.drives !== void 0 && !Array.isArray(raw.drives)) throw new KhrValidationError(`physicsJoints[${jointIdx}].drives on "${nodeName}" must be an array`);
418
+ const rawLimits = raw.limits ?? [];
419
+ const rawDrives = raw.drives ?? [];
420
+ const lin = [
421
+ "unlimited",
422
+ "unlimited",
423
+ "unlimited"
424
+ ];
425
+ const ang = [
426
+ "unlimited",
427
+ "unlimited",
428
+ "unlimited"
429
+ ];
430
+ const linGain = [
431
+ void 0,
432
+ void 0,
433
+ void 0
434
+ ];
435
+ const angGain = [
436
+ void 0,
437
+ void 0,
438
+ void 0
439
+ ];
440
+ const applyAxes = (axesRaw, lim, state, gains) => {
441
+ if (axesRaw === void 0) return;
442
+ if (!Array.isArray(axesRaw)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits axes on "${nodeName}" must be an array`);
443
+ const axes = axesRaw.map((ax) => {
444
+ if (ax !== 0 && ax !== 1 && ax !== 2) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits invalid axis ${String(ax)} on "${nodeName}"`);
445
+ return ax;
446
+ });
447
+ const min = optFiniteNum(lim.min, `physicsJoints[${jointIdx}] limit.min on "${nodeName}"`);
448
+ const max = optFiniteNum(lim.max, `physicsJoints[${jointIdx}] limit.max on "${nodeName}"`);
449
+ if ((lim.min !== void 0 || lim.max !== void 0) && (min === void 0 || max === void 0)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must specify both min and max`);
450
+ if (min !== void 0 && max !== void 0 && min > max) throw new KhrValidationError(`physicsJoints[${jointIdx}] limit.min > limit.max on "${nodeName}"`);
451
+ const stiffness = optFiniteNum(lim.stiffness, `physicsJoints[${jointIdx}] limit.stiffness on "${nodeName}"`, true);
452
+ const damping = optFiniteNum(lim.damping, `physicsJoints[${jointIdx}] limit.damping on "${nodeName}"`, true);
453
+ const locked = min !== void 0 && max !== void 0 && max - min <= 1e-6;
454
+ if (!locked && axes.length > 1) throw new KhrValidationError(`physicsJoints[${jointIdx}] coupled multi-axis limit on "${nodeName}" is unsupported`);
455
+ for (const ax of axes) {
456
+ state[ax] = locked ? "locked" : min !== void 0 && max !== void 0 ? [min, max] : "unlimited";
457
+ if (!locked && (stiffness !== void 0 || damping !== void 0)) gains[ax] = {
458
+ ...stiffness === void 0 ? {} : { stiffness },
459
+ ...damping === void 0 ? {} : { damping }
460
+ };
461
+ }
462
+ };
463
+ for (const lim of rawLimits) {
464
+ if (!isObj(lim)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits entry on "${nodeName}" must be an object`);
465
+ applyAxes(lim.linearAxes, lim, lin, linGain);
466
+ applyAxes(lim.angularAxes, lim, ang, angGain);
467
+ }
468
+ const freeLin = [
469
+ 0,
470
+ 1,
471
+ 2
472
+ ].filter((ax) => lin[ax] !== "locked");
473
+ const freeAng = [
474
+ 0,
475
+ 1,
476
+ 2
477
+ ].filter((ax) => ang[ax] !== "locked");
478
+ let kind;
479
+ let axis = [
480
+ 0,
481
+ 1,
482
+ 0
483
+ ];
484
+ let limits = null;
485
+ let gain;
486
+ if (freeLin.length === 0 && freeAng.length === 0) kind = "fixed";
487
+ else if (freeLin.length === 0 && freeAng.length === 1) {
488
+ kind = "revolute";
489
+ axis = axisVector(freeAng[0]);
490
+ const s = ang[freeAng[0]];
491
+ limits = Array.isArray(s) ? s : null;
492
+ gain = angGain[freeAng[0]];
493
+ } else if (freeAng.length === 0 && freeLin.length === 1) {
494
+ kind = "prismatic";
495
+ axis = axisVector(freeLin[0]);
496
+ const s = lin[freeLin[0]];
497
+ limits = Array.isArray(s) ? s : null;
498
+ gain = linGain[freeLin[0]];
499
+ } else throw new KhrValidationError(`physicsJoints[${jointIdx}] unsupported DOF (${freeLin.length} lin, ${freeAng.length} ang) on "${nodeName}"`);
500
+ const drives = decodeJointDrives(rawDrives, jointIdx, nodeName);
501
+ if (isObj(raw.extras) && Array.isArray(raw.extras.jointAxis) && raw.extras.jointAxis.length === 3 && raw.extras.jointAxis.every(isFiniteNum)) {
502
+ const [jx, jy, jz] = raw.extras.jointAxis;
503
+ const jLen = Math.hypot(jx, jy, jz);
504
+ if (jLen > 1e-8) axis = [
505
+ jx / jLen,
506
+ jy / jLen,
507
+ jz / jLen
508
+ ];
509
+ }
510
+ const anchor1Vec = childNode.getWorldPosition(new THREE.Vector3()).sub(connectedNode.getWorldPosition(new THREE.Vector3())).applyQuaternion(connectedNode.getWorldQuaternion(new THREE.Quaternion()).invert());
511
+ return {
512
+ index: jointIdx,
513
+ nodeName,
514
+ connectedNodeName,
515
+ kind,
516
+ axis,
517
+ limits,
518
+ enableCollision,
519
+ role,
520
+ ...gain?.stiffness === void 0 ? {} : { limitStiffness: gain.stiffness },
521
+ ...gain?.damping === void 0 ? {} : { limitDamping: gain.damping },
522
+ drive: drives[0] ?? null,
523
+ drives,
524
+ anchor1: [
525
+ anchor1Vec.x,
526
+ anchor1Vec.y,
527
+ anchor1Vec.z
528
+ ],
529
+ anchor2: [
91
530
  0,
92
531
  0,
93
532
  0
94
- ], part.axisParent, part.axisChild, part.restRelParentQuat);
95
- const rt = buildJointRuntime({
96
- rapier,
97
- world,
98
- nodeName: part.spec.nodeName,
99
- role: part.joint.role,
100
- kind: part.joint.kind,
101
- object: part.spec.object,
102
- axisParent: part.axisParent,
103
- anchorParent: part.restRelParentPos,
104
- restRelQuat: [
105
- 0,
106
- 0,
107
- 0,
108
- 1
109
- ],
110
- limits: part.joint.limits,
111
- drive: part.joint.drive,
112
- breakaway: part.spec.breakaway,
113
- rapierJoint: imp,
114
- parentBody,
115
- childBody
533
+ ]
534
+ };
535
+ }
536
+ var _quat = new THREE.Quaternion();
537
+ var _invParentQuat = new THREE.Quaternion();
538
+ var _localOrigin = new THREE.Vector3(0, 0, 0);
539
+ function getRelativeQuatArray(obj, parent) {
540
+ obj.updateWorldMatrix(true, false);
541
+ obj.getWorldQuaternion(_quat);
542
+ if (parent) {
543
+ parent.updateWorldMatrix(true, false);
544
+ _quat.premultiply(parent.getWorldQuaternion(_invParentQuat).invert());
545
+ }
546
+ if (_quat.lengthSq() > 0) _quat.normalize();
547
+ else _quat.identity();
548
+ return [
549
+ _quat.x,
550
+ _quat.y,
551
+ _quat.z,
552
+ _quat.w
553
+ ];
554
+ }
555
+ /**
556
+ * Resolves the physical hub shaft center of a wheel or propeller node:
557
+ * uses the authored glTF node origin (`getWorldPosition`) whenever the node has a non-zero transform
558
+ * or its local mesh bounds contain `(0, 0, 0)` (preventing 3-blade rotor / caliper AABB wobble),
559
+ * falling back to mesh AABB center only when an uncentered mesh was exported with its node left at `(0, 0, 0)`.
560
+ */
561
+ function resolveRotorHubPosition(obj) {
562
+ const wp = obj.getWorldPosition(new THREE.Vector3());
563
+ if (wp.lengthSq() > 1e-8) return [
564
+ wp.x,
565
+ wp.y,
566
+ wp.z
567
+ ];
568
+ const invObj = obj.matrixWorld.clone().invert();
569
+ const rel = new THREE.Matrix4();
570
+ const v = new THREE.Vector3();
571
+ const localBox = new THREE.Box3();
572
+ obj.traverse((child) => {
573
+ const mesh = child;
574
+ if (!mesh.isMesh || !mesh.geometry) return;
575
+ const pos = mesh.geometry.getAttribute("position");
576
+ if (!pos) return;
577
+ rel.multiplyMatrices(invObj, mesh.matrixWorld);
578
+ for (let i = 0; i < pos.count; i++) localBox.expandByPoint(v.fromBufferAttribute(pos, i).applyMatrix4(rel));
579
+ });
580
+ if (localBox.isEmpty() || localBox.containsPoint(_localOrigin)) return [
581
+ wp.x,
582
+ wp.y,
583
+ wp.z
584
+ ];
585
+ const c = new THREE.Box3().setFromObject(obj).getCenter(new THREE.Vector3());
586
+ return [
587
+ c.x,
588
+ c.y,
589
+ c.z
590
+ ];
591
+ }
592
+ function optRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
593
+ const val = obj[key];
594
+ if (val === void 0) return void 0;
595
+ if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
596
+ return val;
597
+ }
598
+ function reqRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
599
+ const val = obj[key];
600
+ if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" is missing valid ${tagKind}.${key}`);
601
+ return val;
602
+ }
603
+ function optRotorBool(obj, key, tagKind, owner) {
604
+ const val = obj[key];
605
+ if (val === void 0) return void 0;
606
+ if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" has non-boolean ${tagKind}.${key}`);
607
+ return val;
608
+ }
609
+ function reqRotorBool(obj, key, tagKind, owner) {
610
+ const val = obj[key];
611
+ if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" is missing boolean ${tagKind}.${key}`);
612
+ return val;
613
+ }
614
+ function optBoolOrNumFlag(obj, key, tagKind, owner) {
615
+ const val = obj[key];
616
+ if (val === void 0) return void 0;
617
+ if (typeof val === "boolean") return { flag: val };
618
+ if (isNonNegNum(val)) return {
619
+ flag: val !== 0,
620
+ numeric: val
621
+ };
622
+ throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
623
+ }
624
+ function optCurve(val, key, owner) {
625
+ if (val === void 0) return void 0;
626
+ if (!isObj(val) || !Array.isArray(val.points) || val.points.length === 0) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid ecctrlWheel.${key}`);
627
+ for (const pt of val.points) if (!isObj(pt) || !isFiniteNum(pt.x) || !isFiniteNum(pt.y)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid point in ecctrlWheel.${key}`);
628
+ if (val.samples !== void 0 && !isPosNum(val.samples)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
629
+ return val;
630
+ }
631
+ function decodeWheelTag(obj, name, rawWheel, scene, rawOmiWheel) {
632
+ assertIdentityWorldScale(obj, name);
633
+ const hasOmi = rawOmiWheel !== void 0;
634
+ if (hasOmi && !isObj(rawOmiWheel)) throw new KhrValidationError(`OMI_vehicle_wheel "${name}" must be an object`);
635
+ if (rawWheel !== void 0 && !isObj(rawWheel)) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
636
+ if (!hasOmi && rawWheel === void 0) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
637
+ const ec = isObj(rawWheel) ? rawWheel : {};
638
+ const omi = isObj(rawOmiWheel) ? rawOmiWheel : void 0;
639
+ const omiRadius = omi ? optRotorNum(omi, "radius", "OMI_vehicle_wheel", name, true) : void 0;
640
+ const omiWidth = omi ? optRotorNum(omi, "width", "OMI_vehicle_wheel", name, true) : void 0;
641
+ const radius = optRotorNum(ec, "radius", "ecctrlWheel", name, true) ?? omiRadius;
642
+ const width = optRotorNum(ec, "width", "ecctrlWheel", name, true) ?? omiWidth;
643
+ if (radius === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite radius`);
644
+ if (width === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite width`);
645
+ const omiTravel = omi ? optRotorNum(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
646
+ const omiMaxForce = omi ? optRotorNum(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
647
+ const omiMaxSteerRaw = omi ? optRotorNum(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
648
+ const omiStiffness = omi ? optRotorNum(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
649
+ const omiDampComp = omi ? optRotorNum(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
650
+ const omiDampReb = omi ? optRotorNum(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
651
+ const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
652
+ const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
653
+ const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
654
+ const travel = omi ? optRotorNum(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqRotorNum(ec, "travel", "ecctrlWheel", name);
655
+ const sag = omi ? optRotorNum(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqRotorNum(ec, "sag", "ecctrlWheel", name);
656
+ if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
657
+ const steer = omi ? optRotorBool(ec, "steer", "ecctrlWheel", name) ?? omiSteer?.flag ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqRotorBool(ec, "steer", "ecctrlWheel", name);
658
+ const drive = omi ? optRotorBool(ec, "drive", "ecctrlWheel", name) ?? omiProp?.flag ?? false : reqRotorBool(ec, "drive", "ecctrlWheel", name);
659
+ const brake = omi ? optRotorBool(ec, "brake", "ecctrlWheel", name) ?? true : reqRotorBool(ec, "brake", "ecctrlWheel", name);
660
+ const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
661
+ const springK = optRotorNum(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
662
+ const dampingC = optRotorNum(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
663
+ const maxBrakeTorque = optRotorNum(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
664
+ const maxSteeringAngle = optRotorNum(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
665
+ return {
666
+ nodeName: name,
667
+ object: obj,
668
+ position: resolveRotorHubPosition(obj),
669
+ quaternion: getRelativeQuatArray(obj, scene),
670
+ radius,
671
+ width,
672
+ steer,
673
+ steerInvert: optRotorBool(ec, "steerInvert", "ecctrlWheel", name),
674
+ drive,
675
+ driveInvert: optRotorBool(ec, "driveInvert", "ecctrlWheel", name),
676
+ brake,
677
+ travel,
678
+ sag,
679
+ springK,
680
+ dampingC,
681
+ maxBrakeTorque,
682
+ ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
683
+ rollingResistanceCoef: optRotorNum(ec, "rollingResistanceCoef", "ecctrlWheel", name),
684
+ wheelDensity: optRotorNum(ec, "wheelDensity", "ecctrlWheel", name, true),
685
+ driveTorqueWeight: optRotorNum(ec, "driveTorqueWeight", "ecctrlWheel", name),
686
+ tireGripFactor: optRotorNum(ec, "tireGripFactor", "ecctrlWheel", name),
687
+ latFrictionEllipseScale: optRotorNum(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
688
+ relaxLngRate: optRotorNum(ec, "relaxLngRate", "ecctrlWheel", name),
689
+ relaxLatRate: optRotorNum(ec, "relaxLatRate", "ecctrlWheel", name),
690
+ lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
691
+ latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
692
+ };
693
+ }
694
+ function decodePropellerTag(obj, name, rawPropeller, scene) {
695
+ assertIdentityWorldScale(obj, name);
696
+ if (!isObj(rawPropeller)) throw new KhrValidationError(`ecctrlPropeller "${name}" must be an object`);
697
+ if (!isPosNum(rawPropeller.maxThrust)) throw new KhrValidationError(`ecctrlPropeller "${name}" is missing positive finite ecctrlPropeller.maxThrust`);
698
+ const torqueRatio = optFiniteNum(rawPropeller.torqueRatio, `ecctrlPropeller "${name}".torqueRatio`);
699
+ return {
700
+ nodeName: name,
701
+ object: obj,
702
+ position: resolveRotorHubPosition(obj),
703
+ quaternion: getRelativeQuatArray(obj, scene),
704
+ maxThrust: rawPropeller.maxThrust,
705
+ torqueRatio,
706
+ invertThrust: optRotorBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
707
+ invertTorque: optRotorBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
708
+ };
709
+ }
710
+ function decodeBreakawaySpec(raw) {
711
+ if (!isObj(raw) || !isPosNum(raw.breakImpulseNs)) return void 0;
712
+ const latch = isPosNum(raw.latchImpulseNs) ? raw.latchImpulseNs : void 0;
713
+ return {
714
+ ...latch === void 0 ? {} : { latchImpulseNs: latch },
715
+ breakImpulseNs: raw.breakImpulseNs
716
+ };
717
+ }
718
+ var templateMetaMap = /* @__PURE__ */ new WeakMap();
719
+ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
720
+ const meta = templateMetaMap.get(templateBundle.scene);
721
+ if (!meta) return;
722
+ if (extractRole) for (let i = 0; i < clonedBundle.bodies.length; i++) {
723
+ const rawBody = meta.bodies[i];
724
+ const dstBody = clonedBundle.bodies[i];
725
+ if (!rawBody || !dstBody) continue;
726
+ const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
727
+ dstBody.role = role;
728
+ if (dstBody.joint) dstBody.joint.role = role;
729
+ }
730
+ if (isSocketNode) {
731
+ const sockets = Object.create(null);
732
+ for (const node of meta.nodes) {
733
+ const custom = isSocketNode(node.nodeName, node.extras);
734
+ if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
735
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof node.extras.socketId === "string" ? node.extras.socketId : node.nodeName;
736
+ sockets[key] = [...node.worldPosition];
737
+ }
738
+ if (node.contactDots) for (const [role, pos] of node.contactDots) sockets[role] = [...pos];
739
+ }
740
+ for (const [key, pos] of meta.ikSockets) sockets[key] = [...pos];
741
+ clonedBundle.sockets = sockets;
742
+ }
743
+ }
744
+ var _dotVec = new THREE.Vector3();
745
+ var _dotQuat = new THREE.Quaternion();
746
+ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
747
+ if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
748
+ const wp = obj.getWorldPosition(new THREE.Vector3());
749
+ const worldPosition = [
750
+ wp.x,
751
+ wp.y,
752
+ wp.z
753
+ ];
754
+ const custom = isSocketNode?.(name, extras);
755
+ if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
756
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name;
757
+ sockets[key] = [...worldPosition];
758
+ }
759
+ let contactDots;
760
+ if (extras.contactDots !== void 0) {
761
+ if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
762
+ obj.getWorldQuaternion(_dotQuat);
763
+ contactDots = [];
764
+ for (const dot of extras.contactDots) {
765
+ if (!isObj(dot) || typeof dot.role !== "string" || dot.role.length === 0 || !Array.isArray(dot.pos) || dot.pos.length !== 3 || !dot.pos.every(isFiniteNum)) throw new KhrValidationError(`Node "${name}" has invalid entry in extras.contactDots`);
766
+ _dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_dotQuat).add(wp);
767
+ const dotPos = [
768
+ _dotVec.x,
769
+ _dotVec.y,
770
+ _dotVec.z
771
+ ];
772
+ sockets[dot.role] = dotPos;
773
+ contactDots.push([dot.role, dotPos]);
774
+ }
775
+ }
776
+ return {
777
+ nodeName: name,
778
+ extras,
779
+ worldPosition,
780
+ ...contactDots ? { contactDots } : {}
781
+ };
782
+ }
783
+ function buildNodeGraphLookup(gltf, rawNodes, rawGltf) {
784
+ const parentIdx = new Int32Array(rawNodes.length).fill(-1);
785
+ for (let i = 0; i < rawNodes.length; i++) {
786
+ const node = rawNodes[i];
787
+ if (!isObj(node)) throw new KhrValidationError(`GLTF node[${i}] must be an object`);
788
+ const label = typeof node.name === "string" && node.name.length > 0 ? node.name : String(i);
789
+ if (node.children !== void 0) {
790
+ if (!Array.isArray(node.children)) throw new KhrValidationError(`GLTF node "${label}" children must be an array`);
791
+ for (const c of node.children) if (typeof c !== "number" || !Number.isInteger(c) || c < 0 || c >= rawNodes.length) throw new KhrValidationError(`GLTF node "${label}" has out-of-bounds child index ${String(c)}`);
792
+ }
793
+ }
794
+ let sceneRoots;
795
+ const inActiveScene = /* @__PURE__ */ new Set();
796
+ if (Array.isArray(rawGltf?.scenes)) {
797
+ const sceneIdx = rawGltf.scene ?? 0;
798
+ const sceneDef = rawGltf.scenes[sceneIdx];
799
+ if (!isObj(sceneDef)) throw new KhrValidationError(`GLTF scene[${sceneIdx}] must be an object`);
800
+ if (sceneDef.nodes !== void 0 && !Array.isArray(sceneDef.nodes)) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes must be an array`);
801
+ sceneRoots = (sceneDef.nodes ?? []).map((n, pos) => {
802
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n >= rawNodes.length) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes[${pos}] has invalid node index ${String(n)}`);
803
+ return n;
116
804
  });
117
- rtRef.current = rt;
118
- registry?.add(rt);
119
- onJointReady(rt.nodeName, rt);
120
- return () => {
121
- rtRef.current = null;
122
- registry?.delete(rt);
123
- onJointReady(rt.nodeName, null);
124
- if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
805
+ const stack = [...sceneRoots];
806
+ while (stack.length > 0) {
807
+ const cur = stack.pop();
808
+ if (inActiveScene.has(cur)) continue;
809
+ inActiveScene.add(cur);
810
+ const children = rawNodes[cur].children;
811
+ if (children) for (const c of children) stack.push(c);
812
+ }
813
+ } else for (let i = 0; i < rawNodes.length; i++) inActiveScene.add(i);
814
+ const rootSet = sceneRoots ? new Set(sceneRoots) : void 0;
815
+ for (const i of inActiveScene) {
816
+ const children = rawNodes[i].children;
817
+ if (children) for (const c of children) {
818
+ if (parentIdx[c] !== -1 || rootSet?.has(c)) {
819
+ const label = typeof rawNodes[c].name === "string" && rawNodes[c].name.length > 0 ? rawNodes[c].name : String(c);
820
+ throw new KhrValidationError(`GLTF node "${label}" has multiple parents in active scene`);
821
+ }
822
+ for (let anc = i; anc !== -1; anc = parentIdx[anc]) if (anc === c) {
823
+ const label = typeof rawNodes[c].name === "string" && rawNodes[c].name.length > 0 ? rawNodes[c].name : String(c);
824
+ throw new KhrValidationError(`GLTF node "${label}" has cyclic parent in active scene`);
825
+ }
826
+ parentIdx[c] = i;
827
+ }
828
+ }
829
+ const usedNames = /* @__PURE__ */ new Set();
830
+ const nodeNames = new Array(rawNodes.length);
831
+ const assignName = (idx, dedupe) => {
832
+ const rawName = rawNodes[idx].name;
833
+ let name = typeof rawName === "string" && rawName.length > 0 ? rawName : `node_${idx}`;
834
+ if (dedupe) {
835
+ if (usedNames.has(name)) name = `${name}_${idx}`;
836
+ while (usedNames.has(name)) name = `${name}_`;
837
+ usedNames.add(name);
838
+ }
839
+ nodeNames[idx] = name;
840
+ };
841
+ for (let i = 0; i < rawNodes.length; i++) if (inActiveScene.has(i)) assignName(i, true);
842
+ for (let i = 0; i < rawNodes.length; i++) if (!inActiveScene.has(i)) assignName(i, false);
843
+ const byNodeIdx = /* @__PURE__ */ new Map();
844
+ const byName = /* @__PURE__ */ new Map();
845
+ gltf.scene.traverse((obj) => {
846
+ const nIdx = (gltf.parser?.associations?.get(obj))?.nodes;
847
+ if (typeof nIdx === "number" && inActiveScene.has(nIdx) && !byNodeIdx.has(nIdx)) byNodeIdx.set(nIdx, obj);
848
+ if (obj.name && !byName.has(obj.name)) byName.set(obj.name, obj);
849
+ });
850
+ return {
851
+ parentIdx,
852
+ nodeNames,
853
+ resolveObj: (idx) => {
854
+ if (idx < 0 || idx >= rawNodes.length || !inActiveScene.has(idx)) return void 0;
855
+ const hit = byNodeIdx.get(idx);
856
+ if (hit) return hit;
857
+ const name = nodeNames[idx];
858
+ const sanitized = THREE.PropertyBinding.sanitizeNodeName(name);
859
+ return byName.get(name) ?? byName.get(sanitized) ?? gltf.scene.getObjectByName(name);
860
+ }
861
+ };
862
+ }
863
+ function findOwnerBodyIdx(idx, parentIdx, rawNodes) {
864
+ for (let p = parentIdx[idx]; p !== -1; p = parentIdx[p]) if (rawNodes[p].extensions?.KHR_physics_rigid_bodies?.motion) return p;
865
+ return -1;
866
+ }
867
+ function resolveConnectedBodyIdx(cIdx, parentIdx, rawNodes) {
868
+ const phys = rawNodes[cIdx]?.extensions?.KHR_physics_rigid_bodies;
869
+ if (isObj(phys) && (phys.motion !== void 0 || (phys.collider !== void 0 || phys.joint !== void 0) && findOwnerBodyIdx(cIdx, parentIdx, rawNodes) === -1)) return cIdx;
870
+ const owner = findOwnerBodyIdx(cIdx, parentIdx, rawNodes);
871
+ return owner !== -1 ? owner : cIdx;
872
+ }
873
+ function isInsideRotor(idx, parentIdx, rawNodes) {
874
+ for (let p = idx; p !== -1; p = parentIdx[p]) {
875
+ const node = rawNodes[p];
876
+ const ex = node.extras;
877
+ if (isObj(ex) && (ex.ecctrlWheel !== void 0 || ex.ecctrlPropeller !== void 0)) return true;
878
+ if (isObj(node.extensions) && node.extensions.OMI_vehicle_wheel !== void 0) return true;
879
+ }
880
+ return false;
881
+ }
882
+ function resolveColliderShape(col, ownerName, shapes, nodeNames, resolveObj) {
883
+ if (!isObj(col)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider (expected object)`);
884
+ const geo = col.geometry;
885
+ if (!isObj(geo)) throw new KhrValidationError(`Node "${ownerName}" is missing collider.geometry object`);
886
+ if (geo.shape !== void 0) {
887
+ if (typeof geo.shape !== "number" || !Number.isInteger(geo.shape) || geo.shape < 0 || geo.shape >= shapes.length) throw new KhrValidationError(`Node "${ownerName}" references missing collider.geometry.shape ${String(geo.shape)}`);
888
+ return shapes[geo.shape];
889
+ }
890
+ if (geo.node !== void 0) {
891
+ if (typeof geo.node !== "number" || !Number.isInteger(geo.node)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider.geometry.node`);
892
+ if (geo.convexHull !== void 0 && typeof geo.convexHull !== "boolean") throw new KhrValidationError(`Node "${ownerName}" has non-boolean collider.geometry.convexHull`);
893
+ const target = resolveObj(geo.node);
894
+ const meshName = nodeNames[geo.node] ?? `node_${geo.node}`;
895
+ if (!target) throw new KhrValidationError(`Node "${ownerName}" references missing mesh node "${meshName}"`);
896
+ return extractMeshColliderShape(target, meshName, Boolean(geo.convexHull));
897
+ }
898
+ throw new KhrValidationError(`Node "${ownerName}" collider.geometry must specify shape or node`);
899
+ }
900
+ function extractKhrBundleFromGltf(gltf, options) {
901
+ if (!gltf.scene) throw new KhrValidationError("GLTF asset has no active scene");
902
+ assertSceneIdentityWorldScale(gltf.scene);
903
+ const json = gltf.parser?.json;
904
+ if (!json) throw new KhrValidationError("GLTFParser is missing parsed JSON");
905
+ if (json.extensions !== void 0 && !isObj(json.extensions)) throw new KhrValidationError("glTF extensions must be an object");
906
+ const khrPhys = json.extensions?.KHR_physics_rigid_bodies;
907
+ if (khrPhys !== void 0 && !isObj(khrPhys)) throw new KhrValidationError("KHR_physics_rigid_bodies extension must be an object");
908
+ const khrShapes = json.extensions?.KHR_implicit_shapes;
909
+ if (khrShapes !== void 0 && !isObj(khrShapes)) throw new KhrValidationError("KHR_implicit_shapes extension must be an object");
910
+ const omiExt = json.extensions?.OMI_vehicle_wheel;
911
+ if (omiExt !== void 0 && (!isObj(omiExt) || !Array.isArray(omiExt.wheels))) throw new KhrValidationError("OMI_vehicle_wheel.wheels must be an array");
912
+ const omiWheels = omiExt ? omiExt.wheels : [];
913
+ const shapes = reqArr(khrShapes?.shapes, "KHR_implicit_shapes.shapes").map((s, i) => decodeShape(s, i));
914
+ const materials = reqArr(khrPhys?.physicsMaterials, "KHR_physics_rigid_bodies.physicsMaterials");
915
+ const collisionGroups = decodeCollisionGroups(reqArr(khrPhys?.collisionFilters, "KHR_physics_rigid_bodies.collisionFilters"));
916
+ const joints = reqArr(khrPhys?.physicsJoints, "KHR_physics_rigid_bodies.physicsJoints");
917
+ const rawNodes = reqArr(json.nodes, "glTF nodes");
918
+ const { parentIdx, nodeNames, resolveObj } = buildNodeGraphLookup(gltf, rawNodes, json);
919
+ const nodeMetas = [];
920
+ const sockets = Object.create(null);
921
+ for (let i = 0; i < rawNodes.length; i++) {
922
+ const obj = resolveObj(i);
923
+ if (!obj) continue;
924
+ const rawExt = rawNodes[i].extensions;
925
+ if (rawExt !== void 0 && !isObj(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
926
+ const extras = isObj(rawNodes[i].extras) ? rawNodes[i].extras : {};
927
+ nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, options?.isSocketNode));
928
+ }
929
+ const bodies = [];
930
+ const bodyMetas = [];
931
+ const bodyByIdx = /* @__PURE__ */ new Map();
932
+ const explicitInertiaSet = /* @__PURE__ */ new Set();
933
+ const wheels = [];
934
+ const propellers = [];
935
+ for (let i = 0; i < rawNodes.length; i++) {
936
+ const raw = rawNodes[i];
937
+ const name = nodeNames[i];
938
+ const obj = resolveObj(i);
939
+ if (!obj) continue;
940
+ const extras = isObj(raw.extras) ? raw.extras : {};
941
+ const hasOmiWheel = isObj(raw.extensions) && raw.extensions.OMI_vehicle_wheel !== void 0;
942
+ if (extras.ecctrlWheel !== void 0 || extras.ecctrlPropeller !== void 0 || hasOmiWheel) {
943
+ if (parentIdx[i] !== -1 && isInsideRotor(parentIdx[i], parentIdx, rawNodes)) throw new KhrValidationError(`Nested rotor "${name}" inside detached rotor is unsupported`);
944
+ if (extras.ecctrlPropeller !== void 0 && (extras.ecctrlWheel !== void 0 || hasOmiWheel)) throw new KhrValidationError(`Node "${name}" cannot be both wheel and propeller`);
945
+ if (extras.ecctrlPropeller !== void 0) propellers.push(decodePropellerTag(obj, name, extras.ecctrlPropeller, gltf.scene));
946
+ else {
947
+ let rawOmiWheel;
948
+ if (hasOmiWheel) {
949
+ const omiRef = raw.extensions.OMI_vehicle_wheel;
950
+ if (!isObj(omiRef) || typeof omiRef.wheel !== "number" || !Number.isInteger(omiRef.wheel) || omiRef.wheel < 0 || omiRef.wheel >= omiWheels.length) throw new KhrValidationError(`Node "${name}" references invalid OMI_vehicle_wheel.wheel ${String(isObj(omiRef) ? omiRef.wheel : omiRef)}`);
951
+ rawOmiWheel = omiWheels[omiRef.wheel];
952
+ }
953
+ wheels.push(decodeWheelTag(obj, name, extras.ecctrlWheel, gltf.scene, rawOmiWheel));
954
+ }
955
+ continue;
956
+ }
957
+ if (isInsideRotor(i, parentIdx, rawNodes)) continue;
958
+ const phys = raw.extensions?.KHR_physics_rigid_bodies;
959
+ if (phys === void 0) continue;
960
+ if (!isObj(phys)) throw new KhrValidationError(`Node "${name}" has invalid KHR_physics_rigid_bodies`);
961
+ if (phys.motion === void 0 && phys.collider === void 0 && phys.joint === void 0) continue;
962
+ if (phys.motion === void 0 && findOwnerBodyIdx(i, parentIdx, rawNodes) !== -1) {
963
+ if (phys.joint !== void 0) throw new KhrValidationError(`Node "${name}" has joint without motion`);
964
+ continue;
965
+ }
966
+ if (phys.motion !== void 0 && !isObj(phys.motion)) throw new KhrValidationError(`Node "${name}" has invalid motion`);
967
+ const { hasExplicitInertia, ...motion } = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
968
+ if (hasExplicitInertia) explicitInertiaSet.add(i);
969
+ const role = options?.extractRole?.(name, extras) ?? (typeof extras.role === "string" ? extras.role : null);
970
+ let joint = null;
971
+ if (phys.joint !== void 0) {
972
+ if (!isObj(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
973
+ const rawJ = phys.joint;
974
+ if (typeof rawJ.joint !== "number" || !Number.isInteger(rawJ.joint)) throw new KhrValidationError(`Joint on "${name}" is missing numeric joint index`);
975
+ if (typeof rawJ.connectedNode !== "number" || !Number.isInteger(rawJ.connectedNode)) throw new KhrValidationError(`Joint on "${name}" is missing numeric connectedNode index`);
976
+ if (rawJ.enableCollision !== void 0 && typeof rawJ.enableCollision !== "boolean") throw new KhrValidationError(`Joint on "${name}" has non-boolean enableCollision`);
977
+ const cIdx = resolveConnectedBodyIdx(rawJ.connectedNode, parentIdx, rawNodes);
978
+ const cName = nodeNames[cIdx] ?? `node_${cIdx}`;
979
+ const cObj = resolveObj(cIdx);
980
+ if (!cObj || !resolveObj(rawJ.connectedNode)) throw new KhrValidationError(`Joint on "${name}" targets missing connectedNode "${cName}"`);
981
+ if (isInsideRotor(rawJ.connectedNode, parentIdx, rawNodes) || isInsideRotor(cIdx, parentIdx, rawNodes)) throw new KhrValidationError(`Joint on "${name}" cannot target detached rotor "${cName}"`);
982
+ joint = decodeJoint(joints, rawJ.joint, name, cObj, obj, Boolean(rawJ.enableCollision), role, cName);
983
+ }
984
+ const wp = obj.getWorldPosition(new THREE.Vector3());
985
+ const wq = obj.getWorldQuaternion(new THREE.Quaternion());
986
+ const breakaway = decodeBreakawaySpec(extras.breakaway);
987
+ const spec = {
988
+ nodeName: name,
989
+ ...motion,
990
+ localPosition: [
991
+ wp.x,
992
+ wp.y,
993
+ wp.z
994
+ ],
995
+ localQuaternion: [
996
+ wq.x,
997
+ wq.y,
998
+ wq.z,
999
+ wq.w
1000
+ ],
1001
+ colliders: [],
1002
+ joint,
1003
+ ...breakaway ? { breakaway } : {},
1004
+ object: obj,
1005
+ role
125
1006
  };
126
- }, [
127
- rapier,
128
- world,
129
- part,
130
- parentBodyRef,
131
- registry,
132
- onJointReady
133
- ]);
134
- const onForce = part.spec.breakaway ? (p) => {
135
- rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
136
- } : void 0;
137
- const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
138
- const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
139
- const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
140
- return /* @__PURE__ */ jsxs(RigidBody, {
141
- ref: childRef,
142
- type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
143
- position: worldPose.pos,
144
- quaternion: worldPose.quat,
145
- colliders: false,
146
- onContactForce: onForce,
147
- ...linVel ? { linearVelocity: linVel } : {},
148
- ...angVel ? { angularVelocity: angVel } : {},
149
- ...gravScale === void 0 ? {} : { gravityScale: gravScale },
150
- children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
151
- object: part.spec.object,
152
- position: [
1007
+ bodies.push(spec);
1008
+ bodyMetas.push({
1009
+ nodeName: name,
1010
+ extras
1011
+ });
1012
+ bodyByIdx.set(i, spec);
1013
+ }
1014
+ for (let i = 0; i < rawNodes.length; i++) {
1015
+ if (isInsideRotor(i, parentIdx, rawNodes)) continue;
1016
+ const rawCol = rawNodes[i].extensions?.KHR_physics_rigid_bodies?.collider;
1017
+ if (rawCol === void 0) continue;
1018
+ const obj = resolveObj(i);
1019
+ if (!obj) continue;
1020
+ const ownerIdx = bodyByIdx.has(i) ? i : findOwnerBodyIdx(i, parentIdx, rawNodes);
1021
+ const owner = bodyByIdx.get(ownerIdx);
1022
+ if (!owner) continue;
1023
+ const shape = resolveColliderShape(rawCol, nodeNames[i], shapes, nodeNames, resolveObj);
1024
+ const colDef = rawCol;
1025
+ const rel = ownerIdx === i ? {
1026
+ localPosition: [
153
1027
  0,
154
1028
  0,
155
1029
  0
156
1030
  ],
157
- quaternion: part.restRelRootQuat,
158
- origin
159
- }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
160
- c: col.spec,
161
- position: col.position,
162
- quaternion: col.quaternion,
163
- massProperties: col.massProperties
164
- }, `${part.spec.nodeName}:${cIdx}`))]
1031
+ localQuaternion: [
1032
+ 0,
1033
+ 0,
1034
+ 0,
1035
+ 1
1036
+ ]
1037
+ } : computeRelativePose(owner.object, obj);
1038
+ const mat = decodePhysicsMaterial(materials, colDef.physicsMaterial, nodeNames[i]);
1039
+ let colGroups;
1040
+ if (colDef.collisionFilter !== void 0) {
1041
+ if (typeof colDef.collisionFilter !== "number" || !Number.isInteger(colDef.collisionFilter) || colDef.collisionFilter < 0 || colDef.collisionFilter >= collisionGroups.length) throw new KhrValidationError(`Node "${nodeNames[i]}" references out-of-bounds collisionFilter ${String(colDef.collisionFilter)}`);
1042
+ colGroups = collisionGroups[colDef.collisionFilter];
1043
+ }
1044
+ owner.colliders.push({
1045
+ shape,
1046
+ localPosition: rel.localPosition,
1047
+ localQuaternion: rel.localQuaternion,
1048
+ ...mat,
1049
+ ...colGroups === void 0 ? {} : { collisionGroups: colGroups }
1050
+ });
1051
+ }
1052
+ for (const [idx, body] of bodyByIdx) if (!explicitInertiaSet.has(idx) && !body.isKinematic) body.inertiaDiagonal = computeBodyInertia(body.colliders, body.mass, body.centerOfMass, body.inertiaOrientation, body.nodeName);
1053
+ const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
1054
+ const ikSockets = [];
1055
+ const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
1056
+ if (sceneExtras?.ikSockets !== void 0) {
1057
+ if (!isObj(sceneExtras.ikSockets)) throw new KhrValidationError("scene.extras.ikSockets must be an object");
1058
+ for (const [k, v] of Object.entries(sceneExtras.ikSockets)) {
1059
+ const pos = readFiniteVec3(v, `scene.extras.ikSockets.${k}`);
1060
+ sockets[k] = pos;
1061
+ ikSockets.push([k, pos]);
1062
+ }
1063
+ }
1064
+ const tune = isObj(sceneExtras?.tune) ? sceneExtras.tune : isObj(sceneExtras?.ecctrl) ? sceneExtras.ecctrl : void 0;
1065
+ const droneTune = isObj(sceneExtras?.droneTune) ? sceneExtras.droneTune : void 0;
1066
+ templateMetaMap.set(gltf.scene, {
1067
+ nodes: nodeMetas,
1068
+ bodies: bodyMetas,
1069
+ ikSockets
165
1070
  });
1071
+ return {
1072
+ scene: gltf.scene,
1073
+ bodies,
1074
+ wheels,
1075
+ propellers,
1076
+ sockets,
1077
+ totalDynamicMass,
1078
+ centerOfMass,
1079
+ ...tune ? { tune } : {},
1080
+ ...droneTune ? { droneTune } : {}
1081
+ };
166
1082
  }
167
- function AssemblyRootBody({ plan, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJoints, children }) {
168
- const rbRef = useRef(null);
169
- const partBodyRefs = useMemo(() => new Map(plan.parts.map((p) => [p.spec.nodeName, { current: null }])), [plan]);
170
- const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object)) : null, [plan.parts]);
171
- const jointsMapRef = useRef(/* @__PURE__ */ new Map());
172
- const rootSpec = plan.spec;
173
- useEffect(() => {
174
- onBody(rootSpec.nodeName, rbRef);
175
- onJoints(rootSpec.nodeName, jointsMapRef.current);
176
- return () => {
177
- onBody(rootSpec.nodeName, null);
178
- onJoints(rootSpec.nodeName, null);
1083
+ function createKhrGltfPlugin(options) {
1084
+ return (parser) => {
1085
+ return {
1086
+ name: "KHR_physics_rigid_bodies",
1087
+ ...isHeadlessTextureEnv() ? {
1088
+ beforeRoot() {
1089
+ patchHeadlessTexturePlugins(parser);
1090
+ return null;
1091
+ },
1092
+ loadTexture: (textureIndex) => stubTextureInParser(parser, textureIndex)
1093
+ } : {},
1094
+ afterRoot(gltf) {
1095
+ gltf.userData[KHR_BUNDLE_USERDATA_KEY] = extractKhrBundleFromGltf(gltf, options);
1096
+ return null;
1097
+ }
179
1098
  };
180
- }, [
181
- rootSpec.nodeName,
182
- onBody,
183
- onJoints
184
- ]);
185
- useEffect(() => {
186
- const rb = rbRef.current;
187
- const rm = plan.rootMass;
188
- if (rb && rm) {
189
- rb.setAdditionalMassProperties(rm.mass, rm.centerOfMass, rm.principalAngularInertia, rm.angularInertiaLocalFrame, true);
190
- rb.recomputeMassPropertiesFromColliders();
191
- }
192
- }, [plan.rootMass]);
193
- const handlePartBody = useCallback((nodeName, refObj) => {
194
- const slot = partBodyRefs.get(nodeName);
195
- if (slot) slot.current = refObj?.current ?? null;
196
- onBody(nodeName, refObj);
197
- }, [partBodyRefs, onBody]);
198
- const handleJointReady = useCallback((nodeName, rt) => {
199
- if (rt) jointsMapRef.current.set(nodeName, rt);
200
- else jointsMapRef.current.delete(nodeName);
201
- }, []);
202
- const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
203
- return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
204
- ...rigidBodyProps,
205
- ref: rbRef,
206
- type: bodyType,
207
- position,
208
- quaternion,
209
- colliders: false,
210
- ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
211
- ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
212
- ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
213
- children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
214
- c: col.spec,
215
- position: col.position,
216
- quaternion: col.quaternion,
217
- massProperties: col.massProperties
218
- }, `r${idx}`))]
219
- }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
220
- part,
221
- rootSpec,
222
- rootPos: position,
223
- rootQuat: quaternion,
224
- parentBodyRef: part.parent ? partBodyRefs.get(part.parent.spec.nodeName) : rbRef,
225
- origin: partOrigins?.get(part.spec.object),
226
- onBody: handlePartBody,
227
- onJointReady: handleJointReady
228
- }, part.spec.nodeName))] });
229
- }
230
- // src/KhrAssembly.tsx
231
- function KhrAssembly({ ref, bundle, position = [
232
- 0,
233
- 0,
234
- 0
235
- ], rotation, quaternion, scale, fixedRoot = false, rigidBodyProps, children, ...groupProps }) {
236
- assertUnitScale(scale, "KhrAssembly");
237
- bundle.scene.updateMatrixWorld(true);
238
- assertSceneIdentityWorldScale(bundle.scene);
239
- const plans = useMemo(() => planAssembly(bundle), [bundle]);
240
- const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode)) : null, [plans]);
241
- const [px, py, pz] = position;
242
- const [rx, ry, rz] = rotation ?? [
243
- 0,
244
- 0,
245
- 0
246
- ];
247
- const [qx, qy, qz, qw] = quaternion ?? [
248
- NaN,
249
- NaN,
250
- NaN,
251
- NaN
252
- ];
253
- const spawnQuat = useMemo(() => quaternion ? new THREE.Quaternion(qx, qy, qz, qw) : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
254
- qx,
255
- qy,
256
- qz,
257
- qw,
258
- rx,
259
- ry,
260
- rz
261
- ]);
262
- const rootPoses = useMemo(() => plans.map((p) => {
263
- const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
264
- const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
1099
+ };
1100
+ }
1101
+ async function loadKhrGlb(source, options) {
1102
+ const buf = source instanceof ArrayBuffer ? source : source.byteOffset === 0 && source.byteLength === source.buffer.byteLength && source.buffer instanceof ArrayBuffer ? source.buffer : source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
1103
+ validateGlbHeader(buf);
1104
+ const loader = options?.loader ?? new GLTFLoader();
1105
+ const plugin = createKhrGltfPlugin(options);
1106
+ loader.register(plugin);
1107
+ try {
1108
+ const toErr = (err) => err instanceof KhrValidationError ? err : new KhrValidationError(err instanceof Error ? err.message : "Failed to parse GLB");
1109
+ const bundle = (await new Promise((resolve, reject) => {
1110
+ loader.parse(buf, "", resolve, (err) => reject(toErr(err)));
1111
+ })).userData[KHR_BUNDLE_USERDATA_KEY];
1112
+ if (!bundle) throw new KhrValidationError("Missing parsed KHR bundle on GLTF userData");
1113
+ return bundle;
1114
+ } finally {
1115
+ loader.unregister(plugin);
1116
+ }
1117
+ }
1118
+ // src/exporter.ts
1119
+ function encodeShape(shape, nodeName) {
1120
+ if (shape.type === "box") {
1121
+ if (!Array.isArray(shape.size) || shape.size.length !== 3 || !shape.size.every(isPosNum)) throw new KhrValidationError(`exportKhrGlb: invalid box.size on "${nodeName}"`);
265
1122
  return {
266
- position: [
267
- pos.x,
268
- pos.y,
269
- pos.z
270
- ],
271
- quaternion: [
272
- quat.x,
273
- quat.y,
274
- quat.z,
275
- quat.w
276
- ]
1123
+ type: "box",
1124
+ box: { size: shape.size }
277
1125
  };
278
- }), [
279
- plans,
280
- spawnQuat,
281
- px,
282
- py,
283
- pz
284
- ]);
285
- const bodiesRef = useRef(/* @__PURE__ */ new Map());
286
- const jointsRef = useRef(/* @__PURE__ */ new Map());
287
- const nodeToRoot = useMemo(() => {
288
- const m = /* @__PURE__ */ new Map();
289
- for (const p of plans) {
290
- m.set(p.spec.nodeName, p.spec.nodeName);
291
- for (const part of p.parts) m.set(part.spec.nodeName, p.spec.nodeName);
1126
+ }
1127
+ if (shape.type === "sphere") {
1128
+ if (!isPosNum(shape.radius)) throw new KhrValidationError(`exportKhrGlb: invalid sphere.radius on "${nodeName}"`);
1129
+ return {
1130
+ type: "sphere",
1131
+ sphere: { radius: shape.radius }
1132
+ };
1133
+ }
1134
+ if (!isPosNum(shape.height) || !isPosNum(shape.radiusTop) || !isPosNum(shape.radiusBottom)) throw new KhrValidationError(`exportKhrGlb: invalid ${shape.type} dimensions on "${nodeName}"`);
1135
+ if (Math.abs(shape.radiusTop - shape.radiusBottom) > 1e-6) throw new KhrValidationError(`exportKhrGlb: tapered ${shape.type} (${shape.radiusTop} !== ${shape.radiusBottom}) on "${nodeName}" is unsupported`);
1136
+ return {
1137
+ type: shape.type,
1138
+ [shape.type]: {
1139
+ height: shape.height,
1140
+ radiusTop: shape.radiusTop,
1141
+ radiusBottom: shape.radiusBottom
292
1142
  }
293
- return m;
294
- }, [plans]);
295
- const handleBody = useCallback((nodeName, rb) => {
296
- if (rb) bodiesRef.current.set(nodeName, rb);
297
- else bodiesRef.current.delete(nodeName);
298
- }, []);
299
- const handleJoints = useCallback((rootName, map) => {
300
- if (map) jointsRef.current.set(rootName, map);
301
- else jointsRef.current.delete(rootName);
302
- }, []);
303
- useImperativeHandle(ref, () => ({
304
- getBody: (nodeName) => bodiesRef.current.get(nodeName)?.current ?? null,
305
- setJointTarget: (nodeName, target) => {
306
- const rt = jointsRef.current.get(nodeToRoot.get(nodeName) ?? "")?.get(nodeName);
307
- if (rt) rt.applyTarget(target);
1143
+ };
1144
+ }
1145
+ function normalizeJointAxis(axis, kind, nodeName) {
1146
+ if (!Array.isArray(axis) || axis.length !== 3 || !axis.every(isFiniteNum)) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires a finite axis`);
1147
+ const len = Math.hypot(axis[0], axis[1], axis[2]);
1148
+ if (len <= 1e-8) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires non-zero axis`);
1149
+ const ux = axis[0] / len, uy = axis[1] / len, uz = axis[2] / len;
1150
+ const ax = Math.abs(ux), ay = Math.abs(uy), az = Math.abs(uz);
1151
+ const primary = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2;
1152
+ return {
1153
+ primary,
1154
+ unit: [
1155
+ ux,
1156
+ uy,
1157
+ uz
1158
+ ],
1159
+ isCardinal: (primary === 0 ? ax : primary === 1 ? ay : az) >= 1 - 1e-6
1160
+ };
1161
+ }
1162
+ function encodeJointDrive(drive, defaultType, defaultAxis, nodeName) {
1163
+ if (!isObj(drive)) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" must be an object`);
1164
+ if (drive.mode !== "force" && drive.mode !== "acceleration") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires drive.mode ("force" | "acceleration")`);
1165
+ if (drive.type !== void 0 && drive.type !== "linear" && drive.type !== "angular") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.type`);
1166
+ if (drive.axis !== void 0 && drive.axis !== 0 && drive.axis !== 1 && drive.axis !== 2) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.axis`);
1167
+ const positionTarget = optFiniteNum(drive.positionTarget, `joint drive.positionTarget on "${nodeName}"`);
1168
+ const velocityTarget = optFiniteNum(drive.velocityTarget, `joint drive.velocityTarget on "${nodeName}"`);
1169
+ if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires finite positionTarget or velocityTarget`);
1170
+ const stiffness = optFiniteNum(drive.stiffness, `joint drive.stiffness on "${nodeName}"`, true);
1171
+ const damping = optFiniteNum(drive.damping, `joint drive.damping on "${nodeName}"`, true);
1172
+ const maxForce = optFiniteNum(drive.maxForce, `joint drive.maxForce on "${nodeName}"`, true);
1173
+ return {
1174
+ type: drive.type ?? defaultType,
1175
+ mode: drive.mode,
1176
+ axis: drive.axis ?? defaultAxis,
1177
+ ...positionTarget === void 0 ? {} : { positionTarget },
1178
+ ...velocityTarget === void 0 ? {} : { velocityTarget },
1179
+ ...stiffness === void 0 ? {} : { stiffness },
1180
+ ...damping === void 0 ? {} : { damping },
1181
+ ...maxForce === void 0 ? {} : { maxForce }
1182
+ };
1183
+ }
1184
+ function encodeJoint(j, nodeName) {
1185
+ if (j.kind !== "fixed" && j.kind !== "revolute" && j.kind !== "prismatic") throw new KhrValidationError(`exportKhrGlb: invalid joint.kind "${String(j.kind)}" on "${nodeName}"`);
1186
+ if (j.kind === "fixed") {
1187
+ if (j.drive || j.drives && j.drives.length > 0) throw new KhrValidationError(`exportKhrGlb: fixed joint on "${nodeName}" cannot define drives`);
1188
+ return { limits: [{
1189
+ linearAxes: [
1190
+ 0,
1191
+ 1,
1192
+ 2
1193
+ ],
1194
+ min: 0,
1195
+ max: 0
1196
+ }, {
1197
+ angularAxes: [
1198
+ 0,
1199
+ 1,
1200
+ 2
1201
+ ],
1202
+ min: 0,
1203
+ max: 0
1204
+ }] };
1205
+ }
1206
+ const { primary: ax, unit, isCardinal } = normalizeJointAxis(j.axis, j.kind, nodeName);
1207
+ const lockedAxes = [
1208
+ 0,
1209
+ 1,
1210
+ 2
1211
+ ].filter((i) => i !== ax);
1212
+ if (j.limits && (!Number.isFinite(j.limits[0]) || !Number.isFinite(j.limits[1]) || j.limits[0] > j.limits[1])) throw new KhrValidationError(`exportKhrGlb: joint on "${nodeName}" has invalid joint.limits`);
1213
+ const stiffness = optFiniteNum(j.limitStiffness, `joint.limitStiffness on "${nodeName}"`, true);
1214
+ const damping = optFiniteNum(j.limitDamping, `joint.limitDamping on "${nodeName}"`, true);
1215
+ const freeKey = j.kind === "revolute" ? "angularAxes" : "linearAxes";
1216
+ const freeLimit = j.limits || stiffness !== void 0 || damping !== void 0 ? [{
1217
+ [freeKey]: [ax],
1218
+ ...j.limits ? {
1219
+ min: j.limits[0],
1220
+ max: j.limits[1]
1221
+ } : {},
1222
+ ...stiffness === void 0 ? {} : { stiffness },
1223
+ ...damping === void 0 ? {} : { damping }
1224
+ }] : [];
1225
+ const out = {
1226
+ limits: j.kind === "revolute" ? [
1227
+ {
1228
+ linearAxes: [
1229
+ 0,
1230
+ 1,
1231
+ 2
1232
+ ],
1233
+ min: 0,
1234
+ max: 0
1235
+ },
1236
+ {
1237
+ angularAxes: lockedAxes,
1238
+ min: 0,
1239
+ max: 0
1240
+ },
1241
+ ...freeLimit
1242
+ ] : [
1243
+ {
1244
+ angularAxes: [
1245
+ 0,
1246
+ 1,
1247
+ 2
1248
+ ],
1249
+ min: 0,
1250
+ max: 0
1251
+ },
1252
+ {
1253
+ linearAxes: lockedAxes,
1254
+ min: 0,
1255
+ max: 0
1256
+ },
1257
+ ...freeLimit
1258
+ ],
1259
+ ...!isCardinal || unit[ax] < 0 ? { extras: { jointAxis: unit } } : {}
1260
+ };
1261
+ const drives = j.drives ?? (j.drive ? [j.drive] : []);
1262
+ if (drives.length > 0) out.drives = drives.map((d) => encodeJointDrive(d, j.kind === "revolute" ? "angular" : "linear", ax, nodeName));
1263
+ return out;
1264
+ }
1265
+ function encodeMotion(m, nodeName) {
1266
+ const isKinematic = Boolean(m.isKinematic);
1267
+ if (!isKinematic && !isPosNum(m.mass)) throw new KhrValidationError(`exportKhrGlb: dynamic node "${nodeName}" requires positive finite motion.mass`);
1268
+ if (isKinematic && m.mass !== void 0) optFiniteNum(m.mass, `kinematic motion.mass on "${nodeName}"`, true);
1269
+ if (m.inertiaDiagonal && readFiniteVec3(m.inertiaDiagonal, `${nodeName}.motion.inertiaDiagonal`).some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`exportKhrGlb: invalid motion.inertiaDiagonal on "${nodeName}"`);
1270
+ const gravityFactor = optFiniteNum(m.gravityFactor, `motion.gravityFactor on "${nodeName}"`);
1271
+ return {
1272
+ isKinematic,
1273
+ ...m.mass === void 0 ? {} : { mass: m.mass },
1274
+ ...m.centerOfMass ? { centerOfMass: readFiniteVec3(m.centerOfMass, `${nodeName}.motion.centerOfMass`) } : {},
1275
+ ...m.inertiaDiagonal ? { inertiaDiagonal: m.inertiaDiagonal } : {},
1276
+ ...m.inertiaOrientation ? { inertiaOrientation: readUnitQuat(m.inertiaOrientation, `${nodeName}.motion.inertiaOrientation`) } : {},
1277
+ ...m.linearVelocity ? { linearVelocity: readFiniteVec3(m.linearVelocity, `${nodeName}.motion.linearVelocity`) } : {},
1278
+ ...m.angularVelocity ? { angularVelocity: readFiniteVec3(m.angularVelocity, `${nodeName}.motion.angularVelocity`) } : {},
1279
+ ...gravityFactor === void 0 ? {} : { gravityFactor }
1280
+ };
1281
+ }
1282
+ function encodePhysicsMaterial(col, nodeName) {
1283
+ const friction = optFiniteNum(col.friction, `collider.friction on "${nodeName}"`, true);
1284
+ const restitution = optFiniteNum(col.restitution, `collider.restitution on "${nodeName}"`, true);
1285
+ for (const [k, v] of [["frictionCombine", col.frictionCombine], ["restitutionCombine", col.restitutionCombine]]) if (v !== void 0 && (typeof v !== "string" || !COMBINE_MODES.has(v))) throw new KhrValidationError(`exportKhrGlb: invalid collider.${k} "${String(v)}" on "${nodeName}"`);
1286
+ if (friction === void 0 && restitution === void 0 && col.frictionCombine === void 0 && col.restitutionCombine === void 0) return null;
1287
+ return {
1288
+ ...friction === void 0 ? {} : {
1289
+ staticFriction: friction,
1290
+ dynamicFriction: friction
308
1291
  },
309
- setRoleTarget: (role, target) => {
310
- for (const map of jointsRef.current.values()) for (const rt of map.values()) if (rt.role === role) rt.applyTarget(target);
1292
+ ...restitution === void 0 ? {} : { restitution },
1293
+ ...col.frictionCombine === void 0 ? {} : { frictionCombine: col.frictionCombine },
1294
+ ...col.restitutionCombine === void 0 ? {} : { restitutionCombine: col.restitutionCombine }
1295
+ };
1296
+ }
1297
+ function validateCanonicalSystems(arr, label, nodeName) {
1298
+ if (!Array.isArray(arr) || arr.some((s) => typeof s !== "string" || s.length === 0)) throw new KhrValidationError(`exportKhrGlb: collider.${label} on "${nodeName}" must be an array of non-empty strings`);
1299
+ return [...new Set(arr)];
1300
+ }
1301
+ function encodeCollisionFilter(col, nodeName) {
1302
+ if (col.collideWithSystems !== void 0 && col.notCollideWithSystems !== void 0) throw new KhrValidationError(`exportKhrGlb: collider on "${nodeName}" cannot specify both collideWithSystems and notCollideWithSystems`);
1303
+ if (col.collisionSystems === void 0 && col.collideWithSystems === void 0 && col.notCollideWithSystems === void 0) return null;
1304
+ return {
1305
+ ...col.collisionSystems === void 0 ? {} : { collisionSystems: validateCanonicalSystems(col.collisionSystems, "collisionSystems", nodeName) },
1306
+ ...col.collideWithSystems === void 0 ? {} : { collideWithSystems: validateCanonicalSystems(col.collideWithSystems, "collideWithSystems", nodeName) },
1307
+ ...col.notCollideWithSystems === void 0 ? {} : { notCollideWithSystems: validateCanonicalSystems(col.notCollideWithSystems, "notCollideWithSystems", nodeName) }
1308
+ };
1309
+ }
1310
+ function encodeOmiWheel(wheel, nodeName) {
1311
+ if (!isObj(wheel)) throw new KhrValidationError(`exportKhrGlb: wheel on "${nodeName}" must be an object`);
1312
+ if (!isPosNum(wheel.radius)) throw new KhrValidationError(`exportKhrGlb: wheel.radius on "${nodeName}" must be > 0`);
1313
+ if (!isPosNum(wheel.width)) throw new KhrValidationError(`exportKhrGlb: wheel.width on "${nodeName}" must be > 0`);
1314
+ for (const [k, v] of [["steering", wheel.steering], ["propulsion", wheel.propulsion]]) if (v !== void 0 && typeof v !== "boolean") throw new KhrValidationError(`exportKhrGlb: wheel.${k} on "${nodeName}" must be boolean`);
1315
+ const maxForce = optFiniteNum(wheel.maxForce, `wheel.maxForce on "${nodeName}"`, true);
1316
+ const maxSteeringAngle = optFiniteNum(wheel.maxSteeringAngle, `wheel.maxSteeringAngle on "${nodeName}"`, true);
1317
+ const suspensionStiffness = optFiniteNum(wheel.suspensionStiffness, `wheel.suspensionStiffness on "${nodeName}"`, true);
1318
+ const suspensionDampingCompression = optFiniteNum(wheel.suspensionDampingCompression, `wheel.suspensionDampingCompression on "${nodeName}"`, true);
1319
+ const suspensionDampingRebound = optFiniteNum(wheel.suspensionDampingRebound, `wheel.suspensionDampingRebound on "${nodeName}"`, true);
1320
+ const suspensionTravel = optFiniteNum(wheel.suspensionTravel, `wheel.suspensionTravel on "${nodeName}"`, true);
1321
+ return {
1322
+ radius: wheel.radius,
1323
+ width: wheel.width,
1324
+ ...maxForce === void 0 ? {} : { maxForce },
1325
+ ...wheel.steering === void 0 ? {} : { steering: wheel.steering },
1326
+ ...wheel.propulsion === void 0 ? {} : { propulsion: wheel.propulsion },
1327
+ ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
1328
+ ...suspensionStiffness === void 0 ? {} : { suspensionStiffness },
1329
+ ...suspensionDampingCompression === void 0 ? {} : { suspensionDampingCompression },
1330
+ ...suspensionDampingRebound === void 0 ? {} : { suspensionDampingRebound },
1331
+ ...suspensionTravel === void 0 ? {} : { suspensionTravel }
1332
+ };
1333
+ }
1334
+ function synthesizeOmiWheel(raw) {
1335
+ if (!isObj(raw)) return null;
1336
+ if (!isPosNum(raw.radius) || !isPosNum(raw.width) || !isNonNegNum(raw.travel) || !isNonNegNum(raw.sag) || raw.sag > raw.travel) return null;
1337
+ if (typeof raw.steer !== "boolean" || typeof raw.drive !== "boolean" || typeof raw.brake !== "boolean") return null;
1338
+ const springK = isNonNegNum(raw.springK) ? raw.springK : void 0;
1339
+ const dampingC = isNonNegNum(raw.dampingC) ? raw.dampingC : void 0;
1340
+ const maxForce = isNonNegNum(raw.maxBrakeTorque) ? raw.maxBrakeTorque / raw.radius : void 0;
1341
+ const maxSteeringAngle = isNonNegNum(raw.maxSteeringAngle) ? raw.maxSteeringAngle : void 0;
1342
+ return {
1343
+ radius: raw.radius,
1344
+ width: raw.width,
1345
+ steering: raw.steer,
1346
+ propulsion: raw.drive,
1347
+ suspensionTravel: raw.travel,
1348
+ ...maxForce === void 0 ? {} : { maxForce },
1349
+ ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
1350
+ ...springK === void 0 ? {} : { suspensionStiffness: springK },
1351
+ ...dampingC === void 0 ? {} : {
1352
+ suspensionDampingCompression: dampingC,
1353
+ suspensionDampingRebound: dampingC
311
1354
  }
312
- }), [nodeToRoot]);
313
- if (plans.length === 1) {
314
- const plan = plans[0];
315
- return /* @__PURE__ */ jsx("group", {
316
- ...groupProps,
317
- children: /* @__PURE__ */ jsx(AssemblyRootBody, {
318
- plan,
319
- position: rootPoses[0].position,
320
- quaternion: rootPoses[0].quaternion,
321
- fixedRoot,
322
- rigidBodyProps,
323
- onBody: handleBody,
324
- onJoints: handleJoints,
325
- children: /* @__PURE__ */ jsxs("group", {
326
- position: plan.sceneInRootPos,
327
- quaternion: plan.sceneInRootQuat,
328
- children: [/* @__PURE__ */ jsx(BundleSceneHost, {
329
- bundle,
330
- owner: "KhrAssembly"
331
- }), children]
332
- })
333
- }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
334
- });
1355
+ };
1356
+ }
1357
+ /**
1358
+ * Replaces meshes' material references with shallow material clones ONLY when an unloaded headless Texture
1359
+ * (`!tex.image`) is present, keeping live WebGL materials untouched across async export.
1360
+ */
1361
+ function isolateUnloadedTextures(root) {
1362
+ const swaps = [];
1363
+ const clonedByMat = /* @__PURE__ */ new Map();
1364
+ const sanitizeMat = (mat) => {
1365
+ const cached = clonedByMat.get(mat);
1366
+ if (cached) return cached;
1367
+ const rec = mat;
1368
+ let hasUnloaded = false;
1369
+ for (const slot of Object.keys(rec)) {
1370
+ const val = rec[slot];
1371
+ if (val && typeof val === "object" && val.isTexture && !val.image) {
1372
+ hasUnloaded = true;
1373
+ break;
1374
+ }
1375
+ }
1376
+ if (!hasUnloaded) return mat;
1377
+ const clone = mat.clone();
1378
+ const cloneRec = clone;
1379
+ for (const slot of Object.keys(cloneRec)) {
1380
+ const val = cloneRec[slot];
1381
+ if (val && typeof val === "object" && val.isTexture && !val.image) cloneRec[slot] = null;
1382
+ }
1383
+ clonedByMat.set(mat, clone);
1384
+ return clone;
1385
+ };
1386
+ root.traverse((obj) => {
1387
+ const mesh = obj;
1388
+ if (!mesh.isMesh || !mesh.material) return;
1389
+ if (Array.isArray(mesh.material)) {
1390
+ const next = mesh.material.map(sanitizeMat);
1391
+ if (next.some((m, idx) => m !== mesh.material[idx])) {
1392
+ swaps.push({
1393
+ mesh,
1394
+ origMat: mesh.material,
1395
+ clones: next.filter((m, idx) => m !== mesh.material[idx])
1396
+ });
1397
+ mesh.material = next;
1398
+ }
1399
+ } else {
1400
+ const next = sanitizeMat(mesh.material);
1401
+ if (next !== mesh.material) {
1402
+ swaps.push({
1403
+ mesh,
1404
+ origMat: mesh.material,
1405
+ clones: [next]
1406
+ });
1407
+ mesh.material = next;
1408
+ }
1409
+ }
1410
+ });
1411
+ return swaps;
1412
+ }
1413
+ function internJson(table, map, item) {
1414
+ const key = JSON.stringify(item);
1415
+ let idx = map.get(key);
1416
+ if (idx === void 0) {
1417
+ idx = table.length;
1418
+ table.push(item);
1419
+ map.set(key, idx);
335
1420
  }
336
- return /* @__PURE__ */ jsxs("group", {
337
- ...groupProps,
338
- children: [/* @__PURE__ */ jsxs("group", {
339
- position,
340
- quaternion: [
341
- spawnQuat.x,
342
- spawnQuat.y,
343
- spawnQuat.z,
344
- spawnQuat.w
345
- ],
346
- children: [/* @__PURE__ */ jsx(BundleSceneHost, {
347
- bundle,
348
- owner: "KhrAssembly"
349
- }), children]
350
- }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
351
- plan,
352
- position: rootPoses[idx].position,
353
- quaternion: rootPoses[idx].quaternion,
354
- fixedRoot,
355
- rigidBodyProps,
356
- onBody: handleBody,
357
- onJoints: handleJoints,
358
- children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
359
- object: plan.mountNode,
360
- position: plan.mountPosition,
361
- quaternion: plan.mountQuaternion,
362
- origin: origins?.get(plan.mountNode)
363
- })
364
- }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
1421
+ return idx;
1422
+ }
1423
+ async function exportKhrGlb(root, specs, sceneExtras) {
1424
+ ensureHeadlessFileReader();
1425
+ root.updateMatrixWorld(true);
1426
+ const exporter = new GLTFExporter();
1427
+ const swaps = isolateUnloadedTextures(root);
1428
+ let rawBuf;
1429
+ try {
1430
+ const res = await exporter.parseAsync(root, { binary: true });
1431
+ rawBuf = res instanceof ArrayBuffer ? res : packJsonToGlb(res);
1432
+ } finally {
1433
+ for (const s of swaps) {
1434
+ s.mesh.material = s.origMat;
1435
+ for (const c of s.clones) c.dispose();
1436
+ }
1437
+ }
1438
+ return patchGlbJsonChunk(rawBuf, (gltf) => {
1439
+ const nodes = gltf.nodes ?? [];
1440
+ const nameToIndices = /* @__PURE__ */ new Map();
1441
+ nodes.forEach((n, idx) => {
1442
+ if (!n.name) return;
1443
+ const list = nameToIndices.get(n.name);
1444
+ if (list) list.push(idx);
1445
+ else nameToIndices.set(n.name, [idx]);
1446
+ });
1447
+ const requireNodeIdx = (name) => {
1448
+ const list = nameToIndices.get(name);
1449
+ if (!list || list.length === 0) throw new KhrValidationError(`exportKhrGlb: missing scene node "${name}"`);
1450
+ if (list.length > 1) throw new KhrValidationError(`exportKhrGlb: ambiguous duplicate scene node "${name}" (${list.length} matches)`);
1451
+ return list[0];
1452
+ };
1453
+ const shapes = [];
1454
+ const shapeMap = /* @__PURE__ */ new Map();
1455
+ const materials = [];
1456
+ const matMap = /* @__PURE__ */ new Map();
1457
+ const filters = [];
1458
+ const filterMap = /* @__PURE__ */ new Map();
1459
+ const joints = [];
1460
+ const jointMap = /* @__PURE__ */ new Map();
1461
+ const omiWheels = [];
1462
+ const wheelMap = /* @__PURE__ */ new Map();
1463
+ const seenSpecNodes = /* @__PURE__ */ new Set();
1464
+ const used = new Set(gltf.extensionsUsed ?? []);
1465
+ let hasPhysics = false;
1466
+ const hasPreIndexedOmiWheel = specs.some((s) => isObj(s.extensions) && Object.hasOwn(s.extensions, "OMI_vehicle_wheel") && s.extensions.OMI_vehicle_wheel !== void 0);
1467
+ for (const spec of specs) {
1468
+ if (seenSpecNodes.has(spec.nodeName)) throw new KhrValidationError(`exportKhrGlb: duplicate spec for node "${spec.nodeName}"`);
1469
+ seenSpecNodes.add(spec.nodeName);
1470
+ const node = nodes[requireNodeIdx(spec.nodeName)];
1471
+ if (spec.extras) node.extras = {
1472
+ ...node.extras,
1473
+ ...spec.extras
1474
+ };
1475
+ if (spec.extensions !== void 0) {
1476
+ if (!isObj(spec.extensions)) throw new KhrValidationError(`exportKhrGlb: extensions on "${spec.nodeName}" must be an object`);
1477
+ if (Object.hasOwn(spec.extensions, "OMI_vehicle_wheel") && spec.extensions.OMI_vehicle_wheel !== void 0 && spec.wheel !== void 0) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both wheel and extensions.OMI_vehicle_wheel`);
1478
+ if (Object.hasOwn(spec.extensions, "KHR_physics_rigid_bodies") && spec.extensions.KHR_physics_rigid_bodies !== void 0 && (spec.motion !== void 0 || spec.collider !== void 0 || spec.joint !== void 0)) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both extensions.KHR_physics_rigid_bodies and motion/collider/joint`);
1479
+ node.extensions = {
1480
+ ...node.extensions,
1481
+ ...spec.extensions
1482
+ };
1483
+ for (const extName of Object.keys(spec.extensions)) used.add(extName);
1484
+ }
1485
+ const khr = {};
1486
+ if (spec.motion) {
1487
+ hasPhysics = true;
1488
+ khr.motion = encodeMotion(spec.motion, spec.nodeName);
1489
+ }
1490
+ if (spec.collider) {
1491
+ hasPhysics = true;
1492
+ const col = {};
1493
+ if (spec.collider.shape) col.geometry = { shape: internJson(shapes, shapeMap, encodeShape(spec.collider.shape, spec.nodeName)) };
1494
+ else if (spec.collider.meshNodeName) {
1495
+ if (typeof spec.collider.convexHull !== "boolean") throw new KhrValidationError(`exportKhrGlb: mesh collider on "${spec.nodeName}" requires explicit boolean convexHull`);
1496
+ col.geometry = {
1497
+ node: requireNodeIdx(spec.collider.meshNodeName),
1498
+ convexHull: spec.collider.convexHull
1499
+ };
1500
+ } else throw new KhrValidationError(`exportKhrGlb: collider on "${spec.nodeName}" requires shape or meshNodeName`);
1501
+ const mat = encodePhysicsMaterial(spec.collider, spec.nodeName);
1502
+ if (mat) col.physicsMaterial = internJson(materials, matMap, mat);
1503
+ const filter = encodeCollisionFilter(spec.collider, spec.nodeName);
1504
+ if (filter) col.collisionFilter = internJson(filters, filterMap, filter);
1505
+ khr.collider = col;
1506
+ }
1507
+ if (spec.joint) {
1508
+ hasPhysics = true;
1509
+ const connIdx = requireNodeIdx(spec.joint.connectedNodeName);
1510
+ khr.joint = {
1511
+ joint: internJson(joints, jointMap, encodeJoint(spec.joint, spec.nodeName)),
1512
+ connectedNode: connIdx,
1513
+ enableCollision: Boolean(spec.joint.enableCollision)
1514
+ };
1515
+ }
1516
+ const wheelSpec = spec.wheel ?? (!hasPreIndexedOmiWheel ? synthesizeOmiWheel(spec.extras?.ecctrlWheel) : null);
1517
+ if (wheelSpec) {
1518
+ const wIdx = internJson(omiWheels, wheelMap, encodeOmiWheel(wheelSpec, spec.nodeName));
1519
+ used.add("OMI_vehicle_wheel");
1520
+ node.extensions = {
1521
+ ...node.extensions,
1522
+ OMI_vehicle_wheel: { wheel: wIdx }
1523
+ };
1524
+ }
1525
+ if (Object.keys(khr).length > 0) node.extensions = {
1526
+ ...node.extensions,
1527
+ KHR_physics_rigid_bodies: khr
1528
+ };
1529
+ }
1530
+ if (hasPreIndexedOmiWheel && omiWheels.length > 0) throw new KhrValidationError("exportKhrGlb: cannot mix spec.wheel with spec.extensions.OMI_vehicle_wheel in the same call");
1531
+ if (sceneExtras) {
1532
+ const scene = gltf.scenes?.[gltf.scene ?? 0];
1533
+ if (scene) scene.extras = {
1534
+ ...scene.extras,
1535
+ ...sceneExtras
1536
+ };
1537
+ else gltf.extras = {
1538
+ ...gltf.extras,
1539
+ ...sceneExtras
1540
+ };
1541
+ }
1542
+ gltf.extensions ??= {};
1543
+ if (shapes.length > 0) {
1544
+ used.add("KHR_implicit_shapes");
1545
+ gltf.extensions.KHR_implicit_shapes = { shapes };
1546
+ }
1547
+ if (hasPhysics) {
1548
+ used.add("KHR_physics_rigid_bodies");
1549
+ gltf.extensions.KHR_physics_rigid_bodies = {
1550
+ ...materials.length > 0 ? { physicsMaterials: materials } : {},
1551
+ ...filters.length > 0 ? { collisionFilters: filters } : {},
1552
+ ...joints.length > 0 ? { physicsJoints: joints } : {}
1553
+ };
1554
+ }
1555
+ if (omiWheels.length > 0) {
1556
+ used.add("OMI_vehicle_wheel");
1557
+ gltf.extensions.OMI_vehicle_wheel = { wheels: omiWheels };
1558
+ }
1559
+ if (used.size > 0) gltf.extensionsUsed = [...used];
365
1560
  });
366
1561
  }
367
1562
  // src/useKhrGlb.ts
368
1563
  var KhrGLTFLoader = class extends GLTFLoader {
369
1564
  static khrLoaderScope = Symbol("KhrGLTFLoader");
370
1565
  };
371
- var headlessPlugin = createHeadlessTexturePlugin();
372
1566
  var khrPlugin = createKhrGltfPlugin();
373
1567
  var configuredLoaders = /* @__PURE__ */ new WeakSet();
374
1568
  var customExtendedLoaders = /* @__PURE__ */ new WeakSet();
375
- var customLoaderRegistry = /* @__PURE__ */ new Map();
1569
+ var fnIds = /* @__PURE__ */ new WeakMap();
1570
+ var nextFnId = 1;
1571
+ var scopedRegistry = /* @__PURE__ */ new Map();
376
1572
  function configureKhrLoader(loader) {
377
1573
  if (configuredLoaders.has(loader)) return;
378
1574
  configuredLoaders.add(loader);
379
- if (isHeadlessTextureEnv()) loader.register(headlessPlugin);
380
1575
  loader.register(khrPlugin);
381
1576
  }
382
1577
  function hasCustomLoaderOpts(options) {
383
1578
  return Boolean(options?.extendLoader || options?.cacheKey !== void 0);
384
1579
  }
385
1580
  function getLoaderCacheKey(options) {
386
- return options.cacheKey === void 0 ? `src:${Function.prototype.toString.call(options.extendLoader)}` : `key:${options.cacheKey}`;
1581
+ if (options.cacheKey !== void 0) return `key:${options.cacheKey}`;
1582
+ const fn = options.extendLoader;
1583
+ let id = fnIds.get(fn);
1584
+ if (id === void 0) {
1585
+ id = nextFnId++;
1586
+ fnIds.set(fn, id);
1587
+ }
1588
+ return `fn:${id}`;
1589
+ }
1590
+ function createScopedGltfLoaderClass() {
1591
+ return class ScopedKhrGLTFLoader extends GLTFLoader {};
387
1592
  }
388
1593
  function getScopedLoaderEntry(url, options) {
389
1594
  const key = getLoaderCacheKey(options);
390
- let urlMap = customLoaderRegistry.get(url);
1595
+ let urlMap = scopedRegistry.get(url);
391
1596
  if (!urlMap) {
392
1597
  urlMap = /* @__PURE__ */ new Map();
393
- customLoaderRegistry.set(url, urlMap);
1598
+ scopedRegistry.set(url, urlMap);
394
1599
  }
395
1600
  let entry = urlMap.get(key);
396
1601
  if (!entry) {
397
- const loader = new GLTFLoader();
1602
+ const Proto = createScopedGltfLoaderClass();
398
1603
  const extend = options.extendLoader;
399
1604
  const created = {
400
- loader,
1605
+ Proto,
401
1606
  registerExtensions: (target) => {
402
1607
  configureKhrLoader(target);
403
1608
  if (extend && !customExtendedLoaders.has(target)) try {
404
1609
  extend(target);
405
1610
  customExtendedLoaders.add(target);
406
1611
  } catch (err) {
407
- const map = customLoaderRegistry.get(url);
1612
+ const map = scopedRegistry.get(url);
408
1613
  if (map?.get(key) === created) {
409
1614
  map.delete(key);
410
- if (map.size === 0) customLoaderRegistry.delete(url);
1615
+ if (map.size === 0) scopedRegistry.delete(url);
411
1616
  }
412
1617
  throw err;
413
1618
  }
@@ -422,9 +1627,9 @@ function useKhrGlb(url, options) {
422
1627
  const extractRole = options?.extractRole;
423
1628
  const isSocketNode = options?.isSocketNode;
424
1629
  const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
425
- const loader = scoped ? scoped.loader : KhrGLTFLoader;
1630
+ const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
426
1631
  const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
427
- const template = useLoader(loader, url, reg).userData[KHR_BUNDLE_USERDATA_KEY];
1632
+ const template = useLoader(Proto, url, reg).userData[KHR_BUNDLE_USERDATA_KEY];
428
1633
  if (!template) throw new KhrValidationError(`useKhrGlb: missing "${KHR_BUNDLE_USERDATA_KEY}" on loaded GLTF for "${url}"`);
429
1634
  return useMemo(() => {
430
1635
  const cloned = cloneKhrBundle(template);
@@ -439,33 +1644,33 @@ function useKhrGlb(url, options) {
439
1644
  (function(_useKhrGlb) {
440
1645
  _useKhrGlb.preload = (url, options) => {
441
1646
  const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
442
- const loader = scoped ? scoped.loader : KhrGLTFLoader;
1647
+ const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
443
1648
  const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
444
- useLoader.preload(loader, url, reg);
1649
+ useLoader.preload(Proto, url, reg);
445
1650
  };
446
1651
  _useKhrGlb.clear = (url, options) => {
447
1652
  if (hasCustomLoaderOpts(options)) {
448
- const urlMap = customLoaderRegistry.get(url);
1653
+ const urlMap = scopedRegistry.get(url);
449
1654
  if (!urlMap) return;
450
1655
  const key = getLoaderCacheKey(options);
451
1656
  const entry = urlMap.get(key);
452
1657
  if (entry) {
453
- useLoader.clear(entry.loader, url);
1658
+ useLoader.clear(entry.Proto, url);
454
1659
  urlMap.delete(key);
455
- if (urlMap.size === 0) customLoaderRegistry.delete(url);
1660
+ if (urlMap.size === 0) scopedRegistry.delete(url);
456
1661
  }
457
1662
  } else {
458
1663
  useLoader.clear(KhrGLTFLoader, url);
459
1664
  if (options === void 0) {
460
- const urlMap = customLoaderRegistry.get(url);
1665
+ const urlMap = scopedRegistry.get(url);
461
1666
  if (urlMap) {
462
- for (const entry of urlMap.values()) useLoader.clear(entry.loader, url);
463
- customLoaderRegistry.delete(url);
1667
+ for (const entry of urlMap.values()) useLoader.clear(entry.Proto, url);
1668
+ scopedRegistry.delete(url);
464
1669
  }
465
1670
  }
466
1671
  }
467
1672
  };
468
1673
  })(useKhrGlb || (useKhrGlb = {}));
469
- export { JointRegistryContext, KhrAssembly, KhrCollider, KhrValidationError, PhysicsWorld, SAND3D_RECIPES, SAND3D_RECIPE_MAP, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, buildSand3dRecipe, claimBundleMount, cloneKhrBundle, compileSand3dAssembly, createKhrGltfPlugin, disposeKhrBundle, exportKhrGlb, exportSand3dGlb, findSand3dRecipe, isSand3dFileName, loadKhrGlb, loadSand3dBundle, parseSand3dSource, patchGlbJsonChunk, releaseBundleMount, s3d, useKhrGlb };
1674
+ export { ATTACHED_PANEL_INTERACTION_GROUPS, DETACHED_PANEL_INTERACTION_GROUPS, JointRegistryContext, KhrAssembly, KhrCollider, KhrGLTFLoader, KhrValidationError, PhysicsWorld, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, assignRef, buildJointRuntime, claimBundleMount, cloneKhrBundle, computeShapeInertia, configureJointDrive, createKhrGltfPlugin, createRapierImpulseJoint, createScopedGltfLoaderClass, disposeKhrBundle, exportKhrGlb, isJointOpen, loadKhrGlb, measureJointCoordinate, openTargetForLimits, patchGlbJsonChunk, planAssembly, releaseBundleMount, useKhrGlb };
470
1675
 
471
1676
  //# sourceMappingURL=index.js.map