@khr3/core 0.2.6 → 0.2.7

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