@khr3/core 0.2.0 → 0.2.2

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,39 +1,20 @@
1
- import { E as KhrValidationError, S as WorldGravityContext, T as writeJointPose, _ as computeRelativePose, a as planAssembly, b as readUnitQuat, c as claimBundleMount, d as releaseBundleMount, f as assertIdentityWorldScale, g as computeBodyInertia, h as computeAssemblyMassAndCom, l as cloneKhrBundle, m as assertUnitScale, n as MountSubtreeSlot, p as assertSceneIdentityWorldScale, r as captureSubtreeOrigins, s as KhrCollider, t as BundleSceneHost, u as disposeKhrBundle, v as extractMeshColliderShape, w as stepJoint, x as JointRegistryContext, y as readFiniteVec3 } from "./BundleSceneHost-DUqqPtJF.js";
2
- import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
1
+ import { C as extractMeshColliderShape, E as KhrValidationError, S as computeRelativePose, T as readUnitQuat, _ as assertIdentityWorldScale, a as MountSubtreeSlot, b as computeAssemblyMassAndCom, c as planAssembly, f as KhrCollider, g as releaseBundleMount, h as disposeKhrBundle, i as BundleSceneHost, m as cloneKhrBundle, n as buildJointRuntime, o as captureSubtreeOrigins, p as claimBundleMount, r as createRapierImpulseJoint, t as JointRegistryContext, v as assertSceneIdentityWorldScale, w as readFiniteVec3, x as computeBodyInertia, y as assertUnitScale } from "./physicsEcs-B9XGoZtl.js";
2
+ import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
3
3
  import { useFrame, useLoader } from "@react-three/fiber";
4
4
  import { Physics, RigidBody, useRapier } from "@react-three/rapier";
5
- import * as THREE from "three";
6
- import { jsx, jsxs } from "react/jsx-runtime";
5
+ import { TimeControl } from "@pinkaphant/ecctrl/time";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
7
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
8
+ import * as THREE from "three";
8
9
  import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js";
9
10
  // src/PhysicsWorld.tsx
10
11
  var readVal = (v) => typeof v === "number" ? v : v.current;
11
- function StepDriver({ paused, timeScale, maxDelta, joints, dtRef }) {
12
+ function TimestepPresync({ paused, timeScale, maxDelta }) {
12
13
  const { world } = useRapier();
13
- const frameRef = useRef(0);
14
- useFrame((_, rawDelta) => {
15
- const ts = readVal(timeScale);
14
+ useFrame((_, delta) => {
16
15
  const md = Math.max(0, readVal(maxDelta));
17
- const dt = !paused && ts > 0 && md > 0 && rawDelta > 0 ? Math.min(Math.min(rawDelta, md) * ts, .5) : 0;
18
- if (!(dt > 0)) {
19
- dtRef.current = 0;
20
- return;
21
- }
22
- dtRef.current = dt;
23
- world.timestep = dt;
24
- if (joints.size > 0) {
25
- const frame = ++frameRef.current;
26
- for (const j of joints) stepJoint(j, dt);
27
- for (const j of joints) writeJointPose(j, frame);
28
- }
29
- });
30
- return null;
31
- }
32
- function StepCommit({ dtRef }) {
33
- const { step } = useRapier();
34
- useFrame(() => {
35
- const dt = dtRef.current;
36
- if (dt > 0) step(dt);
16
+ const ts = readVal(timeScale);
17
+ world.timestep = !paused && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
37
18
  });
38
19
  return null;
39
20
  }
@@ -42,39 +23,24 @@ function PhysicsWorld({ paused = false, timeScale = 1, maxDelta = 1 / 30, gravit
42
23
  -9.81,
43
24
  0
44
25
  ], children, ...physicsProps }) {
45
- const joints = useMemo(() => /* @__PURE__ */ new Set(), []);
46
- const dtRef = useRef(0);
47
- const gravityMemo = useMemo(() => [
48
- gravity[0],
49
- gravity[1],
50
- gravity[2]
51
- ], [
52
- gravity[0],
53
- gravity[1],
54
- gravity[2]
55
- ]);
56
- return /* @__PURE__ */ jsx(JointRegistryContext.Provider, {
57
- value: joints,
58
- children: /* @__PURE__ */ jsx(WorldGravityContext.Provider, {
59
- value: gravityMemo,
60
- children: /* @__PURE__ */ jsxs(Physics, {
61
- ...physicsProps,
62
- paused: true,
63
- timeStep: "vary",
64
- gravity,
65
- children: [
66
- /* @__PURE__ */ jsx(StepDriver, {
67
- paused,
68
- timeScale,
69
- maxDelta,
70
- joints,
71
- dtRef
72
- }),
73
- children,
74
- /* @__PURE__ */ jsx(StepCommit, { dtRef })
75
- ]
26
+ return /* @__PURE__ */ jsxs(Physics, {
27
+ ...physicsProps,
28
+ paused: true,
29
+ timeStep: "vary",
30
+ gravity,
31
+ children: [
32
+ /* @__PURE__ */ jsx(TimestepPresync, {
33
+ paused,
34
+ timeScale,
35
+ maxDelta
36
+ }),
37
+ children,
38
+ /* @__PURE__ */ jsx(TimeControl, {
39
+ paused,
40
+ timeScale,
41
+ maxDelta
76
42
  })
77
- })
43
+ ]
78
44
  });
79
45
  }
80
46
  // src/khrGlb.ts
@@ -338,6 +304,16 @@ function decodePropellerTag(obj, name, rawPropeller, scene) {
338
304
  };
339
305
  }
340
306
  // src/khrExtras.ts
307
+ function decodeBreakawaySpec(raw) {
308
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
309
+ const rec = raw;
310
+ if (typeof rec.breakImpulseNs !== "number" || !Number.isFinite(rec.breakImpulseNs) || rec.breakImpulseNs <= 0) return void 0;
311
+ const latch = typeof rec.latchImpulseNs === "number" && Number.isFinite(rec.latchImpulseNs) && rec.latchImpulseNs > 0 ? rec.latchImpulseNs : void 0;
312
+ return {
313
+ ...latch === void 0 ? {} : { latchImpulseNs: latch },
314
+ breakImpulseNs: rec.breakImpulseNs
315
+ };
316
+ }
341
317
  var templateMetaMap = /* @__PURE__ */ new WeakMap();
342
318
  function registerKhrTemplateMeta(scene, meta) {
343
319
  templateMetaMap.set(scene, meta);
@@ -544,6 +520,15 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
544
520
  gain = linGain[freeLin[0]];
545
521
  } else throw new KhrValidationError(`physicsJoints[${jointIdx}] unsupported DOF (${freeLin.length} lin, ${freeAng.length} ang) on "${nodeName}"`);
546
522
  const drives = decodeJointDrives(rawDrives, jointIdx, nodeName);
523
+ if (isObj$2(raw.extras) && Array.isArray(raw.extras.jointAxis) && raw.extras.jointAxis.length === 3 && raw.extras.jointAxis.every((n) => typeof n === "number" && Number.isFinite(n))) {
524
+ const [jx, jy, jz] = raw.extras.jointAxis;
525
+ const jLen = Math.hypot(jx, jy, jz);
526
+ if (jLen > 1e-8) axis = [
527
+ jx / jLen,
528
+ jy / jLen,
529
+ jz / jLen
530
+ ];
531
+ }
547
532
  const anchor1Vec = childNode.getWorldPosition(new THREE.Vector3()).sub(connectedNode.getWorldPosition(new THREE.Vector3())).applyQuaternion(connectedNode.getWorldQuaternion(new THREE.Quaternion()).invert());
548
533
  return {
549
534
  index: jointIdx,
@@ -1009,7 +994,6 @@ function extractKhrBundleFromGltf(gltf, options) {
1009
994
  if (rawExt !== void 0 && !isPlainObject(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
1010
995
  if (isPlainObject(rawExt)) {
1011
996
  if (Object.hasOwn(rawExt, "KOLMO_emitter") && rawExt.KOLMO_emitter !== void 0 && !Object.hasOwn(obj.userData, "KOLMO_emitter")) obj.userData.KOLMO_emitter = structuredClone(rawExt.KOLMO_emitter);
1012
- if (Object.hasOwn(rawExt, "KHR3_vfx_emitter") && rawExt.KHR3_vfx_emitter !== void 0 && !Object.hasOwn(obj.userData, "KHR3_vfx_emitter")) obj.userData.KHR3_vfx_emitter = structuredClone(rawExt.KHR3_vfx_emitter);
1013
997
  }
1014
998
  const extras = isPlainObject(rawNodes[i].extras) ? rawNodes[i].extras : {};
1015
999
  nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, options?.isSocketNode));
@@ -1071,6 +1055,7 @@ function extractKhrBundleFromGltf(gltf, options) {
1071
1055
  }
1072
1056
  const wp = obj.getWorldPosition(new THREE.Vector3());
1073
1057
  const wq = obj.getWorldQuaternion(new THREE.Quaternion());
1058
+ const breakaway = decodeBreakawaySpec(extras.breakaway);
1074
1059
  const spec = {
1075
1060
  nodeName: name,
1076
1061
  ...motion,
@@ -1087,6 +1072,7 @@ function extractKhrBundleFromGltf(gltf, options) {
1087
1072
  ],
1088
1073
  colliders: [],
1089
1074
  joint,
1075
+ ...breakaway ? { breakaway } : {},
1090
1076
  object: obj,
1091
1077
  role
1092
1078
  };
@@ -1205,11 +1191,22 @@ function encodeShape(shape, nodeName) {
1205
1191
  }
1206
1192
  };
1207
1193
  }
1208
- function axisToIndex(axis, kind, nodeName) {
1194
+ function normalizeJointAxis(axis, kind, nodeName) {
1209
1195
  if (!Array.isArray(axis) || axis.length !== 3 || !axis.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires a finite axis`);
1210
- const ax = Math.abs(axis[0]), ay = Math.abs(axis[1]), az = Math.abs(axis[2]);
1211
- if (Math.hypot(ax, ay, az) <= 1e-8) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires non-zero axis`);
1212
- return ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2;
1196
+ const len = Math.hypot(axis[0], axis[1], axis[2]);
1197
+ if (len <= 1e-8) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires non-zero axis`);
1198
+ const ux = axis[0] / len, uy = axis[1] / len, uz = axis[2] / len;
1199
+ const ax = Math.abs(ux), ay = Math.abs(uy), az = Math.abs(uz);
1200
+ const primary = ax >= ay && ax >= az ? 0 : ay >= az ? 1 : 2;
1201
+ return {
1202
+ primary,
1203
+ unit: [
1204
+ ux,
1205
+ uy,
1206
+ uz
1207
+ ],
1208
+ isCardinal: (primary === 0 ? ax : primary === 1 ? ay : az) >= 1 - 1e-6
1209
+ };
1213
1210
  }
1214
1211
  function encodeJointDrive(drive, defaultType, defaultAxis, nodeName) {
1215
1212
  if (!isObj(drive)) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" must be an object`);
@@ -1255,7 +1252,7 @@ function encodeJoint(j, nodeName) {
1255
1252
  max: 0
1256
1253
  }] };
1257
1254
  }
1258
- const ax = axisToIndex(j.axis, j.kind, nodeName);
1255
+ const { primary: ax, unit, isCardinal } = normalizeJointAxis(j.axis, j.kind, nodeName);
1259
1256
  const lockedAxes = [
1260
1257
  0,
1261
1258
  1,
@@ -1274,39 +1271,42 @@ function encodeJoint(j, nodeName) {
1274
1271
  ...stiffness === void 0 ? {} : { stiffness },
1275
1272
  ...damping === void 0 ? {} : { damping }
1276
1273
  }] : [];
1277
- const out = { limits: j.kind === "revolute" ? [
1278
- {
1279
- linearAxes: [
1280
- 0,
1281
- 1,
1282
- 2
1283
- ],
1284
- min: 0,
1285
- max: 0
1286
- },
1287
- {
1288
- angularAxes: lockedAxes,
1289
- min: 0,
1290
- max: 0
1291
- },
1292
- ...freeLimit
1293
- ] : [
1294
- {
1295
- angularAxes: [
1296
- 0,
1297
- 1,
1298
- 2
1299
- ],
1300
- min: 0,
1301
- max: 0
1302
- },
1303
- {
1304
- linearAxes: lockedAxes,
1305
- min: 0,
1306
- max: 0
1307
- },
1308
- ...freeLimit
1309
- ] };
1274
+ const out = {
1275
+ limits: j.kind === "revolute" ? [
1276
+ {
1277
+ linearAxes: [
1278
+ 0,
1279
+ 1,
1280
+ 2
1281
+ ],
1282
+ min: 0,
1283
+ max: 0
1284
+ },
1285
+ {
1286
+ angularAxes: lockedAxes,
1287
+ min: 0,
1288
+ max: 0
1289
+ },
1290
+ ...freeLimit
1291
+ ] : [
1292
+ {
1293
+ angularAxes: [
1294
+ 0,
1295
+ 1,
1296
+ 2
1297
+ ],
1298
+ min: 0,
1299
+ max: 0
1300
+ },
1301
+ {
1302
+ linearAxes: lockedAxes,
1303
+ min: 0,
1304
+ max: 0
1305
+ },
1306
+ ...freeLimit
1307
+ ],
1308
+ ...!isCardinal || unit[ax] < 0 ? { extras: { jointAxis: unit } } : {}
1309
+ };
1310
1310
  const drives = j.drives ?? (j.drive ? [j.drive] : []);
1311
1311
  if (drives.length > 0) out.drives = drives.map((d) => encodeJointDrive(d, j.kind === "revolute" ? "angular" : "linear", ax, nodeName));
1312
1312
  return out;
@@ -1579,15 +1579,139 @@ async function exportKhrGlb(root, specs, sceneExtras) {
1579
1579
  });
1580
1580
  }
1581
1581
  // src/AssemblyRootBody.tsx
1582
- function AssemblyRootBody({ plan, assemblyId, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJoints, children }) {
1583
- const joints = useContext(JointRegistryContext);
1582
+ function ArticulatedPartBody({ part, rootPos, rootQuat, parentBodyRef, origin, onBody, onJointReady }) {
1583
+ const { rapier, world } = useRapier();
1584
+ const registry = useContext(JointRegistryContext);
1585
+ const childRef = useRef(null);
1586
+ const rtRef = useRef(null);
1587
+ const worldPose = useMemo(() => {
1588
+ const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]);
1589
+ const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
1590
+ const quat = rq.clone().multiply(new THREE.Quaternion().fromArray(part.restRelRootQuat)).normalize();
1591
+ return {
1592
+ pos: [
1593
+ pos.x,
1594
+ pos.y,
1595
+ pos.z
1596
+ ],
1597
+ quat: [
1598
+ quat.x,
1599
+ quat.y,
1600
+ quat.z,
1601
+ quat.w
1602
+ ]
1603
+ };
1604
+ }, [
1605
+ part.restRelRootPos,
1606
+ part.restRelRootQuat,
1607
+ rootPos,
1608
+ rootQuat
1609
+ ]);
1610
+ useEffect(() => {
1611
+ onBody(part.spec.nodeName, childRef);
1612
+ return () => onBody(part.spec.nodeName, null);
1613
+ }, [part.spec.nodeName, onBody]);
1614
+ useEffect(() => {
1615
+ const rb = childRef.current;
1616
+ const pm = part.partMass;
1617
+ if (rb && pm) {
1618
+ rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
1619
+ rb.recomputeMassPropertiesFromColliders();
1620
+ }
1621
+ }, [part.partMass]);
1622
+ useEffect(() => {
1623
+ const parentBody = parentBodyRef.current;
1624
+ const childBody = childRef.current;
1625
+ if (!parentBody || !childBody) return;
1626
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
1627
+ 0,
1628
+ 0,
1629
+ 0
1630
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
1631
+ const rt = buildJointRuntime({
1632
+ rapier,
1633
+ world,
1634
+ nodeName: part.spec.nodeName,
1635
+ role: part.joint.role,
1636
+ kind: part.joint.kind,
1637
+ object: part.spec.object,
1638
+ axisParent: part.axisParent,
1639
+ anchorParent: part.restRelParentPos,
1640
+ restRelQuat: part.restRelParentQuat,
1641
+ limits: part.joint.limits,
1642
+ drive: part.joint.drive,
1643
+ breakaway: part.spec.breakaway,
1644
+ rapierJoint: imp,
1645
+ parentBody,
1646
+ childBody
1647
+ });
1648
+ rtRef.current = rt;
1649
+ registry?.add(rt);
1650
+ onJointReady(rt.nodeName, rt);
1651
+ return () => {
1652
+ rtRef.current = null;
1653
+ registry?.delete(rt);
1654
+ onJointReady(rt.nodeName, null);
1655
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1656
+ };
1657
+ }, [
1658
+ rapier,
1659
+ world,
1660
+ part,
1661
+ parentBodyRef,
1662
+ registry,
1663
+ onJointReady
1664
+ ]);
1665
+ const onForce = part.spec.breakaway ? (p) => {
1666
+ rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
1667
+ } : void 0;
1668
+ return /* @__PURE__ */ jsxs(RigidBody, {
1669
+ ref: childRef,
1670
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
1671
+ position: worldPose.pos,
1672
+ quaternion: worldPose.quat,
1673
+ colliders: false,
1674
+ onContactForce: onForce,
1675
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
1676
+ object: part.spec.object,
1677
+ position: [
1678
+ 0,
1679
+ 0,
1680
+ 0
1681
+ ],
1682
+ quaternion: [
1683
+ 0,
1684
+ 0,
1685
+ 0,
1686
+ 1
1687
+ ],
1688
+ origin
1689
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1690
+ c: col.spec,
1691
+ position: col.position,
1692
+ quaternion: col.quaternion,
1693
+ massProperties: col.massProperties
1694
+ }, `${part.spec.nodeName}:${cIdx}`))]
1695
+ });
1696
+ }
1697
+ function AssemblyRootBody({ plan, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJoints, children }) {
1584
1698
  const rbRef = useRef(null);
1585
- const partColliderRefs = useMemo(() => plan.parts.map((p) => p.colliders.map(() => ({ current: null }))), [plan]);
1699
+ const partBodyRefs = useMemo(() => new Map(plan.parts.map((p) => [p.spec.nodeName, { current: null }])), [plan]);
1700
+ const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object)) : null, [plan.parts]);
1701
+ const jointsMapRef = useRef(/* @__PURE__ */ new Map());
1586
1702
  const rootSpec = plan.spec;
1587
1703
  useEffect(() => {
1588
1704
  onBody(rootSpec.nodeName, rbRef);
1589
- return () => onBody(rootSpec.nodeName, null);
1590
- }, [rootSpec, onBody]);
1705
+ onJoints(rootSpec.nodeName, jointsMapRef.current);
1706
+ return () => {
1707
+ onBody(rootSpec.nodeName, null);
1708
+ onJoints(rootSpec.nodeName, null);
1709
+ };
1710
+ }, [
1711
+ rootSpec.nodeName,
1712
+ onBody,
1713
+ onJoints
1714
+ ]);
1591
1715
  useEffect(() => {
1592
1716
  const rb = rbRef.current;
1593
1717
  const rm = plan.rootMass;
@@ -1596,60 +1720,17 @@ function AssemblyRootBody({ plan, assemblyId, position, quaternion, fixedRoot, r
1596
1720
  rb.recomputeMassPropertiesFromColliders();
1597
1721
  }
1598
1722
  }, [plan.rootMass]);
1599
- useLayoutEffect(() => {
1600
- const map = /* @__PURE__ */ new Map();
1601
- for (let i = 0; i < plan.parts.length; i++) {
1602
- const part = plan.parts[i];
1603
- const drive = part.joint.drive;
1604
- const rt = {
1605
- assemblyId,
1606
- nodeName: part.spec.nodeName,
1607
- role: part.joint.role,
1608
- kind: part.joint.kind,
1609
- object: part.spec.object,
1610
- axis: new THREE.Vector3().fromArray(part.joint.axis).normalize(),
1611
- restPosition: part.spec.object.position.clone(),
1612
- restQuaternion: part.spec.object.quaternion.clone(),
1613
- q: 0,
1614
- v: 0,
1615
- positionTarget: drive?.positionTarget ?? null,
1616
- velocityTarget: drive?.velocityTarget ?? 0,
1617
- drive,
1618
- limits: part.joint.limits,
1619
- limitStiffness: part.joint.limitStiffness ?? null,
1620
- limitDamping: part.joint.limitDamping ?? 0,
1621
- inertia: part.inertia,
1622
- parent: part.parent ? map.get(part.parent.spec.nodeName) ?? null : null,
1623
- restRelParent: part.restRelParent,
1624
- current: part.restRelParent.clone(),
1625
- stamp: -1,
1626
- colliders: part.colliders.map((c, idx) => ({
1627
- ref: partColliderRefs[i][idx],
1628
- local: c.local
1629
- }))
1630
- };
1631
- map.set(rt.nodeName, rt);
1632
- joints?.add(rt);
1633
- }
1634
- onJoints(rootSpec.nodeName, map);
1635
- return () => {
1636
- onJoints(rootSpec.nodeName, null);
1637
- for (const rt of map.values()) {
1638
- joints?.delete(rt);
1639
- rt.object.position.copy(rt.restPosition);
1640
- rt.object.quaternion.copy(rt.restQuaternion);
1641
- }
1642
- };
1643
- }, [
1644
- plan,
1645
- joints,
1646
- assemblyId,
1647
- partColliderRefs,
1648
- rootSpec,
1649
- onJoints
1650
- ]);
1723
+ const handlePartBody = useCallback((nodeName, refObj) => {
1724
+ const slot = partBodyRefs.get(nodeName);
1725
+ if (slot) slot.current = refObj?.current ?? null;
1726
+ onBody(nodeName, refObj);
1727
+ }, [partBodyRefs, onBody]);
1728
+ const handleJointReady = useCallback((nodeName, rt) => {
1729
+ if (rt) jointsMapRef.current.set(nodeName, rt);
1730
+ else jointsMapRef.current.delete(nodeName);
1731
+ }, []);
1651
1732
  const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
1652
- return /* @__PURE__ */ jsxs(RigidBody, {
1733
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
1653
1734
  ...rigidBodyProps,
1654
1735
  ref: rbRef,
1655
1736
  type: bodyType,
@@ -1659,26 +1740,23 @@ function AssemblyRootBody({ plan, assemblyId, position, quaternion, fixedRoot, r
1659
1740
  ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
1660
1741
  ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
1661
1742
  ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
1662
- children: [
1663
- children,
1664
- plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1665
- c: col.spec,
1666
- position: col.position,
1667
- quaternion: col.quaternion,
1668
- massProperties: col.massProperties
1669
- }, `r${idx}`)),
1670
- plan.parts.map((part, pIdx) => part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1671
- ref: partColliderRefs[pIdx][cIdx],
1672
- c: col.spec,
1673
- position: col.position,
1674
- quaternion: col.quaternion,
1675
- massProperties: col.massProperties
1676
- }, `${part.spec.nodeName}:${cIdx}`)))
1677
- ]
1678
- });
1743
+ children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1744
+ c: col.spec,
1745
+ position: col.position,
1746
+ quaternion: col.quaternion,
1747
+ massProperties: col.massProperties
1748
+ }, `r${idx}`))]
1749
+ }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
1750
+ part,
1751
+ rootPos: position,
1752
+ rootQuat: quaternion,
1753
+ parentBodyRef: part.parent ? partBodyRefs.get(part.parent.spec.nodeName) : rbRef,
1754
+ origin: partOrigins?.get(part.spec.object),
1755
+ onBody: handlePartBody,
1756
+ onJointReady: handleJointReady
1757
+ }, part.spec.nodeName))] });
1679
1758
  }
1680
1759
  // src/KhrAssembly.tsx
1681
- var nextAssemblyId = 0;
1682
1760
  function KhrAssembly({ ref, bundle, position = [
1683
1761
  0,
1684
1762
  0,
@@ -1687,7 +1765,6 @@ function KhrAssembly({ ref, bundle, position = [
1687
1765
  assertUnitScale(scale, "KhrAssembly");
1688
1766
  bundle.scene.updateMatrixWorld(true);
1689
1767
  assertSceneIdentityWorldScale(bundle.scene);
1690
- const assemblyId = useMemo(() => nextAssemblyId++, []);
1691
1768
  const plans = useMemo(() => planAssembly(bundle), [bundle]);
1692
1769
  const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode)) : null, [plans]);
1693
1770
  const [px, py, pz] = position;
@@ -1744,42 +1821,30 @@ function KhrAssembly({ ref, bundle, position = [
1744
1821
  }
1745
1822
  return m;
1746
1823
  }, [plans]);
1747
- const handleBody = useCallback((rootName, rb) => {
1748
- if (rb) bodiesRef.current.set(rootName, rb);
1749
- else bodiesRef.current.delete(rootName);
1824
+ const handleBody = useCallback((nodeName, rb) => {
1825
+ if (rb) bodiesRef.current.set(nodeName, rb);
1826
+ else bodiesRef.current.delete(nodeName);
1750
1827
  }, []);
1751
1828
  const handleJoints = useCallback((rootName, map) => {
1752
1829
  if (map) jointsRef.current.set(rootName, map);
1753
1830
  else jointsRef.current.delete(rootName);
1754
1831
  }, []);
1755
- useImperativeHandle(ref, () => {
1756
- const setTarget = (rt, target) => {
1757
- if (!rt.drive || rt.drive.stiffness === void 0) throw new KhrValidationError(`Joint "${rt.nodeName}" has no authored drive stiffness; cannot set a position target`);
1758
- rt.positionTarget = target;
1759
- const rb = bodiesRef.current.get(nodeToRoot.get(rt.nodeName))?.current;
1760
- if (rb && rb.isDynamic()) rb.wakeUp();
1761
- };
1762
- return {
1763
- getBody: (nodeName) => {
1764
- const rootName = nodeToRoot.get(nodeName);
1765
- return rootName ? bodiesRef.current.get(rootName)?.current ?? null : null;
1766
- },
1767
- setJointTarget: (nodeName, target) => {
1768
- const rt = jointsRef.current.get(nodeToRoot.get(nodeName) ?? "")?.get(nodeName);
1769
- if (rt) setTarget(rt, target);
1770
- },
1771
- setRoleTarget: (role, target) => {
1772
- for (const map of jointsRef.current.values()) for (const rt of map.values()) if (rt.role === role) setTarget(rt, target);
1773
- }
1774
- };
1775
- }, [nodeToRoot]);
1832
+ useImperativeHandle(ref, () => ({
1833
+ getBody: (nodeName) => bodiesRef.current.get(nodeName)?.current ?? null,
1834
+ setJointTarget: (nodeName, target) => {
1835
+ const rt = jointsRef.current.get(nodeToRoot.get(nodeName) ?? "")?.get(nodeName);
1836
+ if (rt) rt.applyTarget(target);
1837
+ },
1838
+ setRoleTarget: (role, target) => {
1839
+ for (const map of jointsRef.current.values()) for (const rt of map.values()) if (rt.role === role) rt.applyTarget(target);
1840
+ }
1841
+ }), [nodeToRoot]);
1776
1842
  if (plans.length === 1) {
1777
1843
  const plan = plans[0];
1778
1844
  return /* @__PURE__ */ jsx("group", {
1779
1845
  ...groupProps,
1780
1846
  children: /* @__PURE__ */ jsx(AssemblyRootBody, {
1781
1847
  plan,
1782
- assemblyId,
1783
1848
  position: rootPoses[0].position,
1784
1849
  quaternion: rootPoses[0].quaternion,
1785
1850
  fixedRoot,
@@ -1813,7 +1878,6 @@ function KhrAssembly({ ref, bundle, position = [
1813
1878
  }), children]
1814
1879
  }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
1815
1880
  plan,
1816
- assemblyId,
1817
1881
  position: rootPoses[idx].position,
1818
1882
  quaternion: rootPoses[idx].quaternion,
1819
1883
  fixedRoot,