@khr3/core 0.2.6 → 0.2.7

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.
Files changed (43) hide show
  1. package/README.md +169 -9
  2. package/dist/KhrAssembly.d.ts +1 -1
  3. package/dist/KhrCollider.d.ts +5 -1
  4. package/dist/curves-Cf8okB-M.js +542 -0
  5. package/dist/curves-Cf8okB-M.js.map +1 -0
  6. package/dist/curves.js +1 -542
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.js +4 -1544
  9. package/dist/index.js.map +1 -1
  10. package/dist/jointDynamics.d.ts +7 -0
  11. package/dist/khrClone.d.ts +3 -3
  12. package/dist/khrInertia-DgCUCDTx.js +247 -0
  13. package/dist/khrInertia-DgCUCDTx.js.map +1 -0
  14. package/dist/khrVehicleJointHelpers.d.ts +16 -0
  15. package/dist/khrVehicleJoints.d.ts +2 -1
  16. package/dist/khrVehicleSlots.d.ts +11 -3
  17. package/dist/{physicsEcs-dBq4psbC.js → physicsEcs-C00N5zCh.js} +27 -251
  18. package/dist/physicsEcs-C00N5zCh.js.map +1 -0
  19. package/dist/sand3d/sand3dAssemblyHelpers.d.ts +30 -0
  20. package/dist/sand3d/sand3dCavityOps.d.ts +15 -0
  21. package/dist/sand3d/sand3dCompiler.d.ts +121 -0
  22. package/dist/sand3d/sand3dEvaluator.d.ts +80 -0
  23. package/dist/sand3d/sand3dFramesAndEdits.d.ts +30 -0
  24. package/dist/sand3d/sand3dHullAndSweep.d.ts +27 -0
  25. package/dist/sand3d/sand3dParser.d.ts +6 -0
  26. package/dist/sand3d/sand3dPrimitives.d.ts +50 -0
  27. package/dist/sand3d/sand3dProfiles.d.ts +32 -0
  28. package/dist/sand3d/sand3dRecipes.d.ts +5 -0
  29. package/dist/sand3d/sand3dShellOp.d.ts +8 -0
  30. package/dist/sand3d/sand3dSolids.d.ts +32 -0
  31. package/dist/sand3d/sand3dTokenizer.d.ts +8 -0
  32. package/dist/sand3d/sand3dTypes.d.ts +157 -0
  33. package/dist/sand3d-DQ8-OMlo.js +5045 -0
  34. package/dist/sand3d-DQ8-OMlo.js.map +1 -0
  35. package/dist/sand3d.d.ts +23 -0
  36. package/dist/sand3d.js +1 -0
  37. package/dist/vehicle.js +198 -21
  38. package/dist/vehicle.js.map +1 -1
  39. package/dist/wheelLoads.d.ts +3 -1
  40. package/docs/api-reference.md +332 -163
  41. package/package.json +5 -1
  42. package/dist/curves.js.map +0 -1
  43. package/dist/physicsEcs-dBq4psbC.js.map +0 -1
@@ -1,209 +1,378 @@
1
- # `@khr3/core` API Reference
1
+ # `@khr3/core` API & Schema Reference
2
2
 
3
- `@khr3/core` implements `KHR_physics_rigid_bodies`, `KHR_implicit_shapes`, and `OMI_vehicle_wheel` glTF/GLB export, strict loading, multi-body Rapier `ImpulseJoint` assembly hosting (`<KhrAssembly>`), natural-asset-origin `<KhrVehicle>` mounting over `@pinkaphant/ecctrl/vehicle`, and monotone Pacejka curve compilation.
3
+ `@khr3/core` (package overview and quick start in [README.md](../README.md)) implements `KHR_physics_rigid_bodies`, `KHR_implicit_shapes`, and `OMI_vehicle_wheel` glTF 2.0 binary `.glb` serialization and loading, multi-body Rapier `ImpulseJoint` assembly hosting (`<KhrAssembly>`), natural-origin `<KhrVehicle>` mounting over `@pinkaphant/ecctrl/vehicle`, monotone Pacejka curve compilation, and declarative `Sand3D` Code-CAD compilation (`@khr3/core/sand3d`).
4
4
 
5
- Three subpaths are published:
5
+ Four subpaths are published:
6
6
 
7
- - `@khr3/core` — `PhysicsWorld`, `KhrAssembly`, `KhrCollider`, `loadKhrGlb`, `createKhrGltfPlugin`, `useKhrGlb`, `exportKhrGlb`, `patchGlbJsonChunk`, `cloneKhrBundle`, `disposeKhrBundle`, `claimBundleMount`, `releaseBundleMount`, scale validators, `JointRegistryContext`, `KhrValidationError`.
8
- - `@khr3/core/vehicle` — `KhrVehicle`, `solveWheelLoads`, `type KhrVehicleJointsHandle`, `type KhrVehicleProps`, `type KhrWheelConfig`, `type KhrPropellerConfig`, `type SolvedWheel`.
9
- - `@khr3/core/curves` — `compilePacejkaCurve`, `tireGripForSurface`, `engineHorsepowerForPeakTorque`, `TIRE_ARCHETYPES`, `TIRE_SLIP_CURVES`, `ENGINE_TORQUE_CURVES`, `STEER_SPEED_CURVES`.
7
+ - `@khr3/core` ([index.ts](../src/index.ts)) — `PhysicsWorld`, `KhrAssembly`, `KhrCollider`, `loadKhrGlb`, `createKhrGltfPlugin`, `useKhrGlb`, `exportKhrGlb`, `patchGlbJsonChunk`, `cloneKhrBundle`, `disposeKhrBundle`, `claimBundleMount`, `releaseBundleMount`, scale validators, `JointRegistryContext`, `KhrValidationError`, core `Sand3D` entrypoints, and the KHR and Sand3D TypeScript interfaces detailed below.
8
+ - `@khr3/core/vehicle` ([vehicle.ts](../src/vehicle.ts)) — `KhrVehicle`, `solveWheelLoads`, `type KhrVehicleJointsHandle`, `type KhrVehicleProps`, `type KhrWheelConfig`, `type KhrPropellerConfig`, `type SolvedWheel`.
9
+ - `@khr3/core/curves` ([curves.ts](../src/curves.ts)) — `compilePacejkaCurve`, `tireGripForSurface`, `engineHorsepowerForPeakTorque`, `TIRE_ARCHETYPES`, `TIRE_SLIP_CURVES`, `ENGINE_TORQUE_CURVES`, `STEER_SPEED_CURVES`, `type TireArchetypePreset`, `type CurveData`, `type CurvePoint`.
10
+ - `@khr3/core/sand3d` ([sand3d.ts](../src/sand3d.ts)) — `s3d`, `SAND3D_RECIPES`, `SAND3D_RECIPE_MAP`, `findSand3dRecipe`, `buildSand3dRecipe`, `compileSand3dAssembly`, `exportSand3dGlb`, `loadSand3dBundle`, `parseSand3dSource`, `isSand3dFileName`, profile builders, solid builders, topological frames, cavity edits, and kinematic constructors.
10
11
 
11
12
  ---
12
13
 
13
14
  ## `@khr3/core`
14
15
 
15
- ### `<PhysicsWorld>`
16
+ ### `<PhysicsWorld>` ([PhysicsWorld.tsx](../src/PhysicsWorld.tsx))
16
17
 
17
- Wraps `@react-three/rapier`'s `<Physics paused timeStep="vary">` with `@pinkaphant/ecctrl/time` `<TimeControl>` mounted after scene children so vehicle/joint impulses apply before each `step(dt)`.
18
+ Wraps `@react-three/rapier` `<Physics paused timeStep="vary">` with `@pinkaphant/ecctrl/time` `<TimeControl>` mounted after scene children so vehicle and joint impulses apply ahead of each `step(dt)`.
18
19
 
19
20
  | Prop | Type | Default | Description |
20
21
  | :--- | :--- | :--- | :--- |
21
- | `paused` | `boolean` | `false` | Stops physics stepping while mounted |
22
- | `timeScale` | `number \| RefObject<number>` | `1` | Scalar or live ref multiplier (`<= 0` pauses stepping) |
23
- | `maxDelta` | `number \| RefObject<number>` | `1 / 30` | Frame delta clamp before `timeScale` |
22
+ | `paused` | `boolean` | `false` | Holds simulation state stationary while true |
23
+ | `timeScale` | `number \| RefObject<number>` | `1` | Scalar or live ref step multiplier |
24
+ | `maxDelta` | `number \| RefObject<number>` | `1 / 30` | Frame delta upper bound applied ahead of `timeScale` |
24
25
  | `gravity` | `[number, number, number]` | `[0, -9.81, 0]` | World gravity vector forwarded to `<Physics>` |
25
- | `...physicsProps` | `Omit<PhysicsProps, ...>` | — | Forwarded to `@react-three/rapier` `<Physics>` |
26
+ | `...physicsProps` | `Omit<PhysicsProps, ...>` | — | Additional props forwarded to `@react-three/rapier` `<Physics>` |
26
27
 
27
- ---
28
-
29
- ### `<KhrAssembly>` & `JointRegistryContext`
28
+ ### `<KhrAssembly>` and `JointRegistryContext`
30
29
 
31
- Mounts a `KhrAssetBundle` into Rapier as one `<RigidBody>` per jointless root and an independent `<RigidBody>` per jointed child connected to its parent via a real Rapier `ImpulseJoint` (`revolute`, `prismatic`, or `fixed` with motor drives and limits), registering each joint into `JointRegistryContext` (`Set<JointRuntime>`).
30
+ Implemented across [KhrAssembly.tsx](../src/KhrAssembly.tsx), [AssemblyRootBody.tsx](../src/AssemblyRootBody.tsx), [BundleSceneHost.tsx](../src/BundleSceneHost.tsx), [assemblyPlan.ts](../src/assemblyPlan.ts), [jointDynamics.ts](../src/jointDynamics.ts), and [physicsEcs.ts](../src/physicsEcs.ts).
32
31
 
33
- #### `KhrAssemblyProps`
32
+ Mounts a `KhrAssetBundle` into Rapier with one `<RigidBody>` per root body and an independent `<RigidBody>` per jointed child connected via a Rapier `ImpulseJoint` (`revolute`, `prismatic`, or `fixed` with motor drives and limits). `JointRegistryContext` (`Set<JointRuntime> | null`) is an opt-in registry (`null` by default, including inside `<PhysicsWorld>`); Rapier steps `ImpulseJoint` constraints natively and `KhrAssemblyHandle` / `KhrVehicleJointsHandle` (`jointsRef`) operate independently of a provider. Mounting `<JointRegistryContext.Provider value={set}>` registers active `JointRuntime` instances on mount and removes them on unmount.
34
33
 
35
- | Prop | Type | Default | Description |
34
+ | Prop (`KhrAssemblyProps`) | Type | Default | Description |
36
35
  | :--- | :--- | :--- | :--- |
37
- | `bundle` | `KhrAssetBundle` | required | Loaded KHR bundle (asserts identity world/local scale) |
38
- | `position` | `[number, number, number]` | `[0, 0, 0]` | Spawn position |
39
- | `rotation` | `[number, number, number]` | — | Euler rotation |
40
- | `quaternion` | `[number, number, number, number]` | — | Spawn quaternion (overrides `rotation`) |
41
- | `scale` | `ThreeElements["group"]["scale"]` | `1` | Must equal `1`; non-unit scale throws `KhrValidationError` |
42
- | `fixedRoot` | `boolean` | `false` | Turns kinematic roots into `fixed` Rapier bodies |
43
- | `rigidBodyProps` | `Omit<RigidBodyProps, "type" \| "position" \| "rotation" \| "quaternion" \| "colliders" \| "children" \| "ref">` | — | Forwarded to root `<RigidBody>` |
36
+ | `bundle` | `KhrAssetBundle` | required | Validated KHR bundle at unit `[1, 1, 1]` world and local scale |
37
+ | `position` | `[number, number, number]` | `[0, 0, 0]` | Root spawn position |
38
+ | `rotation` | `[number, number, number]` | — | Root Euler rotation in radians |
39
+ | `quaternion` | `[number, number, number, number]` | — | Root spawn quaternion |
40
+ | `scale` | `ThreeElements["group"]["scale"]` | `1` | Enforced unit scale `1` |
41
+ | `fixedRoot` | `boolean` | `false` | `false` mounts kinematic roots (`isKinematic: true`) as `"kinematicPosition"`; `true` mounts kinematic roots as `"fixed"`, while dynamic roots (`isKinematic: false`) mount as `"dynamic"` |
42
+ | `rigidBodyProps` | `Omit<RigidBodyProps, ...>` | — | Props forwarded to root `<RigidBody>` |
44
43
  | `ref` | `React.Ref<KhrAssemblyHandle>` | — | Imperative assembly handle |
45
44
 
46
- #### `KhrAssemblyHandle`
47
-
48
- - `getBody(nodeName: string): RapierRigidBody | null` — returns the `<RigidBody>` owning `nodeName` (including articulated child bodies).
49
- - `setJointTarget(nodeName: string, target: number): void` — configures motor position target on one jointed node.
50
- - `setRoleTarget(role: string, target: number): void` — configures motor position target on every jointed node whose `extras.role === role`.
51
-
52
- #### `JointRegistryContext`, `JointRegistry`, `JointRuntime`, `KhrBreakawaySpec`
53
-
54
- - `JointRegistryContext: React.Context<JointRegistry | null>` (`type JointRegistry = Set<JointRuntime>`).
55
- - `JointRuntime`: `{ nodeName, role, kind, object, axis, limits, drive, positionTarget, velocityTarget, rapierJoint, parentBody, childBody, unlatched, detached, getCoordinate, applyTarget, applyImpactImpulse }`.
56
- - `KhrBreakawaySpec`: `{ latchImpulseNs?: number; breakImpulseNs: number }` — parsed from `node.extras.breakaway`; Rapier `onContactForce` impulses (`totalForceMagnitude * timestep`) `>= latchImpulseNs` release the latch motor so the panel swings freely on its hinge, and impulses `>= breakImpulseNs` remove the Rapier `ImpulseJoint` so the panel detaches cleanly as dynamic debris.
57
-
58
- ---
59
-
60
- ### `<KhrCollider>`
61
-
62
- Builds the Rapier collider corresponding to a `KhrColliderSpec` (`box`, `sphere`, `cylinder`, `capsule`, `convexHull`, or `trimesh`), forwarding `frictionCombine` / `restitutionCombine` as Rapier `frictionCombineRule` / `restitutionCombineRule` (`CoefficientCombineRule`) and passing `massProperties` declaratively at collider creation time.
63
-
64
- - `c: KhrColliderSpec` — required collider shape/pose/material/combine spec.
65
- - `position?: [number, number, number]`, `quaternion?: [number, number, number, number]` — optional local pose overrides.
66
- - `massProperties?: ColliderMass` — carries lumped mass, CoM, and principal inertia declaratively on the root body collider (`density: 0` otherwise).
67
- - `ref?: React.Ref<RapierCollider>` — forwards the underlying Rapier collider handle.
68
-
69
- ---
70
-
71
- ### Export & Load API
72
-
73
- #### `exportKhrGlb(root: THREE.Object3D, specs: readonly KhrExportNodeSpec[], sceneExtras?: Record<string, unknown>): Promise<ArrayBuffer>`
74
-
75
- Exports `root` via Three.js `GLTFExporter` (temporarily stripping any material texture whose `.image` is missing/unloaded and restoring it in a `finally` block so caller materials remain unmutated) and patches `KHR_implicit_shapes`, `KHR_physics_rigid_bodies`, `OMI_vehicle_wheel`, custom node `extensions`, and `sceneExtras` into the binary GLB JSON chunk. Throws `KhrValidationError` on missing nodes, targeted duplicate node names, duplicate `spec.nodeName` entries, mixing `spec.wheel` with `spec.extensions.OMI_vehicle_wheel` in the same call, or mixing `spec.extensions.KHR_physics_rigid_bodies` with `motion`/`collider`/`joint` on the same node.
76
-
77
- Each `KhrExportNodeSpec` targets a unique named node `nodeName` and may specify:
78
- - `motion`: `{ isKinematic?, mass?, centerOfMass?, inertiaDiagonal?, inertiaOrientation?, linearVelocity?, angularVelocity?, gravityFactor? }`
79
- - `collider`: `{ shape?, meshNodeName?, convexHull?, friction?, restitution?, frictionCombine?, restitutionCombine?, collisionSystems?, collideWithSystems?, notCollideWithSystems? }` (`notCollideWithSystems` / `collideWithSystems` may be used without `collisionSystems`)
80
- - `joint`: `{ connectedNodeName, kind: "revolute" | "prismatic" | "fixed", axis?, limits?, limitStiffness?, limitDamping?, enableCollision?, drive?, drives? }` (non-cardinal / negative `axis` unit vectors are preserved losslessly via `physicsJoints[i].extras.jointAxis`)
81
- - `wheel`: `OmiVehicleWheelSpec` — appends to `gltf.extensions.OMI_vehicle_wheel.wheels[]`, adds `"OMI_vehicle_wheel"` to `extensionsUsed`, and writes `node.extensions.OMI_vehicle_wheel = { wheel }`
82
- - `extras`: arbitrary node `extras` (e.g., `role`, `ecctrlWheel`, `ecctrlPropeller`); when `spec.wheel` is omitted and no node pre-defines `extensions.OMI_vehicle_wheel`, a complete valid `extras.ecctrlWheel` (`radius > 0`, `width > 0`, `travel >= 0`, `0 <= sag <= travel`, boolean `steer`, `drive`, `brake`) synthesizes an `OMI_vehicle_wheel` entry automatically
83
- - `extensions`: `Record<string, unknown>` — merged onto `node.extensions` (adds extension names such as `"OMI_vehicle_wheel"`, `"KOLMO_emitter"` to `extensionsUsed`, never `extensionsRequired`; preserves pre-indexed `node.extensions.OMI_vehicle_wheel` when `spec.wheel` is omitted)
45
+ ### `KhrAssemblyHandle`, `JointRuntime`, and `KhrBreakawaySpec`
84
46
 
85
- #### `patchGlbJsonChunk(source: ArrayBuffer | Uint8Array, mutator: (gltf: MutableGltfJson) => void): ArrayBuffer`
47
+ - `getBody(nodeName: string): RapierRigidBody | null` — retrieves the `<RigidBody>` handle for `nodeName`.
48
+ - `setJointTarget(nodeName: string, target: number): void` — sets motor position target on one jointed node.
49
+ - `setRoleTarget(role: string, target: number): void` — sets motor position target across jointed nodes matching `role`.
50
+ - `KhrBreakawaySpec`: `{ latchImpulseNs?: number; breakImpulseNs: number }` — decoded from `node.extras.breakaway`. Contact impulses `>= latchImpulseNs` set `unlatched = true` and switch revolute and prismatic Rapier motors to `0` stiffness free-swing (`min(drive.damping ?? 1, 1.5)` damping) until `applyTarget(target)` restores `unlatched = false` and active drive stiffness; contact impulses `>= breakImpulseNs` remove the Rapier `ImpulseJoint` and set `detached = true`.
86
51
 
87
- Patches an existing GLB JSON chunk in memory with 4-byte GLB alignment while preserving any BIN chunk. `RawGltfJson` and `MutableGltfJson` allow `extensionsRequired`, `OMI_vehicle_wheel`, `KOLMO_emitter`, `KHR_lights_punctual`, and arbitrary extension records on root and nodes.
52
+ Each active joint in `<KhrAssembly>` and `<KhrVehicle>` exposes the following `JointRuntime` record:
88
53
 
89
- #### `loadKhrGlb(source: ArrayBuffer | Uint8Array, options?: LoadKhrGlbOptions): Promise<KhrAssetBundle>`
54
+ | Member (`JointRuntime`) | Type | Description |
55
+ | :--- | :--- | :--- |
56
+ | `nodeName` / `role` | `string` / `string \| null` | Authored glTF node name and semantic role |
57
+ | `kind` / `object` | `"revolute" \| "prismatic" \| "fixed"` / `THREE.Object3D` | Constraint kind and visual scene-graph node |
58
+ | `axis` / `limits` | `THREE.Vector3` / `[number, number] \| null` | Normalized parent-frame joint axis and coordinate limits |
59
+ | `drive` / `positionTarget` / `velocityTarget` | `KhrJointDriveSpec \| null` / `number \| null` / `number` | Authored drive spec and live motor targets |
60
+ | `rapierJoint` / `parentBody` / `childBody` | `RAPIER.ImpulseJoint \| null` / `RAPIER.RigidBody \| null` / `RAPIER.RigidBody \| null` | Live Rapier constraint (`null` after breakaway) and connected rigid bodies |
61
+ | `unlatched` / `detached` | `boolean` / `boolean` | Latch-release state (`>= latchImpulseNs`) and full breakaway state (`>= breakImpulseNs`) |
62
+ | `getCoordinate()` | `() => number` | Measures current revolute angle (radians) or prismatic translation (meters) |
63
+ | `applyTarget(target)` | `(target: number) => void` | Sets `positionTarget = target`, clears `unlatched = false`, reconfigures active drive stiffness, and wakes dynamic bodies |
64
+ | `applyImpactImpulse(impulseNs)` | `(impulseNs: number) => "intact" \| "unlatched" \| "detached"` | Evaluates contact impulse against `latchImpulseNs` and `breakImpulseNs` |
90
65
 
91
- Parses a GLB buffer with `createKhrGltfPlugin(options)` (and headless texture stub—including `EXT_texture_webp`, `EXT_texture_avif`, and `KHR_texture_basisu`—when `document` is absent and either `createImageBitmap` or `self` is absent), validates all `KHR_physics_rigid_bodies`, `KHR_implicit_shapes`, `OMI_vehicle_wheel`, and scale invariants, mirrors node `extensions.KOLMO_emitter` onto `obj.userData` when absent, and returns a `KhrAssetBundle`:
92
- - `scene: THREE.Group`
93
- - `bodies: KhrBodySpec[]`
94
- - `wheels: EcctrlWheelTag[]`
95
- - `propellers: EcctrlPropellerTag[]`
96
- - `sockets: Record<string, [number, number, number]>`
97
- - `totalDynamicMass: number`
98
- - `centerOfMass: [number, number, number]`
99
- - `tune?: Partial<KhrCarConfig>`
100
- - `droneTune?: Partial<KhrDroneConfig>`
66
+ ### `<KhrCollider>` ([KhrCollider.tsx](../src/KhrCollider.tsx))
101
67
 
102
- #### `createKhrGltfPlugin(options?: KhrPluginOptions)`
68
+ Instantiates the Rapier collider matching a `KhrColliderSpec` (`box`, `sphere`, `cylinder`, `capsule`, `convexHull`, or `trimesh`), mapping `frictionCombine` and `restitutionCombine` onto Rapier `CoefficientCombineRule` values and flushing parent body mass properties immediately on mount.
103
69
 
104
- Creates the `GLTFLoader` plugin used by `loadKhrGlb` and `useKhrGlb`.
105
- - `KhrPluginOptions`: `{ extractRole?: (nodeName, extras) => string | null; isSocketNode?: (nodeName, extras) => boolean | string }`
106
- - `LoadKhrGlbOptions`: `KhrPluginOptions & { loader?: GLTFLoader }`
107
- - `UseKhrGlbOptions`: `KhrPluginOptions & { extendLoader?: (loader: GLTFLoader) => void; cacheKey?: string }`
108
-
109
- #### `useKhrGlb(url: string, options?: UseKhrGlbOptions): KhrAssetBundle`
110
-
111
- React Three Fiber Suspense hook (`useKhrGlb.preload(url, options)` and `useKhrGlb.clear(url, options?)` attached) that caches the template parse and returns an isolated `cloneKhrBundle(template)` instance.
112
-
113
- #### Bundle Ownership & Scale Validators
114
-
115
- - `cloneKhrBundle(bundle: KhrAssetBundle): KhrAssetBundle` — deep-clones the Three.js scene graph while rebinding all `bodies`, `wheels`, `propellers`, and collider arrays to cloned `Object3D`s.
116
- - `claimBundleMount(bundle: KhrAssetBundle, ownerComponent: string): void` / `releaseBundleMount(bundle: KhrAssetBundle): void` — prevents accidental dual-mounting of the same live `KhrAssetBundle` scene graph.
117
- - `disposeKhrBundle(bundle: KhrAssetBundle): void` — disposes non-shared geometries, materials, and textures owned by a root template bundle (and releases mount ownership on clones).
118
- - `assertUnitScale(scale: unknown, owner: string): void` / `assertIdentityWorldScale(obj: THREE.Object3D, nodeName: string): void` / `assertSceneIdentityWorldScale(root: THREE.Object3D): void` — enforce unit `[1, 1, 1]` scale.
119
- - `KhrValidationError` — thrown on all invalid schemas, missing masses/inertias, detached nodes, or non-unit scales.
120
-
121
- ---
122
-
123
- ### Schema & Types Reference
124
-
125
- - `KhrCombineMode`: `"average" | "minimum" | "maximum" | "multiply"`
126
- - `KhrImplicitShape`:
127
- - `{ type: "box"; size: [number, number, number] }` (JSON default `box.size = [1, 1, 1]`)
128
- - `{ type: "sphere"; radius: number }` (JSON default `sphere.radius = 0.5`)
129
- - `{ type: "cylinder"; height: number; radiusTop: number; radiusBottom: number }` (JSON defaults `height = 2.0`, `radius = 0.5`, supports `radius` shorthand for both radii; non-tapered only)
130
- - `{ type: "capsule"; height: number; radiusTop: number; radiusBottom: number }` (JSON defaults `height = 1.0`, `radius = 0.5`, supports `radius` shorthand for both radii; non-tapered only)
131
- - `KhrColliderShape`: `KhrImplicitShape | { type: "convexHull"; vertices: Float32Array; meshNodeName: string } | { type: "trimesh"; vertices: Float32Array; indices: Uint32Array; meshNodeName: string }`
132
- - `KhrColliderSpec`: `{ shape, localPosition, localQuaternion, friction?, restitution?, frictionCombine?, restitutionCombine?, collisionGroups? }` (collision system bitmaps are scoped per parsed GLB, up to 16 unique systems per bundle)
133
- - `KhrJointDriveSpec`: `{ type?: "linear" | "angular"; mode: "force" | "acceleration"; axis?: 0 | 1 | 2; positionTarget?; velocityTarget?; stiffness?; damping?; maxForce? }`
134
- - `KhrJointSpec`: `{ index, nodeName, connectedNodeName, kind: "revolute" | "prismatic" | "fixed", axis, limits, limitStiffness?, limitDamping?, enableCollision, drive, drives, anchor1, anchor2, role }`
135
- - `KhrBodySpec`: `{ nodeName, isKinematic, mass, centerOfMass, inertiaDiagonal, inertiaOrientation, linearVelocity?, angularVelocity?, gravityFactor?, localPosition, localQuaternion, colliders, joint, object, role }`
136
- - `OmiVehicleWheelSpec`: `{ radius, width, maxForce?, steering?, propulsion?, maxSteeringAngle?, suspensionStiffness?, suspensionDampingCompression?, suspensionDampingRebound?, suspensionTravel? }`
137
- - `loadKhrGlb` accepts both `boolean` and finite non-negative `number` (`val !== 0`) for `OMI_vehicle_wheel.steering` and `propulsion` (defaulting `maxSteeringAngle` to numeric `steering > 0` when omitted).
138
- - `EcctrlWheelTag`: `{ nodeName, object, position, quaternion?, radius, width, steer, steerInvert?, drive, driveInvert?, brake, travel, sag, springK?, dampingC?, maxBrakeTorque?, maxSteeringAngle?, rollingResistanceCoef?, wheelDensity?, driveTorqueWeight?, tireGripFactor?, latFrictionEllipseScale?, relaxLngRate?, relaxLatRate?, lngSlipRatioCurveData?, latSlipRatioCurveData? }`
139
- - When `OMI_vehicle_wheel` is present (`gltf.extensions.OMI_vehicle_wheel.wheels[]` + node `extensions.OMI_vehicle_wheel.wheel`), `extras.ecctrlWheel` merges over OMI-derived defaults (`travel = suspensionTravel ?? 0.25`, `sag = min(travel * 0.4, 0.1)`, `brake = true`, `dampingC = avg(compression, rebound)`, `maxBrakeTorque = maxForce * radius`, `maxSteeringAngle`). Strict `ecctrlWheel` validation applies when only `extras.ecctrlWheel` is present.
140
- - `EcctrlPropellerTag`: `{ nodeName, object, position, quaternion?, maxThrust, torqueRatio?, invertThrust?, invertTorque? }`
141
- - `KhrCarConfig`: `{ controlMode?, engineHorsepower?, engineMaxRPM?, gearRatios?, finalDriveRatio?, transmissionMode?, shiftUpRPM?, shiftDownRPM?, shiftCooldown?, steerRate?, maxSteerAngle?, reverseTorqueScale?, reverseRPMScale?, engineTorqueCurveData?, steerAngleCurveData? }`
142
- - `KhrDroneConfig`: `{ controlMode?, maxYawRate?, maxHorizSpeed?, maxVertSpeed?, maxTiltAngle?, airDragFactor?, TILT_P?, TILT_D?, YAW_POS_P?, YAW_VEL_P?, VERT_POS_P?, VERT_POS_D?, HORIZ_POS_P?, HORIZ_POS_D?, HORIZ_VEL_P?, VERT_VEL_P? }`
70
+ | Prop (`KhrColliderProps`) | Type | Default | Description |
71
+ | :--- | :--- | :--- | :--- |
72
+ | `c` | `KhrColliderSpec` | required | Decoded KHR shape, local pose, friction, restitution, and filter groups |
73
+ | `position` | `[number, number, number]` | `c.localPosition` | Pose override in the parent `RigidBody` frame |
74
+ | `quaternion` | `[number, number, number, number]` | `c.localQuaternion` | Orientation override in the parent `RigidBody` frame |
75
+ | `massProperties` | `ColliderMass` | `{ density: 0 }` | Declarative `{ mass, centerOfMass, principalAngularInertia, angularInertiaLocalFrame }` |
76
+ | `ref` | `React.Ref<RapierCollider>` | — | Imperative Rapier collider reference |
77
+
78
+ ### Export, Load, and Bundle Schemas
79
+
80
+ Implemented across [khrExporter.ts](../src/khrExporter.ts), [khrExportEncoders.ts](../src/khrExportEncoders.ts), [khrGlb.ts](../src/khrGlb.ts), [khrLoader.ts](../src/khrLoader.ts), [khrPlugin.ts](../src/khrPlugin.ts), [khrPluginHelpers.ts](../src/khrPluginHelpers.ts), [khrBundleFinalize.ts](../src/khrBundleFinalize.ts), [khrParsers.ts](../src/khrParsers.ts), [khrShapeParser.ts](../src/khrShapeParser.ts), [khrJointParser.ts](../src/khrJointParser.ts), [khrRotorDecoders.ts](../src/khrRotorDecoders.ts), [khrExtras.ts](../src/khrExtras.ts), [useKhrGlb.ts](../src/useKhrGlb.ts), [khrClone.ts](../src/khrClone.ts), [khrInertia.ts](../src/khrInertia.ts), [khrMassProps.ts](../src/khrMassProps.ts), [khrTypes.ts](../src/khrTypes.ts), [khrConfigTypes.ts](../src/khrConfigTypes.ts), and [khrVehicleTypes.ts](../src/khrVehicleTypes.ts).
81
+
82
+ - `exportKhrGlb(root, specs, sceneExtras?): Promise<ArrayBuffer>` — serializes `root` through `GLTFExporter` and writes `KHR_implicit_shapes`, `KHR_physics_rigid_bodies`, `OMI_vehicle_wheel`, custom `extensions`, and `sceneExtras` into a 4-byte-aligned binary GLB.
83
+ - `patchGlbJsonChunk(source, mutator): ArrayBuffer` — mutates a GLB JSON chunk in memory while preserving its binary buffer chunk.
84
+ - `loadKhrGlb(source, options?): Promise<KhrAssetBundle>` — parses and validates a binary GLB into a `KhrAssetBundle`, cloning each node's `extensions.KOLMO_emitter` payload onto `object.userData.KOLMO_emitter` and resolving `ikSockets`, `tune`, and `droneTune` from `scene.extras` with fallback to root `gltf.extras`.
85
+ - `createKhrGltfPlugin(options?)` and `useKhrGlb(url, options?)` — `GLTFLoader` plugin factory and Suspense-cached React Three Fiber hook.
86
+ - `cloneKhrBundle`, `claimBundleMount`, `releaseBundleMount`, `disposeKhrBundle` — scene-graph cloning and mount ownership utilities; `disposeKhrBundle(clone)` retires clone mount ownership while preserving shared template GPU resources, whereas `disposeKhrBundle(template)` on a root `loadKhrGlb` or `loadSand3dBundle` bundle disposes unique GPU geometries, materials, and textures once.
87
+ - `assertUnitScale`, `assertIdentityWorldScale`, `assertSceneIdentityWorldScale` — unit `[1, 1, 1]` scale validators throwing `KhrValidationError` on scaled transforms.
88
+
89
+ `exportKhrGlb` accepts an array of `KhrExportNodeSpec` descriptors (with joint drives typed as `KhrJointDriveSpec: { type?: "linear" | "angular"; mode: "force" | "acceleration"; axis?: 0 | 1 | 2; positionTarget?: number; velocityTarget?: number; stiffness?: number; damping?: number; maxForce?: number }`):
90
+
91
+ | Field (`KhrExportNodeSpec`) | Type | Description |
92
+ | :--- | :--- | :--- |
93
+ | `nodeName` | `string` | Unique glTF node name in `root` targeted by this specification (identifies the jointed child node when `joint` is set) |
94
+ | `motion` | `{ isKinematic?, mass?, centerOfMass?, inertiaDiagonal?, inertiaOrientation?, linearVelocity?, angularVelocity?, gravityFactor? }` | Rigid-body motion record written to `KHR_physics_rigid_bodies.motion` |
95
+ | `collider` | `{ shape?, meshNodeName?, convexHull?, friction?, restitution?, frictionCombine?, restitutionCombine?, collisionSystems?, collideWithSystems?, notCollideWithSystems? }` | Analytic `KHR_implicit_shapes` or mesh-referenced collider plus material and collision filter lists |
96
+ | `joint` | `{ connectedNodeName: string; kind: "revolute" \| "prismatic" \| "fixed"; axis?; limits?; limitStiffness?; limitDamping?; enableCollision?; drive?; drives? }` | Constrains child `nodeName` to parent `connectedNodeName`; pivot anchors (`anchor1` in parent local space, `anchor2 = [0, 0, 0]` at the child origin) derive from `nodeName`'s local transform on `root`, `axis` is expressed in the child node's local coordinate frame, singular `drive` configures the primary joint axis, and `drives` (`KhrJointDriveSpec[]`) configures multi-axis 6-DOF drives |
97
+ | `wheel` | `OmiVehicleWheelSpec` | Explicit `OMI_vehicle_wheel` descriptor (auto-synthesized from `extras.ecctrlWheel` if omitted) |
98
+ | `extras` | `Record<string, unknown>` | Node metadata including `breakaway`, `isIkAnchor`, `socketId`, `contactDots` (`Array<{ role: string; pos: [number, number, number] }>` transformed into scene-space `bundle.sockets[role]`), `role`, `ecctrlWheel`, and `ecctrlPropeller` |
99
+ | `extensions` | `Record<string, unknown>` | Custom node-level glTF extensions such as `KOLMO_emitter` merged into `extensionsUsed` |
100
+
101
+ `loadKhrGlb`, `useKhrGlb`, `cloneKhrBundle`, and `loadSand3dBundle` return a `KhrAssetBundle` with the following fields:
102
+
103
+ | Field (`KhrAssetBundle`) | Type | Description |
104
+ | :--- | :--- | :--- |
105
+ | `scene` | `THREE.Group` | Unit-scale root scene hierarchy (with `node.extensions.KOLMO_emitter` cloned onto `node.userData.KOLMO_emitter`) |
106
+ | `bodies` | `KhrBodySpec[]` | Rigid bodies decoded from `KHR_physics_rigid_bodies`: `{ nodeName, isKinematic, mass, centerOfMass, inertiaDiagonal, inertiaOrientation, linearVelocity?, angularVelocity?, gravityFactor?, localPosition, localQuaternion, colliders, joint, breakaway?, object, role }` |
107
+ | `wheels` | `EcctrlWheelTag[]` | Decoded `OMI_vehicle_wheel` and `extras.ecctrlWheel` suspension records |
108
+ | `propellers` | `EcctrlPropellerTag[]` | Decoded `extras.ecctrlPropeller` thrust records |
109
+ | `sockets` | `Record<string, [number, number, number]>` | Scene-space coordinates merged in order (later entries overwrite matching keys): node traversal (`isSocketNode` string return, then `extras.socketId`, then `node.name` when `extras.isIkAnchor === true` or boolean `isSocketNode` returns `true`, followed by each node's `extras.contactDots` roles), then `scene.extras.ikSockets` (with fallback to `gltf.extras.ikSockets`) |
110
+ | `totalDynamicMass` | `number` | Sum of dynamic `KhrBodySpec.mass` values in kilograms |
111
+ | `centerOfMass` | `[number, number, number]` | Mass-weighted composite dynamic center of mass in scene coordinates |
112
+ | `tune` | `Partial<KhrCarConfig>` | Optional ground-vehicle tuning resolved from `scene.extras.tune` with fallback to `gltf.extras.tune` |
113
+ | `droneTune` | `Partial<KhrDroneConfig>` | Optional flight tuning resolved from `scene.extras.droneTune` with fallback to `gltf.extras.droneTune` |
114
+
115
+ ### Wheel, Propeller, and Tuning Interfaces
116
+
117
+ Defined in [khrVehicleTypes.ts](../src/khrVehicleTypes.ts) and [khrConfigTypes.ts](../src/khrConfigTypes.ts):
118
+
119
+ ```ts
120
+ export interface KhrCurvePoint {
121
+ x: number;
122
+ y: number;
123
+ r_in?: number;
124
+ r_out?: number;
125
+ w_in?: number;
126
+ w_out?: number;
127
+ }
128
+
129
+ export interface KhrCurveData {
130
+ points: KhrCurvePoint[];
131
+ samples?: number;
132
+ }
133
+
134
+ export interface OmiVehicleWheelSpec {
135
+ radius: number;
136
+ width: number;
137
+ maxForce?: number;
138
+ steering?: boolean;
139
+ propulsion?: boolean;
140
+ maxSteeringAngle?: number;
141
+ suspensionStiffness?: number;
142
+ suspensionDampingCompression?: number;
143
+ suspensionDampingRebound?: number;
144
+ suspensionTravel?: number;
145
+ }
146
+
147
+ export interface EcctrlWheelTag {
148
+ nodeName: string;
149
+ object: THREE.Object3D;
150
+ position: [number, number, number];
151
+ quaternion?: [number, number, number, number];
152
+ radius: number;
153
+ width: number;
154
+ steer: boolean;
155
+ steerInvert?: boolean;
156
+ drive: boolean;
157
+ driveInvert?: boolean;
158
+ brake: boolean;
159
+ travel: number;
160
+ sag: number;
161
+ springK?: number;
162
+ dampingC?: number;
163
+ maxBrakeTorque?: number;
164
+ maxSteeringAngle?: number;
165
+ rollingResistanceCoef?: number;
166
+ wheelDensity?: number;
167
+ driveTorqueWeight?: number;
168
+ tireGripFactor?: number;
169
+ latFrictionEllipseScale?: number;
170
+ relaxLngRate?: number;
171
+ relaxLatRate?: number;
172
+ lngSlipRatioCurveData?: KhrCurveData;
173
+ latSlipRatioCurveData?: KhrCurveData;
174
+ }
175
+
176
+ export interface EcctrlPropellerTag {
177
+ nodeName: string;
178
+ object: THREE.Object3D;
179
+ position: [number, number, number];
180
+ quaternion?: [number, number, number, number];
181
+ maxThrust: number;
182
+ torqueRatio?: number;
183
+ invertThrust?: boolean;
184
+ invertTorque?: boolean;
185
+ }
186
+
187
+ export interface KhrCarConfig {
188
+ controlMode?: "VELOCITY" | "POSITION";
189
+ engineHorsepower?: number;
190
+ engineMaxRPM?: number;
191
+ gearRatios?: number[];
192
+ finalDriveRatio?: number;
193
+ transmissionMode?: "auto" | "manual";
194
+ shiftUpRPM?: number;
195
+ shiftDownRPM?: number;
196
+ shiftCooldown?: number;
197
+ steerRate?: number;
198
+ maxSteerAngle?: number;
199
+ reverseTorqueScale?: number;
200
+ reverseRPMScale?: number;
201
+ engineTorqueCurveData?: KhrCurveData;
202
+ steerAngleCurveData?: KhrCurveData;
203
+ }
204
+
205
+ export interface KhrDroneConfig {
206
+ controlMode?: "VELOCITY" | "POSITION";
207
+ maxYawRate?: number;
208
+ maxHorizSpeed?: number;
209
+ maxVertSpeed?: number;
210
+ maxTiltAngle?: number;
211
+ airDragFactor?: number;
212
+ TILT_P?: number;
213
+ TILT_D?: number;
214
+ YAW_POS_P?: number;
215
+ YAW_VEL_P?: number;
216
+ VERT_POS_P?: number;
217
+ VERT_POS_D?: number;
218
+ HORIZ_POS_P?: number;
219
+ HORIZ_POS_D?: number;
220
+ HORIZ_VEL_P?: number;
221
+ VERT_VEL_P?: number;
222
+ }
223
+ ```
143
224
 
144
225
  ---
145
226
 
146
227
  ## `@khr3/core/vehicle`
147
228
 
148
- ### `<KhrVehicle>`
229
+ Implemented across [vehicle.ts](../src/vehicle.ts), [KhrVehicle.tsx](../src/KhrVehicle.tsx), [khrVehicleChassis.ts](../src/khrVehicleChassis.ts), [khrVehicleJointHelpers.ts](../src/khrVehicleJointHelpers.ts), [khrVehicleJoints.tsx](../src/khrVehicleJoints.tsx), [khrVehicleRotors.tsx](../src/khrVehicleRotors.tsx), [khrVehicleSlots.tsx](../src/khrVehicleSlots.tsx), and [wheelLoads.ts](../src/wheelLoads.ts).
149
230
 
150
- Mounts an exported vehicle/drone `.glb` at its natural asset origin inside `<EcctrlVehicle>`, passing composite chassis `massProperties` (`mass`, `centerOfMass`, `principalAngularInertia`, `angularInertiaLocalFrame`) declaratively onto the primary `<KhrCollider>`, enforcing zero-gravity `<ShapeCastWheel>` gating (even if `wheelConfig.enable` is passed), and clearing disabled wheel/propeller impulse caches on rotor toggle.
231
+ ### `<KhrVehicle>` and Rotor Mounting
151
232
 
152
- #### Config Types
233
+ `<KhrVehicle>` mounts a vehicle or craft `KhrAssetBundle` inside `@pinkaphant/ecctrl/vehicle` `<EcctrlVehicle>` in a right-handed `+Z` forward, `+Y` up, `+X` left coordinate frame while preserving the scene origin `[0, 0, 0]` and supplying composite chassis `massProperties` via `<KhrCollider>`. `<KhrVehicle>` partitions `frontWheelConfig` (`mountPos[2] >= chassis.com[2]`) and `rearWheelConfig` (`mountPos[2] < chassis.com[2]`) against the composite chassis root `chassis.com[2]`, while calling `solveWheelLoads` against `bundle.totalDynamicMass` and `bundle.centerOfMass`.
153
234
 
154
- - `KhrWheelConfig`: `Partial<Omit<ShapeCastWheelProps, "ref" | "key" | "children">>`
155
- - `KhrPropellerConfig`: `Partial<Omit<ThrustPropellerProps, "ref" | "key" | "children">>`
156
- - `SolvedWheel`: `{ tag: EcctrlWheelTag; cornerMassKg: number; springK: number; dampingC: number; mountPos: [number, number, number] }`
235
+ - **Rotor Mounting ([khrVehicleRotors.tsx](../src/khrVehicleRotors.tsx))**: `KhrVehicleRotors` instantiates `@pinkaphant/ecctrl/vehicle` `<ShapeCastWheel>` (cylinder-cast suspension actuator parameterized by `rayLength`, `rayShapeR`, `rayShapeH`, `springK`, `dampingC`, and Pacejka slip curves) and `<ThrustPropeller>` components, each wrapping `<RotorVisualSlot>` children.
236
+ - **Microgravity Gating & Visual Slots ([khrVehicleSlots.tsx](../src/khrVehicleSlots.tsx))**: Exports `ZeroGWheelGate` and `ZeroGWheelPostClear` (gating `<ShapeCastWheel>` forces in microgravity or `enableCustomGravity` worlds and incrementing `wheelEpoch` upon gravity restoration), `RotorVisualSlot` (reparenting wheel and propeller `THREE.Object3D` subtrees into live rotor groups), `captureRotorOrigins`, and disabled-rotor state reset helpers (`resetAllWheelHits`, `resetDisabledWheelHits`, `resetAllPropellerOutputs`, `resetDisabledRotors`).
237
+ - **Wheel Load Solver ([wheelLoads.ts](../src/wheelLoads.ts))**: `solveWheelLoads(wheels, totalMassKg, com, dampingRatio = 0.7): SolvedWheel[]` solves static-equilibrium corner masses for `N >= 1` wheels around `com` and returns `SolvedWheel` records (`{ tag, cornerMassKg, springK, dampingC, mountPos }`), where `springK = tag.springK ?? (cornerMassKg * 9.81) / Math.max(tag.sag, 1e-4)`, `dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg)`, and `mountPos` adds local `+Y` suspension lift `[0, Math.max(0, tag.travel - tag.sag), 0]` (rotated by `tag.quaternion` when present) to `tag.position`.
157
238
 
158
- #### `KhrVehicleProps`
159
-
160
- Extends `Omit<EcctrlVehicleProps, "ref" | "carConfig" | "droneConfig">`:
161
- - `bundle: KhrAssetBundle` — required bundle with dynamic chassis body (`>= 1` collider) and wheel/propeller tags. Jointed dynamic bodies (`Door_*`, `Hood`, `Trunk`, etc.) mount as independent dynamic `<RigidBody>` panels connected to the chassis via real Rapier `ImpulseJoint`s and register into `JointRegistryContext`.
162
- - `ref?: React.Ref<EcctrlVehicleHandle>` / `vehicleRef?: React.RefObject<EcctrlVehicleHandle | null>`
163
- - `jointsRef?: React.Ref<KhrVehicleJointsHandle>` — imperative handle (`hasJoints`, `jointNames`, `getBody(nodeName)`, `getJointRuntime(nodeName)`, `getJointAngle(nodeName)`, `setJointTarget(nodeName, target)`, `setRoleTarget(role, target)`, `toggleHitObject(hit)`, `toggleRolePrefix(prefix)`) driving articulated vehicle panels via Rapier motor joints (and reporting `unlatched` / `detached` state on `extras.breakaway` impacts).
164
- - `carConfig?: Partial<KhrCarConfig>` — overrides `bundle.tune` (and any `OMI_vehicle_wheel` `maxSteeringAngle` fallback)
165
- - `droneConfig?: Partial<KhrDroneConfig>` — overrides `bundle.droneTune`
166
- - `wheelConfig?: KhrWheelConfig` — shared overrides applied to every `<ShapeCastWheel>`
167
- - `frontWheelConfig?: KhrWheelConfig` / `rearWheelConfig?: KhrWheelConfig` — per-axle (`mountPos[2] >= chassis.com[2]` front vs `< chassis.com[2]` rear) overrides
168
- - `propellerConfig?: KhrPropellerConfig` — shared overrides applied to every `<ThrustPropeller>`
169
- - `colliders` / `scale`: forbidden to override or set non-1 (`KhrValidationError`)
170
-
171
- Defaults applied per wheel unless overridden (preserving `ecctrl` `<ShapeCastWheel>` defaults `groundDetection="shapeCast"` and `minLatRelaxCoeff={0.3}`):
172
- - `rayLength={tag.travel}`, `rayShapeR={tag.radius}`, `rayShapeH={tag.width * 0.5}`, `wheelModelRadius={tag.radius}`
173
- - `wheelModelDensity={tag.wheelDensity ?? (0.035 * cornerMassKg) / (Math.PI * tag.radius * tag.radius * tag.width)}`
174
- - `maxBrakeTorque={tag.maxBrakeTorque ?? cornerMassKg * 9.81 * tag.radius}`
175
-
176
- ### `solveWheelLoads(wheels, totalMassKg, com, dampingRatio = 0.7): SolvedWheel[]`
177
-
178
- Static equilibrium corner-mass distribution for any $N \ge 1$ wheels:
179
- 1. Solves minimum-norm corner masses $m_i$ satisfying $\sum m_i = M$, $\sum (x_i - \text{com}_x) m_i = 0$, $\sum (z_i - \text{com}_z) m_i = 0$, projecting onto $m_i \ge \min(0.05 M, M / N)$ when CoM lies outside the support polygon.
180
- 2. Computes `springK = tag.springK ?? (cornerMassKg * 9.81) / tag.sag` and `dampingC = tag.dampingC ?? 2 * dampingRatio * sqrt(springK * cornerMassKg)`.
181
- 3. Computes natural scene-space `mountPos = tag.position + rotate((0, max(0, tag.travel - tag.sag), 0), tag.quaternion)`.
239
+ | Prop (`KhrVehicleProps`) | Type | Default | Description |
240
+ | :--- | :--- | :--- | :--- |
241
+ | `bundle` | `KhrAssetBundle` | required | Cloned or loaded KHR vehicle/craft bundle at unit `[1, 1, 1]` scale |
242
+ | `position` | `EcctrlVehicleProps["position"]` | `[0, 0.5, 0]` | Chassis spawn position in world space |
243
+ | `ref` | `React.Ref<EcctrlVehicleHandle>` | — | Forwarded React ref receiving the `<EcctrlVehicle>` controller handle |
244
+ | `vehicleRef` | `React.RefObject<EcctrlVehicleHandle \| null>` | — | Mutable ref object synchronized alongside `ref` |
245
+ | `jointsRef` | `React.Ref<KhrVehicleJointsHandle>` | — | Imperative handle for articulated doors, hoods, canopies, and breakaway parts |
246
+ | `enable` | `boolean` | `true` | Enables `<EcctrlVehicle>` input, wheels, and propellers |
247
+ | `enableCustomGravity` | `boolean` | `false` | Activates external gravity field mode and microgravity wheel gating |
248
+ | `carConfig` | `Partial<KhrCarConfig>` | `bundle.tune` | Overrides merged over `bundle.tune` and `OMI_vehicle_wheel.maxSteeringAngle` |
249
+ | `droneConfig` | `Partial<KhrDroneConfig>` | `bundle.droneTune` | Overrides merged over `bundle.droneTune` |
250
+ | `wheelConfig` | `KhrWheelConfig` | — | `Partial<Omit<ShapeCastWheelProps, "ref" \| "key" \| "children">>` applied to every wheel |
251
+ | `frontWheelConfig` | `KhrWheelConfig` | — | Overrides applied to wheels with `mountPos[2] >= chassis.com[2]` |
252
+ | `rearWheelConfig` | `KhrWheelConfig` | — | Overrides applied to wheels with `mountPos[2] < chassis.com[2]` |
253
+ | `propellerConfig` | `KhrPropellerConfig` | — | `Partial<Omit<ThrustPropellerProps, "ref" \| "key" \| "children">>` applied to every propeller |
254
+ | `...ecctrlRest` | `Omit<EcctrlVehicleProps, ...>` | — | Rotation, quaternion, velocities, `gravityScale`, and `<EcctrlVehicle>` props |
255
+
256
+ ### `KhrVehicleJointsHandle` ([khrVehicleJoints.tsx](../src/khrVehicleJoints.tsx))
257
+
258
+ Imperative handle exposed via `<KhrVehicle jointsRef={...} />` for articulated vehicle panels and breakaway parts:
259
+
260
+ | Member | Type | Description |
261
+ | :--- | :--- | :--- |
262
+ | `hasJoints` | `readonly boolean` | True if `bundle.bodies` includes articulated child panels |
263
+ | `jointNames` | `readonly string[]` | Ordered `nodeName` list of articulated vehicle parts |
264
+ | `getBody(nodeName)` | `(nodeName: string) => RapierRigidBody \| null` | Returns the child `<RigidBody>` handle for `nodeName` |
265
+ | `getJointRuntime(nodeName)` | `(nodeName: string) => JointRuntime \| null` | Returns the active `JointRuntime` state for `nodeName` |
266
+ | `getJointAngle(nodeName)` | `(nodeName: string) => number \| null` | Reads the current joint coordinate (radians or meters) |
267
+ | `setJointTarget(nodeName, target)` | `(nodeName: string, target: number) => void` | Sets motor position target on one vehicle joint |
268
+ | `setRoleTarget(role, target)` | `(role: string, target: number) => void` | Sets motor position target across vehicle joints matching `role` |
269
+ | `toggleHitObject(hit)` | `(hit: THREE.Object3D \| null) => boolean` | Walks ancestors of a raycast hit mesh and toggles the enclosing driven joint between `0` and its open limit |
270
+ | `toggleRolePrefix(prefix)` | `(prefix: string) => void` | Toggles driven joints whose `role` or `nodeName` starts with `prefix` (case-insensitive) |
182
271
 
183
272
  ---
184
273
 
185
274
  ## `@khr3/core/curves`
186
275
 
187
- ### `compilePacejkaCurve(B, C, E, samples = 100, axis = "lng"): CurveData`
188
-
189
- Exact 8-knot Fritsch–Carlson monotone Pacejka Magic Formula compiler compatible with `ecctrl` `CurveLUT`:
190
- - `axis = "lng"`: `u = x` (matches `ShapeCastWheel` `lngSlipRatio`).
191
- - `axis = "lat"`: `u = sin((pi / 2) * x)` (matches `ShapeCastWheel` `latSlipRatio`).
276
+ Implemented across [curves.ts](../src/curves.ts) and [pacejka.ts](../src/pacejka.ts).
192
277
 
193
- ### Curve Types
278
+ ### Pacejka Curve Compiler and Presets
194
279
 
195
- - `CurvePoint`: `{ x: number; y: number; r_in?: number; r_out?: number; w_in?: number; w_out?: number }`
196
- - `CurveData`: `{ points: CurvePoint[]; samples?: number }`
197
- - `TireArchetypePreset`: `{ lng: CurveData; lat: CurveData; muPeakLng: number; latFrictionEllipseScale: number; relaxLngRate: number; relaxLatRate: number }`
280
+ - `compilePacejkaCurve(B, C, E, samples = 100, axis = "lng"): CurveData` — evaluates the Pacejka Magic Formula `phi(u) = B * u - E * (B * u - atan(B * u))` and `yRaw(u) = sin(C * atan(phi(u)))`, normalizing by the peak over `x in [0, 1]` into an 8-knot Fritsch–Carlson monotone cubic Hermite `CurveData` (`{ points: CurvePoint[]; samples?: number }`).
281
+ - `axis: "lng"` evaluates `u = x` matching `<ShapeCastWheel>` longitudinal slip ratio `|w * R - vx| / |vx|`.
282
+ - `axis: "lat"` evaluates `u = sin((pi / 2) * x)` matching `<ShapeCastWheel>` normalized lateral slip angle `atan2(|vy|, |vx|) / (pi / 2)`.
283
+ - Each `CurvePoint` (`{ x, y, r_in?, r_out?, w_in?, w_out? }`) encodes Fritsch–Carlson monotone slopes as clamped radian tangent angles `atan(dy / dx)` in `[-1.54, 1.54]` on `r_in` and `r_out` with unit tangent weights `1` (`w_in = 1`, `w_out = 1`).
284
+ - `tireGripForSurface(muPeakLng, groundColliderFriction = 0.5): number` — scales unit-peak Pacejka curves to physical peak longitudinal friction `muPeakLng` via `2 * muPeakLng - groundColliderFriction`, matching `<ShapeCastWheel>` `(rayHitFriction + tireGripFactor) * 0.5`.
285
+ - `engineHorsepowerForPeakTorque(peakTorqueNm, engineMaxRPM): number` — converts physical peak torque (`N*m`) into `carConfig.engineHorsepower` (`peakTorqueNm * engineMaxRPM / 7022`).
286
+ - Exported types and presets: `type CurvePoint`, `type CurveData`, `type TireArchetypePreset`, `TIRE_ARCHETYPES` (`hypercarDry`, `streetDrift90s`, `offroad6x6At`, `gravelRally`, `wetAsphalt`, `snowIce`), `TIRE_SLIP_CURVES` (`streetRadial`, `driftProgressive`, `offroadLug`), `ENGINE_TORQUE_CURVES` (`w16QuadTurbo`, `naScreamer`, `heavyTurboDiesel`, `evDirectDrive`), and `STEER_SPEED_CURVES` (`progressiveHighway`, `driftCountersteer`, `evSingleGearGt`, `heavy6x6AntiRollover`).
198
287
 
199
- ### Scaling Helpers
288
+ ---
200
289
 
201
- - `tireGripForSurface(muPeakLng, groundColliderFriction = 0.5): number` — returns `2 * muPeakLng - groundColliderFriction` inverting `ShapeCastWheel`'s average friction formula.
202
- - `engineHorsepowerForPeakTorque(peakTorqueNm, engineMaxRPM): number` — returns `(peakTorqueNm * engineMaxRPM) / 7022`.
290
+ ## `@khr3/core/sand3d`
291
+
292
+ Implemented across [sand3d.ts](../src/sand3d.ts), [sand3dTypes.ts](../src/sand3d/sand3dTypes.ts), [sand3dProfiles.ts](../src/sand3d/sand3dProfiles.ts), [sand3dSolids.ts](../src/sand3d/sand3dSolids.ts), [sand3dPrimitives.ts](../src/sand3d/sand3dPrimitives.ts), [sand3dHullAndSweep.ts](../src/sand3d/sand3dHullAndSweep.ts), [sand3dFramesAndEdits.ts](../src/sand3d/sand3dFramesAndEdits.ts), [sand3dCavityOps.ts](../src/sand3d/sand3dCavityOps.ts), [sand3dShellOp.ts](../src/sand3d/sand3dShellOp.ts), [sand3dCompiler.ts](../src/sand3d/sand3dCompiler.ts), [sand3dAssemblyHelpers.ts](../src/sand3d/sand3dAssemblyHelpers.ts), [sand3dTokenizer.ts](../src/sand3d/sand3dTokenizer.ts), [sand3dParser.ts](../src/sand3d/sand3dParser.ts), [sand3dEvaluator.ts](../src/sand3d/sand3dEvaluator.ts), and [sand3dRecipes.ts](../src/sand3d/sand3dRecipes.ts).
293
+
294
+ ### Fluent `s3d` Namespace and Builders
295
+
296
+ - **2D Profiles ([sand3dProfiles.ts](../src/sand3d/sand3dProfiles.ts))**: `rect(w, d, { r, chamfer, segments, center })`, `circle(diameter, segmentsOrOpts = 24, center = [0, 0])`, `ngon(sides, radius, startOrOpts = 0, center = [0, 0])`, `star(points, rOuter, rInner, startOrOpts = 0, center = [0, 0])`, `slot(length, width, segmentsOrOpts = 16, center = [0, 0])`, `polygon(pts, holes)`, `subtractProfileHole(profile, hole, offset = [0, 0])`, and `triangulateProfile2D(profile)` (mutual-visibility hole bridging plus ear clipping).
297
+ - **Manifold 3D Solids ([sand3dSolids.ts](../src/sand3d/sand3dSolids.ts), [sand3dPrimitives.ts](../src/sand3d/sand3dPrimitives.ts), [sand3dHullAndSweep.ts](../src/sand3d/sand3dHullAndSweep.ts))**: `extrude(profile, height, opts)`, `revolve(profile, angleDeg = 360, segments = 24, opts)`, `loft(profiles, heights, opts)`, `sweep(profile, path, opts)` (Bishop parallel-transport frames), `helix(profile, { radius, pitch, turns, segmentsPerTurn, name, color })`, `box(w, h, d, opts)`, `cylinder(diameter, height, opts)`, `tube(outerDiameter, innerDiameter, height, opts)`, `cone(diameterBottom, diameterTop, height, opts)`, `sphere(diameter, opts)`, `dome(diameter, heightOrOpts, opts)`, `torus(majorDiameter, tubeDiameter, opts)`, and `hull(pointsOrSolids, opts)` (3D incremental convex hull). 2D-to-3D axis mapping: `extrude` and `loft` map 2D `[u, v]` profile coordinates onto `[X, Z]` and sweep along `+Y`, while `revolve` sweeps `[radius, y]` around `+Y`.
298
+ - **Topological Frames, Deformations, and Cavity Edits ([sand3dFramesAndEdits.ts](../src/sand3d/sand3dFramesAndEdits.ts), [sand3dCavityOps.ts](../src/sand3d/sand3dCavityOps.ts), [sand3dShellOp.ts](../src/sand3d/sand3dShellOp.ts))**: `grid(nx, ny, pitchX, pitchY = pitchX, center = [0, 0])`, `polar(count, radius, startDeg = 0, spanDeg = 360)`, `at(origin, rotDeg = [0, 0, 0])`, `on(target, selector = "top", offset = [0, 0, 0])` (`"top"`, `"bottom"`, `"front"`, `"back"`, `"left"`, `"right"`, `"+X"`, `"-X"`, `"+Y"`, `"-Y"`, `"+Z"`, `"-Z"`, and corner selectors such as `"+X-Y+Z"`), `hole(solid, diameter, { depth, on, face, segments })` (through and blind cylindrical bores defaulting to `face = "top"` `+Y` with re-triangulated planar cap rings), `pocket(solid, profile, depth, { on, face })` (defaulting to `face = "top"` `+Y`), `shell(solid, thickness, { openFace })`, `chamfer(solid, distance)`, `fillet(solid, radius)`, `taper(solid, factor, axis = "Y")`, `twist(solid, angleDeg, axis = "Y")`, `bend(solid, angleDeg, axis = "X")`, `color(solid, shade, { roughness, metalness, opacity })`, `translate(solid, offset)`, `rotate(solid, rotDeg)`, and `unionSolids(solids, name = "union", shade)`.
299
+ - **Low-Level Helpers and Types**: `@khr3/core/sand3d` also exports `sand3dUnitScale`, `signedArea2D`, `cleanLoop2D`, `finalizeManifoldGeometry`, `resolveFaceFrame`, `type Vec2`, `type Vec3`, `type Quat4`, `type Sand3dPartOpts`, `type Sand3dEmitterKind`, and `type Sand3dNodeItem`.
300
+
301
+ ### Kinematic Assembly, Colliders, and `KOLMO_emitter`
302
+
303
+ Implemented in [sand3dCompiler.ts](../src/sand3d/sand3dCompiler.ts) and [sand3dAssemblyHelpers.ts](../src/sand3d/sand3dAssemblyHelpers.ts):
304
+
305
+ - `s3d.part(name, solid, opts)` — places a rigid-body part with mass, density, material color, role, breakaway thresholds, and collider selection: centered `box`, `sphere`, and `cylinder` solids emit analytic `KHR_implicit_shapes` (`{ type: "box", size }`, `{ type: "sphere", radius }`, `{ type: "cylinder", height, radiusTop, radiusBottom }`), while `"hull"` or off-center solids emit mesh-referenced `convexHull` colliders.
306
+ - `s3d.joint(kind, parent, child, opts)` — authors `revolute`, `prismatic`, or `fixed` `KHR_physics_rigid_bodies` constraints with pivot `anchor`, `axis`, `limits`/`range`, `stiffness`, `damping`, `positionTarget`, `velocityTarget`, `latchImpulseNs`, and `breakImpulseNs`.
307
+ - `s3d.wheel(name, opts)` — emits `OMI_vehicle_wheel` and `extras.ecctrlWheel` suspension metadata with Pacejka slip curves.
308
+ - `s3d.thruster(name, opts)` and `s3d.socket(name, position, opts)` — emit `extras.ecctrlPropeller`, `socketId` / `isIkAnchor` nodes, and canonical `KOLMO_emitter` node extensions:
309
+ - `kind`: `"plume" | "sparkle" | "fume" | "trail" | "flare"` (authoring `"muzzle"` normalizes to `kind: "flare"`, `drive: "fire"`, `socket: "muzzle"`).
310
+ - `drive`: `"throttle" | "boost" | "brake" | "slip" | "reverse" | "turn_l" | "turn_r" | "headlight" | "fire" | "damage" | "always"` (11 supported channels).
311
+ - `color`: `[r, g, b]` linear RGB tuple with components in `[0, 1]`; `size`: positive scalar defaulting to `0.34` on thrusters and `s3d.socket` emitters.
312
+ - `compileSand3dAssembly(input, opts): CompiledSand3dAssembly` — returns `{ scene, specs, sceneExtras, assembly }`, scaling `"mm"` coordinates by `0.001` into unit-scale SI meter geometry.
313
+ - `exportSand3dGlb(input, opts): Promise<Uint8Array>` and `loadSand3dBundle(input, opts): Promise<KhrAssetBundle>`.
314
+
315
+ ### Script Parser, `.s3d.json` Manifests, and Recipes
316
+
317
+ Implemented in [sand3dTokenizer.ts](../src/sand3d/sand3dTokenizer.ts), [sand3dParser.ts](../src/sand3d/sand3dParser.ts), [sand3dEvaluator.ts](../src/sand3d/sand3dEvaluator.ts), and [sand3dRecipes.ts](../src/sand3d/sand3dRecipes.ts):
318
+
319
+ - `isSand3dFileName(fileName)` and `parseSand3dSource(source, opts): Sand3dAssembly` — parses `.sand3d`, `.s3d`, `.s3d.py`, `.s3d.ts`, and `.s3d.json` sources. In Python-style `.sand3d` scripts, `snake_case` keyword arguments (`mass_kg`, `density_kg_m3`, `break_impulse_ns`, `latch_impulse_ns`, `max_thrust`, `plume_color`, `open_face`, `twist_deg`) map to `camelCase` builder options (`massKg`, `densityKgM3`, `breakImpulseNs`, `latchImpulseNs`, `maxThrust`, `plumeColor`, `openFace`, `twistDeg`), and `s3d.export(...)` registers the root solid, part, or assembly. `.s3d.json` manifests accept top-level keys `name`, `units` (`"mm" | "m"`), `parts`, `joints`, `wheels`, `thrusters`, and `sockets` (plus optional `carTune`, `droneTune`, and `extras`), forwarding `centered: true` and `collider` options into `box`, `cylinder`, and `sphere` primitives so centered solids emit analytic `KHR_implicit_shapes` colliders.
320
+ - `SAND3D_RECIPES` (`cnc_mounting_bracket`, `hinged_ammo_chest`, `articulated_robot_arm`, `mars_sample_buggy`, `orbital_reaction_thruster`, `cyclotomic_airlock_bulkhead`), `SAND3D_RECIPE_MAP`, `findSand3dRecipe`, and `buildSand3dRecipe`.
321
+
322
+ ```python
323
+ import sand3d as s3d
324
+
325
+ def bracket(w=80, d=40, t=6, hole_d=6.6, pitch=50):
326
+ plate = s3d.extrude(s3d.rect(w, d, r=4), t, color="#94a3b8")
327
+ bored = s3d.hole(plate, hole_d, on=s3d.grid(2, 1, pitch, 0))
328
+ return s3d.assembly("bracket_rig", [
329
+ s3d.part("Bracket_Base", bored, mass_kg=0.45, break_impulse_ns=1200),
330
+ ], units="mm")
331
+
332
+ s3d.export(bracket())
333
+ ```
334
+
335
+ ```json
336
+ {
337
+ "name": "json_pedestal",
338
+ "units": "mm",
339
+ "parts": [
340
+ {
341
+ "name": "ped_root",
342
+ "primitive": "cylinder",
343
+ "diameter": 60,
344
+ "height": 30,
345
+ "centered": true,
346
+ "massKg": 2.5,
347
+ "color": "#38bdf8"
348
+ }
349
+ ],
350
+ "joints": [],
351
+ "wheels": [],
352
+ "thrusters": [],
353
+ "sockets": []
354
+ }
355
+ ```
203
356
 
204
- ### Built-in Presets
357
+ ---
205
358
 
206
- - `TIRE_ARCHETYPES`: `hypercarDry`, `streetDrift90s`, `offroad6x6At`, `gravelRally`, `wetAsphalt`, `snowIce`
207
- - `TIRE_SLIP_CURVES`: `streetRadial`, `driftProgressive`, `offroadLug`
208
- - `ENGINE_TORQUE_CURVES`: `w16QuadTurbo`, `naScreamer`, `heavyTurboDiesel`, `evDirectDrive`
209
- - `STEER_SPEED_CURVES`: `progressiveHighway`, `driftCountersteer`, `evSingleGearGt`, `heavy6x6AntiRollover`
359
+ ## Test Suites
360
+
361
+ ```bash
362
+ npm run typecheck && npm test && npm run build && npm run example
363
+ ```
364
+
365
+ Verified across 12 automated test suites:
366
+
367
+ - [core.test.ts](../src/core.test.ts) — End-to-end KHR export, binary load, collider inertia, and socket extraction.
368
+ - [schemaFixes.test.ts](../src/schemaFixes.test.ts) — glTF schema edge cases, extension preservation, and validation error checks.
369
+ - [omiWheel.test.ts](../src/omiWheel.test.ts) — `OMI_vehicle_wheel` and `extras.ecctrlWheel` synthesis and round-trips.
370
+ - [r3fMount.test.tsx](../src/r3fMount.test.tsx) — React Three Fiber `<PhysicsWorld>`, `<KhrAssembly>`, and `<KhrVehicle>` mounts.
371
+ - [jointRegistryContext.test.tsx](../src/jointRegistryContext.test.tsx) — Opt-in `JointRegistryContext` provider registration and cleanup.
372
+ - [breakaway.test.tsx](../src/breakaway.test.tsx) — Contact-impulse latch release and dynamic joint breakaway.
373
+ - [hybridRotorGate.test.tsx](../src/hybridRotorGate.test.tsx) — Hybrid wheel and propeller switching.
374
+ - [zeroGVehicle.test.tsx](../src/zeroGVehicle.test.tsx) — Microgravity wheel gating and thruster control.
375
+ - [crossPackage.test.ts](../src/crossPackage.test.ts) — Cross-package round-trips dynamically loading optional sibling `../khr3-vehicles`, `../khr3-launchers`, and `../khr3-assets` builds when present.
376
+ - [indexExports.test.ts](../src/indexExports.test.ts) — Root barrel symbol and TypeScript export assertions.
377
+ - [sand3d.test.ts](../src/sand3d/sand3d.test.ts) — `Sand3D` script evaluation, bore geometry, analytic sphere/cylinder colliders, `.s3d.json` manifests, 6 recipes, and GLB round-trips.
378
+ - [workbenchAssets.test.ts](../src/workbenchAssets.test.ts) — Interactive workbench `Sand3D` vehicle/assembly round-trips, gullwing breakaway thresholds, and `0.08` virtual stick deadzone checks.