@khr3/core 0.2.11 → 0.2.12

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 isObj, C as applyRapierBodyMass, D as bodyPoseMatrix, E as assertUnitScale, F as JointRegistryContext, H as optFiniteNum, I as KhrValidationError, L as assignRef, M as readFiniteVec3, N as readUnitQuat, O as buildBodyMassTarget, P as COMBINE_MODES, R as isFiniteNum, S as snapshotSceneWithMountedSubtrees, T as assertSceneIdentityWorldScale, V 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 extractMeshColliderShape, k as computeAssemblyMassAndCom, 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 isNonNegNum } from "./joints-5IgWDD2w.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,7 +169,8 @@ 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
@@ -362,11 +197,12 @@ function decodeMotion(motion, hasMotion, name) {
362
197
  return {
363
198
  isKinematic,
364
199
  hasExplicitMotion: hasMotion,
200
+ hasExplicitCom,
201
+ hasExplicitInertia,
365
202
  mass,
366
203
  centerOfMass,
367
204
  inertiaDiagonal,
368
205
  inertiaOrientation,
369
- hasExplicitInertia,
370
206
  ...linearVelocity ? { linearVelocity } : {},
371
207
  ...angularVelocity ? { angularVelocity } : {},
372
208
  ...gravityFactor === void 0 ? {} : { gravityFactor }
@@ -507,7 +343,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
507
343
  jz / jLen
508
344
  ];
509
345
  }
510
- const anchor1Vec = childNode.getWorldPosition(new THREE.Vector3()).sub(connectedNode.getWorldPosition(new THREE.Vector3())).applyQuaternion(connectedNode.getWorldQuaternion(new THREE.Quaternion()).invert());
346
+ const anchor1Vec = childNode.getWorldPosition(_wpA).sub(connectedNode.getWorldPosition(_wpB)).applyQuaternion(connectedNode.getWorldQuaternion(_wqInv).invert());
511
347
  return {
512
348
  index: jointIdx,
513
349
  nodeName,
@@ -533,9 +369,6 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
533
369
  ]
534
370
  };
535
371
  }
536
- var _quat = new THREE.Quaternion();
537
- var _invParentQuat = new THREE.Quaternion();
538
- var _localOrigin = new THREE.Vector3(0, 0, 0);
539
372
  function getRelativeQuatArray(obj, parent) {
540
373
  obj.updateWorldMatrix(true, false);
541
374
  obj.getWorldQuaternion(_quat);
@@ -559,11 +392,11 @@ function getRelativeQuatArray(obj, parent) {
559
392
  * falling back to mesh AABB center only when an uncentered mesh was exported with its node left at `(0, 0, 0)`.
560
393
  */
561
394
  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
395
+ obj.getWorldPosition(_wpA);
396
+ if (_wpA.lengthSq() > 1e-8) return [
397
+ _wpA.x,
398
+ _wpA.y,
399
+ _wpA.z
567
400
  ];
568
401
  const invObj = obj.matrixWorld.clone().invert();
569
402
  const rel = new THREE.Matrix4();
@@ -578,11 +411,11 @@ function resolveRotorHubPosition(obj) {
578
411
  for (let i = 0; i < pos.count; i++) localBox.expandByPoint(v.fromBufferAttribute(pos, i).applyMatrix4(rel));
579
412
  });
580
413
  if (localBox.isEmpty() || localBox.containsPoint(_localOrigin)) return [
581
- wp.x,
582
- wp.y,
583
- wp.z
414
+ _wpA.x,
415
+ _wpA.y,
416
+ _wpA.z
584
417
  ];
585
- const c = new THREE.Box3().setFromObject(obj).getCenter(new THREE.Vector3());
418
+ const c = new THREE.Box3().setFromObject(obj).getCenter(_wpB);
586
419
  return [
587
420
  c.x,
588
421
  c.y,
@@ -715,41 +548,13 @@ function decodeBreakawaySpec(raw) {
715
548
  breakImpulseNs: raw.breakImpulseNs
716
549
  };
717
550
  }
718
- var templateMetaMap = /* @__PURE__ */ new WeakMap();
719
- function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
720
- const meta = templateMetaMap.get(templateBundle.scene);
721
- if (!meta) return;
722
- if (extractRole) for (let i = 0; i < clonedBundle.bodies.length; i++) {
723
- const rawBody = meta.bodies[i];
724
- const dstBody = clonedBundle.bodies[i];
725
- if (!rawBody || !dstBody) continue;
726
- const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
727
- dstBody.role = role;
728
- if (dstBody.joint) dstBody.joint.role = role;
729
- }
730
- if (isSocketNode) {
731
- const sockets = Object.create(null);
732
- for (const node of meta.nodes) {
733
- const custom = isSocketNode(node.nodeName, node.extras);
734
- if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
735
- const key = typeof custom === "string" && custom.length > 0 ? custom : typeof node.extras.socketId === "string" ? node.extras.socketId : node.nodeName;
736
- sockets[key] = [...node.worldPosition];
737
- }
738
- if (node.contactDots) for (const [role, pos] of node.contactDots) sockets[role] = [...pos];
739
- }
740
- for (const [key, pos] of meta.ikSockets) sockets[key] = [...pos];
741
- clonedBundle.sockets = sockets;
742
- }
743
- }
744
- var _dotVec = new THREE.Vector3();
745
- var _dotQuat = new THREE.Quaternion();
746
551
  function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
747
552
  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());
553
+ obj.getWorldPosition(_wpA);
749
554
  const worldPosition = [
750
- wp.x,
751
- wp.y,
752
- wp.z
555
+ _wpA.x,
556
+ _wpA.y,
557
+ _wpA.z
753
558
  ];
754
559
  const custom = isSocketNode?.(name, extras);
755
560
  if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
@@ -763,7 +568,7 @@ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
763
568
  contactDots = [];
764
569
  for (const dot of extras.contactDots) {
765
570
  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);
571
+ _dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_dotQuat).add(_wpA);
767
572
  const dotPos = [
768
573
  _dotVec.x,
769
574
  _dotVec.y,
@@ -780,6 +585,210 @@ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
780
585
  ...contactDots ? { contactDots } : {}
781
586
  };
782
587
  }
588
+ // src/glb.ts
589
+ /** ASCII "glTF" little-endian fourCC. */
590
+ var GLB_MAGIC = 0x46546c67;
591
+ /** ASCII "JSON" little-endian fourCC. */
592
+ var GLB_JSON_CHUNK = 0x4e4f534a;
593
+ /** ASCII "BIN\0" little-endian fourCC. */
594
+ var GLB_BIN_CHUNK = 5130562;
595
+ function validateGlbHeader(buffer, byteOffset = 0, byteLength = buffer.byteLength - byteOffset) {
596
+ if (byteLength < 20) throw new KhrValidationError("GLB buffer shorter than 20-byte header");
597
+ const view = new DataView(buffer, byteOffset, byteLength);
598
+ if (view.getUint32(0, true) !== 0x46546c67) throw new KhrValidationError("Invalid GLB magic");
599
+ if (view.getUint32(4, true) !== 2) throw new KhrValidationError("Unsupported glTF version");
600
+ const jsonLen = view.getUint32(12, true);
601
+ if (view.getUint32(16, true) !== 0x4e4f534a) throw new KhrValidationError("Missing GLB JSON chunk");
602
+ if (20 + jsonLen > byteLength) throw new KhrValidationError("Truncated GLB JSON chunk");
603
+ return jsonLen;
604
+ }
605
+ function bytesToBase64(bytes) {
606
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
607
+ const CHUNK = 32768;
608
+ const chunks = [];
609
+ for (let i = 0; i < bytes.length; i += CHUNK) chunks.push(String.fromCharCode(...bytes.subarray(i, i + CHUNK)));
610
+ return btoa(chunks.join(""));
611
+ }
612
+ function ensureHeadlessFileReader() {
613
+ if (globalThis.FileReader !== void 0) return;
614
+ class HeadlessFileReader extends EventTarget {
615
+ static EMPTY = 0;
616
+ static LOADING = 1;
617
+ static DONE = 2;
618
+ EMPTY = 0;
619
+ LOADING = 1;
620
+ DONE = 2;
621
+ readyState = 0;
622
+ result = null;
623
+ error = null;
624
+ onload = null;
625
+ onloadend = null;
626
+ onerror = null;
627
+ abort() {
628
+ this.readyState = 2;
629
+ }
630
+ readAsArrayBuffer(blob) {
631
+ this.readyState = 1;
632
+ blob.arrayBuffer().then((buf) => {
633
+ this.result = buf;
634
+ this.readyState = 2;
635
+ this.onload?.({ target: this });
636
+ this.dispatchEvent(new Event("load"));
637
+ this.onloadend?.({ target: this });
638
+ this.dispatchEvent(new Event("loadend"));
639
+ }, (err) => {
640
+ this.error = err;
641
+ this.readyState = 2;
642
+ this.onerror?.(err);
643
+ this.dispatchEvent(new Event("error"));
644
+ this.onloadend?.({ target: this });
645
+ this.dispatchEvent(new Event("loadend"));
646
+ });
647
+ }
648
+ readAsDataURL(blob) {
649
+ this.readyState = 1;
650
+ blob.arrayBuffer().then((buf) => {
651
+ const b64 = bytesToBase64(new Uint8Array(buf));
652
+ this.result = `data:${blob.type || "application/octet-stream"};base64,${b64}`;
653
+ this.readyState = 2;
654
+ this.onload?.({ target: this });
655
+ this.dispatchEvent(new Event("load"));
656
+ this.onloadend?.({ target: this });
657
+ this.dispatchEvent(new Event("loadend"));
658
+ }, (err) => {
659
+ this.error = err;
660
+ this.readyState = 2;
661
+ this.onerror?.(err);
662
+ this.dispatchEvent(new Event("error"));
663
+ this.onloadend?.({ target: this });
664
+ this.dispatchEvent(new Event("loadend"));
665
+ });
666
+ }
667
+ }
668
+ globalThis.FileReader = HeadlessFileReader;
669
+ }
670
+ function packJsonToGlb(gltf) {
671
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
672
+ const paddedJsonLen = jsonBytes.byteLength + 3 & -4;
673
+ const totalLen = 20 + paddedJsonLen;
674
+ const out = new ArrayBuffer(totalLen);
675
+ const dv = new DataView(out);
676
+ const u8 = new Uint8Array(out);
677
+ dv.setUint32(0, GLB_MAGIC, true);
678
+ dv.setUint32(4, 2, true);
679
+ dv.setUint32(8, totalLen, true);
680
+ dv.setUint32(12, paddedJsonLen, true);
681
+ dv.setUint32(16, GLB_JSON_CHUNK, true);
682
+ u8.set(jsonBytes, 20);
683
+ u8.fill(32, 20 + jsonBytes.byteLength, 20 + paddedJsonLen);
684
+ return out;
685
+ }
686
+ function patchGlbJsonChunk(source, mutator) {
687
+ const buf = source instanceof ArrayBuffer ? source : source.buffer;
688
+ const byteOffset = source instanceof ArrayBuffer ? 0 : source.byteOffset;
689
+ const byteLength = source.byteLength;
690
+ const jsonLen = validateGlbHeader(buf, byteOffset, byteLength);
691
+ const dv = new DataView(buf, byteOffset, byteLength);
692
+ let gltf;
693
+ try {
694
+ gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(buf, byteOffset + 20, jsonLen)));
695
+ } catch {
696
+ throw new KhrValidationError("Malformed GLB JSON chunk");
697
+ }
698
+ mutator(gltf);
699
+ const nextJson = new TextEncoder().encode(JSON.stringify(gltf));
700
+ const paddedJsonLen = nextJson.byteLength + 3 & -4;
701
+ const binHeaderOff = 20 + jsonLen;
702
+ const hasBin = binHeaderOff < byteLength;
703
+ let binTag = GLB_BIN_CHUNK;
704
+ let binData = /* @__PURE__ */ new Uint8Array(0);
705
+ if (hasBin) {
706
+ if (binHeaderOff + 8 > byteLength) throw new KhrValidationError("Truncated GLB binary chunk header");
707
+ const binLen = dv.getUint32(binHeaderOff, true);
708
+ binTag = dv.getUint32(binHeaderOff + 4, true);
709
+ if (binHeaderOff + 8 + binLen > byteLength) throw new KhrValidationError("Truncated GLB binary chunk payload");
710
+ binData = new Uint8Array(buf, byteOffset + binHeaderOff + 8, binLen);
711
+ }
712
+ const paddedBinLen = binData.byteLength + 3 & -4;
713
+ const totalLen = 20 + paddedJsonLen + (hasBin ? 8 + paddedBinLen : 0);
714
+ const out = new ArrayBuffer(totalLen);
715
+ const outDv = new DataView(out);
716
+ const outU8 = new Uint8Array(out);
717
+ outDv.setUint32(0, GLB_MAGIC, true);
718
+ outDv.setUint32(4, 2, true);
719
+ outDv.setUint32(8, totalLen, true);
720
+ outDv.setUint32(12, paddedJsonLen, true);
721
+ outDv.setUint32(16, GLB_JSON_CHUNK, true);
722
+ outU8.set(nextJson, 20);
723
+ outU8.fill(32, 20 + nextJson.byteLength, 20 + paddedJsonLen);
724
+ if (hasBin) {
725
+ outDv.setUint32(20 + paddedJsonLen, paddedBinLen, true);
726
+ outDv.setUint32(24 + paddedJsonLen, binTag, true);
727
+ outU8.set(binData, 28 + paddedJsonLen);
728
+ }
729
+ return out;
730
+ }
731
+ // src/loader.ts
732
+ var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
733
+ var HEADLESS_TEXTURE_EXT_NAMES = [
734
+ "EXT_texture_webp",
735
+ "EXT_texture_avif",
736
+ "KHR_texture_basisu"
737
+ ];
738
+ var _nodePos = new THREE.Vector3();
739
+ var _nodeQuat = new THREE.Quaternion();
740
+ function isHeadlessTextureEnv() {
741
+ return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
742
+ }
743
+ function stubTextureInParser(parser, textureIndex) {
744
+ const tex = new THREE.Texture();
745
+ tex.flipY = false;
746
+ parser.associations.set(tex, { textures: textureIndex });
747
+ return Promise.resolve(tex);
748
+ }
749
+ function patchHeadlessTexturePlugins(parser) {
750
+ const plugins = parser.plugins;
751
+ if (!plugins) return;
752
+ for (const extName of HEADLESS_TEXTURE_EXT_NAMES) {
753
+ const existing = plugins[extName];
754
+ if (!existing) continue;
755
+ existing.loadTexture = (textureIndex) => {
756
+ if (!(parser.json?.textures?.[textureIndex])?.extensions?.[extName]) return null;
757
+ return stubTextureInParser(parser, textureIndex);
758
+ };
759
+ }
760
+ }
761
+ function reqArr(val, label) {
762
+ if (val === void 0) return [];
763
+ if (!Array.isArray(val)) throw new KhrValidationError(`${label} must be an array`);
764
+ return val;
765
+ }
766
+ var templateMetaMap = /* @__PURE__ */ new WeakMap();
767
+ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isSocketNode) {
768
+ const meta = templateMetaMap.get(templateBundle.scene);
769
+ if (!meta) return;
770
+ if (extractRole) for (let i = 0; i < clonedBundle.bodies.length; i++) {
771
+ const rawBody = meta.bodies[i];
772
+ const dstBody = clonedBundle.bodies[i];
773
+ if (!rawBody || !dstBody) continue;
774
+ const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (typeof rawBody.extras.role === "string" ? rawBody.extras.role : null);
775
+ dstBody.role = role;
776
+ if (dstBody.joint) dstBody.joint.role = role;
777
+ }
778
+ if (isSocketNode) {
779
+ const sockets = Object.create(null);
780
+ for (const node of meta.nodes) {
781
+ const custom = isSocketNode(node.nodeName, node.extras);
782
+ if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
783
+ const key = typeof custom === "string" && custom.length > 0 ? custom : typeof node.extras.socketId === "string" ? node.extras.socketId : node.nodeName;
784
+ sockets[key] = [...node.worldPosition];
785
+ }
786
+ if (node.contactDots) for (const [role, pos] of node.contactDots) sockets[role] = [...pos];
787
+ }
788
+ for (const [key, pos] of meta.ikSockets) sockets[key] = [...pos];
789
+ clonedBundle.sockets = sockets;
790
+ }
791
+ }
783
792
  function buildNodeGraphLookup(gltf, rawNodes, rawGltf) {
784
793
  const parentIdx = new Int32Array(rawNodes.length).fill(-1);
785
794
  for (let i = 0; i < rawNodes.length; i++) {
@@ -929,7 +938,6 @@ function extractKhrBundleFromGltf(gltf, options) {
929
938
  const bodies = [];
930
939
  const bodyMetas = [];
931
940
  const bodyByIdx = /* @__PURE__ */ new Map();
932
- const explicitInertiaSet = /* @__PURE__ */ new Set();
933
941
  const wheels = [];
934
942
  const propellers = [];
935
943
  for (let i = 0; i < rawNodes.length; i++) {
@@ -964,8 +972,7 @@ function extractKhrBundleFromGltf(gltf, options) {
964
972
  continue;
965
973
  }
966
974
  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);
975
+ const motion = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
969
976
  const role = options?.extractRole?.(name, extras) ?? (typeof extras.role === "string" ? extras.role : null);
970
977
  let joint = null;
971
978
  if (phys.joint !== void 0) {
@@ -981,22 +988,22 @@ function extractKhrBundleFromGltf(gltf, options) {
981
988
  if (isInsideRotor(rawJ.connectedNode, parentIdx, rawNodes) || isInsideRotor(cIdx, parentIdx, rawNodes)) throw new KhrValidationError(`Joint on "${name}" cannot target detached rotor "${cName}"`);
982
989
  joint = decodeJoint(joints, rawJ.joint, name, cObj, obj, Boolean(rawJ.enableCollision), role, cName);
983
990
  }
984
- const wp = obj.getWorldPosition(new THREE.Vector3());
985
- const wq = obj.getWorldQuaternion(new THREE.Quaternion());
991
+ obj.getWorldPosition(_nodePos);
992
+ obj.getWorldQuaternion(_nodeQuat);
986
993
  const breakaway = decodeBreakawaySpec(extras.breakaway);
987
994
  const spec = {
988
995
  nodeName: name,
989
996
  ...motion,
990
997
  localPosition: [
991
- wp.x,
992
- wp.y,
993
- wp.z
998
+ _nodePos.x,
999
+ _nodePos.y,
1000
+ _nodePos.z
994
1001
  ],
995
1002
  localQuaternion: [
996
- wq.x,
997
- wq.y,
998
- wq.z,
999
- wq.w
1003
+ _nodeQuat.x,
1004
+ _nodeQuat.y,
1005
+ _nodeQuat.z,
1006
+ _nodeQuat.w
1000
1007
  ],
1001
1008
  colliders: [],
1002
1009
  joint,
@@ -1049,7 +1056,7 @@ function extractKhrBundleFromGltf(gltf, options) {
1049
1056
  ...colGroups === void 0 ? {} : { collisionGroups: colGroups }
1050
1057
  });
1051
1058
  }
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);
1059
+ for (const body of bodies) if (!body.isKinematic && !body.hasExplicitInertia && body.colliders.length === 0) throw new KhrValidationError(`Dynamic node "${body.nodeName}" is missing motion.inertiaDiagonal and has no colliders`);
1053
1060
  const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
1054
1061
  const ikSockets = [];
1055
1062
  const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
@@ -1422,12 +1429,13 @@ function internJson(table, map, item) {
1422
1429
  }
1423
1430
  async function exportKhrGlb(root, specs, sceneExtras) {
1424
1431
  ensureHeadlessFileReader();
1425
- root.updateMatrixWorld(true);
1432
+ const exportRoot = snapshotSceneWithMountedSubtrees(root);
1433
+ exportRoot.updateMatrixWorld(true);
1426
1434
  const exporter = new GLTFExporter();
1427
- const swaps = isolateUnloadedTextures(root);
1435
+ const swaps = isolateUnloadedTextures(exportRoot);
1428
1436
  let rawBuf;
1429
1437
  try {
1430
- const res = await exporter.parseAsync(root, { binary: true });
1438
+ const res = await exporter.parseAsync(exportRoot, { binary: true });
1431
1439
  rawBuf = res instanceof ArrayBuffer ? res : packJsonToGlb(res);
1432
1440
  } finally {
1433
1441
  for (const s of swaps) {
@@ -1559,6 +1567,508 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1559
1567
  if (used.size > 0) gltf.extensionsUsed = [...used];
1560
1568
  });
1561
1569
  }
1570
+ // src/KhrAssembly.tsx
1571
+ function matrixToRoot(node, sceneRoot) {
1572
+ const out = new THREE.Matrix4();
1573
+ for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
1574
+ if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
1575
+ cur.updateMatrix();
1576
+ out.premultiply(cur.matrix);
1577
+ }
1578
+ return out;
1579
+ }
1580
+ function isSceneDescendant(node, ancestor) {
1581
+ for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
1582
+ return false;
1583
+ }
1584
+ function lowestCommonAncestor(nodes, sceneRoot) {
1585
+ let candidate = nodes[0];
1586
+ while (candidate && candidate !== sceneRoot) {
1587
+ if (nodes.every((n) => isSceneDescendant(n, candidate))) return candidate;
1588
+ candidate = candidate.parent ?? sceneRoot;
1589
+ }
1590
+ return sceneRoot;
1591
+ }
1592
+ function planOwnColliders(body, massTarget, frameQuat) {
1593
+ const one = new THREE.Vector3(1, 1, 1);
1594
+ const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
1595
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
1596
+ const density = massTarget && !massTarget.hasExplicitInertia ? 1 : 0;
1597
+ return body.colliders.map((spec) => {
1598
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
1599
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
1600
+ if (frameMat) local.premultiply(frameMat);
1601
+ local.decompose(pos, quat, scl);
1602
+ quat.normalize();
1603
+ return {
1604
+ spec,
1605
+ position: [
1606
+ pos.x,
1607
+ pos.y,
1608
+ pos.z
1609
+ ],
1610
+ quaternion: [
1611
+ quat.x,
1612
+ quat.y,
1613
+ quat.z,
1614
+ quat.w
1615
+ ],
1616
+ density
1617
+ };
1618
+ });
1619
+ }
1620
+ function planAssembly(bundle) {
1621
+ const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
1622
+ const rootMemo = /* @__PURE__ */ new Map();
1623
+ const depthMemo = /* @__PURE__ */ new Map();
1624
+ const resolveRootAndDepth = (b, visiting = /* @__PURE__ */ new Set()) => {
1625
+ const cachedRoot = rootMemo.get(b.nodeName);
1626
+ const cachedDepth = depthMemo.get(b.nodeName);
1627
+ if (cachedRoot && cachedDepth !== void 0) return {
1628
+ root: cachedRoot,
1629
+ depth: cachedDepth
1630
+ };
1631
+ if (!b.joint) {
1632
+ rootMemo.set(b.nodeName, b);
1633
+ depthMemo.set(b.nodeName, 0);
1634
+ return {
1635
+ root: b,
1636
+ depth: 0
1637
+ };
1638
+ }
1639
+ if (visiting.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
1640
+ visiting.add(b.nodeName);
1641
+ const parent = byName.get(b.joint.connectedNodeName);
1642
+ if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
1643
+ const up = resolveRootAndDepth(parent, visiting);
1644
+ rootMemo.set(b.nodeName, up.root);
1645
+ depthMemo.set(b.nodeName, up.depth + 1);
1646
+ return {
1647
+ root: up.root,
1648
+ depth: up.depth + 1
1649
+ };
1650
+ };
1651
+ for (const b of bundle.bodies) resolveRootAndDepth(b);
1652
+ const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
1653
+ const invRoot = bodyPoseMatrix(root).clone().invert();
1654
+ 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));
1655
+ const partByName = /* @__PURE__ */ new Map();
1656
+ const parts = descendants.map((b) => {
1657
+ const joint = b.joint;
1658
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
1659
+ 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}"`);
1660
+ const parentSpec = parent ? parent.spec : root;
1661
+ const relParentMat = bodyPoseMatrix(parentSpec).clone().invert().multiply(bodyPoseMatrix(b));
1662
+ const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
1663
+ const rpPos = new THREE.Vector3(), tmpQ = new THREE.Quaternion(), rpScl = new THREE.Vector3();
1664
+ relParentMat.decompose(rpPos, tmpQ, rpScl);
1665
+ const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
1666
+ relRootMat.decompose(rrPos, rrQuat, rpScl);
1667
+ rrQuat.normalize();
1668
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
1669
+ const axParentVec = axChildVec.clone().applyQuaternion(rrQuat).normalize();
1670
+ const anchorParent = parent ? [
1671
+ rrPos.x - parent.restRelRootPos[0],
1672
+ rrPos.y - parent.restRelRootPos[1],
1673
+ rrPos.z - parent.restRelRootPos[2]
1674
+ ] : [
1675
+ rpPos.x,
1676
+ rpPos.y,
1677
+ rpPos.z
1678
+ ];
1679
+ const rrQuatTuple = [
1680
+ rrQuat.x,
1681
+ rrQuat.y,
1682
+ rrQuat.z,
1683
+ rrQuat.w
1684
+ ];
1685
+ const massTarget = buildBodyMassTarget(b, rrQuatTuple);
1686
+ const colliders = planOwnColliders(b, massTarget, rrQuat);
1687
+ const plan = {
1688
+ spec: b,
1689
+ joint,
1690
+ parent,
1691
+ restRelParentPos: anchorParent,
1692
+ restRelParentQuat: rrQuatTuple,
1693
+ restRelRootPos: [
1694
+ rrPos.x,
1695
+ rrPos.y,
1696
+ rrPos.z
1697
+ ],
1698
+ restRelRootQuat: rrQuatTuple,
1699
+ axisParent: [
1700
+ axParentVec.x,
1701
+ axParentVec.y,
1702
+ axParentVec.z
1703
+ ],
1704
+ axisChild: [
1705
+ axChildVec.x,
1706
+ axChildVec.y,
1707
+ axChildVec.z
1708
+ ],
1709
+ massTarget,
1710
+ colliders
1711
+ };
1712
+ partByName.set(b.nodeName, plan);
1713
+ return plan;
1714
+ });
1715
+ const massTarget = buildBodyMassTarget(root);
1716
+ const colliders = planOwnColliders(root, massTarget);
1717
+ const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
1718
+ const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
1719
+ const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
1720
+ invRoot.decompose(scenePos, sceneQuat, sceneScl);
1721
+ sceneQuat.normalize();
1722
+ const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
1723
+ mountInRoot.decompose(mountPos, mountQuat, sceneScl);
1724
+ mountQuat.normalize();
1725
+ return {
1726
+ spec: root,
1727
+ sceneInRootPos: [
1728
+ scenePos.x,
1729
+ scenePos.y,
1730
+ scenePos.z
1731
+ ],
1732
+ sceneInRootQuat: [
1733
+ sceneQuat.x,
1734
+ sceneQuat.y,
1735
+ sceneQuat.z,
1736
+ sceneQuat.w
1737
+ ],
1738
+ mountNode,
1739
+ mountPosition: [
1740
+ mountPos.x,
1741
+ mountPos.y,
1742
+ mountPos.z
1743
+ ],
1744
+ mountQuaternion: [
1745
+ mountQuat.x,
1746
+ mountQuat.y,
1747
+ mountQuat.z,
1748
+ mountQuat.w
1749
+ ],
1750
+ massTarget,
1751
+ colliders,
1752
+ parts
1753
+ };
1754
+ });
1755
+ 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`);
1756
+ return plans;
1757
+ }
1758
+ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBody, userData, origin, onBody, onJointReady }) {
1759
+ const { rapier, world } = useRapier();
1760
+ const registry = useContext(JointRegistryContext);
1761
+ const childRef = useRef(null);
1762
+ const rtRef = useRef(null);
1763
+ const [childBody, setChildBody] = React.useState(null);
1764
+ const worldPose = useMemo(() => {
1765
+ const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
1766
+ const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
1767
+ return {
1768
+ pos: [
1769
+ pos.x,
1770
+ pos.y,
1771
+ pos.z
1772
+ ],
1773
+ quat: [
1774
+ rq.x,
1775
+ rq.y,
1776
+ rq.z,
1777
+ rq.w
1778
+ ]
1779
+ };
1780
+ }, [
1781
+ part.restRelRootPos,
1782
+ rootPos,
1783
+ rootQuat
1784
+ ]);
1785
+ const assignChildRef = useCallback((rb) => {
1786
+ childRef.current = rb;
1787
+ setChildBody(rb);
1788
+ onBody(part.spec.nodeName, rb);
1789
+ }, [part.spec.nodeName, onBody]);
1790
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
1791
+ useEffect(() => {
1792
+ if (childBody && part.massTarget) applyRapierBodyMass(childBody, part.massTarget);
1793
+ }, [childBody, part.massTarget]);
1794
+ useEffect(() => {
1795
+ if (!parentBody || !childBody) return;
1796
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
1797
+ 0,
1798
+ 0,
1799
+ 0
1800
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
1801
+ const rt = buildJointRuntime({
1802
+ rapier,
1803
+ world,
1804
+ nodeName: part.spec.nodeName,
1805
+ role: part.joint.role,
1806
+ kind: part.joint.kind,
1807
+ object: part.spec.object,
1808
+ axisParent: part.axisParent,
1809
+ anchorParent: part.restRelParentPos,
1810
+ limits: part.joint.limits,
1811
+ drive: part.joint.drive,
1812
+ breakaway: part.spec.breakaway,
1813
+ rapierJoint: imp,
1814
+ parentBody,
1815
+ childBody
1816
+ });
1817
+ rtRef.current = rt;
1818
+ registry?.add(rt);
1819
+ onJointReady(rt.nodeName, part.spec.object, rt);
1820
+ return () => {
1821
+ rtRef.current = null;
1822
+ registry?.delete(rt);
1823
+ onJointReady(rt.nodeName, part.spec.object, null);
1824
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1825
+ };
1826
+ }, [
1827
+ rapier,
1828
+ world,
1829
+ part,
1830
+ parentBody,
1831
+ childBody,
1832
+ registry,
1833
+ onJointReady
1834
+ ]);
1835
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
1836
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
1837
+ } : void 0, [part.spec.breakaway, world]);
1838
+ const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
1839
+ const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
1840
+ const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
1841
+ return /* @__PURE__ */ jsxs(RigidBody, {
1842
+ ref: assignChildRef,
1843
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
1844
+ position: worldPose.pos,
1845
+ quaternion: worldPose.quat,
1846
+ colliders: false,
1847
+ onContactForce: onForce,
1848
+ ...userData === void 0 ? {} : { userData },
1849
+ ...linVel ? { linearVelocity: linVel } : {},
1850
+ ...angVel ? { angularVelocity: angVel } : {},
1851
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
1852
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
1853
+ object: part.spec.object,
1854
+ position: [
1855
+ 0,
1856
+ 0,
1857
+ 0
1858
+ ],
1859
+ quaternion: part.restRelRootQuat,
1860
+ origin
1861
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1862
+ c: col.spec,
1863
+ position: col.position,
1864
+ quaternion: col.quaternion,
1865
+ density: col.density
1866
+ }, `${part.spec.nodeName}:${cIdx}`))]
1867
+ });
1868
+ }
1869
+ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJointReady, children }) {
1870
+ const [rootBody, setRootBody] = React.useState(null);
1871
+ const [partBodies, setPartBodies] = React.useState(() => /* @__PURE__ */ new Map());
1872
+ const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object), bundleScene) : null, [plan.parts, bundleScene]);
1873
+ const rootSpec = plan.spec;
1874
+ const assignRootRef = useCallback((rb) => {
1875
+ setRootBody(rb);
1876
+ onBody(rootSpec.nodeName, rb);
1877
+ }, [rootSpec.nodeName, onBody]);
1878
+ useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
1879
+ useEffect(() => {
1880
+ if (rootBody && plan.massTarget) applyRapierBodyMass(rootBody, plan.massTarget);
1881
+ }, [rootBody, plan.massTarget]);
1882
+ const handlePartBody = useCallback((nodeName, rb) => {
1883
+ setPartBodies((prev) => {
1884
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
1885
+ const next = new Map(prev);
1886
+ if (rb) next.set(nodeName, rb);
1887
+ else next.delete(nodeName);
1888
+ return next;
1889
+ });
1890
+ onBody(nodeName, rb);
1891
+ }, [onBody]);
1892
+ const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
1893
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
1894
+ ...rigidBodyProps,
1895
+ ref: assignRootRef,
1896
+ type: bodyType,
1897
+ position,
1898
+ quaternion,
1899
+ colliders: false,
1900
+ ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
1901
+ ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
1902
+ ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
1903
+ children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1904
+ c: col.spec,
1905
+ position: col.position,
1906
+ quaternion: col.quaternion,
1907
+ density: col.density
1908
+ }, `r${idx}`))]
1909
+ }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
1910
+ part,
1911
+ rootSpec,
1912
+ rootPos: position,
1913
+ rootQuat: quaternion,
1914
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
1915
+ userData: rigidBodyProps?.userData,
1916
+ origin: partOrigins?.get(part.spec.object),
1917
+ onBody: handlePartBody,
1918
+ onJointReady
1919
+ }, part.spec.nodeName))] });
1920
+ }
1921
+ function KhrAssembly({ ref, bundle, position = [
1922
+ 0,
1923
+ 0,
1924
+ 0
1925
+ ], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
1926
+ assertUnitScale(scale, "KhrAssembly");
1927
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
1928
+ const { world } = useRapier();
1929
+ const applyGravityField = useCustomGravity((s) => s.applyGravityField);
1930
+ const plans = useMemo(() => planAssembly(bundle), [bundle]);
1931
+ const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [plans, bundle.scene]);
1932
+ const [px, py, pz] = position;
1933
+ const [rx, ry, rz] = rotation ?? [
1934
+ 0,
1935
+ 0,
1936
+ 0
1937
+ ];
1938
+ const hasQuat = quaternion !== void 0;
1939
+ const qx = quaternion?.[0] ?? 0;
1940
+ const qy = quaternion?.[1] ?? 0;
1941
+ const qz = quaternion?.[2] ?? 0;
1942
+ const qw = quaternion?.[3] ?? 1;
1943
+ const spawnQuat = useMemo(() => hasQuat ? new THREE.Quaternion(qx, qy, qz, qw).normalize() : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
1944
+ hasQuat,
1945
+ qx,
1946
+ qy,
1947
+ qz,
1948
+ qw,
1949
+ rx,
1950
+ ry,
1951
+ rz
1952
+ ]);
1953
+ const rootPoses = useMemo(() => plans.map((p) => {
1954
+ const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
1955
+ const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
1956
+ return {
1957
+ position: [
1958
+ pos.x,
1959
+ pos.y,
1960
+ pos.z
1961
+ ],
1962
+ quaternion: [
1963
+ quat.x,
1964
+ quat.y,
1965
+ quat.z,
1966
+ quat.w
1967
+ ]
1968
+ };
1969
+ }), [
1970
+ plans,
1971
+ spawnQuat,
1972
+ px,
1973
+ py,
1974
+ pz
1975
+ ]);
1976
+ const bodiesRef = useRef(/* @__PURE__ */ new Map());
1977
+ const jointsRef = useRef(/* @__PURE__ */ new Map());
1978
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
1979
+ const handleBody = useCallback((nodeName, rb) => {
1980
+ if (rb) bodiesRef.current.set(nodeName, rb);
1981
+ else bodiesRef.current.delete(nodeName);
1982
+ }, []);
1983
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
1984
+ if (rt) {
1985
+ jointsRef.current.set(nodeName, rt);
1986
+ byObjectRef.current.set(obj, rt);
1987
+ } else {
1988
+ jointsRef.current.delete(nodeName);
1989
+ byObjectRef.current.delete(obj);
1990
+ }
1991
+ }, []);
1992
+ useFrame(() => {
1993
+ if (!enableCustomGravity || world.timestep <= 0) return;
1994
+ for (const rb of bodiesRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
1995
+ });
1996
+ useImperativeHandle(ref, () => ({
1997
+ get jointNames() {
1998
+ return [...jointsRef.current.keys()];
1999
+ },
2000
+ getBody: (nodeName) => bodiesRef.current.get(nodeName) ?? null,
2001
+ getJointRuntime: (nodeName) => jointsRef.current.get(nodeName) ?? null,
2002
+ setJointTarget: (nodeName, target) => {
2003
+ jointsRef.current.get(nodeName)?.applyTarget(target);
2004
+ },
2005
+ setRoleTarget: (role, target) => {
2006
+ for (const rt of jointsRef.current.values()) if (rt.role === role) rt.applyTarget(target);
2007
+ },
2008
+ toggleHitObject: (hit) => {
2009
+ for (let cur = hit; cur; cur = cur.parent) {
2010
+ const rt = byObjectRef.current.get(cur);
2011
+ if (rt && toggleDrivenJoint(rt)) return true;
2012
+ }
2013
+ return false;
2014
+ }
2015
+ }), []);
2016
+ if (plans.length === 1) {
2017
+ const plan = plans[0];
2018
+ return /* @__PURE__ */ jsx("group", {
2019
+ ...groupProps,
2020
+ children: /* @__PURE__ */ jsx(AssemblyRootBody, {
2021
+ plan,
2022
+ bundleScene: bundle.scene,
2023
+ position: rootPoses[0].position,
2024
+ quaternion: rootPoses[0].quaternion,
2025
+ fixedRoot,
2026
+ rigidBodyProps,
2027
+ onBody: handleBody,
2028
+ onJointReady: handleJointReady,
2029
+ children: /* @__PURE__ */ jsxs("group", {
2030
+ position: plan.sceneInRootPos,
2031
+ quaternion: plan.sceneInRootQuat,
2032
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
2033
+ bundle,
2034
+ owner: "KhrAssembly"
2035
+ }), children]
2036
+ })
2037
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
2038
+ });
2039
+ }
2040
+ return /* @__PURE__ */ jsxs("group", {
2041
+ ...groupProps,
2042
+ children: [/* @__PURE__ */ jsxs("group", {
2043
+ position,
2044
+ quaternion: [
2045
+ spawnQuat.x,
2046
+ spawnQuat.y,
2047
+ spawnQuat.z,
2048
+ spawnQuat.w
2049
+ ],
2050
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
2051
+ bundle,
2052
+ owner: "KhrAssembly"
2053
+ }), children]
2054
+ }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
2055
+ plan,
2056
+ bundleScene: bundle.scene,
2057
+ position: rootPoses[idx].position,
2058
+ quaternion: rootPoses[idx].quaternion,
2059
+ fixedRoot,
2060
+ rigidBodyProps,
2061
+ onBody: handleBody,
2062
+ onJointReady: handleJointReady,
2063
+ children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
2064
+ object: plan.mountNode,
2065
+ position: plan.mountPosition,
2066
+ quaternion: plan.mountQuaternion,
2067
+ origin: origins?.get(plan.mountNode)
2068
+ })
2069
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
2070
+ });
2071
+ }
1562
2072
  // src/useKhrGlb.ts
1563
2073
  var KhrGLTFLoader = class extends GLTFLoader {
1564
2074
  static khrLoaderScope = Symbol("KhrGLTFLoader");
@@ -1671,6 +2181,6 @@ function useKhrGlb(url, options) {
1671
2181
  }
1672
2182
  };
1673
2183
  })(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 };
2184
+ export { ATTACHED_PANEL_INTERACTION_GROUPS, DETACHED_PANEL_INTERACTION_GROUPS, JointRegistryContext, KHR_TRIMESH_FLAGS, KhrAssembly, KhrCollider, KhrGLTFLoader, KhrValidationError, PhysicsWorld, applyRapierBodyMass, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, assignRef, buildBodyMassTarget, buildJointRuntime, claimBundleMount, cloneKhrBundle, closedTargetForLimits, configureJointDrive, createKhrGltfPlugin, createRapierImpulseJoint, createScopedGltfLoaderClass, disposeKhrBundle, exportKhrGlb, isJointOpen, loadKhrGlb, measureJointCoordinate, openTargetForLimits, patchGlbJsonChunk, planAssembly, releaseBundleMount, snapshotSceneWithMountedSubtrees, toggleDrivenJoint, useKhrGlb };
1675
2185
 
1676
2186
  //# sourceMappingURL=index.js.map