@khr3/core 0.2.10 → 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/README.md +8 -0
- package/dist/KhrAssembly.d.ts +44 -8
- package/dist/KhrCollider.d.ts +25 -7
- package/dist/clone.d.ts +45 -0
- package/dist/decoders.d.ts +30 -0
- package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
- package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
- package/dist/index.d.ts +10 -9
- package/dist/index.js +1087 -926
- package/dist/index.js.map +1 -1
- package/dist/inertia.d.ts +41 -0
- package/dist/joints-5IgWDD2w.js +865 -0
- package/dist/joints-5IgWDD2w.js.map +1 -0
- package/dist/{jointDynamics.d.ts → joints.d.ts} +10 -7
- package/dist/loader.d.ts +9 -0
- package/dist/types.d.ts +284 -0
- package/dist/useKhrGlb.d.ts +6 -1
- package/dist/vehicle.d.ts +22 -2
- package/dist/vehicle.js +617 -665
- package/dist/vehicle.js.map +1 -1
- package/dist/vehicleJoints.d.ts +50 -0
- package/dist/wheelLoads.d.ts +5 -4
- package/package.json +4 -16
- package/dist/AssemblyRootBody.d.ts +0 -16
- package/dist/BundleSceneHost.d.ts +0 -23
- package/dist/KhrVehicle.d.ts +0 -20
- package/dist/assemblyPlan.d.ts +0 -61
- package/dist/curves.d.ts +0 -378
- package/dist/curves.js +0 -542
- package/dist/curves.js.map +0 -1
- package/dist/khrBundleFinalize.d.ts +0 -15
- package/dist/khrClone.d.ts +0 -14
- package/dist/khrConfigTypes.d.ts +0 -62
- package/dist/khrExportEncoders.d.ts +0 -8
- package/dist/khrExtras.d.ts +0 -22
- package/dist/khrInertia.d.ts +0 -18
- package/dist/khrJointParser.d.ts +0 -3
- package/dist/khrLoader.d.ts +0 -7
- package/dist/khrMassProps.d.ts +0 -16
- package/dist/khrParsers.d.ts +0 -10
- package/dist/khrPlugin.d.ts +0 -8
- package/dist/khrPluginHelpers.d.ts +0 -26
- package/dist/khrRotorDecoders.d.ts +0 -4
- package/dist/khrShapeParser.d.ts +0 -8
- package/dist/khrTypes.d.ts +0 -141
- package/dist/khrVehicleChassis.d.ts +0 -20
- package/dist/khrVehicleJointHelpers.d.ts +0 -37
- package/dist/khrVehicleJoints.d.ts +0 -30
- package/dist/khrVehicleRotors.d.ts +0 -22
- package/dist/khrVehicleSlots.d.ts +0 -41
- package/dist/khrVehicleTypes.d.ts +0 -52
- package/dist/pacejka.d.ts +0 -22
- package/dist/physicsEcs-Bi0ikONC.js +0 -1156
- package/dist/physicsEcs-Bi0ikONC.js.map +0 -1
- package/dist/physicsEcs.d.ts +0 -25
package/dist/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
|
1
|
+
import React, { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
|
|
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 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";
|
|
5
6
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
-
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
|
|
7
|
-
import { C as computeRelativePose, D as KhrValidationError, E as readUnitQuat, S as computeBodyInertia, T as readFiniteVec3, _ as releaseBundleMount, a as MountSubtreeSlot, b as assertUnitScale, c as planAssembly, f as KhrCollider, h as disposeKhrBundle, i as BundleSceneHost, m as cloneKhrBundle, n as buildJointRuntime, o as captureSubtreeOrigins, p as claimBundleMount, r as createRapierImpulseJoint, t as JointRegistryContext, v as assertIdentityWorldScale, w as extractMeshColliderShape, x as computeAssemblyMassAndCom, y as assertSceneIdentityWorldScale } from "./physicsEcs-Bi0ikONC.js";
|
|
8
7
|
import * as THREE from "three";
|
|
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 }) {
|
|
@@ -14,7 +15,7 @@ function TimestepPresync({ paused, timeScale, maxDelta }) {
|
|
|
14
15
|
useFrame((_, delta) => {
|
|
15
16
|
const md = Math.max(0, readVal(maxDelta));
|
|
16
17
|
const ts = readVal(timeScale);
|
|
17
|
-
world.timestep = !paused && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
|
|
18
|
+
world.timestep = !paused && Number.isFinite(ts) && ts > 0 && md > 0 && delta > 0 ? Math.min(delta, md) * ts : 0;
|
|
18
19
|
});
|
|
19
20
|
return null;
|
|
20
21
|
}
|
|
@@ -23,371 +24,190 @@ function PhysicsWorld({ paused = false, timeScale = 1, maxDelta = 1 / 30, gravit
|
|
|
23
24
|
-9.81,
|
|
24
25
|
0
|
|
25
26
|
], children, ...physicsProps }) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
27
|
+
const jointRegistry = useMemo(() => /* @__PURE__ */ new Set(), []);
|
|
28
|
+
return /* @__PURE__ */ jsx(JointRegistryContext.Provider, {
|
|
29
|
+
value: jointRegistry,
|
|
30
|
+
children: /* @__PURE__ */ jsxs(Physics, {
|
|
31
|
+
...physicsProps,
|
|
32
|
+
paused: true,
|
|
33
|
+
timeStep: "vary",
|
|
34
|
+
gravity,
|
|
35
|
+
children: [
|
|
36
|
+
/* @__PURE__ */ jsx(TimestepPresync, {
|
|
37
|
+
paused,
|
|
38
|
+
timeScale,
|
|
39
|
+
maxDelta
|
|
40
|
+
}),
|
|
41
|
+
children,
|
|
42
|
+
/* @__PURE__ */ jsx(TimeControl, {
|
|
43
|
+
paused,
|
|
44
|
+
timeScale,
|
|
45
|
+
maxDelta
|
|
46
|
+
})
|
|
47
|
+
]
|
|
48
|
+
})
|
|
44
49
|
});
|
|
45
50
|
}
|
|
46
|
-
// src/
|
|
47
|
-
var
|
|
48
|
-
var
|
|
49
|
-
var
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
this.onerror?.(err);
|
|
76
|
-
this.onloadend?.();
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
readAsDataURL(blob) {
|
|
80
|
-
blob.arrayBuffer().then((buf) => {
|
|
81
|
-
const bytes = new Uint8Array(buf);
|
|
82
|
-
let bin = "";
|
|
83
|
-
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
|
|
84
|
-
this.result = `data:${blob.type || "application/octet-stream"};base64,${btoa(bin)}`;
|
|
85
|
-
this.onload?.({ target: this });
|
|
86
|
-
this.onloadend?.();
|
|
87
|
-
}, (err) => {
|
|
88
|
-
this.error = err;
|
|
89
|
-
this.onerror?.(err);
|
|
90
|
-
this.onloadend?.();
|
|
91
|
-
});
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
globalThis.FileReader = PolyfillFileReader;
|
|
95
|
-
}
|
|
96
|
-
function packJsonToGlb(gltf) {
|
|
97
|
-
const jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
|
|
98
|
-
const paddedJsonLen = jsonBytes.byteLength + 3 & -4;
|
|
99
|
-
const totalLen = 20 + paddedJsonLen;
|
|
100
|
-
const out = new ArrayBuffer(totalLen);
|
|
101
|
-
const dv = new DataView(out);
|
|
102
|
-
const u8 = new Uint8Array(out);
|
|
103
|
-
dv.setUint32(0, GLB_MAGIC, true);
|
|
104
|
-
dv.setUint32(4, 2, true);
|
|
105
|
-
dv.setUint32(8, totalLen, true);
|
|
106
|
-
dv.setUint32(12, paddedJsonLen, true);
|
|
107
|
-
dv.setUint32(16, GLB_JSON_CHUNK, true);
|
|
108
|
-
u8.set(jsonBytes, 20);
|
|
109
|
-
u8.fill(32, 20 + jsonBytes.byteLength, 20 + paddedJsonLen);
|
|
110
|
-
return out;
|
|
111
|
-
}
|
|
112
|
-
function patchGlbJsonChunk(source, mutator) {
|
|
113
|
-
const rawBuf = source instanceof ArrayBuffer ? source : source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
114
|
-
const jsonLen = validateGlbHeader(rawBuf);
|
|
115
|
-
const dv = new DataView(rawBuf);
|
|
116
|
-
let gltf;
|
|
117
|
-
try {
|
|
118
|
-
gltf = JSON.parse(new TextDecoder().decode(new Uint8Array(rawBuf, 20, jsonLen)));
|
|
119
|
-
} catch {
|
|
120
|
-
throw new KhrValidationError("Malformed GLB JSON chunk");
|
|
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();
|
|
60
|
+
function decodeShape(raw, idx) {
|
|
61
|
+
if (!isObj(raw)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] must be an object`);
|
|
62
|
+
const type = raw.type;
|
|
63
|
+
if (type === "box") {
|
|
64
|
+
if (raw.box !== void 0 && !isObj(raw.box)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box`);
|
|
65
|
+
const box = isObj(raw.box) ? raw.box : {};
|
|
66
|
+
const size = box.size === void 0 ? [
|
|
67
|
+
1,
|
|
68
|
+
1,
|
|
69
|
+
1
|
|
70
|
+
] : box.size;
|
|
71
|
+
if (!Array.isArray(size) || size.length !== 3 || !size.every(isPosNum)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box.size`);
|
|
72
|
+
return {
|
|
73
|
+
type: "box",
|
|
74
|
+
size: [
|
|
75
|
+
size[0],
|
|
76
|
+
size[1],
|
|
77
|
+
size[2]
|
|
78
|
+
]
|
|
79
|
+
};
|
|
121
80
|
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const totalLen = 20 + paddedJsonLen + (hasBin ? 8 + paddedBinLen : 0);
|
|
132
|
-
const out = new ArrayBuffer(totalLen);
|
|
133
|
-
const outDv = new DataView(out);
|
|
134
|
-
const outU8 = new Uint8Array(out);
|
|
135
|
-
outDv.setUint32(0, GLB_MAGIC, true);
|
|
136
|
-
outDv.setUint32(4, 2, true);
|
|
137
|
-
outDv.setUint32(8, totalLen, true);
|
|
138
|
-
outDv.setUint32(12, paddedJsonLen, true);
|
|
139
|
-
outDv.setUint32(16, GLB_JSON_CHUNK, true);
|
|
140
|
-
outU8.set(nextJson, 20);
|
|
141
|
-
outU8.fill(32, 20 + nextJson.byteLength, 20 + paddedJsonLen);
|
|
142
|
-
if (hasBin) {
|
|
143
|
-
outDv.setUint32(20 + paddedJsonLen, paddedBinLen, true);
|
|
144
|
-
outDv.setUint32(24 + paddedJsonLen, binTag, true);
|
|
145
|
-
outU8.set(binData, 28 + paddedJsonLen);
|
|
81
|
+
if (type === "sphere") {
|
|
82
|
+
if (raw.sphere !== void 0 && !isObj(raw.sphere)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere`);
|
|
83
|
+
const sphere = isObj(raw.sphere) ? raw.sphere : {};
|
|
84
|
+
const radius = sphere.radius === void 0 ? .5 : sphere.radius;
|
|
85
|
+
if (!isPosNum(radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere.radius`);
|
|
86
|
+
return {
|
|
87
|
+
type: "sphere",
|
|
88
|
+
radius
|
|
89
|
+
};
|
|
146
90
|
}
|
|
147
|
-
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
91
|
+
if (type === "cylinder" || type === "capsule") {
|
|
92
|
+
if (raw[type] !== void 0 && !isObj(raw[type])) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}`);
|
|
93
|
+
const g = isObj(raw[type]) ? raw[type] : {};
|
|
94
|
+
const height = g.height === void 0 ? type === "cylinder" ? 2 : 1 : g.height;
|
|
95
|
+
if (!isPosNum(height)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.height`);
|
|
96
|
+
const radiusTop = g.radiusTop === void 0 ? .5 : g.radiusTop;
|
|
97
|
+
const radiusBottom = g.radiusBottom === void 0 ? .5 : g.radiusBottom;
|
|
98
|
+
if (!isPosNum(radiusTop)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusTop`);
|
|
99
|
+
if (!isPosNum(radiusBottom)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusBottom`);
|
|
100
|
+
if (Math.abs(radiusTop - radiusBottom) > 1e-6) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] tapered ${type} (${radiusTop} !== ${radiusBottom}) is unsupported`);
|
|
101
|
+
return {
|
|
102
|
+
type,
|
|
103
|
+
height,
|
|
104
|
+
radiusTop,
|
|
105
|
+
radiusBottom
|
|
106
|
+
};
|
|
160
107
|
}
|
|
161
|
-
|
|
162
|
-
else _quat$1.identity();
|
|
163
|
-
return [
|
|
164
|
-
_quat$1.x || 0,
|
|
165
|
-
_quat$1.y || 0,
|
|
166
|
-
_quat$1.z || 0,
|
|
167
|
-
_quat$1.w || 0
|
|
168
|
-
];
|
|
169
|
-
}
|
|
170
|
-
function optNum$3(obj, key, tagKind, owner, strictlyPos = false) {
|
|
171
|
-
const val = obj[key];
|
|
172
|
-
if (val === void 0) return void 0;
|
|
173
|
-
if (!isFiniteNum$1(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${key}: ${tagKind}.${key}`);
|
|
174
|
-
return val;
|
|
175
|
-
}
|
|
176
|
-
function reqNum(obj, key, tagKind, owner, strictlyPos = false) {
|
|
177
|
-
const val = obj[key];
|
|
178
|
-
if (!isFiniteNum$1(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" is missing valid ${tagKind}.${key}`);
|
|
179
|
-
return val;
|
|
180
|
-
}
|
|
181
|
-
function optBool(obj, key, tagKind, owner) {
|
|
182
|
-
const val = obj[key];
|
|
183
|
-
if (val === void 0) return void 0;
|
|
184
|
-
if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" has non-boolean ${tagKind}.${key}`);
|
|
185
|
-
return val;
|
|
186
|
-
}
|
|
187
|
-
function optBoolOrNumFlag(obj, key, tagKind, owner) {
|
|
188
|
-
const val = obj[key];
|
|
189
|
-
if (val === void 0) return void 0;
|
|
190
|
-
if (typeof val === "boolean") return { flag: val };
|
|
191
|
-
if (isFiniteNum$1(val) && val >= 0) return {
|
|
192
|
-
flag: val !== 0,
|
|
193
|
-
numeric: val
|
|
194
|
-
};
|
|
195
|
-
throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
|
|
196
|
-
}
|
|
197
|
-
function reqBool(obj, key, tagKind, owner) {
|
|
198
|
-
const val = obj[key];
|
|
199
|
-
if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" is missing boolean ${tagKind}.${key}`);
|
|
200
|
-
return val;
|
|
108
|
+
throw new KhrValidationError(`KHR_implicit_shapes[${idx}] unsupported shape type "${String(type)}"`);
|
|
201
109
|
}
|
|
202
|
-
function
|
|
203
|
-
if (
|
|
204
|
-
if (
|
|
205
|
-
|
|
206
|
-
if (val.samples !== void 0 && (!isFiniteNum$1(val.samples) || val.samples <= 0)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
|
|
207
|
-
return val;
|
|
110
|
+
function optCombineMode(v, label) {
|
|
111
|
+
if (v === void 0) return void 0;
|
|
112
|
+
if (typeof v !== "string" || !COMBINE_MODES.has(v)) throw new KhrValidationError(`Invalid ${label}: "${String(v)}"`);
|
|
113
|
+
return v;
|
|
208
114
|
}
|
|
209
|
-
function
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
const
|
|
217
|
-
const
|
|
218
|
-
const
|
|
219
|
-
if (omi) {
|
|
220
|
-
reqNum(omi, "radius", "OMI_vehicle_wheel", name, true);
|
|
221
|
-
reqNum(omi, "width", "OMI_vehicle_wheel", name, true);
|
|
222
|
-
}
|
|
223
|
-
const omiTravel = omi ? optNum$3(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
|
|
224
|
-
const omiMaxForce = omi ? optNum$3(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
|
|
225
|
-
const omiMaxSteerRaw = omi ? optNum$3(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
|
|
226
|
-
const omiStiffness = omi ? optNum$3(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
|
|
227
|
-
const omiDampComp = omi ? optNum$3(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
|
|
228
|
-
const omiDampReb = omi ? optNum$3(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
|
|
229
|
-
const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
|
|
230
|
-
const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
|
|
231
|
-
const omiSteering = omiSteer?.flag;
|
|
232
|
-
const omiPropulsion = omiProp?.flag;
|
|
233
|
-
const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
|
|
234
|
-
const travel = omi ? optNum$3(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqNum(ec, "travel", "ecctrlWheel", name);
|
|
235
|
-
const sag = omi ? optNum$3(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqNum(ec, "sag", "ecctrlWheel", name);
|
|
236
|
-
if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
|
|
237
|
-
const steer = omi ? optBool(ec, "steer", "ecctrlWheel", name) ?? omiSteering ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqBool(ec, "steer", "ecctrlWheel", name);
|
|
238
|
-
const drive = omi ? optBool(ec, "drive", "ecctrlWheel", name) ?? omiPropulsion ?? false : reqBool(ec, "drive", "ecctrlWheel", name);
|
|
239
|
-
const brake = omi ? optBool(ec, "brake", "ecctrlWheel", name) ?? true : reqBool(ec, "brake", "ecctrlWheel", name);
|
|
240
|
-
const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
|
|
241
|
-
const springK = optNum$3(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
|
|
242
|
-
const dampingC = optNum$3(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
|
|
243
|
-
const maxBrakeTorque = optNum$3(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
|
|
244
|
-
const maxSteeringAngle = optNum$3(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
|
|
245
|
-
const box = new THREE.Box3().setFromObject(obj);
|
|
246
|
-
const center = box.isEmpty() ? obj.getWorldPosition(new THREE.Vector3()) : box.getCenter(new THREE.Vector3());
|
|
115
|
+
function decodePhysicsMaterial(rawMaterials, idx, ownerName) {
|
|
116
|
+
if (idx === void 0) return {};
|
|
117
|
+
if (typeof idx !== "number" || !Number.isInteger(idx) || idx < 0 || idx >= rawMaterials.length) throw new KhrValidationError(`Node "${ownerName}" references out-of-bounds physicsMaterial ${String(idx)}`);
|
|
118
|
+
const mat = rawMaterials[idx];
|
|
119
|
+
if (!isObj(mat)) throw new KhrValidationError(`Invalid physicsMaterials[${idx}] on "${ownerName}"`);
|
|
120
|
+
const dynF = optFiniteNum(mat.dynamicFriction, `physicsMaterials[${idx}].dynamicFriction`, true);
|
|
121
|
+
const statF = optFiniteNum(mat.staticFriction, `physicsMaterials[${idx}].staticFriction`, true);
|
|
122
|
+
const rest = optFiniteNum(mat.restitution, `physicsMaterials[${idx}].restitution`, true);
|
|
123
|
+
const frictionCombine = optCombineMode(mat.frictionCombine, `physicsMaterials[${idx}].frictionCombine`);
|
|
124
|
+
const restitutionCombine = optCombineMode(mat.restitutionCombine, `physicsMaterials[${idx}].restitutionCombine`);
|
|
247
125
|
return {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
center.y,
|
|
253
|
-
center.z
|
|
254
|
-
],
|
|
255
|
-
quaternion: getRelativeQuatArray(obj, scene),
|
|
256
|
-
radius,
|
|
257
|
-
width,
|
|
258
|
-
steer,
|
|
259
|
-
steerInvert: optBool(ec, "steerInvert", "ecctrlWheel", name),
|
|
260
|
-
drive,
|
|
261
|
-
driveInvert: optBool(ec, "driveInvert", "ecctrlWheel", name),
|
|
262
|
-
brake,
|
|
263
|
-
travel,
|
|
264
|
-
sag,
|
|
265
|
-
springK,
|
|
266
|
-
dampingC,
|
|
267
|
-
maxBrakeTorque,
|
|
268
|
-
...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
|
|
269
|
-
rollingResistanceCoef: optNum$3(ec, "rollingResistanceCoef", "ecctrlWheel", name),
|
|
270
|
-
wheelDensity: optNum$3(ec, "wheelDensity", "ecctrlWheel", name, true),
|
|
271
|
-
driveTorqueWeight: optNum$3(ec, "driveTorqueWeight", "ecctrlWheel", name),
|
|
272
|
-
tireGripFactor: optNum$3(ec, "tireGripFactor", "ecctrlWheel", name),
|
|
273
|
-
latFrictionEllipseScale: optNum$3(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
|
|
274
|
-
relaxLngRate: optNum$3(ec, "relaxLngRate", "ecctrlWheel", name),
|
|
275
|
-
relaxLatRate: optNum$3(ec, "relaxLatRate", "ecctrlWheel", name),
|
|
276
|
-
lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
|
|
277
|
-
latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
|
|
126
|
+
...dynF !== void 0 || statF !== void 0 ? { friction: dynF ?? statF } : {},
|
|
127
|
+
...rest === void 0 ? {} : { restitution: rest },
|
|
128
|
+
...frictionCombine === void 0 ? {} : { frictionCombine },
|
|
129
|
+
...restitutionCombine === void 0 ? {} : { restitutionCombine }
|
|
278
130
|
};
|
|
279
131
|
}
|
|
280
|
-
function
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if (
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
const center = box.isEmpty() ? obj.getWorldPosition(new THREE.Vector3()) : box.getCenter(new THREE.Vector3());
|
|
291
|
-
return {
|
|
292
|
-
nodeName: name,
|
|
293
|
-
object: obj,
|
|
294
|
-
position: [
|
|
295
|
-
center.x,
|
|
296
|
-
center.y,
|
|
297
|
-
center.z
|
|
298
|
-
],
|
|
299
|
-
quaternion: getRelativeQuatArray(obj, scene),
|
|
300
|
-
maxThrust: rawPropeller.maxThrust,
|
|
301
|
-
torqueRatio,
|
|
302
|
-
invertThrust: optBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
|
|
303
|
-
invertTorque: optBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
|
|
132
|
+
function decodeCollisionGroups(rawFilters) {
|
|
133
|
+
const collisionSystemIds = /* @__PURE__ */ new Map([["default", 0]]);
|
|
134
|
+
let nextCollisionBit = 1;
|
|
135
|
+
const bitFor = (sys) => {
|
|
136
|
+
const hit = collisionSystemIds.get(sys);
|
|
137
|
+
if (hit !== void 0) return hit;
|
|
138
|
+
if (nextCollisionBit > 15) throw new KhrValidationError(`Exceeded Rapier 16-group limit for collisionSystem "${sys}"`);
|
|
139
|
+
const b = nextCollisionBit++;
|
|
140
|
+
collisionSystemIds.set(sys, b);
|
|
141
|
+
return b;
|
|
304
142
|
};
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
breakImpulseNs: rec.breakImpulseNs
|
|
143
|
+
const maskFor = (arr, label) => {
|
|
144
|
+
if (arr === void 0) return 0;
|
|
145
|
+
if (!Array.isArray(arr)) throw new KhrValidationError(`collisionFilter.${label} must be an array`);
|
|
146
|
+
let mask = 0;
|
|
147
|
+
for (const s of arr) {
|
|
148
|
+
if (typeof s !== "string" || s.length === 0) throw new KhrValidationError(`collisionFilter.${label} has invalid system`);
|
|
149
|
+
mask |= 1 << bitFor(s);
|
|
150
|
+
}
|
|
151
|
+
return mask;
|
|
315
152
|
};
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
Object.defineProperty(sockets, key, {
|
|
323
|
-
value: pos,
|
|
324
|
-
enumerable: true,
|
|
325
|
-
configurable: true,
|
|
326
|
-
writable: true
|
|
153
|
+
return rawFilters.map((f, idx) => {
|
|
154
|
+
if (!isObj(f)) throw new KhrValidationError(`collisionFilters[${idx}] must be an object`);
|
|
155
|
+
if (f.collideWithSystems !== void 0 && f.notCollideWithSystems !== void 0) throw new KhrValidationError(`collisionFilters[${idx}] cannot specify both collideWithSystems and notCollideWithSystems`);
|
|
156
|
+
const membership = maskFor(f.collisionSystems, "collisionSystems");
|
|
157
|
+
const filter = f.collideWithSystems === void 0 ? 65535 & ~maskFor(f.notCollideWithSystems, "notCollideWithSystems") : maskFor(f.collideWithSystems, "collideWithSystems");
|
|
158
|
+
return (membership & 65535) << 16 | filter & 65535;
|
|
327
159
|
});
|
|
328
160
|
}
|
|
329
|
-
function
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
161
|
+
function decodeMotion(motion, hasMotion, name) {
|
|
162
|
+
if (motion.isKinematic !== void 0 && typeof motion.isKinematic !== "boolean") throw new KhrValidationError(`Node "${name}" has non-boolean motion.isKinematic`);
|
|
163
|
+
const isKinematic = !hasMotion || Boolean(motion.isKinematic);
|
|
164
|
+
let mass = 0;
|
|
165
|
+
if (!isKinematic) {
|
|
166
|
+
if (!isPosNum(motion.mass)) throw new KhrValidationError(`Dynamic node "${name}" is missing positive finite motion.mass`);
|
|
167
|
+
mass = motion.mass;
|
|
168
|
+
} else if (motion.mass !== void 0) {
|
|
169
|
+
if (!isNonNegNum(motion.mass)) throw new KhrValidationError(`Kinematic node "${name}" has invalid motion.mass`);
|
|
170
|
+
mass = motion.mass;
|
|
339
171
|
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
|
|
357
|
-
const wp = obj.getWorldPosition(new THREE.Vector3());
|
|
358
|
-
const worldPosition = [
|
|
359
|
-
wp.x,
|
|
360
|
-
wp.y,
|
|
361
|
-
wp.z
|
|
172
|
+
const hasExplicitCom = motion.centerOfMass !== void 0;
|
|
173
|
+
const centerOfMass = !hasExplicitCom ? [
|
|
174
|
+
0,
|
|
175
|
+
0,
|
|
176
|
+
0
|
|
177
|
+
] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
|
|
178
|
+
const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
|
|
179
|
+
0,
|
|
180
|
+
0,
|
|
181
|
+
0,
|
|
182
|
+
1
|
|
183
|
+
] : readUnitQuat(motion.inertiaOrientation, `${name}.motion.inertiaOrientation`);
|
|
184
|
+
let inertiaDiagonal = [
|
|
185
|
+
0,
|
|
186
|
+
0,
|
|
187
|
+
0
|
|
362
188
|
];
|
|
363
|
-
const
|
|
364
|
-
if (
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
|
|
368
|
-
obj.getWorldQuaternion(_quat);
|
|
369
|
-
contactDots = [];
|
|
370
|
-
for (const dot of extras.contactDots) {
|
|
371
|
-
if (!isObj$3(dot) || typeof dot.role !== "string" || dot.role.length === 0 || !Array.isArray(dot.pos) || dot.pos.length !== 3 || !dot.pos.every(isFiniteNum)) throw new KhrValidationError(`Node "${name}" has invalid entry in extras.contactDots`);
|
|
372
|
-
_dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_quat).add(wp);
|
|
373
|
-
const dotPos = [
|
|
374
|
-
_dotVec.x,
|
|
375
|
-
_dotVec.y,
|
|
376
|
-
_dotVec.z
|
|
377
|
-
];
|
|
378
|
-
setSocket(sockets, dot.role, dotPos);
|
|
379
|
-
contactDots.push([dot.role, dotPos]);
|
|
380
|
-
}
|
|
189
|
+
const hasExplicitInertia = motion.inertiaDiagonal !== void 0;
|
|
190
|
+
if (hasExplicitInertia) {
|
|
191
|
+
inertiaDiagonal = readFiniteVec3(motion.inertiaDiagonal, `${name}.motion.inertiaDiagonal`);
|
|
192
|
+
if (inertiaDiagonal.some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`Node "${name}" has invalid motion.inertiaDiagonal`);
|
|
381
193
|
}
|
|
194
|
+
const linearVelocity = motion.linearVelocity === void 0 ? void 0 : readFiniteVec3(motion.linearVelocity, `${name}.motion.linearVelocity`);
|
|
195
|
+
const angularVelocity = motion.angularVelocity === void 0 ? void 0 : readFiniteVec3(motion.angularVelocity, `${name}.motion.angularVelocity`);
|
|
196
|
+
const gravityFactor = optFiniteNum(motion.gravityFactor, `${name}.motion.gravityFactor`);
|
|
382
197
|
return {
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
198
|
+
isKinematic,
|
|
199
|
+
hasExplicitMotion: hasMotion,
|
|
200
|
+
hasExplicitCom,
|
|
201
|
+
hasExplicitInertia,
|
|
202
|
+
mass,
|
|
203
|
+
centerOfMass,
|
|
204
|
+
inertiaDiagonal,
|
|
205
|
+
inertiaOrientation,
|
|
206
|
+
...linearVelocity ? { linearVelocity } : {},
|
|
207
|
+
...angularVelocity ? { angularVelocity } : {},
|
|
208
|
+
...gravityFactor === void 0 ? {} : { gravityFactor }
|
|
387
209
|
};
|
|
388
210
|
}
|
|
389
|
-
// src/khrJointParser.ts
|
|
390
|
-
var isObj$2 = (v) => typeof v === "object" && !!v && !Array.isArray(v);
|
|
391
211
|
var axisVector = (axis) => axis === 0 ? [
|
|
392
212
|
1,
|
|
393
213
|
0,
|
|
@@ -401,25 +221,19 @@ var axisVector = (axis) => axis === 0 ? [
|
|
|
401
221
|
0,
|
|
402
222
|
1
|
|
403
223
|
];
|
|
404
|
-
function optNum$2(v, label, nonNeg = false) {
|
|
405
|
-
if (v !== void 0) {
|
|
406
|
-
if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}`);
|
|
407
|
-
return v;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
224
|
function decodeJointDrives(rawDrives, jointIdx, nodeName) {
|
|
411
225
|
return rawDrives.map((d, i) => {
|
|
412
226
|
const label = `physicsJoints[${jointIdx}].drives[${i}] on "${nodeName}"`;
|
|
413
|
-
if (!isObj
|
|
227
|
+
if (!isObj(d)) throw new KhrValidationError(`${label} must be an object`);
|
|
414
228
|
if (d.mode !== "force" && d.mode !== "acceleration") throw new KhrValidationError(`${label} missing valid drive.mode`);
|
|
415
229
|
if (d.axis !== 0 && d.axis !== 1 && d.axis !== 2) throw new KhrValidationError(`${label} missing valid drive.axis (0|1|2)`);
|
|
416
230
|
if (d.type !== void 0 && d.type !== "linear" && d.type !== "angular") throw new KhrValidationError(`${label} invalid drive.type`);
|
|
417
|
-
const positionTarget =
|
|
418
|
-
const velocityTarget =
|
|
231
|
+
const positionTarget = optFiniteNum(d.positionTarget, `${label} drive.positionTarget`);
|
|
232
|
+
const velocityTarget = optFiniteNum(d.velocityTarget, `${label} drive.velocityTarget`);
|
|
419
233
|
if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`${label} requires finite drive.positionTarget or drive.velocityTarget`);
|
|
420
|
-
const stiffness =
|
|
421
|
-
const damping =
|
|
422
|
-
const maxForce =
|
|
234
|
+
const stiffness = optFiniteNum(d.stiffness, `${label} drive.stiffness`, true);
|
|
235
|
+
const damping = optFiniteNum(d.damping, `${label} drive.damping`, true);
|
|
236
|
+
const maxForce = optFiniteNum(d.maxForce, `${label} drive.maxForce`, true);
|
|
423
237
|
return {
|
|
424
238
|
...d.type ? { type: d.type } : {},
|
|
425
239
|
mode: d.mode,
|
|
@@ -434,7 +248,7 @@ function decodeJointDrives(rawDrives, jointIdx, nodeName) {
|
|
|
434
248
|
}
|
|
435
249
|
function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, enableCollision, role, connectedNodeName = connectedNode.name) {
|
|
436
250
|
const raw = rawJoints[jointIdx];
|
|
437
|
-
if (!isObj
|
|
251
|
+
if (!isObj(raw)) throw new KhrValidationError(`physicsJoints[${jointIdx}] out of bounds for "${nodeName}"`);
|
|
438
252
|
if (raw.limits !== void 0 && !Array.isArray(raw.limits)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must be an array`);
|
|
439
253
|
if (raw.drives !== void 0 && !Array.isArray(raw.drives)) throw new KhrValidationError(`physicsJoints[${jointIdx}].drives on "${nodeName}" must be an array`);
|
|
440
254
|
const rawLimits = raw.limits ?? [];
|
|
@@ -466,12 +280,12 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
|
|
|
466
280
|
if (ax !== 0 && ax !== 1 && ax !== 2) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits invalid axis ${String(ax)} on "${nodeName}"`);
|
|
467
281
|
return ax;
|
|
468
282
|
});
|
|
469
|
-
const min =
|
|
470
|
-
const max =
|
|
283
|
+
const min = optFiniteNum(lim.min, `physicsJoints[${jointIdx}] limit.min on "${nodeName}"`);
|
|
284
|
+
const max = optFiniteNum(lim.max, `physicsJoints[${jointIdx}] limit.max on "${nodeName}"`);
|
|
471
285
|
if ((lim.min !== void 0 || lim.max !== void 0) && (min === void 0 || max === void 0)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits on "${nodeName}" must specify both min and max`);
|
|
472
286
|
if (min !== void 0 && max !== void 0 && min > max) throw new KhrValidationError(`physicsJoints[${jointIdx}] limit.min > limit.max on "${nodeName}"`);
|
|
473
|
-
const stiffness =
|
|
474
|
-
const damping =
|
|
287
|
+
const stiffness = optFiniteNum(lim.stiffness, `physicsJoints[${jointIdx}] limit.stiffness on "${nodeName}"`, true);
|
|
288
|
+
const damping = optFiniteNum(lim.damping, `physicsJoints[${jointIdx}] limit.damping on "${nodeName}"`, true);
|
|
475
289
|
const locked = min !== void 0 && max !== void 0 && max - min <= 1e-6;
|
|
476
290
|
if (!locked && axes.length > 1) throw new KhrValidationError(`physicsJoints[${jointIdx}] coupled multi-axis limit on "${nodeName}" is unsupported`);
|
|
477
291
|
for (const ax of axes) {
|
|
@@ -483,7 +297,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
|
|
|
483
297
|
}
|
|
484
298
|
};
|
|
485
299
|
for (const lim of rawLimits) {
|
|
486
|
-
if (!isObj
|
|
300
|
+
if (!isObj(lim)) throw new KhrValidationError(`physicsJoints[${jointIdx}].limits entry on "${nodeName}" must be an object`);
|
|
487
301
|
applyAxes(lim.linearAxes, lim, lin, linGain);
|
|
488
302
|
applyAxes(lim.angularAxes, lim, ang, angGain);
|
|
489
303
|
}
|
|
@@ -520,7 +334,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
|
|
|
520
334
|
gain = linGain[freeLin[0]];
|
|
521
335
|
} else throw new KhrValidationError(`physicsJoints[${jointIdx}] unsupported DOF (${freeLin.length} lin, ${freeAng.length} ang) on "${nodeName}"`);
|
|
522
336
|
const drives = decodeJointDrives(rawDrives, jointIdx, nodeName);
|
|
523
|
-
if (isObj
|
|
337
|
+
if (isObj(raw.extras) && Array.isArray(raw.extras.jointAxis) && raw.extras.jointAxis.length === 3 && raw.extras.jointAxis.every(isFiniteNum)) {
|
|
524
338
|
const [jx, jy, jz] = raw.extras.jointAxis;
|
|
525
339
|
const jLen = Math.hypot(jx, jy, jz);
|
|
526
340
|
if (jLen > 1e-8) axis = [
|
|
@@ -529,7 +343,7 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
|
|
|
529
343
|
jz / jLen
|
|
530
344
|
];
|
|
531
345
|
}
|
|
532
|
-
const anchor1Vec = childNode.getWorldPosition(
|
|
346
|
+
const anchor1Vec = childNode.getWorldPosition(_wpA).sub(connectedNode.getWorldPosition(_wpB)).applyQuaternion(connectedNode.getWorldQuaternion(_wqInv).invert());
|
|
533
347
|
return {
|
|
534
348
|
index: jointIdx,
|
|
535
349
|
nodeName,
|
|
@@ -555,192 +369,374 @@ function decodeJoint(rawJoints, jointIdx, nodeName, connectedNode, childNode, en
|
|
|
555
369
|
]
|
|
556
370
|
};
|
|
557
371
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
"maximum",
|
|
565
|
-
"multiply"
|
|
566
|
-
]);
|
|
567
|
-
function optNum$1(v, label, nonNeg = false) {
|
|
568
|
-
if (v !== void 0) {
|
|
569
|
-
if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}`);
|
|
570
|
-
return v;
|
|
372
|
+
function getRelativeQuatArray(obj, parent) {
|
|
373
|
+
obj.updateWorldMatrix(true, false);
|
|
374
|
+
obj.getWorldQuaternion(_quat);
|
|
375
|
+
if (parent) {
|
|
376
|
+
parent.updateWorldMatrix(true, false);
|
|
377
|
+
_quat.premultiply(parent.getWorldQuaternion(_invParentQuat).invert());
|
|
571
378
|
}
|
|
379
|
+
if (_quat.lengthSq() > 0) _quat.normalize();
|
|
380
|
+
else _quat.identity();
|
|
381
|
+
return [
|
|
382
|
+
_quat.x,
|
|
383
|
+
_quat.y,
|
|
384
|
+
_quat.z,
|
|
385
|
+
_quat.w
|
|
386
|
+
];
|
|
572
387
|
}
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
388
|
+
/**
|
|
389
|
+
* Resolves the physical hub shaft center of a wheel or propeller node:
|
|
390
|
+
* uses the authored glTF node origin (`getWorldPosition`) whenever the node has a non-zero transform
|
|
391
|
+
* or its local mesh bounds contain `(0, 0, 0)` (preventing 3-blade rotor / caliper AABB wobble),
|
|
392
|
+
* falling back to mesh AABB center only when an uncentered mesh was exported with its node left at `(0, 0, 0)`.
|
|
393
|
+
*/
|
|
394
|
+
function resolveRotorHubPosition(obj) {
|
|
395
|
+
obj.getWorldPosition(_wpA);
|
|
396
|
+
if (_wpA.lengthSq() > 1e-8) return [
|
|
397
|
+
_wpA.x,
|
|
398
|
+
_wpA.y,
|
|
399
|
+
_wpA.z
|
|
400
|
+
];
|
|
401
|
+
const invObj = obj.matrixWorld.clone().invert();
|
|
402
|
+
const rel = new THREE.Matrix4();
|
|
403
|
+
const v = new THREE.Vector3();
|
|
404
|
+
const localBox = new THREE.Box3();
|
|
405
|
+
obj.traverse((child) => {
|
|
406
|
+
const mesh = child;
|
|
407
|
+
if (!mesh.isMesh || !mesh.geometry) return;
|
|
408
|
+
const pos = mesh.geometry.getAttribute("position");
|
|
409
|
+
if (!pos) return;
|
|
410
|
+
rel.multiplyMatrices(invObj, mesh.matrixWorld);
|
|
411
|
+
for (let i = 0; i < pos.count; i++) localBox.expandByPoint(v.fromBufferAttribute(pos, i).applyMatrix4(rel));
|
|
412
|
+
});
|
|
413
|
+
if (localBox.isEmpty() || localBox.containsPoint(_localOrigin)) return [
|
|
414
|
+
_wpA.x,
|
|
415
|
+
_wpA.y,
|
|
416
|
+
_wpA.z
|
|
417
|
+
];
|
|
418
|
+
const c = new THREE.Box3().setFromObject(obj).getCenter(_wpB);
|
|
419
|
+
return [
|
|
420
|
+
c.x,
|
|
421
|
+
c.y,
|
|
422
|
+
c.z
|
|
423
|
+
];
|
|
577
424
|
}
|
|
578
|
-
function
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
if (
|
|
582
|
-
|
|
583
|
-
const box = isObj$1(raw.box) ? raw.box : {};
|
|
584
|
-
const size = box.size === void 0 ? [
|
|
585
|
-
1,
|
|
586
|
-
1,
|
|
587
|
-
1
|
|
588
|
-
] : box.size;
|
|
589
|
-
if (!Array.isArray(size) || size.length !== 3 || !size.every(isPos$2)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid box.size`);
|
|
590
|
-
return {
|
|
591
|
-
type: "box",
|
|
592
|
-
size: [
|
|
593
|
-
size[0],
|
|
594
|
-
size[1],
|
|
595
|
-
size[2]
|
|
596
|
-
]
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
if (type === "sphere") {
|
|
600
|
-
if (raw.sphere !== void 0 && !isObj$1(raw.sphere)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere`);
|
|
601
|
-
const sphere = isObj$1(raw.sphere) ? raw.sphere : {};
|
|
602
|
-
const radius = sphere.radius === void 0 ? .5 : sphere.radius;
|
|
603
|
-
if (!isPos$2(radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid sphere.radius`);
|
|
604
|
-
return {
|
|
605
|
-
type: "sphere",
|
|
606
|
-
radius
|
|
607
|
-
};
|
|
608
|
-
}
|
|
609
|
-
if (type === "cylinder" || type === "capsule") {
|
|
610
|
-
if (raw[type] !== void 0 && !isObj$1(raw[type])) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}`);
|
|
611
|
-
const g = isObj$1(raw[type]) ? raw[type] : {};
|
|
612
|
-
const height = g.height === void 0 ? type === "cylinder" ? 2 : 1 : g.height;
|
|
613
|
-
if (!isPos$2(height)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.height`);
|
|
614
|
-
if (g.radius !== void 0 && !isPos$2(g.radius)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radius`);
|
|
615
|
-
const baseR = g.radius === void 0 ? .5 : g.radius;
|
|
616
|
-
const radiusTop = g.radiusTop === void 0 ? baseR : g.radiusTop;
|
|
617
|
-
const radiusBottom = g.radiusBottom === void 0 ? baseR : g.radiusBottom;
|
|
618
|
-
if (!isPos$2(radiusTop)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusTop`);
|
|
619
|
-
if (!isPos$2(radiusBottom)) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] invalid ${type}.radiusBottom`);
|
|
620
|
-
if (Math.abs(radiusTop - radiusBottom) > 1e-6) throw new KhrValidationError(`KHR_implicit_shapes[${idx}] tapered ${type} (${radiusTop} !== ${radiusBottom}) is unsupported`);
|
|
621
|
-
return {
|
|
622
|
-
type,
|
|
623
|
-
height,
|
|
624
|
-
radiusTop,
|
|
625
|
-
radiusBottom
|
|
626
|
-
};
|
|
627
|
-
}
|
|
628
|
-
throw new KhrValidationError(`KHR_implicit_shapes[${idx}] unsupported shape type "${String(type)}"`);
|
|
425
|
+
function optRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
|
|
426
|
+
const val = obj[key];
|
|
427
|
+
if (val === void 0) return void 0;
|
|
428
|
+
if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
|
|
429
|
+
return val;
|
|
629
430
|
}
|
|
630
|
-
function
|
|
631
|
-
|
|
632
|
-
if (
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
const
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
431
|
+
function reqRotorNum(obj, key, tagKind, owner, strictlyPos = false) {
|
|
432
|
+
const val = obj[key];
|
|
433
|
+
if (!isFiniteNum(val) || (strictlyPos ? val <= 0 : val < 0)) throw new KhrValidationError(`${tagKind} "${owner}" is missing valid ${tagKind}.${key}`);
|
|
434
|
+
return val;
|
|
435
|
+
}
|
|
436
|
+
function optRotorBool(obj, key, tagKind, owner) {
|
|
437
|
+
const val = obj[key];
|
|
438
|
+
if (val === void 0) return void 0;
|
|
439
|
+
if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" has non-boolean ${tagKind}.${key}`);
|
|
440
|
+
return val;
|
|
441
|
+
}
|
|
442
|
+
function reqRotorBool(obj, key, tagKind, owner) {
|
|
443
|
+
const val = obj[key];
|
|
444
|
+
if (typeof val !== "boolean") throw new KhrValidationError(`${tagKind} "${owner}" is missing boolean ${tagKind}.${key}`);
|
|
445
|
+
return val;
|
|
446
|
+
}
|
|
447
|
+
function optBoolOrNumFlag(obj, key, tagKind, owner) {
|
|
448
|
+
const val = obj[key];
|
|
449
|
+
if (val === void 0) return void 0;
|
|
450
|
+
if (typeof val === "boolean") return { flag: val };
|
|
451
|
+
if (isNonNegNum(val)) return {
|
|
452
|
+
flag: val !== 0,
|
|
453
|
+
numeric: val
|
|
454
|
+
};
|
|
455
|
+
throw new KhrValidationError(`${tagKind} "${owner}" has invalid ${tagKind}.${key}`);
|
|
456
|
+
}
|
|
457
|
+
function optCurve(val, key, owner) {
|
|
458
|
+
if (val === void 0) return void 0;
|
|
459
|
+
if (!isObj(val) || !Array.isArray(val.points) || val.points.length === 0) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid ecctrlWheel.${key}`);
|
|
460
|
+
for (const pt of val.points) if (!isObj(pt) || !isFiniteNum(pt.x) || !isFiniteNum(pt.y)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid point in ecctrlWheel.${key}`);
|
|
461
|
+
if (val.samples !== void 0 && !isPosNum(val.samples)) throw new KhrValidationError(`ecctrlWheel "${owner}" has invalid samples in ecctrlWheel.${key}`);
|
|
462
|
+
return val;
|
|
463
|
+
}
|
|
464
|
+
function decodeWheelTag(obj, name, rawWheel, scene, rawOmiWheel) {
|
|
465
|
+
assertIdentityWorldScale(obj, name);
|
|
466
|
+
const hasOmi = rawOmiWheel !== void 0;
|
|
467
|
+
if (hasOmi && !isObj(rawOmiWheel)) throw new KhrValidationError(`OMI_vehicle_wheel "${name}" must be an object`);
|
|
468
|
+
if (rawWheel !== void 0 && !isObj(rawWheel)) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
|
|
469
|
+
if (!hasOmi && rawWheel === void 0) throw new KhrValidationError(`ecctrlWheel "${name}" must be an object`);
|
|
470
|
+
const ec = isObj(rawWheel) ? rawWheel : {};
|
|
471
|
+
const omi = isObj(rawOmiWheel) ? rawOmiWheel : void 0;
|
|
472
|
+
const omiRadius = omi ? optRotorNum(omi, "radius", "OMI_vehicle_wheel", name, true) : void 0;
|
|
473
|
+
const omiWidth = omi ? optRotorNum(omi, "width", "OMI_vehicle_wheel", name, true) : void 0;
|
|
474
|
+
const radius = optRotorNum(ec, "radius", "ecctrlWheel", name, true) ?? omiRadius;
|
|
475
|
+
const width = optRotorNum(ec, "width", "ecctrlWheel", name, true) ?? omiWidth;
|
|
476
|
+
if (radius === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite radius`);
|
|
477
|
+
if (width === void 0) throw new KhrValidationError(`Wheel "${name}" is missing positive finite width`);
|
|
478
|
+
const omiTravel = omi ? optRotorNum(omi, "suspensionTravel", "OMI_vehicle_wheel", name) : void 0;
|
|
479
|
+
const omiMaxForce = omi ? optRotorNum(omi, "maxForce", "OMI_vehicle_wheel", name) : void 0;
|
|
480
|
+
const omiMaxSteerRaw = omi ? optRotorNum(omi, "maxSteeringAngle", "OMI_vehicle_wheel", name) : void 0;
|
|
481
|
+
const omiStiffness = omi ? optRotorNum(omi, "suspensionStiffness", "OMI_vehicle_wheel", name) : void 0;
|
|
482
|
+
const omiDampComp = omi ? optRotorNum(omi, "suspensionDampingCompression", "OMI_vehicle_wheel", name) : void 0;
|
|
483
|
+
const omiDampReb = omi ? optRotorNum(omi, "suspensionDampingRebound", "OMI_vehicle_wheel", name) : void 0;
|
|
484
|
+
const omiSteer = omi ? optBoolOrNumFlag(omi, "steering", "OMI_vehicle_wheel", name) : void 0;
|
|
485
|
+
const omiProp = omi ? optBoolOrNumFlag(omi, "propulsion", "OMI_vehicle_wheel", name) : void 0;
|
|
486
|
+
const omiMaxSteer = omiMaxSteerRaw ?? (omiSteer?.numeric !== void 0 && omiSteer.numeric > 0 ? omiSteer.numeric : void 0);
|
|
487
|
+
const travel = omi ? optRotorNum(ec, "travel", "ecctrlWheel", name) ?? omiTravel ?? .25 : reqRotorNum(ec, "travel", "ecctrlWheel", name);
|
|
488
|
+
const sag = omi ? optRotorNum(ec, "sag", "ecctrlWheel", name) ?? (travel > 0 ? Math.min(travel * .4, .1) : 0) : reqRotorNum(ec, "sag", "ecctrlWheel", name);
|
|
489
|
+
if (sag > travel) throw new KhrValidationError(`ecctrlWheel "${name}" has invalid sag (${sag}) > travel (${travel})`);
|
|
490
|
+
const steer = omi ? optRotorBool(ec, "steer", "ecctrlWheel", name) ?? omiSteer?.flag ?? (omiMaxSteer !== void 0 ? omiMaxSteer > 0 : false) : reqRotorBool(ec, "steer", "ecctrlWheel", name);
|
|
491
|
+
const drive = omi ? optRotorBool(ec, "drive", "ecctrlWheel", name) ?? omiProp?.flag ?? false : reqRotorBool(ec, "drive", "ecctrlWheel", name);
|
|
492
|
+
const brake = omi ? optRotorBool(ec, "brake", "ecctrlWheel", name) ?? true : reqRotorBool(ec, "brake", "ecctrlWheel", name);
|
|
493
|
+
const omiDamping = omiDampComp !== void 0 && omiDampReb !== void 0 ? .5 * (omiDampComp + omiDampReb) : omiDampComp ?? omiDampReb;
|
|
494
|
+
const springK = optRotorNum(ec, "springK", "ecctrlWheel", name) ?? omiStiffness;
|
|
495
|
+
const dampingC = optRotorNum(ec, "dampingC", "ecctrlWheel", name) ?? omiDamping;
|
|
496
|
+
const maxBrakeTorque = optRotorNum(ec, "maxBrakeTorque", "ecctrlWheel", name) ?? (omiMaxForce !== void 0 ? omiMaxForce * radius : void 0);
|
|
497
|
+
const maxSteeringAngle = optRotorNum(ec, "maxSteeringAngle", "ecctrlWheel", name) ?? omiMaxSteer;
|
|
640
498
|
return {
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
499
|
+
nodeName: name,
|
|
500
|
+
object: obj,
|
|
501
|
+
position: resolveRotorHubPosition(obj),
|
|
502
|
+
quaternion: getRelativeQuatArray(obj, scene),
|
|
503
|
+
radius,
|
|
504
|
+
width,
|
|
505
|
+
steer,
|
|
506
|
+
steerInvert: optRotorBool(ec, "steerInvert", "ecctrlWheel", name),
|
|
507
|
+
drive,
|
|
508
|
+
driveInvert: optRotorBool(ec, "driveInvert", "ecctrlWheel", name),
|
|
509
|
+
brake,
|
|
510
|
+
travel,
|
|
511
|
+
sag,
|
|
512
|
+
springK,
|
|
513
|
+
dampingC,
|
|
514
|
+
maxBrakeTorque,
|
|
515
|
+
...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
|
|
516
|
+
rollingResistanceCoef: optRotorNum(ec, "rollingResistanceCoef", "ecctrlWheel", name),
|
|
517
|
+
wheelDensity: optRotorNum(ec, "wheelDensity", "ecctrlWheel", name, true),
|
|
518
|
+
driveTorqueWeight: optRotorNum(ec, "driveTorqueWeight", "ecctrlWheel", name),
|
|
519
|
+
tireGripFactor: optRotorNum(ec, "tireGripFactor", "ecctrlWheel", name),
|
|
520
|
+
latFrictionEllipseScale: optRotorNum(ec, "latFrictionEllipseScale", "ecctrlWheel", name),
|
|
521
|
+
relaxLngRate: optRotorNum(ec, "relaxLngRate", "ecctrlWheel", name),
|
|
522
|
+
relaxLatRate: optRotorNum(ec, "relaxLatRate", "ecctrlWheel", name),
|
|
523
|
+
lngSlipRatioCurveData: optCurve(ec.lngSlipRatioCurveData, "lngSlipRatioCurveData", name),
|
|
524
|
+
latSlipRatioCurveData: optCurve(ec.latSlipRatioCurveData, "latSlipRatioCurveData", name)
|
|
645
525
|
};
|
|
646
526
|
}
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
527
|
+
function decodePropellerTag(obj, name, rawPropeller, scene) {
|
|
528
|
+
assertIdentityWorldScale(obj, name);
|
|
529
|
+
if (!isObj(rawPropeller)) throw new KhrValidationError(`ecctrlPropeller "${name}" must be an object`);
|
|
530
|
+
if (!isPosNum(rawPropeller.maxThrust)) throw new KhrValidationError(`ecctrlPropeller "${name}" is missing positive finite ecctrlPropeller.maxThrust`);
|
|
531
|
+
const torqueRatio = optFiniteNum(rawPropeller.torqueRatio, `ecctrlPropeller "${name}".torqueRatio`);
|
|
532
|
+
return {
|
|
533
|
+
nodeName: name,
|
|
534
|
+
object: obj,
|
|
535
|
+
position: resolveRotorHubPosition(obj),
|
|
536
|
+
quaternion: getRelativeQuatArray(obj, scene),
|
|
537
|
+
maxThrust: rawPropeller.maxThrust,
|
|
538
|
+
torqueRatio,
|
|
539
|
+
invertThrust: optRotorBool(rawPropeller, "invertThrust", "ecctrlPropeller", name),
|
|
540
|
+
invertTorque: optRotorBool(rawPropeller, "invertTorque", "ecctrlPropeller", name)
|
|
541
|
+
};
|
|
655
542
|
}
|
|
656
|
-
function
|
|
657
|
-
if (
|
|
658
|
-
const
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
const
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
] : readFiniteVec3(motion.centerOfMass, `${name}.motion.centerOfMass`);
|
|
672
|
-
const inertiaOrientation = motion.inertiaOrientation === void 0 ? [
|
|
673
|
-
0,
|
|
674
|
-
0,
|
|
675
|
-
0,
|
|
676
|
-
1
|
|
677
|
-
] : readUnitQuat(motion.inertiaOrientation, `${name}.motion.inertiaOrientation`);
|
|
678
|
-
let inertiaDiagonal = [
|
|
679
|
-
0,
|
|
680
|
-
0,
|
|
681
|
-
0
|
|
543
|
+
function decodeBreakawaySpec(raw) {
|
|
544
|
+
if (!isObj(raw) || !isPosNum(raw.breakImpulseNs)) return void 0;
|
|
545
|
+
const latch = isPosNum(raw.latchImpulseNs) ? raw.latchImpulseNs : void 0;
|
|
546
|
+
return {
|
|
547
|
+
...latch === void 0 ? {} : { latchImpulseNs: latch },
|
|
548
|
+
breakImpulseNs: raw.breakImpulseNs
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
function collectNodeSockets(obj, name, extras, sockets, isSocketNode) {
|
|
552
|
+
if (extras.socketId !== void 0 && (typeof extras.socketId !== "string" || extras.socketId.length === 0)) throw new KhrValidationError(`Node "${name}" has invalid extras.socketId`);
|
|
553
|
+
obj.getWorldPosition(_wpA);
|
|
554
|
+
const worldPosition = [
|
|
555
|
+
_wpA.x,
|
|
556
|
+
_wpA.y,
|
|
557
|
+
_wpA.z
|
|
682
558
|
];
|
|
683
|
-
const
|
|
684
|
-
if (
|
|
685
|
-
|
|
686
|
-
|
|
559
|
+
const custom = isSocketNode?.(name, extras);
|
|
560
|
+
if (custom || extras.isIkAnchor === true || typeof extras.socketId === "string") {
|
|
561
|
+
const key = typeof custom === "string" && custom.length > 0 ? custom : typeof extras.socketId === "string" ? extras.socketId : name;
|
|
562
|
+
sockets[key] = [...worldPosition];
|
|
563
|
+
}
|
|
564
|
+
let contactDots;
|
|
565
|
+
if (extras.contactDots !== void 0) {
|
|
566
|
+
if (!Array.isArray(extras.contactDots)) throw new KhrValidationError(`Node "${name}" has invalid extras.contactDots (expected array)`);
|
|
567
|
+
obj.getWorldQuaternion(_dotQuat);
|
|
568
|
+
contactDots = [];
|
|
569
|
+
for (const dot of extras.contactDots) {
|
|
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`);
|
|
571
|
+
_dotVec.set(dot.pos[0], dot.pos[1], dot.pos[2]).applyQuaternion(_dotQuat).add(_wpA);
|
|
572
|
+
const dotPos = [
|
|
573
|
+
_dotVec.x,
|
|
574
|
+
_dotVec.y,
|
|
575
|
+
_dotVec.z
|
|
576
|
+
];
|
|
577
|
+
sockets[dot.role] = dotPos;
|
|
578
|
+
contactDots.push([dot.role, dotPos]);
|
|
579
|
+
}
|
|
687
580
|
}
|
|
688
|
-
const linearVelocity = motion.linearVelocity === void 0 ? void 0 : readFiniteVec3(motion.linearVelocity, `${name}.motion.linearVelocity`);
|
|
689
|
-
const angularVelocity = motion.angularVelocity === void 0 ? void 0 : readFiniteVec3(motion.angularVelocity, `${name}.motion.angularVelocity`);
|
|
690
|
-
const gravityFactor = optNum(motion.gravityFactor, `${name}.motion.gravityFactor`);
|
|
691
581
|
return {
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
inertiaOrientation,
|
|
697
|
-
hasExplicitInertia,
|
|
698
|
-
...linearVelocity ? { linearVelocity } : {},
|
|
699
|
-
...angularVelocity ? { angularVelocity } : {},
|
|
700
|
-
...gravityFactor === void 0 ? {} : { gravityFactor }
|
|
582
|
+
nodeName: name,
|
|
583
|
+
extras,
|
|
584
|
+
worldPosition,
|
|
585
|
+
...contactDots ? { contactDots } : {}
|
|
701
586
|
};
|
|
702
587
|
}
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
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;
|
|
721
629
|
}
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
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;
|
|
731
669
|
}
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
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;
|
|
738
730
|
}
|
|
731
|
+
// src/loader.ts
|
|
732
|
+
var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
|
|
739
733
|
var HEADLESS_TEXTURE_EXT_NAMES = [
|
|
740
734
|
"EXT_texture_webp",
|
|
741
735
|
"EXT_texture_avif",
|
|
742
736
|
"KHR_texture_basisu"
|
|
743
737
|
];
|
|
738
|
+
var _nodePos = new THREE.Vector3();
|
|
739
|
+
var _nodeQuat = new THREE.Quaternion();
|
|
744
740
|
function isHeadlessTextureEnv() {
|
|
745
741
|
return typeof document === "undefined" && (typeof createImageBitmap === "undefined" || typeof self === "undefined");
|
|
746
742
|
}
|
|
@@ -762,21 +758,42 @@ function patchHeadlessTexturePlugins(parser) {
|
|
|
762
758
|
};
|
|
763
759
|
}
|
|
764
760
|
}
|
|
765
|
-
function
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
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
|
+
}
|
|
774
791
|
}
|
|
775
|
-
function buildNodeGraphLookup(gltf, rawNodes, rawGltf
|
|
792
|
+
function buildNodeGraphLookup(gltf, rawNodes, rawGltf) {
|
|
776
793
|
const parentIdx = new Int32Array(rawNodes.length).fill(-1);
|
|
777
794
|
for (let i = 0; i < rawNodes.length; i++) {
|
|
778
795
|
const node = rawNodes[i];
|
|
779
|
-
if (!
|
|
796
|
+
if (!isObj(node)) throw new KhrValidationError(`GLTF node[${i}] must be an object`);
|
|
780
797
|
const label = typeof node.name === "string" && node.name.length > 0 ? node.name : String(i);
|
|
781
798
|
if (node.children !== void 0) {
|
|
782
799
|
if (!Array.isArray(node.children)) throw new KhrValidationError(`GLTF node "${label}" children must be an array`);
|
|
@@ -788,7 +805,7 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
|
|
|
788
805
|
if (Array.isArray(rawGltf?.scenes)) {
|
|
789
806
|
const sceneIdx = rawGltf.scene ?? 0;
|
|
790
807
|
const sceneDef = rawGltf.scenes[sceneIdx];
|
|
791
|
-
if (!
|
|
808
|
+
if (!isObj(sceneDef)) throw new KhrValidationError(`GLTF scene[${sceneIdx}] must be an object`);
|
|
792
809
|
if (sceneDef.nodes !== void 0 && !Array.isArray(sceneDef.nodes)) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes must be an array`);
|
|
793
810
|
sceneRoots = (sceneDef.nodes ?? []).map((n, pos) => {
|
|
794
811
|
if (typeof n !== "number" || !Number.isInteger(n) || n < 0 || n >= rawNodes.length) throw new KhrValidationError(`GLTF scene[${sceneIdx}].nodes[${pos}] has invalid node index ${String(n)}`);
|
|
@@ -839,20 +856,6 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
|
|
|
839
856
|
if (typeof nIdx === "number" && inActiveScene.has(nIdx) && !byNodeIdx.has(nIdx)) byNodeIdx.set(nIdx, obj);
|
|
840
857
|
if (obj.name && !byName.has(obj.name)) byName.set(obj.name, obj);
|
|
841
858
|
});
|
|
842
|
-
if (sceneRoots && gltf.scene.children.length === sceneRoots.length) {
|
|
843
|
-
const seen = /* @__PURE__ */ new Set();
|
|
844
|
-
const matchTree = (idx, obj) => {
|
|
845
|
-
if (seen.has(idx)) return;
|
|
846
|
-
seen.add(idx);
|
|
847
|
-
if (!byNodeIdx.has(idx)) byNodeIdx.set(idx, obj);
|
|
848
|
-
const children = rawNodes[idx].children;
|
|
849
|
-
if (!children || children.length === 0) return;
|
|
850
|
-
const offset = obj.children.length - children.length;
|
|
851
|
-
if (offset < 0) return;
|
|
852
|
-
for (let k = 0; k < children.length; k++) matchTree(children[k], obj.children[offset + k]);
|
|
853
|
-
};
|
|
854
|
-
for (let k = 0; k < sceneRoots.length; k++) matchTree(sceneRoots[k], gltf.scene.children[k]);
|
|
855
|
-
}
|
|
856
859
|
return {
|
|
857
860
|
parentIdx,
|
|
858
861
|
nodeNames,
|
|
@@ -866,32 +869,13 @@ function buildNodeGraphLookup(gltf, rawNodes, rawGltf = gltf.parser?.json) {
|
|
|
866
869
|
}
|
|
867
870
|
};
|
|
868
871
|
}
|
|
869
|
-
function resolveColliderShape(col, ownerName, shapes, nodeNames, resolveObj) {
|
|
870
|
-
if (!isPlainObject(col)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider (expected object)`);
|
|
871
|
-
const geo = col.geometry;
|
|
872
|
-
if (!isPlainObject(geo)) throw new KhrValidationError(`Node "${ownerName}" is missing collider.geometry object`);
|
|
873
|
-
if (geo.shape !== void 0) {
|
|
874
|
-
if (typeof geo.shape !== "number" || !Number.isInteger(geo.shape) || geo.shape < 0 || geo.shape >= shapes.length) throw new KhrValidationError(`Node "${ownerName}" references missing collider.geometry.shape ${String(geo.shape)}`);
|
|
875
|
-
return shapes[geo.shape];
|
|
876
|
-
}
|
|
877
|
-
if (geo.node !== void 0) {
|
|
878
|
-
if (typeof geo.node !== "number" || !Number.isInteger(geo.node)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider.geometry.node`);
|
|
879
|
-
if (geo.convexHull !== void 0 && typeof geo.convexHull !== "boolean") throw new KhrValidationError(`Node "${ownerName}" has non-boolean collider.geometry.convexHull`);
|
|
880
|
-
const target = resolveObj(geo.node);
|
|
881
|
-
const meshName = nodeNames[geo.node] ?? `node_${geo.node}`;
|
|
882
|
-
if (!target) throw new KhrValidationError(`Node "${ownerName}" references missing mesh node "${meshName}"`);
|
|
883
|
-
return extractMeshColliderShape(target, meshName, Boolean(geo.convexHull));
|
|
884
|
-
}
|
|
885
|
-
throw new KhrValidationError(`Node "${ownerName}" collider.geometry must specify shape or node`);
|
|
886
|
-
}
|
|
887
|
-
// src/khrBundleFinalize.ts
|
|
888
872
|
function findOwnerBodyIdx(idx, parentIdx, rawNodes) {
|
|
889
873
|
for (let p = parentIdx[idx]; p !== -1; p = parentIdx[p]) if (rawNodes[p].extensions?.KHR_physics_rigid_bodies?.motion) return p;
|
|
890
874
|
return -1;
|
|
891
875
|
}
|
|
892
876
|
function resolveConnectedBodyIdx(cIdx, parentIdx, rawNodes) {
|
|
893
877
|
const phys = rawNodes[cIdx]?.extensions?.KHR_physics_rigid_bodies;
|
|
894
|
-
if (
|
|
878
|
+
if (isObj(phys) && (phys.motion !== void 0 || (phys.collider !== void 0 || phys.joint !== void 0) && findOwnerBodyIdx(cIdx, parentIdx, rawNodes) === -1)) return cIdx;
|
|
895
879
|
const owner = findOwnerBodyIdx(cIdx, parentIdx, rawNodes);
|
|
896
880
|
return owner !== -1 ? owner : cIdx;
|
|
897
881
|
}
|
|
@@ -899,87 +883,41 @@ function isInsideRotor(idx, parentIdx, rawNodes) {
|
|
|
899
883
|
for (let p = idx; p !== -1; p = parentIdx[p]) {
|
|
900
884
|
const node = rawNodes[p];
|
|
901
885
|
const ex = node.extras;
|
|
902
|
-
if (
|
|
903
|
-
if (
|
|
886
|
+
if (isObj(ex) && (ex.ecctrlWheel !== void 0 || ex.ecctrlPropeller !== void 0)) return true;
|
|
887
|
+
if (isObj(node.extensions) && node.extensions.OMI_vehicle_wheel !== void 0) return true;
|
|
904
888
|
}
|
|
905
889
|
return false;
|
|
906
890
|
}
|
|
907
|
-
function
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
const ownerIdx = bodyByIdx.has(i) ? i : findOwnerBodyIdx(i, parentIdx, rawNodes);
|
|
915
|
-
const owner = bodyByIdx.get(ownerIdx);
|
|
916
|
-
if (!owner) continue;
|
|
917
|
-
const shape = resolveColliderShape(rawCol, nodeNames[i], shapes, nodeNames, resolveObj);
|
|
918
|
-
const colDef = rawCol;
|
|
919
|
-
const rel = ownerIdx === i ? {
|
|
920
|
-
localPosition: [
|
|
921
|
-
0,
|
|
922
|
-
0,
|
|
923
|
-
0
|
|
924
|
-
],
|
|
925
|
-
localQuaternion: [
|
|
926
|
-
0,
|
|
927
|
-
0,
|
|
928
|
-
0,
|
|
929
|
-
1
|
|
930
|
-
]
|
|
931
|
-
} : computeRelativePose(owner.object, obj);
|
|
932
|
-
const mat = decodePhysicsMaterial(materials, colDef.physicsMaterial, nodeNames[i]);
|
|
933
|
-
let colGroups;
|
|
934
|
-
if (colDef.collisionFilter !== void 0) {
|
|
935
|
-
if (typeof colDef.collisionFilter !== "number" || !Number.isInteger(colDef.collisionFilter) || colDef.collisionFilter < 0 || colDef.collisionFilter >= collisionGroups.length) throw new KhrValidationError(`Node "${nodeNames[i]}" references out-of-bounds collisionFilter ${String(colDef.collisionFilter)}`);
|
|
936
|
-
colGroups = collisionGroups[colDef.collisionFilter];
|
|
937
|
-
}
|
|
938
|
-
owner.colliders.push({
|
|
939
|
-
shape,
|
|
940
|
-
localPosition: rel.localPosition,
|
|
941
|
-
localQuaternion: rel.localQuaternion,
|
|
942
|
-
...mat,
|
|
943
|
-
...colGroups === void 0 ? {} : { collisionGroups: colGroups }
|
|
944
|
-
});
|
|
891
|
+
function resolveColliderShape(col, ownerName, shapes, nodeNames, resolveObj) {
|
|
892
|
+
if (!isObj(col)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider (expected object)`);
|
|
893
|
+
const geo = col.geometry;
|
|
894
|
+
if (!isObj(geo)) throw new KhrValidationError(`Node "${ownerName}" is missing collider.geometry object`);
|
|
895
|
+
if (geo.shape !== void 0) {
|
|
896
|
+
if (typeof geo.shape !== "number" || !Number.isInteger(geo.shape) || geo.shape < 0 || geo.shape >= shapes.length) throw new KhrValidationError(`Node "${ownerName}" references missing collider.geometry.shape ${String(geo.shape)}`);
|
|
897
|
+
return shapes[geo.shape];
|
|
945
898
|
}
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
if (sceneExtras?.ikSockets !== void 0) {
|
|
954
|
-
if (!isPlainObject(sceneExtras.ikSockets)) throw new KhrValidationError("scene.extras.ikSockets must be an object");
|
|
955
|
-
for (const [k, v] of Object.entries(sceneExtras.ikSockets)) {
|
|
956
|
-
const pos = readFiniteVec3(v, `scene.extras.ikSockets.${k}`);
|
|
957
|
-
setSocket(sockets, k, pos);
|
|
958
|
-
ikSockets.push([k, pos]);
|
|
959
|
-
}
|
|
899
|
+
if (geo.node !== void 0) {
|
|
900
|
+
if (typeof geo.node !== "number" || !Number.isInteger(geo.node)) throw new KhrValidationError(`Node "${ownerName}" has invalid collider.geometry.node`);
|
|
901
|
+
if (geo.convexHull !== void 0 && typeof geo.convexHull !== "boolean") throw new KhrValidationError(`Node "${ownerName}" has non-boolean collider.geometry.convexHull`);
|
|
902
|
+
const target = resolveObj(geo.node);
|
|
903
|
+
const meshName = nodeNames[geo.node] ?? `node_${geo.node}`;
|
|
904
|
+
if (!target) throw new KhrValidationError(`Node "${ownerName}" references missing mesh node "${meshName}"`);
|
|
905
|
+
return extractMeshColliderShape(target, meshName, Boolean(geo.convexHull));
|
|
960
906
|
}
|
|
961
|
-
|
|
962
|
-
ikSockets,
|
|
963
|
-
tune: isPlainObject(sceneExtras?.tune) ? sceneExtras.tune : void 0,
|
|
964
|
-
droneTune: isPlainObject(sceneExtras?.droneTune) ? sceneExtras.droneTune : void 0
|
|
965
|
-
};
|
|
907
|
+
throw new KhrValidationError(`Node "${ownerName}" collider.geometry must specify shape or node`);
|
|
966
908
|
}
|
|
967
|
-
// src/khrPlugin.ts
|
|
968
|
-
var KHR_BUNDLE_USERDATA_KEY = "khrBundle";
|
|
969
909
|
function extractKhrBundleFromGltf(gltf, options) {
|
|
970
910
|
if (!gltf.scene) throw new KhrValidationError("GLTF asset has no active scene");
|
|
971
|
-
gltf.scene.updateMatrixWorld(true);
|
|
972
911
|
assertSceneIdentityWorldScale(gltf.scene);
|
|
973
912
|
const json = gltf.parser?.json;
|
|
974
913
|
if (!json) throw new KhrValidationError("GLTFParser is missing parsed JSON");
|
|
975
|
-
if (json.extensions !== void 0 && !
|
|
914
|
+
if (json.extensions !== void 0 && !isObj(json.extensions)) throw new KhrValidationError("glTF extensions must be an object");
|
|
976
915
|
const khrPhys = json.extensions?.KHR_physics_rigid_bodies;
|
|
977
|
-
if (khrPhys !== void 0 && !
|
|
916
|
+
if (khrPhys !== void 0 && !isObj(khrPhys)) throw new KhrValidationError("KHR_physics_rigid_bodies extension must be an object");
|
|
978
917
|
const khrShapes = json.extensions?.KHR_implicit_shapes;
|
|
979
|
-
if (khrShapes !== void 0 && !
|
|
918
|
+
if (khrShapes !== void 0 && !isObj(khrShapes)) throw new KhrValidationError("KHR_implicit_shapes extension must be an object");
|
|
980
919
|
const omiExt = json.extensions?.OMI_vehicle_wheel;
|
|
981
|
-
if (omiExt !== void 0 && !
|
|
982
|
-
if (omiExt !== void 0 && !Array.isArray(omiExt.wheels)) throw new KhrValidationError("OMI_vehicle_wheel.wheels must be an array");
|
|
920
|
+
if (omiExt !== void 0 && (!isObj(omiExt) || !Array.isArray(omiExt.wheels))) throw new KhrValidationError("OMI_vehicle_wheel.wheels must be an array");
|
|
983
921
|
const omiWheels = omiExt ? omiExt.wheels : [];
|
|
984
922
|
const shapes = reqArr(khrShapes?.shapes, "KHR_implicit_shapes.shapes").map((s, i) => decodeShape(s, i));
|
|
985
923
|
const materials = reqArr(khrPhys?.physicsMaterials, "KHR_physics_rigid_bodies.physicsMaterials");
|
|
@@ -987,27 +925,19 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
987
925
|
const joints = reqArr(khrPhys?.physicsJoints, "KHR_physics_rigid_bodies.physicsJoints");
|
|
988
926
|
const rawNodes = reqArr(json.nodes, "glTF nodes");
|
|
989
927
|
const { parentIdx, nodeNames, resolveObj } = buildNodeGraphLookup(gltf, rawNodes, json);
|
|
990
|
-
gltf.scene.traverse((child) => {
|
|
991
|
-
if (child.userData && Object.getPrototypeOf(child.userData) !== Object.prototype) Object.setPrototypeOf(child.userData, Object.prototype);
|
|
992
|
-
});
|
|
993
928
|
const nodeMetas = [];
|
|
994
|
-
const sockets =
|
|
929
|
+
const sockets = Object.create(null);
|
|
995
930
|
for (let i = 0; i < rawNodes.length; i++) {
|
|
996
931
|
const obj = resolveObj(i);
|
|
997
932
|
if (!obj) continue;
|
|
998
|
-
if (Object.getPrototypeOf(obj.userData) !== Object.prototype) Object.setPrototypeOf(obj.userData, Object.prototype);
|
|
999
933
|
const rawExt = rawNodes[i].extensions;
|
|
1000
|
-
if (rawExt !== void 0 && !
|
|
1001
|
-
|
|
1002
|
-
if (Object.hasOwn(rawExt, "KOLMO_emitter") && rawExt.KOLMO_emitter !== void 0 && !Object.hasOwn(obj.userData, "KOLMO_emitter")) obj.userData.KOLMO_emitter = structuredClone(rawExt.KOLMO_emitter);
|
|
1003
|
-
}
|
|
1004
|
-
const extras = isPlainObject(rawNodes[i].extras) ? rawNodes[i].extras : {};
|
|
934
|
+
if (rawExt !== void 0 && !isObj(rawExt)) throw new KhrValidationError(`Node "${nodeNames[i]}" has invalid extensions`);
|
|
935
|
+
const extras = isObj(rawNodes[i].extras) ? rawNodes[i].extras : {};
|
|
1005
936
|
nodeMetas.push(collectNodeSockets(obj, nodeNames[i], extras, sockets, options?.isSocketNode));
|
|
1006
937
|
}
|
|
1007
938
|
const bodies = [];
|
|
1008
939
|
const bodyMetas = [];
|
|
1009
940
|
const bodyByIdx = /* @__PURE__ */ new Map();
|
|
1010
|
-
const explicitInertiaSet = /* @__PURE__ */ new Set();
|
|
1011
941
|
const wheels = [];
|
|
1012
942
|
const propellers = [];
|
|
1013
943
|
for (let i = 0; i < rawNodes.length; i++) {
|
|
@@ -1015,8 +945,8 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1015
945
|
const name = nodeNames[i];
|
|
1016
946
|
const obj = resolveObj(i);
|
|
1017
947
|
if (!obj) continue;
|
|
1018
|
-
const extras =
|
|
1019
|
-
const hasOmiWheel =
|
|
948
|
+
const extras = isObj(raw.extras) ? raw.extras : {};
|
|
949
|
+
const hasOmiWheel = isObj(raw.extensions) && raw.extensions.OMI_vehicle_wheel !== void 0;
|
|
1020
950
|
if (extras.ecctrlWheel !== void 0 || extras.ecctrlPropeller !== void 0 || hasOmiWheel) {
|
|
1021
951
|
if (parentIdx[i] !== -1 && isInsideRotor(parentIdx[i], parentIdx, rawNodes)) throw new KhrValidationError(`Nested rotor "${name}" inside detached rotor is unsupported`);
|
|
1022
952
|
if (extras.ecctrlPropeller !== void 0 && (extras.ecctrlWheel !== void 0 || hasOmiWheel)) throw new KhrValidationError(`Node "${name}" cannot be both wheel and propeller`);
|
|
@@ -1025,7 +955,7 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1025
955
|
let rawOmiWheel;
|
|
1026
956
|
if (hasOmiWheel) {
|
|
1027
957
|
const omiRef = raw.extensions.OMI_vehicle_wheel;
|
|
1028
|
-
if (!
|
|
958
|
+
if (!isObj(omiRef) || typeof omiRef.wheel !== "number" || !Number.isInteger(omiRef.wheel) || omiRef.wheel < 0 || omiRef.wheel >= omiWheels.length) throw new KhrValidationError(`Node "${name}" references invalid OMI_vehicle_wheel.wheel ${String(isObj(omiRef) ? omiRef.wheel : omiRef)}`);
|
|
1029
959
|
rawOmiWheel = omiWheels[omiRef.wheel];
|
|
1030
960
|
}
|
|
1031
961
|
wheels.push(decodeWheelTag(obj, name, extras.ecctrlWheel, gltf.scene, rawOmiWheel));
|
|
@@ -1035,19 +965,18 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1035
965
|
if (isInsideRotor(i, parentIdx, rawNodes)) continue;
|
|
1036
966
|
const phys = raw.extensions?.KHR_physics_rigid_bodies;
|
|
1037
967
|
if (phys === void 0) continue;
|
|
1038
|
-
if (!
|
|
968
|
+
if (!isObj(phys)) throw new KhrValidationError(`Node "${name}" has invalid KHR_physics_rigid_bodies`);
|
|
1039
969
|
if (phys.motion === void 0 && phys.collider === void 0 && phys.joint === void 0) continue;
|
|
1040
970
|
if (phys.motion === void 0 && findOwnerBodyIdx(i, parentIdx, rawNodes) !== -1) {
|
|
1041
971
|
if (phys.joint !== void 0) throw new KhrValidationError(`Node "${name}" has joint without motion`);
|
|
1042
972
|
continue;
|
|
1043
973
|
}
|
|
1044
|
-
if (phys.motion !== void 0 && !
|
|
1045
|
-
const
|
|
1046
|
-
if (hasExplicitInertia) explicitInertiaSet.add(i);
|
|
974
|
+
if (phys.motion !== void 0 && !isObj(phys.motion)) throw new KhrValidationError(`Node "${name}" has invalid motion`);
|
|
975
|
+
const motion = decodeMotion(phys.motion ?? {}, phys.motion !== void 0, name);
|
|
1047
976
|
const role = options?.extractRole?.(name, extras) ?? (typeof extras.role === "string" ? extras.role : null);
|
|
1048
977
|
let joint = null;
|
|
1049
978
|
if (phys.joint !== void 0) {
|
|
1050
|
-
if (!
|
|
979
|
+
if (!isObj(phys.joint)) throw new KhrValidationError(`Node "${name}" has invalid joint`);
|
|
1051
980
|
const rawJ = phys.joint;
|
|
1052
981
|
if (typeof rawJ.joint !== "number" || !Number.isInteger(rawJ.joint)) throw new KhrValidationError(`Joint on "${name}" is missing numeric joint index`);
|
|
1053
982
|
if (typeof rawJ.connectedNode !== "number" || !Number.isInteger(rawJ.connectedNode)) throw new KhrValidationError(`Joint on "${name}" is missing numeric connectedNode index`);
|
|
@@ -1059,22 +988,22 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1059
988
|
if (isInsideRotor(rawJ.connectedNode, parentIdx, rawNodes) || isInsideRotor(cIdx, parentIdx, rawNodes)) throw new KhrValidationError(`Joint on "${name}" cannot target detached rotor "${cName}"`);
|
|
1060
989
|
joint = decodeJoint(joints, rawJ.joint, name, cObj, obj, Boolean(rawJ.enableCollision), role, cName);
|
|
1061
990
|
}
|
|
1062
|
-
|
|
1063
|
-
|
|
991
|
+
obj.getWorldPosition(_nodePos);
|
|
992
|
+
obj.getWorldQuaternion(_nodeQuat);
|
|
1064
993
|
const breakaway = decodeBreakawaySpec(extras.breakaway);
|
|
1065
994
|
const spec = {
|
|
1066
995
|
nodeName: name,
|
|
1067
996
|
...motion,
|
|
1068
997
|
localPosition: [
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
998
|
+
_nodePos.x,
|
|
999
|
+
_nodePos.y,
|
|
1000
|
+
_nodePos.z
|
|
1072
1001
|
],
|
|
1073
1002
|
localQuaternion: [
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1003
|
+
_nodeQuat.x,
|
|
1004
|
+
_nodeQuat.y,
|
|
1005
|
+
_nodeQuat.z,
|
|
1006
|
+
_nodeQuat.w
|
|
1078
1007
|
],
|
|
1079
1008
|
colliders: [],
|
|
1080
1009
|
joint,
|
|
@@ -1089,11 +1018,59 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1089
1018
|
});
|
|
1090
1019
|
bodyByIdx.set(i, spec);
|
|
1091
1020
|
}
|
|
1092
|
-
|
|
1093
|
-
|
|
1021
|
+
for (let i = 0; i < rawNodes.length; i++) {
|
|
1022
|
+
if (isInsideRotor(i, parentIdx, rawNodes)) continue;
|
|
1023
|
+
const rawCol = rawNodes[i].extensions?.KHR_physics_rigid_bodies?.collider;
|
|
1024
|
+
if (rawCol === void 0) continue;
|
|
1025
|
+
const obj = resolveObj(i);
|
|
1026
|
+
if (!obj) continue;
|
|
1027
|
+
const ownerIdx = bodyByIdx.has(i) ? i : findOwnerBodyIdx(i, parentIdx, rawNodes);
|
|
1028
|
+
const owner = bodyByIdx.get(ownerIdx);
|
|
1029
|
+
if (!owner) continue;
|
|
1030
|
+
const shape = resolveColliderShape(rawCol, nodeNames[i], shapes, nodeNames, resolveObj);
|
|
1031
|
+
const colDef = rawCol;
|
|
1032
|
+
const rel = ownerIdx === i ? {
|
|
1033
|
+
localPosition: [
|
|
1034
|
+
0,
|
|
1035
|
+
0,
|
|
1036
|
+
0
|
|
1037
|
+
],
|
|
1038
|
+
localQuaternion: [
|
|
1039
|
+
0,
|
|
1040
|
+
0,
|
|
1041
|
+
0,
|
|
1042
|
+
1
|
|
1043
|
+
]
|
|
1044
|
+
} : computeRelativePose(owner.object, obj);
|
|
1045
|
+
const mat = decodePhysicsMaterial(materials, colDef.physicsMaterial, nodeNames[i]);
|
|
1046
|
+
let colGroups;
|
|
1047
|
+
if (colDef.collisionFilter !== void 0) {
|
|
1048
|
+
if (typeof colDef.collisionFilter !== "number" || !Number.isInteger(colDef.collisionFilter) || colDef.collisionFilter < 0 || colDef.collisionFilter >= collisionGroups.length) throw new KhrValidationError(`Node "${nodeNames[i]}" references out-of-bounds collisionFilter ${String(colDef.collisionFilter)}`);
|
|
1049
|
+
colGroups = collisionGroups[colDef.collisionFilter];
|
|
1050
|
+
}
|
|
1051
|
+
owner.colliders.push({
|
|
1052
|
+
shape,
|
|
1053
|
+
localPosition: rel.localPosition,
|
|
1054
|
+
localQuaternion: rel.localQuaternion,
|
|
1055
|
+
...mat,
|
|
1056
|
+
...colGroups === void 0 ? {} : { collisionGroups: colGroups }
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
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`);
|
|
1094
1060
|
const { totalDynamicMass, centerOfMass } = computeAssemblyMassAndCom(bodies);
|
|
1095
|
-
const
|
|
1096
|
-
|
|
1061
|
+
const ikSockets = [];
|
|
1062
|
+
const sceneExtras = json.scenes?.[json.scene ?? 0]?.extras ?? json.extras;
|
|
1063
|
+
if (sceneExtras?.ikSockets !== void 0) {
|
|
1064
|
+
if (!isObj(sceneExtras.ikSockets)) throw new KhrValidationError("scene.extras.ikSockets must be an object");
|
|
1065
|
+
for (const [k, v] of Object.entries(sceneExtras.ikSockets)) {
|
|
1066
|
+
const pos = readFiniteVec3(v, `scene.extras.ikSockets.${k}`);
|
|
1067
|
+
sockets[k] = pos;
|
|
1068
|
+
ikSockets.push([k, pos]);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
const tune = isObj(sceneExtras?.tune) ? sceneExtras.tune : isObj(sceneExtras?.ecctrl) ? sceneExtras.ecctrl : void 0;
|
|
1072
|
+
const droneTune = isObj(sceneExtras?.droneTune) ? sceneExtras.droneTune : void 0;
|
|
1073
|
+
templateMetaMap.set(gltf.scene, {
|
|
1097
1074
|
nodes: nodeMetas,
|
|
1098
1075
|
bodies: bodyMetas,
|
|
1099
1076
|
ikSockets
|
|
@@ -1106,8 +1083,8 @@ function extractKhrBundleFromGltf(gltf, options) {
|
|
|
1106
1083
|
sockets,
|
|
1107
1084
|
totalDynamicMass,
|
|
1108
1085
|
centerOfMass,
|
|
1109
|
-
tune,
|
|
1110
|
-
droneTune
|
|
1086
|
+
...tune ? { tune } : {},
|
|
1087
|
+
...droneTune ? { droneTune } : {}
|
|
1111
1088
|
};
|
|
1112
1089
|
}
|
|
1113
1090
|
function createKhrGltfPlugin(options) {
|
|
@@ -1128,27 +1105,16 @@ function createKhrGltfPlugin(options) {
|
|
|
1128
1105
|
};
|
|
1129
1106
|
};
|
|
1130
1107
|
}
|
|
1131
|
-
// src/khrLoader.ts
|
|
1132
|
-
var headlessPlugin$1 = createHeadlessTexturePlugin();
|
|
1133
|
-
function createDefaultGltfLoader() {
|
|
1134
|
-
const loader = new GLTFLoader();
|
|
1135
|
-
if (isHeadlessTextureEnv()) loader.register(headlessPlugin$1);
|
|
1136
|
-
return loader;
|
|
1137
|
-
}
|
|
1138
1108
|
async function loadKhrGlb(source, options) {
|
|
1139
|
-
const
|
|
1140
|
-
const buf = new ArrayBuffer(bytes.byteLength);
|
|
1141
|
-
new Uint8Array(buf).set(bytes);
|
|
1109
|
+
const buf = source instanceof ArrayBuffer ? source : source.byteOffset === 0 && source.byteLength === source.buffer.byteLength && source.buffer instanceof ArrayBuffer ? source.buffer : source.buffer.slice(source.byteOffset, source.byteOffset + source.byteLength);
|
|
1142
1110
|
validateGlbHeader(buf);
|
|
1143
|
-
const loader = options?.loader ??
|
|
1111
|
+
const loader = options?.loader ?? new GLTFLoader();
|
|
1144
1112
|
const plugin = createKhrGltfPlugin(options);
|
|
1145
1113
|
loader.register(plugin);
|
|
1146
1114
|
try {
|
|
1147
1115
|
const toErr = (err) => err instanceof KhrValidationError ? err : new KhrValidationError(err instanceof Error ? err.message : "Failed to parse GLB");
|
|
1148
1116
|
const bundle = (await new Promise((resolve, reject) => {
|
|
1149
1117
|
loader.parse(buf, "", resolve, (err) => reject(toErr(err)));
|
|
1150
|
-
}).catch((err) => {
|
|
1151
|
-
throw toErr(err);
|
|
1152
1118
|
})).userData[KHR_BUNDLE_USERDATA_KEY];
|
|
1153
1119
|
if (!bundle) throw new KhrValidationError("Missing parsed KHR bundle on GLTF userData");
|
|
1154
1120
|
return bundle;
|
|
@@ -1156,21 +1122,7 @@ async function loadKhrGlb(source, options) {
|
|
|
1156
1122
|
loader.unregister(plugin);
|
|
1157
1123
|
}
|
|
1158
1124
|
}
|
|
1159
|
-
// src/
|
|
1160
|
-
var isPosNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
1161
|
-
var isObj = (v) => typeof v === "object" && !!v && !Array.isArray(v);
|
|
1162
|
-
var COMBINE_MODES = /* @__PURE__ */ new Set([
|
|
1163
|
-
"average",
|
|
1164
|
-
"minimum",
|
|
1165
|
-
"maximum",
|
|
1166
|
-
"multiply"
|
|
1167
|
-
]);
|
|
1168
|
-
function optFinite(v, label, nonNeg = false) {
|
|
1169
|
-
if (v !== void 0) {
|
|
1170
|
-
if (typeof v !== "number" || !Number.isFinite(v) || nonNeg && v < 0) throw new KhrValidationError(`exportKhrGlb: ${label} must be finite${nonNeg ? " >= 0" : ""}`);
|
|
1171
|
-
return v;
|
|
1172
|
-
}
|
|
1173
|
-
}
|
|
1125
|
+
// src/exporter.ts
|
|
1174
1126
|
function encodeShape(shape, nodeName) {
|
|
1175
1127
|
if (shape.type === "box") {
|
|
1176
1128
|
if (!Array.isArray(shape.size) || shape.size.length !== 3 || !shape.size.every(isPosNum)) throw new KhrValidationError(`exportKhrGlb: invalid box.size on "${nodeName}"`);
|
|
@@ -1198,7 +1150,7 @@ function encodeShape(shape, nodeName) {
|
|
|
1198
1150
|
};
|
|
1199
1151
|
}
|
|
1200
1152
|
function normalizeJointAxis(axis, kind, nodeName) {
|
|
1201
|
-
if (!Array.isArray(axis) || axis.length !== 3 || !axis.every(
|
|
1153
|
+
if (!Array.isArray(axis) || axis.length !== 3 || !axis.every(isFiniteNum)) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires a finite axis`);
|
|
1202
1154
|
const len = Math.hypot(axis[0], axis[1], axis[2]);
|
|
1203
1155
|
if (len <= 1e-8) throw new KhrValidationError(`exportKhrGlb: ${kind} joint on "${nodeName}" requires non-zero axis`);
|
|
1204
1156
|
const ux = axis[0] / len, uy = axis[1] / len, uz = axis[2] / len;
|
|
@@ -1219,12 +1171,12 @@ function encodeJointDrive(drive, defaultType, defaultAxis, nodeName) {
|
|
|
1219
1171
|
if (drive.mode !== "force" && drive.mode !== "acceleration") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires drive.mode ("force" | "acceleration")`);
|
|
1220
1172
|
if (drive.type !== void 0 && drive.type !== "linear" && drive.type !== "angular") throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.type`);
|
|
1221
1173
|
if (drive.axis !== void 0 && drive.axis !== 0 && drive.axis !== 1 && drive.axis !== 2) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" has invalid drive.axis`);
|
|
1222
|
-
const positionTarget =
|
|
1223
|
-
const velocityTarget =
|
|
1174
|
+
const positionTarget = optFiniteNum(drive.positionTarget, `joint drive.positionTarget on "${nodeName}"`);
|
|
1175
|
+
const velocityTarget = optFiniteNum(drive.velocityTarget, `joint drive.velocityTarget on "${nodeName}"`);
|
|
1224
1176
|
if (positionTarget === void 0 && velocityTarget === void 0) throw new KhrValidationError(`exportKhrGlb: joint drive on "${nodeName}" requires finite positionTarget or velocityTarget`);
|
|
1225
|
-
const stiffness =
|
|
1226
|
-
const damping =
|
|
1227
|
-
const maxForce =
|
|
1177
|
+
const stiffness = optFiniteNum(drive.stiffness, `joint drive.stiffness on "${nodeName}"`, true);
|
|
1178
|
+
const damping = optFiniteNum(drive.damping, `joint drive.damping on "${nodeName}"`, true);
|
|
1179
|
+
const maxForce = optFiniteNum(drive.maxForce, `joint drive.maxForce on "${nodeName}"`, true);
|
|
1228
1180
|
return {
|
|
1229
1181
|
type: drive.type ?? defaultType,
|
|
1230
1182
|
mode: drive.mode,
|
|
@@ -1265,8 +1217,8 @@ function encodeJoint(j, nodeName) {
|
|
|
1265
1217
|
2
|
|
1266
1218
|
].filter((i) => i !== ax);
|
|
1267
1219
|
if (j.limits && (!Number.isFinite(j.limits[0]) || !Number.isFinite(j.limits[1]) || j.limits[0] > j.limits[1])) throw new KhrValidationError(`exportKhrGlb: joint on "${nodeName}" has invalid joint.limits`);
|
|
1268
|
-
const stiffness =
|
|
1269
|
-
const damping =
|
|
1220
|
+
const stiffness = optFiniteNum(j.limitStiffness, `joint.limitStiffness on "${nodeName}"`, true);
|
|
1221
|
+
const damping = optFiniteNum(j.limitDamping, `joint.limitDamping on "${nodeName}"`, true);
|
|
1270
1222
|
const freeKey = j.kind === "revolute" ? "angularAxes" : "linearAxes";
|
|
1271
1223
|
const freeLimit = j.limits || stiffness !== void 0 || damping !== void 0 ? [{
|
|
1272
1224
|
[freeKey]: [ax],
|
|
@@ -1320,9 +1272,9 @@ function encodeJoint(j, nodeName) {
|
|
|
1320
1272
|
function encodeMotion(m, nodeName) {
|
|
1321
1273
|
const isKinematic = Boolean(m.isKinematic);
|
|
1322
1274
|
if (!isKinematic && !isPosNum(m.mass)) throw new KhrValidationError(`exportKhrGlb: dynamic node "${nodeName}" requires positive finite motion.mass`);
|
|
1323
|
-
if (isKinematic && m.mass !== void 0)
|
|
1275
|
+
if (isKinematic && m.mass !== void 0) optFiniteNum(m.mass, `kinematic motion.mass on "${nodeName}"`, true);
|
|
1324
1276
|
if (m.inertiaDiagonal && readFiniteVec3(m.inertiaDiagonal, `${nodeName}.motion.inertiaDiagonal`).some((n) => isKinematic ? n < 0 : n <= 0)) throw new KhrValidationError(`exportKhrGlb: invalid motion.inertiaDiagonal on "${nodeName}"`);
|
|
1325
|
-
|
|
1277
|
+
const gravityFactor = optFiniteNum(m.gravityFactor, `motion.gravityFactor on "${nodeName}"`);
|
|
1326
1278
|
return {
|
|
1327
1279
|
isKinematic,
|
|
1328
1280
|
...m.mass === void 0 ? {} : { mass: m.mass },
|
|
@@ -1331,12 +1283,12 @@ function encodeMotion(m, nodeName) {
|
|
|
1331
1283
|
...m.inertiaOrientation ? { inertiaOrientation: readUnitQuat(m.inertiaOrientation, `${nodeName}.motion.inertiaOrientation`) } : {},
|
|
1332
1284
|
...m.linearVelocity ? { linearVelocity: readFiniteVec3(m.linearVelocity, `${nodeName}.motion.linearVelocity`) } : {},
|
|
1333
1285
|
...m.angularVelocity ? { angularVelocity: readFiniteVec3(m.angularVelocity, `${nodeName}.motion.angularVelocity`) } : {},
|
|
1334
|
-
...
|
|
1286
|
+
...gravityFactor === void 0 ? {} : { gravityFactor }
|
|
1335
1287
|
};
|
|
1336
1288
|
}
|
|
1337
1289
|
function encodePhysicsMaterial(col, nodeName) {
|
|
1338
|
-
const friction =
|
|
1339
|
-
const restitution =
|
|
1290
|
+
const friction = optFiniteNum(col.friction, `collider.friction on "${nodeName}"`, true);
|
|
1291
|
+
const restitution = optFiniteNum(col.restitution, `collider.restitution on "${nodeName}"`, true);
|
|
1340
1292
|
for (const [k, v] of [["frictionCombine", col.frictionCombine], ["restitutionCombine", col.restitutionCombine]]) if (v !== void 0 && (typeof v !== "string" || !COMBINE_MODES.has(v))) throw new KhrValidationError(`exportKhrGlb: invalid collider.${k} "${String(v)}" on "${nodeName}"`);
|
|
1341
1293
|
if (friction === void 0 && restitution === void 0 && col.frictionCombine === void 0 && col.restitutionCombine === void 0) return null;
|
|
1342
1294
|
return {
|
|
@@ -1349,17 +1301,17 @@ function encodePhysicsMaterial(col, nodeName) {
|
|
|
1349
1301
|
...col.restitutionCombine === void 0 ? {} : { restitutionCombine: col.restitutionCombine }
|
|
1350
1302
|
};
|
|
1351
1303
|
}
|
|
1352
|
-
function
|
|
1304
|
+
function validateCanonicalSystems(arr, label, nodeName) {
|
|
1353
1305
|
if (!Array.isArray(arr) || arr.some((s) => typeof s !== "string" || s.length === 0)) throw new KhrValidationError(`exportKhrGlb: collider.${label} on "${nodeName}" must be an array of non-empty strings`);
|
|
1354
|
-
return arr;
|
|
1306
|
+
return [...new Set(arr)];
|
|
1355
1307
|
}
|
|
1356
1308
|
function encodeCollisionFilter(col, nodeName) {
|
|
1357
1309
|
if (col.collideWithSystems !== void 0 && col.notCollideWithSystems !== void 0) throw new KhrValidationError(`exportKhrGlb: collider on "${nodeName}" cannot specify both collideWithSystems and notCollideWithSystems`);
|
|
1358
1310
|
if (col.collisionSystems === void 0 && col.collideWithSystems === void 0 && col.notCollideWithSystems === void 0) return null;
|
|
1359
1311
|
return {
|
|
1360
|
-
...col.collisionSystems === void 0 ? {} : { collisionSystems:
|
|
1361
|
-
...col.collideWithSystems === void 0 ? {} : { collideWithSystems:
|
|
1362
|
-
...col.notCollideWithSystems === void 0 ? {} : { notCollideWithSystems:
|
|
1312
|
+
...col.collisionSystems === void 0 ? {} : { collisionSystems: validateCanonicalSystems(col.collisionSystems, "collisionSystems", nodeName) },
|
|
1313
|
+
...col.collideWithSystems === void 0 ? {} : { collideWithSystems: validateCanonicalSystems(col.collideWithSystems, "collideWithSystems", nodeName) },
|
|
1314
|
+
...col.notCollideWithSystems === void 0 ? {} : { notCollideWithSystems: validateCanonicalSystems(col.notCollideWithSystems, "notCollideWithSystems", nodeName) }
|
|
1363
1315
|
};
|
|
1364
1316
|
}
|
|
1365
1317
|
function encodeOmiWheel(wheel, nodeName) {
|
|
@@ -1367,12 +1319,12 @@ function encodeOmiWheel(wheel, nodeName) {
|
|
|
1367
1319
|
if (!isPosNum(wheel.radius)) throw new KhrValidationError(`exportKhrGlb: wheel.radius on "${nodeName}" must be > 0`);
|
|
1368
1320
|
if (!isPosNum(wheel.width)) throw new KhrValidationError(`exportKhrGlb: wheel.width on "${nodeName}" must be > 0`);
|
|
1369
1321
|
for (const [k, v] of [["steering", wheel.steering], ["propulsion", wheel.propulsion]]) if (v !== void 0 && typeof v !== "boolean") throw new KhrValidationError(`exportKhrGlb: wheel.${k} on "${nodeName}" must be boolean`);
|
|
1370
|
-
const maxForce =
|
|
1371
|
-
const maxSteeringAngle =
|
|
1372
|
-
const suspensionStiffness =
|
|
1373
|
-
const suspensionDampingCompression =
|
|
1374
|
-
const suspensionDampingRebound =
|
|
1375
|
-
const suspensionTravel =
|
|
1322
|
+
const maxForce = optFiniteNum(wheel.maxForce, `wheel.maxForce on "${nodeName}"`, true);
|
|
1323
|
+
const maxSteeringAngle = optFiniteNum(wheel.maxSteeringAngle, `wheel.maxSteeringAngle on "${nodeName}"`, true);
|
|
1324
|
+
const suspensionStiffness = optFiniteNum(wheel.suspensionStiffness, `wheel.suspensionStiffness on "${nodeName}"`, true);
|
|
1325
|
+
const suspensionDampingCompression = optFiniteNum(wheel.suspensionDampingCompression, `wheel.suspensionDampingCompression on "${nodeName}"`, true);
|
|
1326
|
+
const suspensionDampingRebound = optFiniteNum(wheel.suspensionDampingRebound, `wheel.suspensionDampingRebound on "${nodeName}"`, true);
|
|
1327
|
+
const suspensionTravel = optFiniteNum(wheel.suspensionTravel, `wheel.suspensionTravel on "${nodeName}"`, true);
|
|
1376
1328
|
return {
|
|
1377
1329
|
radius: wheel.radius,
|
|
1378
1330
|
width: wheel.width,
|
|
@@ -1386,24 +1338,20 @@ function encodeOmiWheel(wheel, nodeName) {
|
|
|
1386
1338
|
...suspensionTravel === void 0 ? {} : { suspensionTravel }
|
|
1387
1339
|
};
|
|
1388
1340
|
}
|
|
1389
|
-
// src/khrExporter.ts
|
|
1390
|
-
var isPos = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
1391
|
-
var isNonNeg = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
|
|
1392
1341
|
function synthesizeOmiWheel(raw) {
|
|
1393
|
-
if (!
|
|
1394
|
-
|
|
1395
|
-
if (
|
|
1396
|
-
|
|
1397
|
-
const
|
|
1398
|
-
const
|
|
1399
|
-
const
|
|
1400
|
-
const maxSteeringAngle = isNonNeg(ec.maxSteeringAngle) ? ec.maxSteeringAngle : void 0;
|
|
1342
|
+
if (!isObj(raw)) return null;
|
|
1343
|
+
if (!isPosNum(raw.radius) || !isPosNum(raw.width) || !isNonNegNum(raw.travel) || !isNonNegNum(raw.sag) || raw.sag > raw.travel) return null;
|
|
1344
|
+
if (typeof raw.steer !== "boolean" || typeof raw.drive !== "boolean" || typeof raw.brake !== "boolean") return null;
|
|
1345
|
+
const springK = isNonNegNum(raw.springK) ? raw.springK : void 0;
|
|
1346
|
+
const dampingC = isNonNegNum(raw.dampingC) ? raw.dampingC : void 0;
|
|
1347
|
+
const maxForce = isNonNegNum(raw.maxBrakeTorque) ? raw.maxBrakeTorque / raw.radius : void 0;
|
|
1348
|
+
const maxSteeringAngle = isNonNegNum(raw.maxSteeringAngle) ? raw.maxSteeringAngle : void 0;
|
|
1401
1349
|
return {
|
|
1402
|
-
radius:
|
|
1403
|
-
width:
|
|
1404
|
-
steering:
|
|
1405
|
-
propulsion:
|
|
1406
|
-
suspensionTravel:
|
|
1350
|
+
radius: raw.radius,
|
|
1351
|
+
width: raw.width,
|
|
1352
|
+
steering: raw.steer,
|
|
1353
|
+
propulsion: raw.drive,
|
|
1354
|
+
suspensionTravel: raw.travel,
|
|
1407
1355
|
...maxForce === void 0 ? {} : { maxForce },
|
|
1408
1356
|
...maxSteeringAngle === void 0 ? {} : { maxSteeringAngle },
|
|
1409
1357
|
...springK === void 0 ? {} : { suspensionStiffness: springK },
|
|
@@ -1413,39 +1361,87 @@ function synthesizeOmiWheel(raw) {
|
|
|
1413
1361
|
}
|
|
1414
1362
|
};
|
|
1415
1363
|
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1364
|
+
/**
|
|
1365
|
+
* Replaces meshes' material references with shallow material clones ONLY when an unloaded headless Texture
|
|
1366
|
+
* (`!tex.image`) is present, keeping live WebGL materials untouched across async export.
|
|
1367
|
+
*/
|
|
1368
|
+
function isolateUnloadedTextures(root) {
|
|
1369
|
+
const swaps = [];
|
|
1370
|
+
const clonedByMat = /* @__PURE__ */ new Map();
|
|
1371
|
+
const sanitizeMat = (mat) => {
|
|
1372
|
+
const cached = clonedByMat.get(mat);
|
|
1373
|
+
if (cached) return cached;
|
|
1374
|
+
const rec = mat;
|
|
1375
|
+
let hasUnloaded = false;
|
|
1376
|
+
for (const slot of Object.keys(rec)) {
|
|
1377
|
+
const val = rec[slot];
|
|
1378
|
+
if (val && typeof val === "object" && val.isTexture && !val.image) {
|
|
1379
|
+
hasUnloaded = true;
|
|
1380
|
+
break;
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
if (!hasUnloaded) return mat;
|
|
1384
|
+
const clone = mat.clone();
|
|
1385
|
+
const cloneRec = clone;
|
|
1386
|
+
for (const slot of Object.keys(cloneRec)) {
|
|
1387
|
+
const val = cloneRec[slot];
|
|
1388
|
+
if (val && typeof val === "object" && val.isTexture && !val.image) cloneRec[slot] = null;
|
|
1389
|
+
}
|
|
1390
|
+
clonedByMat.set(mat, clone);
|
|
1391
|
+
return clone;
|
|
1392
|
+
};
|
|
1418
1393
|
root.traverse((obj) => {
|
|
1419
|
-
const
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
const
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1394
|
+
const mesh = obj;
|
|
1395
|
+
if (!mesh.isMesh || !mesh.material) return;
|
|
1396
|
+
if (Array.isArray(mesh.material)) {
|
|
1397
|
+
const next = mesh.material.map(sanitizeMat);
|
|
1398
|
+
if (next.some((m, idx) => m !== mesh.material[idx])) {
|
|
1399
|
+
swaps.push({
|
|
1400
|
+
mesh,
|
|
1401
|
+
origMat: mesh.material,
|
|
1402
|
+
clones: next.filter((m, idx) => m !== mesh.material[idx])
|
|
1403
|
+
});
|
|
1404
|
+
mesh.material = next;
|
|
1405
|
+
}
|
|
1406
|
+
} else {
|
|
1407
|
+
const next = sanitizeMat(mesh.material);
|
|
1408
|
+
if (next !== mesh.material) {
|
|
1409
|
+
swaps.push({
|
|
1410
|
+
mesh,
|
|
1411
|
+
origMat: mesh.material,
|
|
1412
|
+
clones: [next]
|
|
1413
|
+
});
|
|
1414
|
+
mesh.material = next;
|
|
1433
1415
|
}
|
|
1434
1416
|
}
|
|
1435
1417
|
});
|
|
1436
|
-
return
|
|
1418
|
+
return swaps;
|
|
1419
|
+
}
|
|
1420
|
+
function internJson(table, map, item) {
|
|
1421
|
+
const key = JSON.stringify(item);
|
|
1422
|
+
let idx = map.get(key);
|
|
1423
|
+
if (idx === void 0) {
|
|
1424
|
+
idx = table.length;
|
|
1425
|
+
table.push(item);
|
|
1426
|
+
map.set(key, idx);
|
|
1427
|
+
}
|
|
1428
|
+
return idx;
|
|
1437
1429
|
}
|
|
1438
1430
|
async function exportKhrGlb(root, specs, sceneExtras) {
|
|
1439
1431
|
ensureHeadlessFileReader();
|
|
1440
|
-
root
|
|
1432
|
+
const exportRoot = snapshotSceneWithMountedSubtrees(root);
|
|
1433
|
+
exportRoot.updateMatrixWorld(true);
|
|
1441
1434
|
const exporter = new GLTFExporter();
|
|
1442
|
-
const
|
|
1435
|
+
const swaps = isolateUnloadedTextures(exportRoot);
|
|
1443
1436
|
let rawBuf;
|
|
1444
1437
|
try {
|
|
1445
|
-
const res = await exporter.parseAsync(
|
|
1438
|
+
const res = await exporter.parseAsync(exportRoot, { binary: true });
|
|
1446
1439
|
rawBuf = res instanceof ArrayBuffer ? res : packJsonToGlb(res);
|
|
1447
1440
|
} finally {
|
|
1448
|
-
for (const
|
|
1441
|
+
for (const s of swaps) {
|
|
1442
|
+
s.mesh.material = s.origMat;
|
|
1443
|
+
for (const c of s.clones) c.dispose();
|
|
1444
|
+
}
|
|
1449
1445
|
}
|
|
1450
1446
|
return patchGlbJsonChunk(rawBuf, (gltf) => {
|
|
1451
1447
|
const nodes = gltf.nodes ?? [];
|
|
@@ -1463,17 +1459,19 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1463
1459
|
return list[0];
|
|
1464
1460
|
};
|
|
1465
1461
|
const shapes = [];
|
|
1466
|
-
const
|
|
1462
|
+
const shapeMap = /* @__PURE__ */ new Map();
|
|
1467
1463
|
const materials = [];
|
|
1468
|
-
const
|
|
1464
|
+
const matMap = /* @__PURE__ */ new Map();
|
|
1469
1465
|
const filters = [];
|
|
1470
|
-
const
|
|
1466
|
+
const filterMap = /* @__PURE__ */ new Map();
|
|
1471
1467
|
const joints = [];
|
|
1468
|
+
const jointMap = /* @__PURE__ */ new Map();
|
|
1472
1469
|
const omiWheels = [];
|
|
1470
|
+
const wheelMap = /* @__PURE__ */ new Map();
|
|
1473
1471
|
const seenSpecNodes = /* @__PURE__ */ new Set();
|
|
1474
1472
|
const used = new Set(gltf.extensionsUsed ?? []);
|
|
1475
1473
|
let hasPhysics = false;
|
|
1476
|
-
const hasPreIndexedOmiWheel = specs.some((s) =>
|
|
1474
|
+
const hasPreIndexedOmiWheel = specs.some((s) => isObj(s.extensions) && Object.hasOwn(s.extensions, "OMI_vehicle_wheel") && s.extensions.OMI_vehicle_wheel !== void 0);
|
|
1477
1475
|
for (const spec of specs) {
|
|
1478
1476
|
if (seenSpecNodes.has(spec.nodeName)) throw new KhrValidationError(`exportKhrGlb: duplicate spec for node "${spec.nodeName}"`);
|
|
1479
1477
|
seenSpecNodes.add(spec.nodeName);
|
|
@@ -1483,7 +1481,7 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1483
1481
|
...spec.extras
|
|
1484
1482
|
};
|
|
1485
1483
|
if (spec.extensions !== void 0) {
|
|
1486
|
-
if (!
|
|
1484
|
+
if (!isObj(spec.extensions)) throw new KhrValidationError(`exportKhrGlb: extensions on "${spec.nodeName}" must be an object`);
|
|
1487
1485
|
if (Object.hasOwn(spec.extensions, "OMI_vehicle_wheel") && spec.extensions.OMI_vehicle_wheel !== void 0 && spec.wheel !== void 0) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both wheel and extensions.OMI_vehicle_wheel`);
|
|
1488
1486
|
if (Object.hasOwn(spec.extensions, "KHR_physics_rigid_bodies") && spec.extensions.KHR_physics_rigid_bodies !== void 0 && (spec.motion !== void 0 || spec.collider !== void 0 || spec.joint !== void 0)) throw new KhrValidationError(`exportKhrGlb: node "${spec.nodeName}" cannot specify both extensions.KHR_physics_rigid_bodies and motion/collider/joint`);
|
|
1489
1487
|
node.extensions = {
|
|
@@ -1500,17 +1498,8 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1500
1498
|
if (spec.collider) {
|
|
1501
1499
|
hasPhysics = true;
|
|
1502
1500
|
const col = {};
|
|
1503
|
-
if (spec.collider.shape) {
|
|
1504
|
-
|
|
1505
|
-
const key = JSON.stringify(encoded);
|
|
1506
|
-
let sIdx = shapeIndexByJson.get(key);
|
|
1507
|
-
if (sIdx === void 0) {
|
|
1508
|
-
sIdx = shapes.length;
|
|
1509
|
-
shapes.push(encoded);
|
|
1510
|
-
shapeIndexByJson.set(key, sIdx);
|
|
1511
|
-
}
|
|
1512
|
-
col.geometry = { shape: sIdx };
|
|
1513
|
-
} else if (spec.collider.meshNodeName) {
|
|
1501
|
+
if (spec.collider.shape) col.geometry = { shape: internJson(shapes, shapeMap, encodeShape(spec.collider.shape, spec.nodeName)) };
|
|
1502
|
+
else if (spec.collider.meshNodeName) {
|
|
1514
1503
|
if (typeof spec.collider.convexHull !== "boolean") throw new KhrValidationError(`exportKhrGlb: mesh collider on "${spec.nodeName}" requires explicit boolean convexHull`);
|
|
1515
1504
|
col.geometry = {
|
|
1516
1505
|
node: requireNodeIdx(spec.collider.meshNodeName),
|
|
@@ -1518,43 +1507,23 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1518
1507
|
};
|
|
1519
1508
|
} else throw new KhrValidationError(`exportKhrGlb: collider on "${spec.nodeName}" requires shape or meshNodeName`);
|
|
1520
1509
|
const mat = encodePhysicsMaterial(spec.collider, spec.nodeName);
|
|
1521
|
-
if (mat)
|
|
1522
|
-
const key = JSON.stringify(mat);
|
|
1523
|
-
let mIdx = matIndexByJson.get(key);
|
|
1524
|
-
if (mIdx === void 0) {
|
|
1525
|
-
mIdx = materials.length;
|
|
1526
|
-
materials.push(mat);
|
|
1527
|
-
matIndexByJson.set(key, mIdx);
|
|
1528
|
-
}
|
|
1529
|
-
col.physicsMaterial = mIdx;
|
|
1530
|
-
}
|
|
1510
|
+
if (mat) col.physicsMaterial = internJson(materials, matMap, mat);
|
|
1531
1511
|
const filter = encodeCollisionFilter(spec.collider, spec.nodeName);
|
|
1532
|
-
if (filter)
|
|
1533
|
-
const key = JSON.stringify(filter);
|
|
1534
|
-
let fIdx = filterIndexByJson.get(key);
|
|
1535
|
-
if (fIdx === void 0) {
|
|
1536
|
-
fIdx = filters.length;
|
|
1537
|
-
filters.push(filter);
|
|
1538
|
-
filterIndexByJson.set(key, fIdx);
|
|
1539
|
-
}
|
|
1540
|
-
col.collisionFilter = fIdx;
|
|
1541
|
-
}
|
|
1512
|
+
if (filter) col.collisionFilter = internJson(filters, filterMap, filter);
|
|
1542
1513
|
khr.collider = col;
|
|
1543
1514
|
}
|
|
1544
1515
|
if (spec.joint) {
|
|
1545
1516
|
hasPhysics = true;
|
|
1546
1517
|
const connIdx = requireNodeIdx(spec.joint.connectedNodeName);
|
|
1547
|
-
joints.push(encodeJoint(spec.joint, spec.nodeName));
|
|
1548
1518
|
khr.joint = {
|
|
1549
|
-
joint: joints
|
|
1519
|
+
joint: internJson(joints, jointMap, encodeJoint(spec.joint, spec.nodeName)),
|
|
1550
1520
|
connectedNode: connIdx,
|
|
1551
1521
|
enableCollision: Boolean(spec.joint.enableCollision)
|
|
1552
1522
|
};
|
|
1553
1523
|
}
|
|
1554
1524
|
const wheelSpec = spec.wheel ?? (!hasPreIndexedOmiWheel ? synthesizeOmiWheel(spec.extras?.ecctrlWheel) : null);
|
|
1555
1525
|
if (wheelSpec) {
|
|
1556
|
-
const wIdx = omiWheels.
|
|
1557
|
-
omiWheels.push(encodeOmiWheel(wheelSpec, spec.nodeName));
|
|
1526
|
+
const wIdx = internJson(omiWheels, wheelMap, encodeOmiWheel(wheelSpec, spec.nodeName));
|
|
1558
1527
|
used.add("OMI_vehicle_wheel");
|
|
1559
1528
|
node.extensions = {
|
|
1560
1529
|
...node.extensions,
|
|
@@ -1598,12 +1567,200 @@ async function exportKhrGlb(root, specs, sceneExtras) {
|
|
|
1598
1567
|
if (used.size > 0) gltf.extensionsUsed = [...used];
|
|
1599
1568
|
});
|
|
1600
1569
|
}
|
|
1601
|
-
// src/
|
|
1602
|
-
function
|
|
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 }) {
|
|
1603
1759
|
const { rapier, world } = useRapier();
|
|
1604
1760
|
const registry = useContext(JointRegistryContext);
|
|
1605
1761
|
const childRef = useRef(null);
|
|
1606
1762
|
const rtRef = useRef(null);
|
|
1763
|
+
const [childBody, setChildBody] = React.useState(null);
|
|
1607
1764
|
const worldPose = useMemo(() => {
|
|
1608
1765
|
const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
|
|
1609
1766
|
const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
|
|
@@ -1625,21 +1782,16 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef,
|
|
|
1625
1782
|
rootPos,
|
|
1626
1783
|
rootQuat
|
|
1627
1784
|
]);
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1785
|
+
const assignChildRef = useCallback((rb) => {
|
|
1786
|
+
childRef.current = rb;
|
|
1787
|
+
setChildBody(rb);
|
|
1788
|
+
onBody(part.spec.nodeName, rb);
|
|
1631
1789
|
}, [part.spec.nodeName, onBody]);
|
|
1790
|
+
useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
|
|
1632
1791
|
useEffect(() => {
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
if (rb && pm) {
|
|
1636
|
-
rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
|
|
1637
|
-
rb.recomputeMassPropertiesFromColliders();
|
|
1638
|
-
}
|
|
1639
|
-
}, [part.partMass]);
|
|
1792
|
+
if (childBody && part.massTarget) applyRapierBodyMass(childBody, part.massTarget);
|
|
1793
|
+
}, [childBody, part.massTarget]);
|
|
1640
1794
|
useEffect(() => {
|
|
1641
|
-
const parentBody = parentBodyRef.current;
|
|
1642
|
-
const childBody = childRef.current;
|
|
1643
1795
|
if (!parentBody || !childBody) return;
|
|
1644
1796
|
const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
|
|
1645
1797
|
0,
|
|
@@ -1655,12 +1807,6 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef,
|
|
|
1655
1807
|
object: part.spec.object,
|
|
1656
1808
|
axisParent: part.axisParent,
|
|
1657
1809
|
anchorParent: part.restRelParentPos,
|
|
1658
|
-
restRelQuat: [
|
|
1659
|
-
0,
|
|
1660
|
-
0,
|
|
1661
|
-
0,
|
|
1662
|
-
1
|
|
1663
|
-
],
|
|
1664
1810
|
limits: part.joint.limits,
|
|
1665
1811
|
drive: part.joint.drive,
|
|
1666
1812
|
breakaway: part.spec.breakaway,
|
|
@@ -1670,34 +1816,36 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef,
|
|
|
1670
1816
|
});
|
|
1671
1817
|
rtRef.current = rt;
|
|
1672
1818
|
registry?.add(rt);
|
|
1673
|
-
onJointReady(rt.nodeName, rt);
|
|
1819
|
+
onJointReady(rt.nodeName, part.spec.object, rt);
|
|
1674
1820
|
return () => {
|
|
1675
1821
|
rtRef.current = null;
|
|
1676
1822
|
registry?.delete(rt);
|
|
1677
|
-
onJointReady(rt.nodeName, null);
|
|
1823
|
+
onJointReady(rt.nodeName, part.spec.object, null);
|
|
1678
1824
|
if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
|
|
1679
1825
|
};
|
|
1680
1826
|
}, [
|
|
1681
1827
|
rapier,
|
|
1682
1828
|
world,
|
|
1683
1829
|
part,
|
|
1684
|
-
|
|
1830
|
+
parentBody,
|
|
1831
|
+
childBody,
|
|
1685
1832
|
registry,
|
|
1686
1833
|
onJointReady
|
|
1687
1834
|
]);
|
|
1688
|
-
const onForce = part.spec.breakaway ? (p) => {
|
|
1689
|
-
rtRef.current?.applyImpactImpulse(p.totalForceMagnitude *
|
|
1690
|
-
} : void 0;
|
|
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]);
|
|
1691
1838
|
const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
|
|
1692
1839
|
const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
|
|
1693
1840
|
const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
|
|
1694
1841
|
return /* @__PURE__ */ jsxs(RigidBody, {
|
|
1695
|
-
ref:
|
|
1842
|
+
ref: assignChildRef,
|
|
1696
1843
|
type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
|
|
1697
1844
|
position: worldPose.pos,
|
|
1698
1845
|
quaternion: worldPose.quat,
|
|
1699
1846
|
colliders: false,
|
|
1700
1847
|
onContactForce: onForce,
|
|
1848
|
+
...userData === void 0 ? {} : { userData },
|
|
1701
1849
|
...linVel ? { linearVelocity: linVel } : {},
|
|
1702
1850
|
...angVel ? { angularVelocity: angVel } : {},
|
|
1703
1851
|
...gravScale === void 0 ? {} : { gravityScale: gravScale },
|
|
@@ -1714,49 +1862,37 @@ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBodyRef,
|
|
|
1714
1862
|
c: col.spec,
|
|
1715
1863
|
position: col.position,
|
|
1716
1864
|
quaternion: col.quaternion,
|
|
1717
|
-
|
|
1865
|
+
density: col.density
|
|
1718
1866
|
}, `${part.spec.nodeName}:${cIdx}`))]
|
|
1719
1867
|
});
|
|
1720
1868
|
}
|
|
1721
|
-
function AssemblyRootBody({ plan, position, quaternion, fixedRoot, rigidBodyProps, onBody,
|
|
1722
|
-
const
|
|
1723
|
-
const
|
|
1724
|
-
const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object)) : null, [plan.parts]);
|
|
1725
|
-
const jointsMapRef = useRef(/* @__PURE__ */ new Map());
|
|
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]);
|
|
1726
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]);
|
|
1727
1879
|
useEffect(() => {
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
const rb = rbRef.current;
|
|
1741
|
-
const rm = plan.rootMass;
|
|
1742
|
-
if (rb && rm) {
|
|
1743
|
-
rb.setAdditionalMassProperties(rm.mass, rm.centerOfMass, rm.principalAngularInertia, rm.angularInertiaLocalFrame, true);
|
|
1744
|
-
rb.recomputeMassPropertiesFromColliders();
|
|
1745
|
-
}
|
|
1746
|
-
}, [plan.rootMass]);
|
|
1747
|
-
const handlePartBody = useCallback((nodeName, refObj) => {
|
|
1748
|
-
const slot = partBodyRefs.get(nodeName);
|
|
1749
|
-
if (slot) slot.current = refObj?.current ?? null;
|
|
1750
|
-
onBody(nodeName, refObj);
|
|
1751
|
-
}, [partBodyRefs, onBody]);
|
|
1752
|
-
const handleJointReady = useCallback((nodeName, rt) => {
|
|
1753
|
-
if (rt) jointsMapRef.current.set(nodeName, rt);
|
|
1754
|
-
else jointsMapRef.current.delete(nodeName);
|
|
1755
|
-
}, []);
|
|
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]);
|
|
1756
1892
|
const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
|
|
1757
1893
|
return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
|
|
1758
1894
|
...rigidBodyProps,
|
|
1759
|
-
ref:
|
|
1895
|
+
ref: assignRootRef,
|
|
1760
1896
|
type: bodyType,
|
|
1761
1897
|
position,
|
|
1762
1898
|
quaternion,
|
|
@@ -1768,43 +1904,44 @@ function AssemblyRootBody({ plan, position, quaternion, fixedRoot, rigidBodyProp
|
|
|
1768
1904
|
c: col.spec,
|
|
1769
1905
|
position: col.position,
|
|
1770
1906
|
quaternion: col.quaternion,
|
|
1771
|
-
|
|
1907
|
+
density: col.density
|
|
1772
1908
|
}, `r${idx}`))]
|
|
1773
1909
|
}), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
|
|
1774
1910
|
part,
|
|
1775
1911
|
rootSpec,
|
|
1776
1912
|
rootPos: position,
|
|
1777
1913
|
rootQuat: quaternion,
|
|
1778
|
-
|
|
1914
|
+
parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
|
|
1915
|
+
userData: rigidBodyProps?.userData,
|
|
1779
1916
|
origin: partOrigins?.get(part.spec.object),
|
|
1780
1917
|
onBody: handlePartBody,
|
|
1781
|
-
onJointReady
|
|
1918
|
+
onJointReady
|
|
1782
1919
|
}, part.spec.nodeName))] });
|
|
1783
1920
|
}
|
|
1784
|
-
// src/KhrAssembly.tsx
|
|
1785
1921
|
function KhrAssembly({ ref, bundle, position = [
|
|
1786
1922
|
0,
|
|
1787
1923
|
0,
|
|
1788
1924
|
0
|
|
1789
|
-
], rotation, quaternion, scale, fixedRoot = false, rigidBodyProps, children, ...groupProps }) {
|
|
1925
|
+
], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
|
|
1790
1926
|
assertUnitScale(scale, "KhrAssembly");
|
|
1791
|
-
bundle.scene
|
|
1792
|
-
|
|
1927
|
+
useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
|
|
1928
|
+
const { world } = useRapier();
|
|
1929
|
+
const applyGravityField = useCustomGravity((s) => s.applyGravityField);
|
|
1793
1930
|
const plans = useMemo(() => planAssembly(bundle), [bundle]);
|
|
1794
|
-
const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode)) : null, [plans]);
|
|
1931
|
+
const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [plans, bundle.scene]);
|
|
1795
1932
|
const [px, py, pz] = position;
|
|
1796
1933
|
const [rx, ry, rz] = rotation ?? [
|
|
1797
1934
|
0,
|
|
1798
1935
|
0,
|
|
1799
1936
|
0
|
|
1800
1937
|
];
|
|
1801
|
-
const
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
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,
|
|
1808
1945
|
qx,
|
|
1809
1946
|
qy,
|
|
1810
1947
|
qz,
|
|
@@ -1838,44 +1975,57 @@ function KhrAssembly({ ref, bundle, position = [
|
|
|
1838
1975
|
]);
|
|
1839
1976
|
const bodiesRef = useRef(/* @__PURE__ */ new Map());
|
|
1840
1977
|
const jointsRef = useRef(/* @__PURE__ */ new Map());
|
|
1841
|
-
const
|
|
1842
|
-
const m = /* @__PURE__ */ new Map();
|
|
1843
|
-
for (const p of plans) {
|
|
1844
|
-
m.set(p.spec.nodeName, p.spec.nodeName);
|
|
1845
|
-
for (const part of p.parts) m.set(part.spec.nodeName, p.spec.nodeName);
|
|
1846
|
-
}
|
|
1847
|
-
return m;
|
|
1848
|
-
}, [plans]);
|
|
1978
|
+
const byObjectRef = useRef(/* @__PURE__ */ new Map());
|
|
1849
1979
|
const handleBody = useCallback((nodeName, rb) => {
|
|
1850
1980
|
if (rb) bodiesRef.current.set(nodeName, rb);
|
|
1851
1981
|
else bodiesRef.current.delete(nodeName);
|
|
1852
1982
|
}, []);
|
|
1853
|
-
const
|
|
1854
|
-
if (
|
|
1855
|
-
|
|
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
|
+
}
|
|
1856
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
|
+
});
|
|
1857
1996
|
useImperativeHandle(ref, () => ({
|
|
1858
|
-
|
|
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,
|
|
1859
2002
|
setJointTarget: (nodeName, target) => {
|
|
1860
|
-
|
|
1861
|
-
if (rt) rt.applyTarget(target);
|
|
2003
|
+
jointsRef.current.get(nodeName)?.applyTarget(target);
|
|
1862
2004
|
},
|
|
1863
2005
|
setRoleTarget: (role, target) => {
|
|
1864
|
-
for (const
|
|
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;
|
|
1865
2014
|
}
|
|
1866
|
-
}), [
|
|
2015
|
+
}), []);
|
|
1867
2016
|
if (plans.length === 1) {
|
|
1868
2017
|
const plan = plans[0];
|
|
1869
2018
|
return /* @__PURE__ */ jsx("group", {
|
|
1870
2019
|
...groupProps,
|
|
1871
2020
|
children: /* @__PURE__ */ jsx(AssemblyRootBody, {
|
|
1872
2021
|
plan,
|
|
2022
|
+
bundleScene: bundle.scene,
|
|
1873
2023
|
position: rootPoses[0].position,
|
|
1874
2024
|
quaternion: rootPoses[0].quaternion,
|
|
1875
2025
|
fixedRoot,
|
|
1876
2026
|
rigidBodyProps,
|
|
1877
2027
|
onBody: handleBody,
|
|
1878
|
-
|
|
2028
|
+
onJointReady: handleJointReady,
|
|
1879
2029
|
children: /* @__PURE__ */ jsxs("group", {
|
|
1880
2030
|
position: plan.sceneInRootPos,
|
|
1881
2031
|
quaternion: plan.sceneInRootQuat,
|
|
@@ -1903,12 +2053,13 @@ function KhrAssembly({ ref, bundle, position = [
|
|
|
1903
2053
|
}), children]
|
|
1904
2054
|
}), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
|
|
1905
2055
|
plan,
|
|
2056
|
+
bundleScene: bundle.scene,
|
|
1906
2057
|
position: rootPoses[idx].position,
|
|
1907
2058
|
quaternion: rootPoses[idx].quaternion,
|
|
1908
2059
|
fixedRoot,
|
|
1909
2060
|
rigidBodyProps,
|
|
1910
2061
|
onBody: handleBody,
|
|
1911
|
-
|
|
2062
|
+
onJointReady: handleJointReady,
|
|
1912
2063
|
children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
|
|
1913
2064
|
object: plan.mountNode,
|
|
1914
2065
|
position: plan.mountPosition,
|
|
@@ -1922,46 +2073,56 @@ function KhrAssembly({ ref, bundle, position = [
|
|
|
1922
2073
|
var KhrGLTFLoader = class extends GLTFLoader {
|
|
1923
2074
|
static khrLoaderScope = Symbol("KhrGLTFLoader");
|
|
1924
2075
|
};
|
|
1925
|
-
var headlessPlugin = createHeadlessTexturePlugin();
|
|
1926
2076
|
var khrPlugin = createKhrGltfPlugin();
|
|
1927
2077
|
var configuredLoaders = /* @__PURE__ */ new WeakSet();
|
|
1928
2078
|
var customExtendedLoaders = /* @__PURE__ */ new WeakSet();
|
|
1929
|
-
var
|
|
2079
|
+
var fnIds = /* @__PURE__ */ new WeakMap();
|
|
2080
|
+
var nextFnId = 1;
|
|
2081
|
+
var scopedRegistry = /* @__PURE__ */ new Map();
|
|
1930
2082
|
function configureKhrLoader(loader) {
|
|
1931
2083
|
if (configuredLoaders.has(loader)) return;
|
|
1932
2084
|
configuredLoaders.add(loader);
|
|
1933
|
-
if (isHeadlessTextureEnv()) loader.register(headlessPlugin);
|
|
1934
2085
|
loader.register(khrPlugin);
|
|
1935
2086
|
}
|
|
1936
2087
|
function hasCustomLoaderOpts(options) {
|
|
1937
2088
|
return Boolean(options?.extendLoader || options?.cacheKey !== void 0);
|
|
1938
2089
|
}
|
|
1939
2090
|
function getLoaderCacheKey(options) {
|
|
1940
|
-
|
|
2091
|
+
if (options.cacheKey !== void 0) return `key:${options.cacheKey}`;
|
|
2092
|
+
const fn = options.extendLoader;
|
|
2093
|
+
let id = fnIds.get(fn);
|
|
2094
|
+
if (id === void 0) {
|
|
2095
|
+
id = nextFnId++;
|
|
2096
|
+
fnIds.set(fn, id);
|
|
2097
|
+
}
|
|
2098
|
+
return `fn:${id}`;
|
|
2099
|
+
}
|
|
2100
|
+
function createScopedGltfLoaderClass() {
|
|
2101
|
+
return class ScopedKhrGLTFLoader extends GLTFLoader {};
|
|
1941
2102
|
}
|
|
1942
2103
|
function getScopedLoaderEntry(url, options) {
|
|
1943
2104
|
const key = getLoaderCacheKey(options);
|
|
1944
|
-
let urlMap =
|
|
2105
|
+
let urlMap = scopedRegistry.get(url);
|
|
1945
2106
|
if (!urlMap) {
|
|
1946
2107
|
urlMap = /* @__PURE__ */ new Map();
|
|
1947
|
-
|
|
2108
|
+
scopedRegistry.set(url, urlMap);
|
|
1948
2109
|
}
|
|
1949
2110
|
let entry = urlMap.get(key);
|
|
1950
2111
|
if (!entry) {
|
|
1951
|
-
const
|
|
2112
|
+
const Proto = createScopedGltfLoaderClass();
|
|
1952
2113
|
const extend = options.extendLoader;
|
|
1953
2114
|
const created = {
|
|
1954
|
-
|
|
2115
|
+
Proto,
|
|
1955
2116
|
registerExtensions: (target) => {
|
|
1956
2117
|
configureKhrLoader(target);
|
|
1957
2118
|
if (extend && !customExtendedLoaders.has(target)) try {
|
|
1958
2119
|
extend(target);
|
|
1959
2120
|
customExtendedLoaders.add(target);
|
|
1960
2121
|
} catch (err) {
|
|
1961
|
-
const map =
|
|
2122
|
+
const map = scopedRegistry.get(url);
|
|
1962
2123
|
if (map?.get(key) === created) {
|
|
1963
2124
|
map.delete(key);
|
|
1964
|
-
if (map.size === 0)
|
|
2125
|
+
if (map.size === 0) scopedRegistry.delete(url);
|
|
1965
2126
|
}
|
|
1966
2127
|
throw err;
|
|
1967
2128
|
}
|
|
@@ -1976,9 +2137,9 @@ function useKhrGlb(url, options) {
|
|
|
1976
2137
|
const extractRole = options?.extractRole;
|
|
1977
2138
|
const isSocketNode = options?.isSocketNode;
|
|
1978
2139
|
const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
|
|
1979
|
-
const
|
|
2140
|
+
const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
|
|
1980
2141
|
const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
|
|
1981
|
-
const template = useLoader(
|
|
2142
|
+
const template = useLoader(Proto, url, reg).userData[KHR_BUNDLE_USERDATA_KEY];
|
|
1982
2143
|
if (!template) throw new KhrValidationError(`useKhrGlb: missing "${KHR_BUNDLE_USERDATA_KEY}" on loaded GLTF for "${url}"`);
|
|
1983
2144
|
return useMemo(() => {
|
|
1984
2145
|
const cloned = cloneKhrBundle(template);
|
|
@@ -1993,33 +2154,33 @@ function useKhrGlb(url, options) {
|
|
|
1993
2154
|
(function(_useKhrGlb) {
|
|
1994
2155
|
_useKhrGlb.preload = (url, options) => {
|
|
1995
2156
|
const scoped = hasCustomLoaderOpts(options) ? getScopedLoaderEntry(url, options) : null;
|
|
1996
|
-
const
|
|
2157
|
+
const Proto = scoped ? scoped.Proto : KhrGLTFLoader;
|
|
1997
2158
|
const reg = scoped ? scoped.registerExtensions : configureKhrLoader;
|
|
1998
|
-
useLoader.preload(
|
|
2159
|
+
useLoader.preload(Proto, url, reg);
|
|
1999
2160
|
};
|
|
2000
2161
|
_useKhrGlb.clear = (url, options) => {
|
|
2001
2162
|
if (hasCustomLoaderOpts(options)) {
|
|
2002
|
-
const urlMap =
|
|
2163
|
+
const urlMap = scopedRegistry.get(url);
|
|
2003
2164
|
if (!urlMap) return;
|
|
2004
2165
|
const key = getLoaderCacheKey(options);
|
|
2005
2166
|
const entry = urlMap.get(key);
|
|
2006
2167
|
if (entry) {
|
|
2007
|
-
useLoader.clear(entry.
|
|
2168
|
+
useLoader.clear(entry.Proto, url);
|
|
2008
2169
|
urlMap.delete(key);
|
|
2009
|
-
if (urlMap.size === 0)
|
|
2170
|
+
if (urlMap.size === 0) scopedRegistry.delete(url);
|
|
2010
2171
|
}
|
|
2011
2172
|
} else {
|
|
2012
2173
|
useLoader.clear(KhrGLTFLoader, url);
|
|
2013
2174
|
if (options === void 0) {
|
|
2014
|
-
const urlMap =
|
|
2175
|
+
const urlMap = scopedRegistry.get(url);
|
|
2015
2176
|
if (urlMap) {
|
|
2016
|
-
for (const entry of urlMap.values()) useLoader.clear(entry.
|
|
2017
|
-
|
|
2177
|
+
for (const entry of urlMap.values()) useLoader.clear(entry.Proto, url);
|
|
2178
|
+
scopedRegistry.delete(url);
|
|
2018
2179
|
}
|
|
2019
2180
|
}
|
|
2020
2181
|
}
|
|
2021
2182
|
};
|
|
2022
2183
|
})(useKhrGlb || (useKhrGlb = {}));
|
|
2023
|
-
export { JointRegistryContext, KhrAssembly, KhrCollider, KhrValidationError, PhysicsWorld, assertIdentityWorldScale, assertSceneIdentityWorldScale, assertUnitScale, claimBundleMount, cloneKhrBundle, createKhrGltfPlugin, disposeKhrBundle, exportKhrGlb, loadKhrGlb, patchGlbJsonChunk, 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 };
|
|
2024
2185
|
|
|
2025
2186
|
//# sourceMappingURL=index.js.map
|