@khr3/core 0.2.12 → 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/README.md +54 -3
- package/dist/KhrAssembly.d.ts +3 -4
- package/dist/decoders.d.ts +5 -2
- package/dist/heightfield.d.ts +45 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +360 -27
- package/dist/index.js.map +1 -1
- package/dist/inertia.d.ts +29 -17
- package/dist/{joints-5IgWDD2w.js → joints-H3uae8pm.js} +600 -126
- package/dist/joints-H3uae8pm.js.map +1 -0
- package/dist/types.d.ts +12 -0
- package/dist/vehicle.js +26 -82
- package/dist/vehicle.js.map +1 -1
- package/dist/vehicleJoints.d.ts +2 -2
- package/docs/api-reference.md +160 -0
- package/package.json +4 -3
- package/dist/joints-5IgWDD2w.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo
|
|
|
2
2
|
import { useFrame, useLoader } from "@react-three/fiber";
|
|
3
3
|
import { Physics, RigidBody, useRapier } from "@react-three/rapier";
|
|
4
4
|
import { TimeControl } from "@pinkaphant/ecctrl/time";
|
|
5
|
-
import { A as computeRelativePose, B as
|
|
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
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";
|
|
@@ -175,7 +175,8 @@ function decodeMotion(motion, hasMotion, name) {
|
|
|
175
175
|
0,
|
|
176
176
|
0
|
|
177
177
|
] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
|
|
178
|
-
const
|
|
178
|
+
const hasExplicitInertiaOrientation = motion.inertiaOrientation !== void 0;
|
|
179
|
+
const inertiaOrientation = !hasExplicitInertiaOrientation ? [
|
|
179
180
|
0,
|
|
180
181
|
0,
|
|
181
182
|
0,
|
|
@@ -199,6 +200,7 @@ function decodeMotion(motion, hasMotion, name) {
|
|
|
199
200
|
hasExplicitMotion: hasMotion,
|
|
200
201
|
hasExplicitCom,
|
|
201
202
|
hasExplicitInertia,
|
|
203
|
+
hasExplicitInertiaOrientation,
|
|
202
204
|
mass,
|
|
203
205
|
centerOfMass,
|
|
204
206
|
inertiaDiagonal,
|
|
@@ -548,7 +550,49 @@ function decodeBreakawaySpec(raw) {
|
|
|
548
550
|
breakImpulseNs: raw.breakImpulseNs
|
|
549
551
|
};
|
|
550
552
|
}
|
|
551
|
-
|
|
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) {
|
|
552
596
|
if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
|
|
553
597
|
obj.getWorldPosition(_wpA);
|
|
554
598
|
const worldPosition = [
|
|
@@ -556,10 +600,51 @@ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
|
|
|
556
600
|
_wpA.y,
|
|
557
601
|
_wpA.z
|
|
558
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;
|
|
559
632
|
const custom = isSocketNode?.(name, extras);
|
|
560
633
|
if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
|
|
561
634
|
const key = typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name;
|
|
562
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
|
+
}
|
|
563
648
|
}
|
|
564
649
|
let contactDots;
|
|
565
650
|
if (extras.contactDots !== void 0) {
|
|
@@ -582,6 +667,8 @@ function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
|
|
|
582
667
|
nodeName: name,
|
|
583
668
|
extras,
|
|
584
669
|
worldPosition,
|
|
670
|
+
...emitterSocket ? { emitterSocket } : {},
|
|
671
|
+
...inferredSocket ? { inferredSocket } : {},
|
|
585
672
|
...contactDots ? { contactDots } : {}
|
|
586
673
|
};
|
|
587
674
|
}
|
|
@@ -771,12 +858,13 @@ function applyKhrCustomExtractors(clonedBundle, templateBundle, extractRole, isS
|
|
|
771
858
|
const rawBody = meta.bodies[i];
|
|
772
859
|
const dstBody = clonedBundle.bodies[i];
|
|
773
860
|
if (!rawBody || !dstBody) continue;
|
|
774
|
-
const role = extractRole(rawBody.nodeName, rawBody.extras) ?? (
|
|
861
|
+
const role = extractRole(rawBody.nodeName, rawBody.extras) ?? extractDefaultBodyRole(rawBody.extras);
|
|
775
862
|
dstBody.role = role;
|
|
776
863
|
if (dstBody.joint) dstBody.joint.role = role;
|
|
777
864
|
}
|
|
778
865
|
if (isSocketNode) {
|
|
779
866
|
const sockets = Object.create(null);
|
|
867
|
+
for (const [k, v] of Object.entries(templateBundle.sockets)) sockets[k] = [...v];
|
|
780
868
|
for (const node of meta.nodes) {
|
|
781
869
|
const custom = isSocketNode(node.nodeName, node.extras);
|
|
782
870
|
if (custom || node.extras.isIkAnchor === true || typeof node.extras.socketId === "string") {
|
|
@@ -927,13 +1015,14 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
927
1015
|
const { parentIdx, nodeNames, resolveObj } = buildNodeGraphLookup(gltf, rawNodes, json);
|
|
928
1016
|
const nodeMetas = [];
|
|
929
1017
|
const sockets = Object.create(null);
|
|
1018
|
+
const emitters = [];
|
|
930
1019
|
for (let i = 0; i < rawNodes.length; i++) {
|
|
931
1020
|
const obj = resolveObj(i);
|
|
932
1021
|
if (!obj) continue;
|
|
933
1022
|
const rawExt = rawNodes[i].extensions;
|
|
934
1023
|
if (rawExt !== void 0 && !isObj(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
|
|
935
1024
|
const extras = isObj(rawNodes[i].extras) ? rawNodes[i].extras : {};
|
|
936
|
-
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));
|
|
937
1026
|
}
|
|
938
1027
|
const bodies = [];
|
|
939
1028
|
const bodyMetas = [];
|
|
@@ -973,7 +1062,7 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
973
1062
|
}
|
|
974
1063
|
if (phys.motion !== void 0 && !isObj(phys.motion)) throw new KhrValidationError(`Node "${name}" has invalid motion`);
|
|
975
1064
|
const motion = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
|
|
976
|
-
const role = options?.extractRole?.(name, extras) ?? (
|
|
1065
|
+
const role = options?.extractRole?.(name, extras) ?? extractDefaultBodyRole(extras);
|
|
977
1066
|
let joint = null;
|
|
978
1067
|
if (phys.joint !== void 0) {
|
|
979
1068
|
if (!isObj(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
|
|
@@ -1056,7 +1145,12 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1056
1145
|
...colGroups === void 0 ? {} : { collisionGroups: colGroups }
|
|
1057
1146
|
});
|
|
1058
1147
|
}
|
|
1059
|
-
for (const body of bodies) if (!body.isKinematic && !body.hasExplicitInertia
|
|
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
|
+
}
|
|
1060
1154
|
const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
|
|
1061
1155
|
const ikSockets = [];
|
|
1062
1156
|
const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
|
|
@@ -1080,6 +1174,7 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1080
1174
|
bodies,
|
|
1081
1175
|
wheels,
|
|
1082
1176
|
propellers,
|
|
1177
|
+
emitters,
|
|
1083
1178
|
sockets,
|
|
1084
1179
|
totalDynamicMass,
|
|
1085
1180
|
centerOfMass,
|
|
@@ -1567,6 +1662,173 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1567
1662
|
if (used.size > 0) gltf.extensionsUsed = [...used];
|
|
1568
1663
|
});
|
|
1569
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
|
+
}
|
|
1570
1832
|
// src/KhrAssembly.tsx
|
|
1571
1833
|
function matrixToRoot(node, sceneRoot) {
|
|
1572
1834
|
const out = new THREE.Matrix4();
|
|
@@ -1589,11 +1851,10 @@ function lowestCommonAncestor(nodes, sceneRoot) {
|
|
|
1589
1851
|
}
|
|
1590
1852
|
return sceneRoot;
|
|
1591
1853
|
}
|
|
1592
|
-
function planOwnColliders(body,
|
|
1854
|
+
function planOwnColliders(body, frameQuat) {
|
|
1593
1855
|
const one = new THREE.Vector3(1, 1, 1);
|
|
1594
1856
|
const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
|
|
1595
1857
|
const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
|
|
1596
|
-
const density = massTarget && !massTarget.hasExplicitInertia ? 1 : 0;
|
|
1597
1858
|
return body.colliders.map((spec) => {
|
|
1598
1859
|
const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
|
|
1599
1860
|
const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
|
|
@@ -1612,8 +1873,7 @@ function planOwnColliders(body, massTarget, frameQuat) {
|
|
|
1612
1873
|
quat.y,
|
|
1613
1874
|
quat.z,
|
|
1614
1875
|
quat.w
|
|
1615
|
-
]
|
|
1616
|
-
density
|
|
1876
|
+
]
|
|
1617
1877
|
};
|
|
1618
1878
|
});
|
|
1619
1879
|
}
|
|
@@ -1682,8 +1942,9 @@ function planAssembly(bundle) {
|
|
|
1682
1942
|
rrQuat.z,
|
|
1683
1943
|
rrQuat.w
|
|
1684
1944
|
];
|
|
1685
|
-
const
|
|
1686
|
-
const
|
|
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);
|
|
1687
1948
|
const plan = {
|
|
1688
1949
|
spec: b,
|
|
1689
1950
|
joint,
|
|
@@ -1706,14 +1967,14 @@ function planAssembly(bundle) {
|
|
|
1706
1967
|
axChildVec.y,
|
|
1707
1968
|
axChildVec.z
|
|
1708
1969
|
],
|
|
1709
|
-
|
|
1970
|
+
lumpedMass,
|
|
1710
1971
|
colliders
|
|
1711
1972
|
};
|
|
1712
1973
|
partByName.set(b.nodeName, plan);
|
|
1713
1974
|
return plan;
|
|
1714
1975
|
});
|
|
1715
|
-
const
|
|
1716
|
-
const colliders = planOwnColliders(root
|
|
1976
|
+
const lumpedMass = computeLumpedMassProps([root], invRoot);
|
|
1977
|
+
const colliders = planOwnColliders(root);
|
|
1717
1978
|
const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
|
|
1718
1979
|
const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
|
|
1719
1980
|
const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
|
|
@@ -1747,7 +2008,7 @@ function planAssembly(bundle) {
|
|
|
1747
2008
|
mountQuat.z,
|
|
1748
2009
|
mountQuat.w
|
|
1749
2010
|
],
|
|
1750
|
-
|
|
2011
|
+
lumpedMass,
|
|
1751
2012
|
colliders,
|
|
1752
2013
|
parts
|
|
1753
2014
|
};
|
|
@@ -1789,8 +2050,8 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBody, us
|
|
|
1789
2050
|
}, [part.spec.nodeName, onBody]);
|
|
1790
2051
|
useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
|
|
1791
2052
|
useEffect(() => {
|
|
1792
|
-
if (childBody && part.
|
|
1793
|
-
}, [childBody, part.
|
|
2053
|
+
if (childBody && part.lumpedMass) applyRapierBodyMass(childBody, part.lumpedMass);
|
|
2054
|
+
}, [childBody, part.lumpedMass]);
|
|
1794
2055
|
useEffect(() => {
|
|
1795
2056
|
if (!parentBody || !childBody) return;
|
|
1796
2057
|
const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
|
|
@@ -1861,8 +2122,7 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBody, us
|
|
|
1861
2122
|
}), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
|
|
1862
2123
|
c: col.spec,
|
|
1863
2124
|
position: col.position,
|
|
1864
|
-
quaternion: col.quaternion
|
|
1865
|
-
density: col.density
|
|
2125
|
+
quaternion: col.quaternion
|
|
1866
2126
|
}, `${part.spec.nodeName}:${cIdx}`))]
|
|
1867
2127
|
});
|
|
1868
2128
|
}
|
|
@@ -1877,8 +2137,8 @@ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot,
|
|
|
1877
2137
|
}, [rootSpec.nodeName, onBody]);
|
|
1878
2138
|
useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
|
|
1879
2139
|
useEffect(() => {
|
|
1880
|
-
if (rootBody && plan.
|
|
1881
|
-
}, [rootBody, plan.
|
|
2140
|
+
if (rootBody && plan.lumpedMass) applyRapierBodyMass(rootBody, plan.lumpedMass);
|
|
2141
|
+
}, [rootBody, plan.lumpedMass]);
|
|
1882
2142
|
const handlePartBody = useCallback((nodeName, rb) => {
|
|
1883
2143
|
setPartBodies((prev) => {
|
|
1884
2144
|
if ((prev.get(nodeName) ?? null) === rb) return prev;
|
|
@@ -1903,8 +2163,7 @@ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot,
|
|
|
1903
2163
|
children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
|
|
1904
2164
|
c: col.spec,
|
|
1905
2165
|
position: col.position,
|
|
1906
|
-
quaternion: col.quaternion
|
|
1907
|
-
density: col.density
|
|
2166
|
+
quaternion: col.quaternion
|
|
1908
2167
|
}, `r${idx}`))]
|
|
1909
2168
|
}), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
|
|
1910
2169
|
part,
|
|
@@ -1928,7 +2187,43 @@ function KhrAssembly({ ref, bundle, position = [
|
|
|
1928
2187
|
const { world } = useRapier();
|
|
1929
2188
|
const applyGravityField = useCustomGravity((s) => s.applyGravityField);
|
|
1930
2189
|
const plans = useMemo(() => planAssembly(bundle), [bundle]);
|
|
1931
|
-
const
|
|
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
|
+
]);
|
|
1932
2227
|
const [px, py, pz] = position;
|
|
1933
2228
|
const [rx, ry, rz] = rotation ?? [
|
|
1934
2229
|
0,
|
|
@@ -2013,6 +2308,44 @@ function KhrAssembly({ ref, bundle, position = [
|
|
|
2013
2308
|
return false;
|
|
2014
2309
|
}
|
|
2015
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
|
+
});
|
|
2016
2349
|
if (plans.length === 1) {
|
|
2017
2350
|
const plan = plans[0];
|
|
2018
2351
|
return /* @__PURE__ */ jsx("group", {
|
|
@@ -2181,6 +2514,6 @@ function useKhrGlb(url, options) {
|
|
|
2181
2514
|
}
|
|
2182
2515
|
};
|
|
2183
2516
|
})(useKhrGlb || (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,
|
|
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 };
|
|
2185
2518
|
|
|
2186
2519
|
//# sourceMappingURL=index.js.map
|