@khr3/core 0.2.11 → 0.2.13

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.
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
- import { useMemo } from "react";
1
+ import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
2
2
  import { useFrame, useLoader } from "@react-three/fiber";
3
- import { Physics, useRapier } from "@react-three/rapier";
3
+ import { Physics, RigidBody, useRapier } from "@react-three/rapier";
4
4
  import { TimeControl } from "@pinkaphant/ecctrl/time";
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";
5
+ import { A as computeRelativePose, B as assignRef, C as applyRapierBodyMass, D as bodyPoseMatrix, E as assertUnitScale, F as readUnitQuat, G as optFiniteNum, H as isNonNegNum, I as resolveBodyMassFromColliders, L as COMBINE_MODES, M as extractMeshColliderShape, N as jacobiPrincipalInertia, O as computeAssemblyMassAndCom, P as readFiniteVec3, R as JointRegistryContext, S as snapshotSceneWithMountedSubtrees, T as assertSceneIdentityWorldScale, U as isObj, V as isFiniteNum, W as isPosNum, _ as cloneKhrBundle, a as configureJointDrive, b as releaseBundleMount, c as measureJointCoordinate, d as KHR_TRIMESH_FLAGS, f as KhrCollider, g as claimBundleMount, h as captureSubtreeOrigins, i as closedTargetForLimits, j as computeShapeInertia, k as computeLumpedMassProps, l as openTargetForLimits, m as MountSubtreeSlot, n as DETACHED_PANEL_INTERACTION_GROUPS, o as createRapierImpulseJoint, p as BundleSceneHost, r as buildJointRuntime, s as isJointOpen, t as ATTACHED_PANEL_INTERACTION_GROUPS, u as toggleDrivenJoint, v as disposeKhrBundle, w as assertIdentityWorldScale, z as KhrValidationError } from "./joints-H3uae8pm.js";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
7
  import * as THREE from "three";
8
8
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
9
9
  import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
10
+ import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
10
11
  // src/PhysicsWorld.tsx
11
12
  var readVal = (v) => typeof v === "number" ? v : v.current;
12
13
  function TimestepPresync({ paused, timeScale, maxDelta }) {
@@ -47,182 +48,15 @@ function PhysicsWorld({ paused = false, timeScale = 1, maxDelta = 1 / 30, gravit
47
48
  })
48
49
  });
49
50
  }
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
- }
51
+ // src/decoders.ts
52
+ var _quat = new THREE.Quaternion();
53
+ var _invParentQuat = new THREE.Quaternion();
54
+ var _localOrigin = new THREE.Vector3(0, 0, 0);
55
+ var _wpA = new THREE.Vector3();
56
+ var _wpB = new THREE.Vector3();
57
+ var _wqInv = new THREE.Quaternion();
58
+ var _dotVec = new THREE.Vector3();
59
+ var _dotQuat = new THREE.Quaternion();
226
60
  function decodeShape(raw, idx) {
227
61
  if (!isObj(raw)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] must be an object`);
228
62
  const type = raw.type;
@@ -335,12 +169,14 @@ function decodeMotion(motion, hasMotion, name) {
335
169
  if (!isNonNegNum(motion.mass)) throw new KhrValidationError(`Kinematic node "${name}" has invalid motion.mass`);
336
170
  mass = motion.mass;
337
171
  }
338
- const centerOfMass = motion.centerOfMass === void 0 ? [
172
+ const hasExplicitCom = motion.centerOfMass !== void 0;
173
+ const centerOfMass = !hasExplicitCom ? [
339
174
  0,
340
175
  0,
341
176
  0
342
177
  ] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
343
- const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
178
+ const hasExplicitInertiaOrientation = motion.inertiaOrientation !== void 0;
179
+ const inertiaOrientation = !hasExplicitInertiaOrientation ? [
344
180
  0,
345
181
  0,
346
182
  0,
@@ -362,11 +198,13 @@ function decodeMotion(motion, hasMotion, name) {
362
198
  return {
363
199
  isKinematic,
364
200
  hasExplicitMotion: hasMotion,
201
+ hasExplicitCom,
202
+ hasExplicitInertia,
203
+ hasExplicitInertiaOrientation,
365
204
  mass,
366
205
  centerOfMass,
367
206
  inertiaDiagonal,
368
207
  inertiaOrientation,
369
- hasExplicitInertia,
370
208
  ...linearVelocity ? { linearVelocity } : {},
371
209
  ...angularVelocity ? { angularVelocity } : {},
372
210
  ...gravityFactor === void 0 ? {} : { gravityFactor }
@@ -507,7 +345,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
507
345
  jz / jLen
508
346
  ];
509
347
  }
510
- const anchor1Vec = childNode.getWorldPosition(new THREE.Vector3()).sub(connectedNode.getWorldPosition(new THREE.Vector3())).applyQuaternion(connectedNode.getWorldQuaternion(new THREE.Quaternion()).invert());
348
+ const anchor1Vec = childNode.getWorldPosition(_wpA).sub(connectedNode.getWorldPosition(_wpB)).applyQuaternion(connectedNode.getWorldQuaternion(_wqInv).invert());
511
349
  return {
512
350
  index: jointIdx,
513
351
  nodeName,
@@ -533,9 +371,6 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
533
371
  ]
534
372
  };
535
373
  }
536
- var _quat = new THREE.Quaternion();
537
- var _invParentQuat = new THREE.Quaternion();
538
- var _localOrigin = new THREE.Vector3(0, 0, 0);
539
374
  function getRelativeQuatArray(obj, parent) {
540
375
  obj.updateWorldMatrix(true, false);
541
376
  obj.getWorldQuaternion(_quat);
@@ -559,11 +394,11 @@ function getRelativeQuatArray(obj, parent) {
559
394
  * falling back to mesh AABB center only when an uncentered mesh was exported with its node left at `(0, 0, 0)`.
560
395
  */
561
396
  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
397
+ obj.getWorldPosition(_wpA);
398
+ if (_wpA.lengthSq() > 1e-8) return [
399
+ _wpA.x,
400
+ _wpA.y,
401
+ _wpA.z
567
402
  ];
568
403
  const invObj = obj.matrixWorld.clone().invert();
569
404
  const rel = new THREE.Matrix4();
@@ -578,11 +413,11 @@ function resolveRotorHubPosition(obj) {
578
413
  for (let i = 0; i < pos.count; i++) localBox.expandByPoint(v.fromBufferAttribute(pos, i).applyMatrix4(rel));
579
414
  });
580
415
  if (localBox.isEmpty() || localBox.containsPoint(_localOrigin)) return [
581
- wp.x,
582
- wp.y,
583
- wp.z
416
+ _wpA.x,
417
+ _wpA.y,
418
+ _wpA.z
584
419
  ];
585
- const c = new THREE.Box3().setFromObject(obj).getCenter(new THREE.Vector3());
420
+ const c = new THREE.Box3().setFromObject(obj).getCenter(_wpB);
586
421
  return [
587
422
  c.x,
588
423
  c.y,
@@ -628,92 +463,392 @@ function optCurve(val, key, owner) {
628
463
  if (val.samples !== void 0 && !isPosNum(val.samples)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
629
464
  return val;
630
465
  }
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
- };
466
+ function decodeWheelTag(obj, name, rawWheel, scene, rawOmiWheel) {
467
+ assertIdentityWorldScale(obj, name);
468
+ const hasOmi = rawOmiWheel !== void 0;
469
+ if (hasOmi && !isObj(rawOmiWheel)) throw new KhrValidationError(`OMI_vehicle_wheel "${name}" must be an object`);
470
+ if (rawWheel !== void 0 && !isObj(rawWheel)) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
471
+ if (!hasOmi && rawWheel === void 0) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
472
+ const ec = isObj(rawWheel) ? rawWheel : {};
473
+ const omi = isObj(rawOmiWheel) ? rawOmiWheel : void 0;
474
+ const omiRadius = omi ? optRotorNum(omi, "radius", "OMI_vehicle_wheel", name, true) : void 0;
475
+ const omiWidth = omi ? optRotorNum(omi, "width", "OMI_vehicle_wheel", name, true) : void 0;
476
+ const radius = optRotorNum(ec, "radius", "ecctrlWheel", name, true) ?? omiRadius;
477
+ const width = optRotorNum(ec, "width", "ecctrlWheel", name, true) ?? omiWidth;
478
+ if (radius === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite radius`);
479
+ if (width === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite width`);
480
+ const omiTravel = omi ? optRotorNum(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
481
+ const omiMaxForce = omi ? optRotorNum(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
482
+ const omiMaxSteerRaw = omi ? optRotorNum(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
483
+ const omiStiffness = omi ? optRotorNum(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
484
+ const omiDampComp = omi ? optRotorNum(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
485
+ const omiDampReb = omi ? optRotorNum(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
486
+ const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
487
+ const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
488
+ const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
489
+ const travel = omi ? optRotorNum(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqRotorNum(ec, "travel", "ecctrlWheel", name);
490
+ const sag = omi ? optRotorNum(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqRotorNum(ec, "sag", "ecctrlWheel", name);
491
+ if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
492
+ const steer = omi ? optRotorBool(ec, "steer", "ecctrlWheel", name) ?? omiSteer?.flag ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqRotorBool(ec, "steer", "ecctrlWheel", name);
493
+ const drive = omi ? optRotorBool(ec, "drive", "ecctrlWheel", name) ?? omiProp?.flag ?? false : reqRotorBool(ec, "drive", "ecctrlWheel", name);
494
+ const brake = omi ? optRotorBool(ec, "brake", "ecctrlWheel", name) ?? true : reqRotorBool(ec, "brake", "ecctrlWheel", name);
495
+ const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
496
+ const springK = optRotorNum(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
497
+ const dampingC = optRotorNum(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
498
+ const maxBrakeTorque = optRotorNum(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
499
+ const maxSteeringAngle = optRotorNum(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
500
+ return {
501
+ nodeName: name,
502
+ object: obj,
503
+ position: resolveRotorHubPosition(obj),
504
+ quaternion: getRelativeQuatArray(obj, scene),
505
+ radius,
506
+ width,
507
+ steer,
508
+ steerInvert: optRotorBool(ec, "steerInvert", "ecctrlWheel", name),
509
+ drive,
510
+ driveInvert: optRotorBool(ec, "driveInvert", "ecctrlWheel", name),
511
+ brake,
512
+ travel,
513
+ sag,
514
+ springK,
515
+ dampingC,
516
+ maxBrakeTorque,
517
+ ...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
518
+ rollingResistanceCoef: optRotorNum(ec, "rollingResistanceCoef", "ecctrlWheel", name),
519
+ wheelDensity: optRotorNum(ec, "wheelDensity", "ecctrlWheel", name, true),
520
+ driveTorqueWeight: optRotorNum(ec, "driveTorqueWeight", "ecctrlWheel", name),
521
+ tireGripFactor: optRotorNum(ec, "tireGripFactor", "ecctrlWheel", name),
522
+ latFrictionEllipseScale: optRotorNum(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
523
+ relaxLngRate: optRotorNum(ec, "relaxLngRate", "ecctrlWheel", name),
524
+ relaxLatRate: optRotorNum(ec, "relaxLatRate", "ecctrlWheel", name),
525
+ lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
526
+ latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
527
+ };
528
+ }
529
+ function decodePropellerTag(obj, name, rawPropeller, scene) {
530
+ assertIdentityWorldScale(obj, name);
531
+ if (!isObj(rawPropeller)) throw new KhrValidationError(`ecctrlPropeller "${name}" must be an object`);
532
+ if (!isPosNum(rawPropeller.maxThrust)) throw new KhrValidationError(`ecctrlPropeller "${name}" is missing positive finite ecctrlPropeller.maxThrust`);
533
+ const torqueRatio = optFiniteNum(rawPropeller.torqueRatio, `ecctrlPropeller "${name}".torqueRatio`);
534
+ return {
535
+ nodeName: name,
536
+ object: obj,
537
+ position: resolveRotorHubPosition(obj),
538
+ quaternion: getRelativeQuatArray(obj, scene),
539
+ maxThrust: rawPropeller.maxThrust,
540
+ torqueRatio,
541
+ invertThrust: optRotorBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
542
+ invertTorque: optRotorBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
543
+ };
544
+ }
545
+ function decodeBreakawaySpec(raw) {
546
+ if (!isObj(raw) || !isPosNum(raw.breakImpulseNs)) return void 0;
547
+ const latch = isPosNum(raw.latchImpulseNs) ? raw.latchImpulseNs : void 0;
548
+ return {
549
+ ...latch === void 0 ? {} : { latchImpulseNs: latch },
550
+ breakImpulseNs: raw.breakImpulseNs
551
+ };
552
+ }
553
+ var SOCKET_PREFIX_RE = /^(?:socket|ik)_(.+)$/i;
554
+ var SEAT_NODE_RE = /^seat(?:_[lr])?$/i;
555
+ var _seatBox = new THREE.Box3();
556
+ var _seatCenter = new THREE.Vector3();
557
+ function resolveNodePivotOrMeshCenter(obj) {
558
+ obj.getWorldPosition(_wpA);
559
+ if (_wpA.lengthSq() > 1e-8) return [
560
+ _wpA.x,
561
+ _wpA.y,
562
+ _wpA.z
563
+ ];
564
+ _seatBox.makeEmpty();
565
+ obj.traverse((child) => {
566
+ const mesh = child;
567
+ if (mesh.isMesh && mesh.geometry) _seatBox.expandByObject(mesh);
568
+ });
569
+ if (!_seatBox.isEmpty()) {
570
+ _seatBox.getCenter(_seatCenter);
571
+ return [
572
+ _seatCenter.x,
573
+ _seatCenter.y,
574
+ _seatCenter.z
575
+ ];
576
+ }
577
+ return [
578
+ _wpA.x,
579
+ _wpA.y,
580
+ _wpA.z
581
+ ];
582
+ }
583
+ function extractDefaultBodyRole(extras) {
584
+ for (const key of [
585
+ "role",
586
+ "vehicleRole",
587
+ "buildingRole",
588
+ "weaponRole"
589
+ ]) {
590
+ const val = extras[key];
591
+ if (typeof val === "string" && val.length > 0) return val;
592
+ }
593
+ return null;
594
+ }
595
+ function collectNodeSockets(obj, name, extras, sockets, emitters, scene, rawExtensions, isSocketNode) {
596
+ if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
597
+ obj.getWorldPosition(_wpA);
598
+ const worldPosition = [
599
+ _wpA.x,
600
+ _wpA.y,
601
+ _wpA.z
602
+ ];
603
+ let emitterSocket;
604
+ const rawEmitter = rawExtensions?.KOLMO_emitter;
605
+ if (rawEmitter !== void 0) {
606
+ if (!isObj(rawEmitter)) throw new KhrValidationError(`Node "${name}" has invalid extensions.KOLMO_emitter`);
607
+ if (rawEmitter.socket !== void 0) {
608
+ if (typeof rawEmitter.socket !== "string" || rawEmitter.socket.length === 0) throw new KhrValidationError(`Node "${name}" has invalid KOLMO_emitter.socket`);
609
+ emitterSocket = rawEmitter.socket;
610
+ sockets[emitterSocket] = [...worldPosition];
611
+ sockets[name] = [...worldPosition];
612
+ }
613
+ if (rawEmitter.kind !== void 0) {
614
+ if (typeof rawEmitter.kind !== "string" || rawEmitter.kind.length === 0) throw new KhrValidationError(`Node "${name}" has invalid KOLMO_emitter.kind`);
615
+ if (rawEmitter.drive !== void 0 && (typeof rawEmitter.drive !== "string" || rawEmitter.drive.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid KOLMO_emitter.drive`);
616
+ let color;
617
+ if (rawEmitter.color !== void 0) color = readFiniteVec3(rawEmitter.color, `${name}.KOLMO_emitter.color`);
618
+ const size = optFiniteNum(rawEmitter.size, `${name}.KOLMO_emitter.size`, true);
619
+ emitters.push({
620
+ nodeName: name,
621
+ kind: rawEmitter.kind,
622
+ ...typeof rawEmitter.drive === "string" ? { drive: rawEmitter.drive } : {},
623
+ ...color ? { color } : {},
624
+ ...size === void 0 ? {} : { size },
625
+ position: [...worldPosition],
626
+ quaternion: getRelativeQuatArray(obj, scene),
627
+ object: obj
628
+ });
629
+ }
630
+ }
631
+ let inferredSocket;
632
+ const custom = isSocketNode?.(name, extras);
633
+ if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
634
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name;
635
+ sockets[key] = [...worldPosition];
636
+ } else if (!emitterSocket) {
637
+ const prefixMatch = SOCKET_PREFIX_RE.exec(name);
638
+ if (prefixMatch) {
639
+ inferredSocket = prefixMatch[1].toLowerCase();
640
+ sockets[inferredSocket] ??= [...worldPosition];
641
+ sockets[name] ??= [...worldPosition];
642
+ } else if (SEAT_NODE_RE.test(name)) {
643
+ const seatPos = resolveNodePivotOrMeshCenter(obj);
644
+ sockets[name] = seatPos;
645
+ if (/^seat(?:_l)?$/i.test(name)) sockets.seat ??= [...seatPos];
646
+ inferredSocket = name;
647
+ }
648
+ }
649
+ let contactDots;
650
+ if (extras.contactDots !== void 0) {
651
+ if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
652
+ obj.getWorldQuaternion(_dotQuat);
653
+ contactDots = [];
654
+ for (const dot of extras.contactDots) {
655
+ 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`);
656
+ _dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_dotQuat).add(_wpA);
657
+ const dotPos = [
658
+ _dotVec.x,
659
+ _dotVec.y,
660
+ _dotVec.z
661
+ ];
662
+ sockets[dot.role] = dotPos;
663
+ contactDots.push([dot.role, dotPos]);
664
+ }
665
+ }
666
+ return {
667
+ nodeName: name,
668
+ extras,
669
+ worldPosition,
670
+ ...emitterSocket ? { emitterSocket } : {},
671
+ ...inferredSocket ? { inferredSocket } : {},
672
+ ...contactDots ? { contactDots } : {}
673
+ };
674
+ }
675
+ // src/glb.ts
676
+ /** ASCII "glTF" little-endian fourCC. */
677
+ var GLB_MAGIC = 0x46546c67;
678
+ /** ASCII "JSON" little-endian fourCC. */
679
+ var GLB_JSON_CHUNK = 0x4e4f534a;
680
+ /** ASCII "BIN\0" little-endian fourCC. */
681
+ var GLB_BIN_CHUNK = 5130562;
682
+ function validateGlbHeader(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
683
+ if (byteLength < 20) throw new KhrValidationError("GLB buffer shorter than 20-byte header");
684
+ const view = new DataView(buffer, byteOffset, byteLength);
685
+ if (view.getUint32(0, true) !== 0x46546c67) throw new KhrValidationError("Invalid GLB magic");
686
+ if (view.getUint32(4, true) !== 2) throw new KhrValidationError("Unsupported glTF version");
687
+ const jsonLen = view.getUint32(12, true);
688
+ if (view.getUint32(16, true) !== 0x4e4f534a) throw new KhrValidationError("Missing GLB JSON chunk");
689
+ if (20 + jsonLen > byteLength) throw new KhrValidationError("Truncated GLB JSON chunk");
690
+ return jsonLen;
691
+ }
692
+ function bytesToBase64(bytes) {
693
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
694
+ const CHUNK = 32768;
695
+ const chunks = [];
696
+ for (let i = 0; i < bytes.length; i += CHUNK) chunks.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK)));
697
+ return btoa(chunks.join(""));
698
+ }
699
+ function ensureHeadlessFileReader() {
700
+ if (globalThis.FileReader !== void 0) return;
701
+ class HeadlessFileReader extends EventTarget {
702
+ static EMPTY = 0;
703
+ static LOADING = 1;
704
+ static DONE = 2;
705
+ EMPTY = 0;
706
+ LOADING = 1;
707
+ DONE = 2;
708
+ readyState = 0;
709
+ result = null;
710
+ error = null;
711
+ onload = null;
712
+ onloadend = null;
713
+ onerror = null;
714
+ abort() {
715
+ this.readyState = 2;
716
+ }
717
+ readAsArrayBuffer(blob) {
718
+ this.readyState = 1;
719
+ blob.arrayBuffer().then((buf) => {
720
+ this.result = buf;
721
+ this.readyState = 2;
722
+ this.onload?.({ target: this });
723
+ this.dispatchEvent(new Event("load"));
724
+ this.onloadend?.({ target: this });
725
+ this.dispatchEvent(new Event("loadend"));
726
+ }, (err) => {
727
+ this.error = err;
728
+ this.readyState = 2;
729
+ this.onerror?.(err);
730
+ this.dispatchEvent(new Event("error"));
731
+ this.onloadend?.({ target: this });
732
+ this.dispatchEvent(new Event("loadend"));
733
+ });
734
+ }
735
+ readAsDataURL(blob) {
736
+ this.readyState = 1;
737
+ blob.arrayBuffer().then((buf) => {
738
+ const b64 = bytesToBase64(new Uint8Array(buf));
739
+ this.result = `data:${blob.type || "application/octet-stream"};base64,${b64}`;
740
+ this.readyState = 2;
741
+ this.onload?.({ target: this });
742
+ this.dispatchEvent(new Event("load"));
743
+ this.onloadend?.({ target: this });
744
+ this.dispatchEvent(new Event("loadend"));
745
+ }, (err) => {
746
+ this.error = err;
747
+ this.readyState = 2;
748
+ this.onerror?.(err);
749
+ this.dispatchEvent(new Event("error"));
750
+ this.onloadend?.({ target: this });
751
+ this.dispatchEvent(new Event("loadend"));
752
+ });
753
+ }
754
+ }
755
+ globalThis.FileReader = HeadlessFileReader;
756
+ }
757
+ function packJsonToGlb(gltf) {
758
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
759
+ const paddedJsonLen = jsonBytes.byteLength + 3 & -4;
760
+ const totalLen = 20 + paddedJsonLen;
761
+ const out = new ArrayBuffer(totalLen);
762
+ const dv = new DataView(out);
763
+ const u8 = new Uint8Array(out);
764
+ dv.setUint32(0, GLB_MAGIC, true);
765
+ dv.setUint32(4, 2, true);
766
+ dv.setUint32(8, totalLen, true);
767
+ dv.setUint32(12, paddedJsonLen, true);
768
+ dv.setUint32(16, GLB_JSON_CHUNK, true);
769
+ u8.set(jsonBytes, 20);
770
+ u8.fill(32, 20 + jsonBytes.byteLength, 20 + paddedJsonLen);
771
+ return out;
772
+ }
773
+ function patchGlbJsonChunk(source, mutator) {
774
+ const buf = source instanceof ArrayBuffer ? source : source.buffer;
775
+ const byteOffset = source instanceof ArrayBuffer ? 0 : source.byteOffset;
776
+ const byteLength = source.byteLength;
777
+ const jsonLen = validateGlbHeader(buf, byteOffset, byteLength);
778
+ const dv = new DataView(buf, byteOffset, byteLength);
779
+ let gltf;
780
+ try {
781
+ gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, byteOffset + 20, jsonLen)));
782
+ } catch {
783
+ throw new KhrValidationError("Malformed GLB JSON chunk");
784
+ }
785
+ mutator(gltf);
786
+ const nextJson = new TextEncoder().encode(JSON.stringify(gltf));
787
+ const paddedJsonLen = nextJson.byteLength + 3 & -4;
788
+ const binHeaderOff = 20 + jsonLen;
789
+ const hasBin = binHeaderOff < byteLength;
790
+ let binTag = GLB_BIN_CHUNK;
791
+ let binData = /* @__PURE__ */ new Uint8Array(0);
792
+ if (hasBin) {
793
+ if (binHeaderOff + 8 > byteLength) throw new KhrValidationError("Truncated GLB binary chunk header");
794
+ const binLen = dv.getUint32(binHeaderOff, true);
795
+ binTag = dv.getUint32(binHeaderOff + 4, true);
796
+ if (binHeaderOff + 8 + binLen > byteLength) throw new KhrValidationError("Truncated GLB binary chunk payload");
797
+ binData = new Uint8Array(buf, byteOffset + binHeaderOff + 8, binLen);
798
+ }
799
+ const paddedBinLen = binData.byteLength + 3 & -4;
800
+ const totalLen = 20 + paddedJsonLen + (hasBin ? 8 + paddedBinLen : 0);
801
+ const out = new ArrayBuffer(totalLen);
802
+ const outDv = new DataView(out);
803
+ const outU8 = new Uint8Array(out);
804
+ outDv.setUint32(0, GLB_MAGIC, true);
805
+ outDv.setUint32(4, 2, true);
806
+ outDv.setUint32(8, totalLen, true);
807
+ outDv.setUint32(12, paddedJsonLen, true);
808
+ outDv.setUint32(16, GLB_JSON_CHUNK, true);
809
+ outU8.set(nextJson, 20);
810
+ outU8.fill(32, 20 + nextJson.byteLength, 20 + paddedJsonLen);
811
+ if (hasBin) {
812
+ outDv.setUint32(20 + paddedJsonLen, paddedBinLen, true);
813
+ outDv.setUint32(24 + paddedJsonLen, binTag, true);
814
+ outU8.set(binData, 28 + paddedJsonLen);
815
+ }
816
+ return out;
817
+ }
818
+ // src/loader.ts
819
+ var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
820
+ var HEADLESS_TEXTURE_EXT_NAMES = [
821
+ "EXT_texture_webp",
822
+ "EXT_texture_avif",
823
+ "KHR_texture_basisu"
824
+ ];
825
+ var _nodePos = new THREE.Vector3();
826
+ var _nodeQuat = new THREE.Quaternion();
827
+ function isHeadlessTextureEnv() {
828
+ return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
829
+ }
830
+ function stubTextureInParser(parser, textureIndex) {
831
+ const tex = new THREE.Texture();
832
+ tex.flipY = false;
833
+ parser.associations.set(tex, { textures: textureIndex });
834
+ return Promise.resolve(tex);
693
835
  }
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
- };
836
+ function patchHeadlessTexturePlugins(parser) {
837
+ const plugins = parser.plugins;
838
+ if (!plugins) return;
839
+ for (const extName of HEADLESS_TEXTURE_EXT_NAMES) {
840
+ const existing = plugins[extName];
841
+ if (!existing) continue;
842
+ existing.loadTexture = (textureIndex) => {
843
+ if (!(parser.json?.textures?.[textureIndex])?.extensions?.[extName]) return null;
844
+ return stubTextureInParser(parser, textureIndex);
845
+ };
846
+ }
709
847
  }
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
- };
848
+ function reqArr(val, label) {
849
+ if (val === void 0) return [];
850
+ if (!Array.isArray(val)) throw new KhrValidationError(`${label} must be an array`);
851
+ return val;
717
852
  }
718
853
  var templateMetaMap = /* @__PURE__ */ new WeakMap();
719
854
  function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
@@ -723,12 +858,13 @@ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isS
723
858
  const rawBody = meta.bodies[i];
724
859
  const dstBody = clonedBundle.bodies[i];
725
860
  if (!rawBody || !dstBody) continue;
726
- const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
861
+ const role = extractRole(rawBody.nodeName, rawBody.extras) ?? extractDefaultBodyRole(rawBody.extras);
727
862
  dstBody.role = role;
728
863
  if (dstBody.joint) dstBody.joint.role = role;
729
864
  }
730
865
  if (isSocketNode) {
731
866
  const sockets = Object.create(null);
867
+ for (const [k, v] of Object.entries(templateBundle.sockets)) sockets[k] = [...v];
732
868
  for (const node of meta.nodes) {
733
869
  const custom = isSocketNode(node.nodeName, node.extras);
734
870
  if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
@@ -741,45 +877,6 @@ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isS
741
877
  clonedBundle.sockets = sockets;
742
878
  }
743
879
  }
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
880
  function buildNodeGraphLookup(gltf, rawNodes, rawGltf) {
784
881
  const parentIdx = new Int32Array(rawNodes.length).fill(-1);
785
882
  for (let i = 0; i < rawNodes.length; i++) {
@@ -918,18 +1015,18 @@ function extractKhrBundleFromGltf(gltf, options) {
918
1015
  const { parentIdx, nodeNames, resolveObj } = buildNodeGraphLookup(gltf, rawNodes, json);
919
1016
  const nodeMetas = [];
920
1017
  const sockets = Object.create(null);
1018
+ const emitters = [];
921
1019
  for (let i = 0; i < rawNodes.length; i++) {
922
1020
  const obj = resolveObj(i);
923
1021
  if (!obj) continue;
924
1022
  const rawExt = rawNodes[i].extensions;
925
1023
  if (rawExt !== void 0 && !isObj(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
926
1024
  const extras = isObj(rawNodes[i].extras) ? rawNodes[i].extras : {};
927
- nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, options?.isSocketNode));
1025
+ nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, emitters, gltf.scene, rawExt, options?.isSocketNode));
928
1026
  }
929
1027
  const bodies = [];
930
1028
  const bodyMetas = [];
931
1029
  const bodyByIdx = /* @__PURE__ */ new Map();
932
- const explicitInertiaSet = /* @__PURE__ */ new Set();
933
1030
  const wheels = [];
934
1031
  const propellers = [];
935
1032
  for (let i = 0; i < rawNodes.length; i++) {
@@ -964,9 +1061,8 @@ function extractKhrBundleFromGltf(gltf, options) {
964
1061
  continue;
965
1062
  }
966
1063
  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);
1064
+ const motion = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
1065
+ const role = options?.extractRole?.(name, extras) ?? extractDefaultBodyRole(extras);
970
1066
  let joint = null;
971
1067
  if (phys.joint !== void 0) {
972
1068
  if (!isObj(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
@@ -981,22 +1077,22 @@ function extractKhrBundleFromGltf(gltf, options) {
981
1077
  if (isInsideRotor(rawJ.connectedNode, parentIdx, rawNodes) || isInsideRotor(cIdx, parentIdx, rawNodes)) throw new KhrValidationError(`Joint on "${name}" cannot target detached rotor "${cName}"`);
982
1078
  joint = decodeJoint(joints, rawJ.joint, name, cObj, obj, Boolean(rawJ.enableCollision), role, cName);
983
1079
  }
984
- const wp = obj.getWorldPosition(new THREE.Vector3());
985
- const wq = obj.getWorldQuaternion(new THREE.Quaternion());
1080
+ obj.getWorldPosition(_nodePos);
1081
+ obj.getWorldQuaternion(_nodeQuat);
986
1082
  const breakaway = decodeBreakawaySpec(extras.breakaway);
987
1083
  const spec = {
988
1084
  nodeName: name,
989
1085
  ...motion,
990
1086
  localPosition: [
991
- wp.x,
992
- wp.y,
993
- wp.z
1087
+ _nodePos.x,
1088
+ _nodePos.y,
1089
+ _nodePos.z
994
1090
  ],
995
1091
  localQuaternion: [
996
- wq.x,
997
- wq.y,
998
- wq.z,
999
- wq.w
1092
+ _nodeQuat.x,
1093
+ _nodeQuat.y,
1094
+ _nodeQuat.z,
1095
+ _nodeQuat.w
1000
1096
  ],
1001
1097
  colliders: [],
1002
1098
  joint,
@@ -1049,7 +1145,12 @@ function extractKhrBundleFromGltf(gltf, options) {
1049
1145
  ...colGroups === void 0 ? {} : { collisionGroups: colGroups }
1050
1146
  });
1051
1147
  }
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);
1148
+ for (const body of bodies) if (!body.isKinematic && !body.hasExplicitInertia) {
1149
+ const solved = resolveBodyMassFromColliders(body.colliders, body.mass, body.hasExplicitCom ? body.centerOfMass : null, body.hasExplicitInertiaOrientation ? body.inertiaOrientation : null, body.nodeName);
1150
+ body.centerOfMass = solved.centerOfMass;
1151
+ body.inertiaDiagonal = solved.inertiaDiagonal;
1152
+ body.inertiaOrientation = solved.inertiaOrientation;
1153
+ }
1053
1154
  const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
1054
1155
  const ikSockets = [];
1055
1156
  const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
@@ -1073,6 +1174,7 @@ function extractKhrBundleFromGltf(gltf, options) {
1073
1174
  bodies,
1074
1175
  wheels,
1075
1176
  propellers,
1177
+ emitters,
1076
1178
  sockets,
1077
1179
  totalDynamicMass,
1078
1180
  centerOfMass,
@@ -1422,12 +1524,13 @@ function internJson(table, map, item) {
1422
1524
  }
1423
1525
  async function exportKhrGlb(root, specs, sceneExtras) {
1424
1526
  ensureHeadlessFileReader();
1425
- root.updateMatrixWorld(true);
1527
+ const exportRoot = snapshotSceneWithMountedSubtrees(root);
1528
+ exportRoot.updateMatrixWorld(true);
1426
1529
  const exporter = new GLTFExporter();
1427
- const swaps = isolateUnloadedTextures(root);
1530
+ const swaps = isolateUnloadedTextures(exportRoot);
1428
1531
  let rawBuf;
1429
1532
  try {
1430
- const res = await exporter.parseAsync(root, { binary: true });
1533
+ const res = await exporter.parseAsync(exportRoot, { binary: true });
1431
1534
  rawBuf = res instanceof ArrayBuffer ? res : packJsonToGlb(res);
1432
1535
  } finally {
1433
1536
  for (const s of swaps) {
@@ -1559,6 +1662,746 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1559
1662
  if (used.size > 0) gltf.extensionsUsed = [...used];
1560
1663
  });
1561
1664
  }
1665
+ // src/heightfield.tsx
1666
+ /** `RAPIER.HeightFieldFlags.FIX_INTERNAL_EDGES` (1) — eliminates internal grid-edge ghost contact normals. */
1667
+ var KHR_HEIGHTFIELD_FLAGS = 1;
1668
+ /**
1669
+ * Transposes a row-major `(nrows + 1) * (ncols + 1)` height grid (`heights[zRow * (ncols + 1) + xCol]`,
1670
+ * as returned by `@khr3/roads` `sampleHeightfield` and Three.js `PlaneGeometry`) into Rapier WASM's
1671
+ * column-major layout (`out[xCol * (nrows + 1) + zRow]`).
1672
+ */
1673
+ function transposeHeightfieldForRapier(rowMajor, nrows, ncols = nrows, out) {
1674
+ if (!Number.isInteger(nrows) || nrows < 1 || !Number.isInteger(ncols) || ncols < 1) throw new KhrValidationError(`transposeHeightfieldForRapier: nrows (${nrows}) and ncols (${ncols}) must be integers >= 1`);
1675
+ const strideX = ncols + 1;
1676
+ const strideZ = nrows + 1;
1677
+ const expected = strideZ * strideX;
1678
+ if (rowMajor.length !== expected) throw new KhrValidationError(`transposeHeightfieldForRapier: expected (${nrows} + 1) * (${ncols} + 1) = ${expected} samples, got ${rowMajor.length}`);
1679
+ const dst = out && out.length === expected ? out : new Float32Array(expected);
1680
+ for (let zRow = 0; zRow <= nrows; zRow++) {
1681
+ const rowBase = zRow * strideX;
1682
+ for (let xCol = 0; xCol <= ncols; xCol++) dst[xCol * strideZ + zRow] = rowMajor[rowBase + xCol];
1683
+ }
1684
+ return dst;
1685
+ }
1686
+ /**
1687
+ * Samples `heightFn(x, z)` directly in Rapier WASM's column-major `(nrows + 1) * (ncols + 1)` layout
1688
+ * over `[originX, originX + sizeX] x [originZ, originZ + sizeZ]`.
1689
+ */
1690
+ function sampleRapierHeightfield(heightFn, originX, originZ, sizeX, sizeZ, nrows, ncols = nrows, out) {
1691
+ if (!Number.isInteger(nrows) || nrows < 1 || !Number.isInteger(ncols) || ncols < 1) throw new KhrValidationError(`sampleRapierHeightfield: nrows (${nrows}) and ncols (${ncols}) must be integers >= 1`);
1692
+ if (!(sizeX > 0 && sizeZ > 0 && Number.isFinite(sizeX) && Number.isFinite(sizeZ))) throw new KhrValidationError(`sampleRapierHeightfield: sizeX (${sizeX}) and sizeZ (${sizeZ}) must be finite > 0`);
1693
+ const strideZ = nrows + 1;
1694
+ const total = strideZ * (ncols + 1);
1695
+ const dst = out && out.length === total ? out : new Float32Array(total);
1696
+ for (let xCol = 0; xCol <= ncols; xCol++) {
1697
+ const x = originX + xCol / ncols * sizeX;
1698
+ const colBase = xCol * strideZ;
1699
+ for (let zRow = 0; zRow <= nrows; zRow++) {
1700
+ const z = originZ + zRow / nrows * sizeZ;
1701
+ dst[colBase + zRow] = heightFn(x, z);
1702
+ }
1703
+ }
1704
+ return dst;
1705
+ }
1706
+ /**
1707
+ * Builds an indexed Three.js `BufferGeometry` centered at `(0, 0, 0)` spanning
1708
+ * `[-sizeX/2, +sizeX/2] x [-sizeZ/2, +sizeZ/2]` whose vertex positions, cell triangulation,
1709
+ * and finite-difference normals match Rapier's `HeightField` collider 1:1.
1710
+ */
1711
+ function createHeightfieldGeometry(heights, sizeX, sizeZ, nrows, ncols = nrows, layout = "rapier-column-major") {
1712
+ const strideZ = nrows + 1;
1713
+ const strideX = ncols + 1;
1714
+ const expected = strideZ * strideX;
1715
+ if (heights.length !== expected) throw new KhrValidationError(`createHeightfieldGeometry: expected ${expected} height samples for ${nrows}x${ncols} cells, got ${heights.length}`);
1716
+ const readH = layout === "rapier-column-major" ? (zRow, xCol) => heights[xCol * strideZ + zRow] : (zRow, xCol) => heights[zRow * strideX + xCol];
1717
+ const positions = new Float32Array(expected * 3);
1718
+ const normals = new Float32Array(expected * 3);
1719
+ const uvs = new Float32Array(expected * 2);
1720
+ const dx = sizeX / ncols;
1721
+ const dz = sizeZ / nrows;
1722
+ const halfX = sizeX * .5;
1723
+ const halfZ = sizeZ * .5;
1724
+ let vIdx = 0;
1725
+ for (let zRow = 0; zRow <= nrows; zRow++) {
1726
+ const z = -halfZ + zRow * dz;
1727
+ const v = zRow / nrows;
1728
+ for (let xCol = 0; xCol <= ncols; xCol++) {
1729
+ const x = -halfX + xCol * dx;
1730
+ const y = readH(zRow, xCol);
1731
+ positions[vIdx * 3] = x;
1732
+ positions[vIdx * 3 + 1] = y;
1733
+ positions[vIdx * 3 + 2] = z;
1734
+ const hL = readH(zRow, Math.max(0, xCol - 1));
1735
+ const hR = readH(zRow, Math.min(ncols, xCol + 1));
1736
+ const hD = readH(Math.max(0, zRow - 1), xCol);
1737
+ const hU = readH(Math.min(nrows, zRow + 1), xCol);
1738
+ const spanX = (Math.min(ncols, xCol + 1) - Math.max(0, xCol - 1)) * dx;
1739
+ const spanZ = (Math.min(nrows, zRow + 1) - Math.max(0, zRow - 1)) * dz;
1740
+ const dhdx = spanX > 0 ? (hR - hL) / spanX : 0;
1741
+ const dhdz = spanZ > 0 ? (hU - hD) / spanZ : 0;
1742
+ const invLen = 1 / Math.hypot(dhdx, 1, dhdz);
1743
+ normals[vIdx * 3] = -dhdx * invLen;
1744
+ normals[vIdx * 3 + 1] = invLen;
1745
+ normals[vIdx * 3 + 2] = -dhdz * invLen;
1746
+ uvs[vIdx * 2] = xCol / ncols;
1747
+ uvs[vIdx * 2 + 1] = v;
1748
+ vIdx++;
1749
+ }
1750
+ }
1751
+ const triIndices = new Uint32Array(nrows * ncols * 6);
1752
+ let iPtr = 0;
1753
+ for (let zRow = 0; zRow < nrows; zRow++) for (let xCol = 0; xCol < ncols; xCol++) {
1754
+ const i00 = zRow * strideX + xCol;
1755
+ const i10 = i00 + 1;
1756
+ const i01 = i00 + strideX;
1757
+ const i11 = i01 + 1;
1758
+ triIndices[iPtr++] = i00;
1759
+ triIndices[iPtr++] = i01;
1760
+ triIndices[iPtr++] = i10;
1761
+ triIndices[iPtr++] = i10;
1762
+ triIndices[iPtr++] = i01;
1763
+ triIndices[iPtr++] = i11;
1764
+ }
1765
+ const geo = new THREE.BufferGeometry();
1766
+ geo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
1767
+ geo.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
1768
+ geo.setAttribute("uv", new THREE.BufferAttribute(uvs, 2));
1769
+ geo.setIndex(new THREE.BufferAttribute(triIndices, 1));
1770
+ geo.computeBoundingSphere();
1771
+ return geo;
1772
+ }
1773
+ /**
1774
+ * Direct Rapier WASM heightfield body & collider (`HeightFieldFlags.FIX_INTERNAL_EDGES`),
1775
+ * bypassing `@react-three/rapier`'s broken `<HeightfieldCollider>` `scaleColliderArgs` mutation.
1776
+ */
1777
+ function KhrHeightfield({ ref, colliderRef, heights, segments, size, layout = "rapier-column-major", friction = .85, restitution = .05, collisionGroups, solverGroups, version = 0, children, ...rbProps }) {
1778
+ const { rapier, world } = useRapier();
1779
+ const rbRef = useRef(null);
1780
+ const nrows = typeof segments === "number" ? segments : segments[0];
1781
+ const ncols = typeof segments === "number" ? segments : segments[1];
1782
+ const [sizeX, sizeZ] = size;
1783
+ const assignRb = (rb) => {
1784
+ rbRef.current = rb;
1785
+ assignRef(ref, rb);
1786
+ };
1787
+ useEffect(() => {
1788
+ const rb = rbRef.current;
1789
+ if (!rb || !world.getRigidBody(rb.handle)) return;
1790
+ const colHeights = layout === "row-major" ? transposeHeightfieldForRapier(heights, nrows, ncols) : heights;
1791
+ const expected = (nrows + 1) * (ncols + 1);
1792
+ if (colHeights.length !== expected) throw new KhrValidationError(`KhrHeightfield: expected ${expected} samples for ${nrows}x${ncols} cells, got ${colHeights.length}`);
1793
+ const desc = rapier.ColliderDesc.heightfield(nrows, ncols, colHeights, {
1794
+ x: sizeX,
1795
+ y: 1,
1796
+ z: sizeZ
1797
+ }, 1);
1798
+ desc.setFriction(friction);
1799
+ desc.setRestitution(restitution);
1800
+ if (collisionGroups !== void 0) desc.setCollisionGroups(collisionGroups);
1801
+ if (solverGroups !== void 0 || collisionGroups !== void 0) desc.setSolverGroups(solverGroups ?? collisionGroups);
1802
+ const col = world.createCollider(desc, rb);
1803
+ assignRef(colliderRef, col);
1804
+ return () => {
1805
+ assignRef(colliderRef, null);
1806
+ if (world.getCollider(col.handle)) world.removeCollider(col, false);
1807
+ };
1808
+ }, [
1809
+ rapier,
1810
+ world,
1811
+ heights,
1812
+ nrows,
1813
+ ncols,
1814
+ sizeX,
1815
+ sizeZ,
1816
+ layout,
1817
+ friction,
1818
+ restitution,
1819
+ collisionGroups,
1820
+ solverGroups,
1821
+ version,
1822
+ colliderRef
1823
+ ]);
1824
+ return /* @__PURE__ */ jsx(RigidBody, {
1825
+ ...rbProps,
1826
+ ref: assignRb,
1827
+ type: "fixed",
1828
+ colliders: false,
1829
+ children
1830
+ });
1831
+ }
1832
+ // src/KhrAssembly.tsx
1833
+ function matrixToRoot(node, sceneRoot) {
1834
+ const out = new THREE.Matrix4();
1835
+ for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
1836
+ if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
1837
+ cur.updateMatrix();
1838
+ out.premultiply(cur.matrix);
1839
+ }
1840
+ return out;
1841
+ }
1842
+ function isSceneDescendant(node, ancestor) {
1843
+ for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
1844
+ return false;
1845
+ }
1846
+ function lowestCommonAncestor(nodes, sceneRoot) {
1847
+ let candidate = nodes[0];
1848
+ while (candidate && candidate !== sceneRoot) {
1849
+ if (nodes.every((n) => isSceneDescendant(n, candidate))) return candidate;
1850
+ candidate = candidate.parent ?? sceneRoot;
1851
+ }
1852
+ return sceneRoot;
1853
+ }
1854
+ function planOwnColliders(body, frameQuat) {
1855
+ const one = new THREE.Vector3(1, 1, 1);
1856
+ const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
1857
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
1858
+ return body.colliders.map((spec) => {
1859
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
1860
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
1861
+ if (frameMat) local.premultiply(frameMat);
1862
+ local.decompose(pos, quat, scl);
1863
+ quat.normalize();
1864
+ return {
1865
+ spec,
1866
+ position: [
1867
+ pos.x,
1868
+ pos.y,
1869
+ pos.z
1870
+ ],
1871
+ quaternion: [
1872
+ quat.x,
1873
+ quat.y,
1874
+ quat.z,
1875
+ quat.w
1876
+ ]
1877
+ };
1878
+ });
1879
+ }
1880
+ function planAssembly(bundle) {
1881
+ const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
1882
+ const rootMemo = /* @__PURE__ */ new Map();
1883
+ const depthMemo = /* @__PURE__ */ new Map();
1884
+ const resolveRootAndDepth = (b, visiting = /* @__PURE__ */ new Set()) => {
1885
+ const cachedRoot = rootMemo.get(b.nodeName);
1886
+ const cachedDepth = depthMemo.get(b.nodeName);
1887
+ if (cachedRoot && cachedDepth !== void 0) return {
1888
+ root: cachedRoot,
1889
+ depth: cachedDepth
1890
+ };
1891
+ if (!b.joint) {
1892
+ rootMemo.set(b.nodeName, b);
1893
+ depthMemo.set(b.nodeName, 0);
1894
+ return {
1895
+ root: b,
1896
+ depth: 0
1897
+ };
1898
+ }
1899
+ if (visiting.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
1900
+ visiting.add(b.nodeName);
1901
+ const parent = byName.get(b.joint.connectedNodeName);
1902
+ if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
1903
+ const up = resolveRootAndDepth(parent, visiting);
1904
+ rootMemo.set(b.nodeName, up.root);
1905
+ depthMemo.set(b.nodeName, up.depth + 1);
1906
+ return {
1907
+ root: up.root,
1908
+ depth: up.depth + 1
1909
+ };
1910
+ };
1911
+ for (const b of bundle.bodies) resolveRootAndDepth(b);
1912
+ const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
1913
+ const invRoot = bodyPoseMatrix(root).clone().invert();
1914
+ const descendants = bundle.bodies.filter((b) => b.joint && rootMemo.get(b.nodeName) === root).sort((a, b) => (depthMemo.get(a.nodeName) ?? 0) - (depthMemo.get(b.nodeName) ?? 0));
1915
+ const partByName = /* @__PURE__ */ new Map();
1916
+ const parts = descendants.map((b) => {
1917
+ const joint = b.joint;
1918
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
1919
+ if (parent && !isSceneDescendant(b.object, parent.spec.object)) throw new KhrValidationError(`Jointed node "${b.nodeName}" must be a scene-graph descendant of its jointed parent "${joint.connectedNodeName}"`);
1920
+ const parentSpec = parent ? parent.spec : root;
1921
+ const relParentMat = bodyPoseMatrix(parentSpec).clone().invert().multiply(bodyPoseMatrix(b));
1922
+ const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
1923
+ const rpPos = new THREE.Vector3(), tmpQ = new THREE.Quaternion(), rpScl = new THREE.Vector3();
1924
+ relParentMat.decompose(rpPos, tmpQ, rpScl);
1925
+ const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
1926
+ relRootMat.decompose(rrPos, rrQuat, rpScl);
1927
+ rrQuat.normalize();
1928
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
1929
+ const axParentVec = axChildVec.clone().applyQuaternion(rrQuat).normalize();
1930
+ const anchorParent = parent ? [
1931
+ rrPos.x - parent.restRelRootPos[0],
1932
+ rrPos.y - parent.restRelRootPos[1],
1933
+ rrPos.z - parent.restRelRootPos[2]
1934
+ ] : [
1935
+ rpPos.x,
1936
+ rpPos.y,
1937
+ rpPos.z
1938
+ ];
1939
+ const rrQuatTuple = [
1940
+ rrQuat.x,
1941
+ rrQuat.y,
1942
+ rrQuat.z,
1943
+ rrQuat.w
1944
+ ];
1945
+ const invPartFrame = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion().fromArray(root.localQuaternion), new THREE.Vector3(1, 1, 1)).invert();
1946
+ const lumpedMass = computeLumpedMassProps([b], invPartFrame);
1947
+ const colliders = planOwnColliders(b, rrQuat);
1948
+ const plan = {
1949
+ spec: b,
1950
+ joint,
1951
+ parent,
1952
+ restRelParentPos: anchorParent,
1953
+ restRelParentQuat: rrQuatTuple,
1954
+ restRelRootPos: [
1955
+ rrPos.x,
1956
+ rrPos.y,
1957
+ rrPos.z
1958
+ ],
1959
+ restRelRootQuat: rrQuatTuple,
1960
+ axisParent: [
1961
+ axParentVec.x,
1962
+ axParentVec.y,
1963
+ axParentVec.z
1964
+ ],
1965
+ axisChild: [
1966
+ axChildVec.x,
1967
+ axChildVec.y,
1968
+ axChildVec.z
1969
+ ],
1970
+ lumpedMass,
1971
+ colliders
1972
+ };
1973
+ partByName.set(b.nodeName, plan);
1974
+ return plan;
1975
+ });
1976
+ const lumpedMass = computeLumpedMassProps([root], invRoot);
1977
+ const colliders = planOwnColliders(root);
1978
+ const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
1979
+ const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
1980
+ const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
1981
+ invRoot.decompose(scenePos, sceneQuat, sceneScl);
1982
+ sceneQuat.normalize();
1983
+ const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
1984
+ mountInRoot.decompose(mountPos, mountQuat, sceneScl);
1985
+ mountQuat.normalize();
1986
+ return {
1987
+ spec: root,
1988
+ sceneInRootPos: [
1989
+ scenePos.x,
1990
+ scenePos.y,
1991
+ scenePos.z
1992
+ ],
1993
+ sceneInRootQuat: [
1994
+ sceneQuat.x,
1995
+ sceneQuat.y,
1996
+ sceneQuat.z,
1997
+ sceneQuat.w
1998
+ ],
1999
+ mountNode,
2000
+ mountPosition: [
2001
+ mountPos.x,
2002
+ mountPos.y,
2003
+ mountPos.z
2004
+ ],
2005
+ mountQuaternion: [
2006
+ mountQuat.x,
2007
+ mountQuat.y,
2008
+ mountQuat.z,
2009
+ mountQuat.w
2010
+ ],
2011
+ lumpedMass,
2012
+ colliders,
2013
+ parts
2014
+ };
2015
+ });
2016
+ for (const a of plans) for (const b of plans) if (a !== b && isSceneDescendant(b.mountNode, a.mountNode)) throw new KhrValidationError(`Root bodies "${a.spec.nodeName}" and "${b.spec.nodeName}" share scene subtree "${a.mountNode.name}"; split them into separate glTF branches`);
2017
+ return plans;
2018
+ }
2019
+ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBody, userData, origin, onBody, onJointReady }) {
2020
+ const { rapier, world } = useRapier();
2021
+ const registry = useContext(JointRegistryContext);
2022
+ const childRef = useRef(null);
2023
+ const rtRef = useRef(null);
2024
+ const [childBody, setChildBody] = React.useState(null);
2025
+ const worldPose = useMemo(() => {
2026
+ const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
2027
+ const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
2028
+ return {
2029
+ pos: [
2030
+ pos.x,
2031
+ pos.y,
2032
+ pos.z
2033
+ ],
2034
+ quat: [
2035
+ rq.x,
2036
+ rq.y,
2037
+ rq.z,
2038
+ rq.w
2039
+ ]
2040
+ };
2041
+ }, [
2042
+ part.restRelRootPos,
2043
+ rootPos,
2044
+ rootQuat
2045
+ ]);
2046
+ const assignChildRef = useCallback((rb) => {
2047
+ childRef.current = rb;
2048
+ setChildBody(rb);
2049
+ onBody(part.spec.nodeName, rb);
2050
+ }, [part.spec.nodeName, onBody]);
2051
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
2052
+ useEffect(() => {
2053
+ if (childBody && part.lumpedMass) applyRapierBodyMass(childBody, part.lumpedMass);
2054
+ }, [childBody, part.lumpedMass]);
2055
+ useEffect(() => {
2056
+ if (!parentBody || !childBody) return;
2057
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
2058
+ 0,
2059
+ 0,
2060
+ 0
2061
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
2062
+ const rt = buildJointRuntime({
2063
+ rapier,
2064
+ world,
2065
+ nodeName: part.spec.nodeName,
2066
+ role: part.joint.role,
2067
+ kind: part.joint.kind,
2068
+ object: part.spec.object,
2069
+ axisParent: part.axisParent,
2070
+ anchorParent: part.restRelParentPos,
2071
+ limits: part.joint.limits,
2072
+ drive: part.joint.drive,
2073
+ breakaway: part.spec.breakaway,
2074
+ rapierJoint: imp,
2075
+ parentBody,
2076
+ childBody
2077
+ });
2078
+ rtRef.current = rt;
2079
+ registry?.add(rt);
2080
+ onJointReady(rt.nodeName, part.spec.object, rt);
2081
+ return () => {
2082
+ rtRef.current = null;
2083
+ registry?.delete(rt);
2084
+ onJointReady(rt.nodeName, part.spec.object, null);
2085
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
2086
+ };
2087
+ }, [
2088
+ rapier,
2089
+ world,
2090
+ part,
2091
+ parentBody,
2092
+ childBody,
2093
+ registry,
2094
+ onJointReady
2095
+ ]);
2096
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
2097
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
2098
+ } : void 0, [part.spec.breakaway, world]);
2099
+ const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
2100
+ const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
2101
+ const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
2102
+ return /* @__PURE__ */ jsxs(RigidBody, {
2103
+ ref: assignChildRef,
2104
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
2105
+ position: worldPose.pos,
2106
+ quaternion: worldPose.quat,
2107
+ colliders: false,
2108
+ onContactForce: onForce,
2109
+ ...userData === void 0 ? {} : { userData },
2110
+ ...linVel ? { linearVelocity: linVel } : {},
2111
+ ...angVel ? { angularVelocity: angVel } : {},
2112
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
2113
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
2114
+ object: part.spec.object,
2115
+ position: [
2116
+ 0,
2117
+ 0,
2118
+ 0
2119
+ ],
2120
+ quaternion: part.restRelRootQuat,
2121
+ origin
2122
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
2123
+ c: col.spec,
2124
+ position: col.position,
2125
+ quaternion: col.quaternion
2126
+ }, `${part.spec.nodeName}:${cIdx}`))]
2127
+ });
2128
+ }
2129
+ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJointReady, children }) {
2130
+ const [rootBody, setRootBody] = React.useState(null);
2131
+ const [partBodies, setPartBodies] = React.useState(() => /* @__PURE__ */ new Map());
2132
+ const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object), bundleScene) : null, [plan.parts, bundleScene]);
2133
+ const rootSpec = plan.spec;
2134
+ const assignRootRef = useCallback((rb) => {
2135
+ setRootBody(rb);
2136
+ onBody(rootSpec.nodeName, rb);
2137
+ }, [rootSpec.nodeName, onBody]);
2138
+ useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
2139
+ useEffect(() => {
2140
+ if (rootBody && plan.lumpedMass) applyRapierBodyMass(rootBody, plan.lumpedMass);
2141
+ }, [rootBody, plan.lumpedMass]);
2142
+ const handlePartBody = useCallback((nodeName, rb) => {
2143
+ setPartBodies((prev) => {
2144
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
2145
+ const next = new Map(prev);
2146
+ if (rb) next.set(nodeName, rb);
2147
+ else next.delete(nodeName);
2148
+ return next;
2149
+ });
2150
+ onBody(nodeName, rb);
2151
+ }, [onBody]);
2152
+ const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
2153
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
2154
+ ...rigidBodyProps,
2155
+ ref: assignRootRef,
2156
+ type: bodyType,
2157
+ position,
2158
+ quaternion,
2159
+ colliders: false,
2160
+ ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
2161
+ ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
2162
+ ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
2163
+ children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
2164
+ c: col.spec,
2165
+ position: col.position,
2166
+ quaternion: col.quaternion
2167
+ }, `r${idx}`))]
2168
+ }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
2169
+ part,
2170
+ rootSpec,
2171
+ rootPos: position,
2172
+ rootQuat: quaternion,
2173
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
2174
+ userData: rigidBodyProps?.userData,
2175
+ origin: partOrigins?.get(part.spec.object),
2176
+ onBody: handlePartBody,
2177
+ onJointReady
2178
+ }, part.spec.nodeName))] });
2179
+ }
2180
+ function KhrAssembly({ ref, bundle, position = [
2181
+ 0,
2182
+ 0,
2183
+ 0
2184
+ ], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
2185
+ assertUnitScale(scale, "KhrAssembly");
2186
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
2187
+ const { world } = useRapier();
2188
+ const applyGravityField = useCustomGravity((s) => s.applyGravityField);
2189
+ const plans = useMemo(() => planAssembly(bundle), [bundle]);
2190
+ const isStaticMultiRootCompound = useMemo(() => fixedRoot && plans.length > 1 && plans.every((p) => p.spec.isKinematic && p.parts.length === 0), [fixedRoot, plans]);
2191
+ const compoundColliders = useMemo(() => {
2192
+ if (!isStaticMultiRootCompound) return null;
2193
+ const one = new THREE.Vector3(1, 1, 1);
2194
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
2195
+ const out = [];
2196
+ for (const p of plans) {
2197
+ const bMat = bodyPoseMatrix(p.spec);
2198
+ for (let idx = 0; idx < p.spec.colliders.length; idx++) {
2199
+ const c = p.spec.colliders[idx];
2200
+ const cMat = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(c.localPosition), new THREE.Quaternion().fromArray(c.localQuaternion), one);
2201
+ bMat.clone().multiply(cMat).decompose(pos, quat, scl);
2202
+ quat.normalize();
2203
+ out.push({
2204
+ key: `${p.spec.nodeName}:${idx}`,
2205
+ spec: c,
2206
+ position: [
2207
+ pos.x,
2208
+ pos.y,
2209
+ pos.z
2210
+ ],
2211
+ quaternion: [
2212
+ quat.x,
2213
+ quat.y,
2214
+ quat.z,
2215
+ quat.w
2216
+ ]
2217
+ });
2218
+ }
2219
+ }
2220
+ return out;
2221
+ }, [isStaticMultiRootCompound, plans]);
2222
+ const origins = useMemo(() => !isStaticMultiRootCompound && plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [
2223
+ isStaticMultiRootCompound,
2224
+ plans,
2225
+ bundle.scene
2226
+ ]);
2227
+ const [px, py, pz] = position;
2228
+ const [rx, ry, rz] = rotation ?? [
2229
+ 0,
2230
+ 0,
2231
+ 0
2232
+ ];
2233
+ const hasQuat = quaternion !== void 0;
2234
+ const qx = quaternion?.[0] ?? 0;
2235
+ const qy = quaternion?.[1] ?? 0;
2236
+ const qz = quaternion?.[2] ?? 0;
2237
+ const qw = quaternion?.[3] ?? 1;
2238
+ const spawnQuat = useMemo(() => hasQuat ? new THREE.Quaternion(qx, qy, qz, qw).normalize() : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
2239
+ hasQuat,
2240
+ qx,
2241
+ qy,
2242
+ qz,
2243
+ qw,
2244
+ rx,
2245
+ ry,
2246
+ rz
2247
+ ]);
2248
+ const rootPoses = useMemo(() => plans.map((p) => {
2249
+ const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
2250
+ const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
2251
+ return {
2252
+ position: [
2253
+ pos.x,
2254
+ pos.y,
2255
+ pos.z
2256
+ ],
2257
+ quaternion: [
2258
+ quat.x,
2259
+ quat.y,
2260
+ quat.z,
2261
+ quat.w
2262
+ ]
2263
+ };
2264
+ }), [
2265
+ plans,
2266
+ spawnQuat,
2267
+ px,
2268
+ py,
2269
+ pz
2270
+ ]);
2271
+ const bodiesRef = useRef(/* @__PURE__ */ new Map());
2272
+ const jointsRef = useRef(/* @__PURE__ */ new Map());
2273
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
2274
+ const handleBody = useCallback((nodeName, rb) => {
2275
+ if (rb) bodiesRef.current.set(nodeName, rb);
2276
+ else bodiesRef.current.delete(nodeName);
2277
+ }, []);
2278
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
2279
+ if (rt) {
2280
+ jointsRef.current.set(nodeName, rt);
2281
+ byObjectRef.current.set(obj, rt);
2282
+ } else {
2283
+ jointsRef.current.delete(nodeName);
2284
+ byObjectRef.current.delete(obj);
2285
+ }
2286
+ }, []);
2287
+ useFrame(() => {
2288
+ if (!enableCustomGravity || world.timestep <= 0) return;
2289
+ for (const rb of bodiesRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
2290
+ });
2291
+ useImperativeHandle(ref, () => ({
2292
+ get jointNames() {
2293
+ return [...jointsRef.current.keys()];
2294
+ },
2295
+ getBody: (nodeName) => bodiesRef.current.get(nodeName) ?? null,
2296
+ getJointRuntime: (nodeName) => jointsRef.current.get(nodeName) ?? null,
2297
+ setJointTarget: (nodeName, target) => {
2298
+ jointsRef.current.get(nodeName)?.applyTarget(target);
2299
+ },
2300
+ setRoleTarget: (role, target) => {
2301
+ for (const rt of jointsRef.current.values()) if (rt.role === role) rt.applyTarget(target);
2302
+ },
2303
+ toggleHitObject: (hit) => {
2304
+ for (let cur = hit; cur; cur = cur.parent) {
2305
+ const rt = byObjectRef.current.get(cur);
2306
+ if (rt && toggleDrivenJoint(rt)) return true;
2307
+ }
2308
+ return false;
2309
+ }
2310
+ }), []);
2311
+ const assignCompoundRef = useCallback((rb) => {
2312
+ for (const p of plans) if (rb) bodiesRef.current.set(p.spec.nodeName, rb);
2313
+ else bodiesRef.current.delete(p.spec.nodeName);
2314
+ }, [plans]);
2315
+ useEffect(() => {
2316
+ if (!isStaticMultiRootCompound) return;
2317
+ return () => {
2318
+ for (const p of plans) bodiesRef.current.delete(p.spec.nodeName);
2319
+ };
2320
+ }, [isStaticMultiRootCompound, plans]);
2321
+ if (isStaticMultiRootCompound && compoundColliders) return /* @__PURE__ */ jsx("group", {
2322
+ ...groupProps,
2323
+ children: /* @__PURE__ */ jsxs(RigidBody, {
2324
+ ...rigidBodyProps,
2325
+ ref: assignCompoundRef,
2326
+ type: "fixed",
2327
+ position,
2328
+ quaternion: [
2329
+ spawnQuat.x,
2330
+ spawnQuat.y,
2331
+ spawnQuat.z,
2332
+ spawnQuat.w
2333
+ ],
2334
+ colliders: false,
2335
+ children: [
2336
+ /* @__PURE__ */ jsx(BundleSceneHost, {
2337
+ bundle,
2338
+ owner: "KhrAssembly"
2339
+ }),
2340
+ children,
2341
+ compoundColliders.map((col) => /* @__PURE__ */ jsx(KhrCollider, {
2342
+ c: col.spec,
2343
+ position: col.position,
2344
+ quaternion: col.quaternion
2345
+ }, col.key))
2346
+ ]
2347
+ })
2348
+ });
2349
+ if (plans.length === 1) {
2350
+ const plan = plans[0];
2351
+ return /* @__PURE__ */ jsx("group", {
2352
+ ...groupProps,
2353
+ children: /* @__PURE__ */ jsx(AssemblyRootBody, {
2354
+ plan,
2355
+ bundleScene: bundle.scene,
2356
+ position: rootPoses[0].position,
2357
+ quaternion: rootPoses[0].quaternion,
2358
+ fixedRoot,
2359
+ rigidBodyProps,
2360
+ onBody: handleBody,
2361
+ onJointReady: handleJointReady,
2362
+ children: /* @__PURE__ */ jsxs("group", {
2363
+ position: plan.sceneInRootPos,
2364
+ quaternion: plan.sceneInRootQuat,
2365
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
2366
+ bundle,
2367
+ owner: "KhrAssembly"
2368
+ }), children]
2369
+ })
2370
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
2371
+ });
2372
+ }
2373
+ return /* @__PURE__ */ jsxs("group", {
2374
+ ...groupProps,
2375
+ children: [/* @__PURE__ */ jsxs("group", {
2376
+ position,
2377
+ quaternion: [
2378
+ spawnQuat.x,
2379
+ spawnQuat.y,
2380
+ spawnQuat.z,
2381
+ spawnQuat.w
2382
+ ],
2383
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
2384
+ bundle,
2385
+ owner: "KhrAssembly"
2386
+ }), children]
2387
+ }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
2388
+ plan,
2389
+ bundleScene: bundle.scene,
2390
+ position: rootPoses[idx].position,
2391
+ quaternion: rootPoses[idx].quaternion,
2392
+ fixedRoot,
2393
+ rigidBodyProps,
2394
+ onBody: handleBody,
2395
+ onJointReady: handleJointReady,
2396
+ children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
2397
+ object: plan.mountNode,
2398
+ position: plan.mountPosition,
2399
+ quaternion: plan.mountQuaternion,
2400
+ origin: origins?.get(plan.mountNode)
2401
+ })
2402
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
2403
+ });
2404
+ }
1562
2405
  // src/useKhrGlb.ts
1563
2406
  var KhrGLTFLoader = class extends GLTFLoader {
1564
2407
  static khrLoaderScope = Symbol("KhrGLTFLoader");
@@ -1671,6 +2514,6 @@ function useKhrGlb(url, options) {
1671
2514
  }
1672
2515
  };
1673
2516
  })(useKhrGlb || (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 };
2517
+ export { ATTACHED_PANEL_INTERACTION_GROUPS, DETACHED_PANEL_INTERACTION_GROUPS, JointRegistryContext, KHR_HEIGHTFIELD_FLAGS, KHR_TRIMESH_FLAGS, KhrAssembly, KhrCollider, KhrGLTFLoader, KhrHeightfield, KhrValidationError, PhysicsWorld, applyRapierBodyMass, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, assignRef, buildJointRuntime, claimBundleMount, cloneKhrBundle, closedTargetForLimits, computeLumpedMassProps, computeShapeInertia, configureJointDrive, createHeightfieldGeometry, createKhrGltfPlugin, createRapierImpulseJoint, createScopedGltfLoaderClass, disposeKhrBundle, exportKhrGlb, isJointOpen, jacobiPrincipalInertia, loadKhrGlb, measureJointCoordinate, openTargetForLimits, patchGlbJsonChunk, planAssembly, releaseBundleMount, resolveBodyMassFromColliders, sampleRapierHeightfield, snapshotSceneWithMountedSubtrees, toggleDrivenJoint, transposeHeightfieldForRapier, useKhrGlb };
1675
2518
 
1676
2519
  //# sourceMappingURL=index.js.map