@khr3/launchers 0.2.1 → 0.2.3

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 CHANGED
@@ -1,9 +1,12 @@
1
1
  # `@khr3/launchers`
2
2
 
3
- Zero-dependency KHR firearm & launcher moving-part planner (`receiver`, `bolt`, `pump`, `trigger`, `magazine`, `barrel`, `stock`, `screen_rect`), rail/character mount sockets, data-driven ammo catalog, and deterministic 60Hz cycle state machine for `@khr3/core` and `Kolmo`.
3
+ Zero-dependency KHR articulated launcher moving-part planner (`receiver`, `bolt`, `pump`, `trigger`, `magazine`, `barrel`, `stock`, `screen_rect`), rail and character mount sockets, SI ammo catalog, and deterministic cycle state machine for `@khr3/core` and `Kolmo`.
4
4
 
5
5
  - **Zero dependencies & zero `koota`**: Pure TypeScript ESM with `.d.ts` declarations.
6
- - **Articulated KHR output**: `planLauncher(recipe)` lumps fixed parts into `Receiver_Root` (with exact parallel-axis mass & box inertia) and emits prismatic/revolute `KHR_physics_rigid_bodies` joints + spring drives for `Bolt`, `Trigger`, and `Pump`, ready for `@khr3/core` `exportKhrGlb`.
6
+ - **Articulated KHR physics output**: `planLauncher(recipe)` lumps fixed parts and mounted rail attachments into `Receiver_Root` — diagonalizing the full 3x3 parallel-axis inertia tensor into `inertiaDiagonal` + right-handed `inertiaOrientation` quaternion (`[qx, qy, qz, qw]`) — and emits prismatic/revolute `KHR_physics_rigid_bodies` joints with critically damped spring drives for `Bolt`, `Trigger`, and `Pump`.
7
+
8
+ - Full API & integration reference: [docs/api-reference.md](./docs/api-reference.md)
9
+ - Runnable example: [example/index.ts](./example/index.ts)
7
10
 
8
11
  ## Install
9
12
 
@@ -15,30 +18,37 @@ npm install @khr3/launchers
15
18
 
16
19
  | Area | Exports |
17
20
  | --- | --- |
18
- | **Schema & Ammo** | `LAUNCHER_PART_ROLES`, `LAUNCHER_SOCKETS`, `RAIL_SOCKETS`, `CHARACTER_SOCKETS`, `DEFAULT_AMMO_CATALOG`, `validateLauncherSpec` |
19
- | **Recipes & Multi-Body Planner** | `KOLMOGOROV_PISTOL`, `KOLMOGOROV_CARBINE`, `KOLMOGOROV_SHOTGUN`, `LAUNCHER_RECIPES`, `findLauncherRecipe`, `buildLauncherParts`, `resolveLauncherSockets`, `planLauncher` |
20
- | **Deterministic Runtime** | `createLauncherState`, `stepLauncher`, `attachModule`, `detachModule` (fire cadence, bolt/pump cycling, magazine depletion, timed reload, recoil impulse, rail attachments) |
21
+ | **Schema & Ammo** | `LAUNCHER_PART_ROLES`, `LAUNCHER_SOCKETS`, `RAIL_SOCKETS`, `CHARACTER_SOCKETS`, `DEFAULT_AMMO_CATALOG` (`pistol`, `rifle`, `shells_12g`, `laser`, `orb`, `rocket`), `validateLauncherSpec` |
22
+ | **Recipes & Multi-Body Planner** | `PISTOL_9MM`, `CARBINE_556`, `SHOTGUN_12G` (aliases for `KOLMOGOROV_PISTOL`, `KOLMOGOROV_CARBINE`, `KOLMOGOROV_SHOTGUN`), `LAUNCHER_RECIPES`, `findLauncherRecipe`, `buildLauncherParts`, `resolveLauncherSockets`, `sumLauncherBoxes`, `diagonalizeInertiaTensor`, `planLauncher` |
23
+ | **Deterministic Runtime** | `createLauncherState`, `stepLauncher`, `attachModule`, `detachModule` (fractional cooldown carry, smooth `C1` bolt/pump cycle curve, magazine depletion, timed or instant reload, recoil impulse, rail attachments) |
21
24
 
22
25
  ## 1. Plan an Articulated KHR3 Launcher `.glb`
23
26
 
24
27
  ```ts
25
- import { KOLMOGOROV_CARBINE, planLauncher } from "@khr3/launchers";
26
-
27
- const plan = planLauncher(KOLMOGOROV_CARBINE);
28
- // plan.nodes -> scene hierarchy (Receiver_Root + articulated Bolt/Trigger + Socket_* nodes)
29
- // plan.specs -> KhrExportNodeSpec-compatible rigid bodies, colliders, and prismatic/revolute joints
30
- // plan.sceneExtras -> { launcher: plan.spec } for `@khr3/core` exportKhrGlb(root, plan.specs, plan.sceneExtras)
28
+ import { CARBINE_556, attachModule, planLauncher } from "@khr3/launchers";
29
+
30
+ const equipped = {
31
+ ...CARBINE_556,
32
+ spec: attachModule(CARBINE_556.spec, { id: "optic_1x", rail: "rail_top", massKg: 0.14 }),
33
+ };
34
+
35
+ const plan = planLauncher(equipped);
36
+ // plan.nodes -> scene hierarchy (Receiver_Root + articulated Bolt/Trigger + authored Socket_* nodes)
37
+ // plan.specs -> KhrLauncherNodeSpecLike rigid bodies, colliders, and prismatic/revolute joints
38
+ // plan.inertiaDiagonal -> principal moments [I1, I2, I3] in kg*m^2
39
+ // plan.inertiaOrientation -> unit quaternion [qx, qy, qz, qw] (R * diag(I) * R^T === T)
31
40
  ```
32
41
 
33
- ## 2. Step the Deterministic Firing & Reload Cycle
42
+ ## 2. Step the Deterministic Launch & Reload Cycle
34
43
 
35
44
  ```ts
36
- import { KOLMOGOROV_PISTOL, createLauncherState, stepLauncher } from "@khr3/launchers";
45
+ import { DEFAULT_AMMO_CATALOG, PISTOL_9MM, createLauncherState, stepLauncher } from "@khr3/launchers";
37
46
 
38
- const state = createLauncherState(KOLMOGOROV_PISTOL.spec);
39
- const step = stepLauncher(state, { trigger: true, reload: false }, 1 / 60);
47
+ const state = createLauncherState(PISTOL_9MM.spec);
48
+ const ev = stepLauncher(state, { trigger: true, reload: false }, 1 / 60);
40
49
 
41
- if (step.fired) {
42
- // Spawn round from `muzzle` socket with `step.ammo.muzzleSpeedMs` and apply `step.recoilImpulseNs`
50
+ if (ev) {
51
+ const ammo = DEFAULT_AMMO_CATALOG[ev.ammoId];
52
+ // Spawn projectile at `ev.muzzleLocal` with `ammo.muzzleSpeedMs` and apply `ev.recoilImpulseNs`
43
53
  }
44
54
  ```
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Exact 3x3 parallel-axis rigid-body inertia tensor assembly and principal-axis
3
+ * Rutishauser-Jacobi diagonalization with Shepperd SO(3) -> unit quaternion extraction.
4
+ */
5
+ import { type Vec3 } from "./launcherParts.js";
6
+ /** glTF / KHR_physics_rigid_bodies right-handed unit quaternion `[qx, qy, qz, qw]`. */
7
+ export type Quat = [number, number, number, number];
8
+ export interface MassBoxLike {
9
+ readonly massKg: number;
10
+ readonly center: Vec3;
11
+ readonly size: Vec3;
12
+ }
13
+ export interface LumpedInertiaProps {
14
+ readonly massKg: number;
15
+ readonly centerOfMass: Vec3;
16
+ readonly inertiaDiagonal: Vec3;
17
+ readonly inertiaOrientation: Quat;
18
+ readonly inertiaTensor: readonly [Vec3, Vec3, Vec3];
19
+ }
20
+ export declare function diagonalizeInertiaTensor(t00: number, t11: number, t22: number, t01: number, t02: number, t12: number): {
21
+ inertiaDiagonal: Vec3;
22
+ inertiaOrientation: Quat;
23
+ };
24
+ export declare function sumLauncherBoxes(parts: readonly MassBoxLike[]): LumpedInertiaProps;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Exact 3x3 parallel-axis rigid-body inertia tensor assembly and principal-axis
3
+ * Rutishauser-Jacobi diagonalization with Shepperd SO(3) -> unit quaternion extraction.
4
+ */
5
+ import { boxInertiaDiagonal } from "./launcherParts.js";
6
+ function mat3ToUnitQuat(r) {
7
+ const [r00, r01, r02] = r[0];
8
+ const [r10, r11, r12] = r[1];
9
+ const [r20, r21, r22] = r[2];
10
+ const tr = r00 + r11 + r22;
11
+ let x;
12
+ let y;
13
+ let z;
14
+ let w;
15
+ if (tr > 0) {
16
+ const s = 2 * Math.sqrt(1 + tr);
17
+ w = 0.25 * s;
18
+ x = (r21 - r12) / s;
19
+ y = (r02 - r20) / s;
20
+ z = (r10 - r01) / s;
21
+ }
22
+ else if (r00 > r11 && r00 > r22) {
23
+ const s = 2 * Math.sqrt(1 + r00 - r11 - r22);
24
+ x = 0.25 * s;
25
+ y = (r10 + r01) / s;
26
+ z = (r02 + r20) / s;
27
+ w = (r21 - r12) / s;
28
+ }
29
+ else if (r11 > r22) {
30
+ const s = 2 * Math.sqrt(1 + r11 - r00 - r22);
31
+ x = (r10 + r01) / s;
32
+ y = 0.25 * s;
33
+ z = (r21 + r12) / s;
34
+ w = (r02 - r20) / s;
35
+ }
36
+ else {
37
+ const s = 2 * Math.sqrt(1 + r22 - r00 - r11);
38
+ x = (r02 + r20) / s;
39
+ y = (r21 + r12) / s;
40
+ z = 0.25 * s;
41
+ w = (r10 - r01) / s;
42
+ }
43
+ const inv = (w < 0 ? -1 : 1) / Math.hypot(x, y, z, w);
44
+ return [x * inv || 0, y * inv || 0, z * inv || 0, w * inv || 0];
45
+ }
46
+ const JACOBI_PAIRS = [
47
+ [0, 1, 2],
48
+ [0, 2, 1],
49
+ [1, 2, 0],
50
+ ];
51
+ export function diagonalizeInertiaTensor(t00, t11, t22, t01, t02, t12) {
52
+ const a = [
53
+ [t00, t01, t02],
54
+ [t01, t11, t12],
55
+ [t02, t12, t22],
56
+ ];
57
+ const v = [
58
+ [1, 0, 0],
59
+ [0, 1, 0],
60
+ [0, 0, 1],
61
+ ];
62
+ for (let iter = 0; iter < 32; iter++) {
63
+ let best = 0;
64
+ let maxOff = Math.abs(a[0][1]);
65
+ if (Math.abs(a[0][2]) > maxOff) {
66
+ maxOff = Math.abs(a[0][2]);
67
+ best = 1;
68
+ }
69
+ if (Math.abs(a[1][2]) > maxOff) {
70
+ maxOff = Math.abs(a[1][2]);
71
+ best = 2;
72
+ }
73
+ const scale = Math.abs(a[0][0]) + Math.abs(a[1][1]) + Math.abs(a[2][2]);
74
+ if (maxOff <= 1e-15 * scale)
75
+ break;
76
+ const [p, q, r] = JACOBI_PAIRS[best];
77
+ const apq = a[p][q];
78
+ const tau = (a[q][q] - a[p][p]) / (2 * apq);
79
+ const t = (tau >= 0 ? 1 : -1) / (Math.abs(tau) + Math.sqrt(1 + tau * tau));
80
+ const c = 1 / Math.sqrt(1 + t * t);
81
+ const s = t * c;
82
+ a[p][p] -= t * apq;
83
+ a[q][q] += t * apq;
84
+ a[p][q] = 0;
85
+ a[q][p] = 0;
86
+ const arp = a[r][p];
87
+ const arq = a[r][q];
88
+ a[r][p] = c * arp - s * arq;
89
+ a[p][r] = a[r][p];
90
+ a[r][q] = s * arp + c * arq;
91
+ a[q][r] = a[r][q];
92
+ for (let i = 0; i < 3; i++) {
93
+ const vip = v[i][p];
94
+ const viq = v[i][q];
95
+ v[i][p] = c * vip - s * viq;
96
+ v[i][q] = s * vip + c * viq;
97
+ }
98
+ }
99
+ return {
100
+ inertiaDiagonal: [Math.max(0, a[0][0]), Math.max(0, a[1][1]), Math.max(0, a[2][2])],
101
+ inertiaOrientation: mat3ToUnitQuat(v),
102
+ };
103
+ }
104
+ export function sumLauncherBoxes(parts) {
105
+ let m = 0;
106
+ let cx = 0;
107
+ let cy = 0;
108
+ let cz = 0;
109
+ for (const p of parts) {
110
+ if (!Number.isFinite(p.massKg) || p.massKg < 0) {
111
+ throw new RangeError("sumLauncherBoxes: part massKg must be finite and >= 0");
112
+ }
113
+ m += p.massKg;
114
+ cx += p.massKg * p.center[0];
115
+ cy += p.massKg * p.center[1];
116
+ cz += p.massKg * p.center[2];
117
+ }
118
+ if (!(m > 0) || !Number.isFinite(m)) {
119
+ throw new RangeError("sumLauncherBoxes: total mass must be finite and > 0");
120
+ }
121
+ cx /= m;
122
+ cy /= m;
123
+ cz /= m;
124
+ let txx = 0;
125
+ let tyy = 0;
126
+ let tzz = 0;
127
+ let txy = 0;
128
+ let txz = 0;
129
+ let tyz = 0;
130
+ for (const p of parts) {
131
+ const own = boxInertiaDiagonal(p.massKg, p.size);
132
+ const dx = p.center[0] - cx;
133
+ const dy = p.center[1] - cy;
134
+ const dz = p.center[2] - cz;
135
+ txx += own[0] + p.massKg * (dy * dy + dz * dz);
136
+ tyy += own[1] + p.massKg * (dx * dx + dz * dz);
137
+ tzz += own[2] + p.massKg * (dx * dx + dy * dy);
138
+ txy -= p.massKg * dx * dy;
139
+ txz -= p.massKg * dx * dz;
140
+ tyz -= p.massKg * dy * dz;
141
+ }
142
+ const { inertiaDiagonal, inertiaOrientation } = diagonalizeInertiaTensor(txx, tyy, tzz, txy, txz, tyz);
143
+ return {
144
+ massKg: m,
145
+ centerOfMass: [cx || 0, cy || 0, cz || 0],
146
+ inertiaDiagonal,
147
+ inertiaOrientation,
148
+ inertiaTensor: [
149
+ [txx, txy, txz],
150
+ [txy, tyy, tyz],
151
+ [txz, tyz, tzz],
152
+ ],
153
+ };
154
+ }
@@ -1,11 +1,13 @@
1
1
  /**
2
- * Turn a parametric launcher recipe into the scene node tree and `KhrExportNodeSpecLike[]`
2
+ * Turn a parametric launcher recipe into the scene node tree and `KhrLauncherNodeSpecLike[]`
3
3
  * consumed by `@khr3/core` `exportKhrGlb`.
4
- * Fixed parts lump into `Receiver_Root`; articulated parts (`Bolt`, `Trigger`, `Pump`) emit
5
- * `KHR_physics_rigid_bodies` prismatic/revolute joints with spring drives.
4
+ * Fixed parts and rail attachments lump into `Receiver_Root`; articulated parts (`Bolt`, `Trigger`,
5
+ * `Pump`) emit `KHR_physics_rigid_bodies` prismatic/revolute joints with spring drives.
6
6
  */
7
- import { type LauncherPart, type LauncherRecipe, type Vec3 } from "./launcherParts.js";
8
- import type { LauncherSocketName, LauncherSpec, Vec3Tuple } from "./schema.js";
7
+ import { diagonalizeInertiaTensor, sumLauncherBoxes, type LumpedInertiaProps, type MassBoxLike, type Quat } from "./inertia.js";
8
+ import { type LauncherPart, type LauncherRecipe, type ResolvedLauncherSockets, type Vec3 } from "./launcherParts.js";
9
+ import { type LauncherSpec } from "./schema.js";
10
+ export { diagonalizeInertiaTensor, sumLauncherBoxes, type LumpedInertiaProps, type MassBoxLike, type Quat };
9
11
  export interface LauncherNode {
10
12
  readonly name: string;
11
13
  readonly parent: string;
@@ -19,6 +21,7 @@ export interface KhrLauncherNodeSpecLike {
19
21
  readonly mass?: number;
20
22
  readonly centerOfMass?: Vec3;
21
23
  readonly inertiaDiagonal?: Vec3;
24
+ readonly inertiaOrientation?: Quat;
22
25
  };
23
26
  readonly collider?: {
24
27
  readonly shape: {
@@ -49,7 +52,8 @@ export interface LauncherPlan {
49
52
  readonly fixedMassKg: number;
50
53
  readonly centerOfMass: Vec3;
51
54
  readonly inertiaDiagonal: Vec3;
52
- readonly sockets: Record<LauncherSocketName, Vec3Tuple>;
55
+ readonly inertiaOrientation: Quat;
56
+ readonly sockets: ResolvedLauncherSockets;
53
57
  readonly nodes: LauncherNode[];
54
58
  readonly specs: KhrLauncherNodeSpecLike[];
55
59
  }
@@ -1,39 +1,49 @@
1
1
  /**
2
- * Turn a parametric launcher recipe into the scene node tree and `KhrExportNodeSpecLike[]`
2
+ * Turn a parametric launcher recipe into the scene node tree and `KhrLauncherNodeSpecLike[]`
3
3
  * consumed by `@khr3/core` `exportKhrGlb`.
4
- * Fixed parts lump into `Receiver_Root`; articulated parts (`Bolt`, `Trigger`, `Pump`) emit
5
- * `KHR_physics_rigid_bodies` prismatic/revolute joints with spring drives.
4
+ * Fixed parts and rail attachments lump into `Receiver_Root`; articulated parts (`Bolt`, `Trigger`,
5
+ * `Pump`) emit `KHR_physics_rigid_bodies` prismatic/revolute joints with spring drives.
6
6
  */
7
- import { boxInertiaDiagonal, buildLauncherParts, resolveLauncherSockets, } from "./launcherParts.js";
8
- function sumLauncherBoxes(parts) {
9
- let m = 0;
10
- const c = [0, 0, 0];
11
- for (const p of parts) {
12
- m += p.massKg;
13
- c[0] += p.massKg * p.center[0];
14
- c[1] += p.massKg * p.center[1];
15
- c[2] += p.massKg * p.center[2];
16
- }
17
- c[0] /= m;
18
- c[1] /= m;
19
- c[2] /= m;
20
- const diag = [0, 0, 0];
21
- for (const p of parts) {
22
- const own = boxInertiaDiagonal(p.massKg, p.size);
23
- const dx = p.center[0] - c[0], dy = p.center[1] - c[1], dz = p.center[2] - c[2];
24
- diag[0] += own[0] + p.massKg * (dy * dy + dz * dz);
25
- diag[1] += own[1] + p.massKg * (dx * dx + dz * dz);
26
- diag[2] += own[2] + p.massKg * (dx * dx + dy * dy);
7
+ import { diagonalizeInertiaTensor, sumLauncherBoxes } from "./inertia.js";
8
+ import { boxInertiaDiagonal, buildLauncherParts, resolveLauncherSockets } from "./launcherParts.js";
9
+ import { RAIL_SOCKETS } from "./schema.js";
10
+ export { diagonalizeInertiaTensor, sumLauncherBoxes };
11
+ function fallbackRailSocket(d, rail) {
12
+ if (rail === "rail_top")
13
+ return [0, d.receiverHeight * 0.5 + 0.008, 0];
14
+ if (rail === "rail_under")
15
+ return [0, -d.receiverHeight * 0.5 - 0.008, d.receiverLength * 0.35];
16
+ return [0, d.receiverHeight * 0.25, d.receiverLength * 0.5 + d.barrelLength];
17
+ }
18
+ function buildAttachmentMassBoxes(recipe, sockets) {
19
+ const attachments = recipe.spec.attachments;
20
+ if (!attachments)
21
+ return [];
22
+ const boxes = [];
23
+ for (const rail of RAIL_SOCKETS) {
24
+ const att = attachments[rail];
25
+ if (att && att.massKg > 0) {
26
+ const pos = sockets[rail] ?? fallbackRailSocket(recipe.dims, rail);
27
+ boxes.push({
28
+ massKg: att.massKg,
29
+ center: [pos[0], pos[1], pos[2]],
30
+ size: [0, 0, 0],
31
+ });
32
+ }
27
33
  }
28
- return { massKg: m, centerOfMass: c, inertiaDiagonal: diag };
34
+ return boxes;
29
35
  }
30
36
  export function planLauncher(recipe, friction = 0.5) {
37
+ if (!Number.isFinite(friction) || friction < 0) {
38
+ throw new RangeError(`planLauncher(${recipe.id}): friction must be finite and >= 0`);
39
+ }
31
40
  const parts = buildLauncherParts(recipe);
41
+ const sockets = resolveLauncherSockets(recipe);
42
+ const attachmentBoxes = buildAttachmentMassBoxes(recipe, sockets);
32
43
  const fixed = parts.filter((p) => !p.joint);
33
44
  const moving = parts.filter((p) => p.joint);
34
- const total = sumLauncherBoxes(parts);
35
- const rootProps = sumLauncherBoxes(fixed);
36
- const sockets = resolveLauncherSockets(recipe);
45
+ const total = sumLauncherBoxes([...parts, ...attachmentBoxes]);
46
+ const rootProps = sumLauncherBoxes([...fixed, ...attachmentBoxes]);
37
47
  const nodes = [
38
48
  { name: "Receiver_Root", parent: "root", position: [0, 0, 0], size: [0, 0, 0] },
39
49
  ];
@@ -45,6 +55,7 @@ export function planLauncher(recipe, friction = 0.5) {
45
55
  mass: rootProps.massKg,
46
56
  centerOfMass: rootProps.centerOfMass,
47
57
  inertiaDiagonal: rootProps.inertiaDiagonal,
58
+ inertiaOrientation: rootProps.inertiaOrientation,
48
59
  },
49
60
  extras: {
50
61
  role: "receiver",
@@ -65,7 +76,11 @@ export function planLauncher(recipe, friction = 0.5) {
65
76
  }
66
77
  for (const p of moving) {
67
78
  const j = p.joint;
68
- const localOffset = [p.center[0] - j.anchor[0], p.center[1] - j.anchor[1], p.center[2] - j.anchor[2]];
79
+ const localOffset = [
80
+ p.center[0] - j.anchor[0],
81
+ p.center[1] - j.anchor[1],
82
+ p.center[2] - j.anchor[2],
83
+ ];
69
84
  const ownDiag = boxInertiaDiagonal(p.massKg, p.size);
70
85
  nodes.push({ name: p.name, parent: "Receiver_Root", position: j.anchor, size: [0, 0, 0] });
71
86
  nodes.push({ name: `${p.name}_Collider`, parent: p.name, position: localOffset, size: p.size });
@@ -80,6 +95,7 @@ export function planLauncher(recipe, friction = 0.5) {
80
95
  mass: p.massKg,
81
96
  centerOfMass: localOffset,
82
97
  inertiaDiagonal: ownDiag,
98
+ inertiaOrientation: [0, 0, 0, 1],
83
99
  },
84
100
  joint: {
85
101
  connectedNodeName: "Receiver_Root",
@@ -97,8 +113,15 @@ export function planLauncher(recipe, friction = 0.5) {
97
113
  });
98
114
  }
99
115
  for (const [sockName, pos] of Object.entries(sockets)) {
116
+ if (!pos)
117
+ continue;
100
118
  const nodeName = `Socket_${sockName}`;
101
- nodes.push({ name: nodeName, parent: "Receiver_Root", position: [pos[0], pos[1], pos[2]], size: [0, 0, 0] });
119
+ nodes.push({
120
+ name: nodeName,
121
+ parent: "Receiver_Root",
122
+ position: [pos[0], pos[1], pos[2]],
123
+ size: [0, 0, 0],
124
+ });
102
125
  specs.push({
103
126
  nodeName,
104
127
  extras: { socketId: sockName, isIkAnchor: sockName.startsWith("grip_") },
@@ -112,6 +135,7 @@ export function planLauncher(recipe, friction = 0.5) {
112
135
  fixedMassKg: rootProps.massKg,
113
136
  centerOfMass: total.centerOfMass,
114
137
  inertiaDiagonal: total.inertiaDiagonal,
138
+ inertiaOrientation: total.inertiaOrientation,
115
139
  sockets,
116
140
  nodes,
117
141
  specs,
@@ -3,7 +3,7 @@
3
3
  * Frame: SI metres, +Y up, +Z muzzle forward (or -Z muzzle in Khronos emitter space; socket `muzzle` gives exact local point).
4
4
  * Zero runtime dependencies.
5
5
  */
6
- import type { LauncherPartRole, LauncherSocketName, LauncherSpec, Vec3Tuple } from "./schema.js";
6
+ import { type LauncherPartRole, type LauncherSocketName, type LauncherSpec, type Vec3Tuple } from "./schema.js";
7
7
  export type Vec3 = [number, number, number];
8
8
  export interface LauncherJointSpec {
9
9
  readonly kind: "prismatic" | "revolute";
@@ -53,6 +53,10 @@ export interface LauncherRecipe {
53
53
  readonly dims: LauncherDims;
54
54
  readonly masses: LauncherMasses;
55
55
  }
56
+ export type ResolvedLauncherSockets = Partial<Record<LauncherSocketName, Vec3Tuple>> & {
57
+ readonly grip_primary: Vec3Tuple;
58
+ readonly muzzle: Vec3Tuple;
59
+ };
56
60
  export declare function boxInertiaDiagonal(massKg: number, size: Vec3): Vec3;
57
61
  export declare function buildLauncherParts(recipe: LauncherRecipe): LauncherPart[];
58
- export declare function resolveLauncherSockets(recipe: LauncherRecipe): Record<LauncherSocketName, Vec3Tuple>;
62
+ export declare function resolveLauncherSockets(recipe: LauncherRecipe): ResolvedLauncherSockets;
@@ -1,16 +1,54 @@
1
+ /**
2
+ * Parametric multi-part launcher definition: receiver, barrel, bolt/slide, pump, trigger, magazine, stock.
3
+ * Frame: SI metres, +Y up, +Z muzzle forward (or -Z muzzle in Khronos emitter space; socket `muzzle` gives exact local point).
4
+ * Zero runtime dependencies.
5
+ */
6
+ import { LAUNCHER_SOCKETS, validateLauncherSpec } from "./schema.js";
7
+ function isPosFinite(v) {
8
+ return Number.isFinite(v) && v > 0;
9
+ }
10
+ function isNonNegFinite(v) {
11
+ return Number.isFinite(v) && v >= 0;
12
+ }
1
13
  export function boxInertiaDiagonal(massKg, size) {
2
14
  const [x, y, z] = size;
3
15
  const k = massKg / 12;
4
16
  return [k * (y * y + z * z), k * (x * x + z * z), k * (x * x + y * y)];
5
17
  }
6
18
  export function buildLauncherParts(recipe) {
19
+ validateLauncherSpec(recipe.spec);
7
20
  const d = recipe.dims;
8
21
  const m = recipe.masses;
9
- if (!(d.receiverLength > 0 && d.receiverWidth > 0 && d.receiverHeight > 0 && d.barrelLength > 0)) {
10
- throw new RangeError(`launcherParts(${recipe.id}): dimensions must be > 0`);
22
+ if (!(isPosFinite(d.receiverLength) &&
23
+ isPosFinite(d.receiverWidth) &&
24
+ isPosFinite(d.receiverHeight) &&
25
+ isPosFinite(d.barrelLength) &&
26
+ isPosFinite(d.barrelDiameter) &&
27
+ isPosFinite(d.gripHeight) &&
28
+ isPosFinite(d.magLength) &&
29
+ isPosFinite(d.boltStroke))) {
30
+ throw new RangeError(`launcherParts(${recipe.id}): all dimensions must be finite and > 0`);
31
+ }
32
+ if (!(isPosFinite(m.receiver) &&
33
+ isPosFinite(m.barrel) &&
34
+ isPosFinite(m.bolt) &&
35
+ isPosFinite(m.trigger) &&
36
+ isPosFinite(m.magazine) &&
37
+ isNonNegFinite(m.stock) &&
38
+ isNonNegFinite(m.pump) &&
39
+ (m.screen === undefined || isNonNegFinite(m.screen)))) {
40
+ throw new RangeError(`launcherParts(${recipe.id}): core part masses must be finite and > 0`);
11
41
  }
12
42
  const zBarrelCenter = d.receiverLength * 0.5 + d.barrelLength * 0.5;
13
43
  const yBarrel = d.receiverHeight * 0.25;
44
+ const boltOmega = Math.max(90, 7.5 * recipe.spec.fireRateHz);
45
+ const magDepthZ = 0.045;
46
+ const triggerDepthZ = 0.016;
47
+ const minClearanceZ = (magDepthZ + triggerDepthZ) * 0.5 + 0.01;
48
+ const magZ = d.hasStock ? 0.04 : -d.receiverLength * 0.18;
49
+ const triggerZ = d.hasStock
50
+ ? Math.min(-d.receiverLength * 0.12, magZ - minClearanceZ)
51
+ : Math.max(d.receiverLength * 0.12, magZ + minClearanceZ);
14
52
  const parts = [
15
53
  {
16
54
  name: "Receiver",
@@ -37,31 +75,31 @@ export function buildLauncherParts(recipe) {
37
75
  anchor: [0, d.receiverHeight * 0.35, 0],
38
76
  axis: [0, 0, 1],
39
77
  limits: [-d.boltStroke, 0],
40
- stiffness: 420,
41
- damping: 24,
78
+ stiffness: boltOmega * boltOmega,
79
+ damping: 2 * boltOmega,
42
80
  },
43
81
  },
44
82
  {
45
83
  name: "Trigger",
46
84
  role: "trigger",
47
85
  massKg: m.trigger,
48
- center: [0, -d.receiverHeight * 0.55, -d.receiverLength * 0.12],
49
- size: [d.receiverWidth * 0.28, 0.028, 0.016],
86
+ center: [0, -d.receiverHeight * 0.5 - 0.015, triggerZ],
87
+ size: [d.receiverWidth * 0.28, 0.028, triggerDepthZ],
50
88
  joint: {
51
89
  kind: "revolute",
52
- anchor: [0, -d.receiverHeight * 0.42, -d.receiverLength * 0.12],
90
+ anchor: [0, -d.receiverHeight * 0.5, triggerZ],
53
91
  axis: [1, 0, 0],
54
92
  limits: [0, 0.45],
55
93
  stiffness: 80,
56
- damping: 8,
94
+ damping: 18,
57
95
  },
58
96
  },
59
97
  {
60
98
  name: "Magazine",
61
99
  role: "magazine",
62
100
  massKg: m.magazine,
63
- center: [0, -d.receiverHeight * 0.5 - d.magLength * 0.45, d.hasStock ? 0.04 : -d.receiverLength * 0.18],
64
- size: [d.receiverWidth * 0.68, d.magLength, 0.045],
101
+ center: [0, -d.receiverHeight * 0.5 - d.magLength * 0.45, magZ],
102
+ size: [d.receiverWidth * 0.68, d.magLength, magDepthZ],
65
103
  },
66
104
  ];
67
105
  if (d.hasStock && m.stock > 0) {
@@ -87,8 +125,8 @@ export function buildLauncherParts(recipe) {
87
125
  anchor: [0, -d.receiverHeight * 0.1, pumpZ],
88
126
  axis: [0, 0, 1],
89
127
  limits: [-0.095, 0],
90
- stiffness: 320,
91
- damping: 20,
128
+ stiffness: 900,
129
+ damping: 60,
92
130
  },
93
131
  });
94
132
  }
@@ -107,13 +145,14 @@ export function resolveLauncherSockets(recipe) {
107
145
  const d = recipe.dims;
108
146
  const s = recipe.spec.sockets;
109
147
  const zMuzzle = d.receiverLength * 0.5 + d.barrelLength;
110
- return {
148
+ const out = {
111
149
  grip_primary: s.grip_primary ?? [0, -d.receiverHeight * 0.5 - d.gripHeight * 0.5, -d.receiverLength * 0.2],
112
- grip_secondary: s.grip_secondary ?? [0, -d.receiverHeight * 0.25, d.receiverLength * 0.5 + d.barrelLength * 0.35],
113
- rail_top: s.rail_top ?? [0, d.receiverHeight * 0.5 + 0.008, 0],
114
- rail_under: s.rail_under ?? [0, -d.receiverHeight * 0.5 - 0.008, d.receiverLength * 0.35],
115
150
  muzzle: s.muzzle ?? [0, d.receiverHeight * 0.25, zMuzzle],
116
- eject_port: s.eject_port ?? [d.receiverWidth * 0.52, d.receiverHeight * 0.25, 0.02],
117
- sight_align: s.sight_align ?? [0, d.receiverHeight * 0.5 + 0.022, -d.receiverLength * 0.25],
118
151
  };
152
+ for (const key of LAUNCHER_SOCKETS) {
153
+ const val = s[key];
154
+ if (val !== undefined)
155
+ out[key] = val;
156
+ }
157
+ return out;
119
158
  }
package/dist/recipes.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { LauncherRecipe } from "./launcherParts.js";
1
+ import { type LauncherRecipe } from "./launcherParts.js";
2
2
  export declare const KOLMOGOROV_PISTOL: LauncherRecipe;
3
3
  export declare const KOLMOGOROV_CARBINE: LauncherRecipe;
4
4
  export declare const KOLMOGOROV_SHOTGUN: LauncherRecipe;
package/dist/recipes.js CHANGED
@@ -1,24 +1,25 @@
1
+ import {} from "./launcherParts.js";
1
2
  import { DEFAULT_AMMO_CATALOG } from "./schema.js";
2
- export const KOLMOGOROV_PISTOL = Object.freeze({
3
+ export const KOLMOGOROV_PISTOL = {
3
4
  id: "kolmogorov_pistol",
4
5
  label: "Kolmogorov 9mm Sidearm",
5
6
  r2Key: "weapons/kolmogorov_pistol.glb",
6
- spec: Object.freeze({
7
+ spec: {
7
8
  id: "kolmogorov_pistol",
8
9
  ammoId: DEFAULT_AMMO_CATALOG.pistol.id,
9
10
  fireRateHz: 6.5,
10
11
  magazineCapacity: 15,
11
12
  reloadSec: 1.4,
12
- recoilImpulseNs: 2.4,
13
- sockets: Object.freeze({
13
+ recoilImpulseNs: 3.4,
14
+ sockets: {
14
15
  grip_primary: [0, -0.06, -0.04],
15
16
  rail_under: [0, -0.015, 0.08],
16
- muzzle: [0, 0.02, 0.19],
17
+ muzzle: [0, 0.0105, 0.19],
17
18
  eject_port: [0.016, 0.024, 0.02],
18
19
  sight_align: [0, 0.038, -0.06],
19
- }),
20
- }),
21
- dims: Object.freeze({
20
+ },
21
+ },
22
+ dims: {
22
23
  receiverLength: 0.16,
23
24
  receiverWidth: 0.032,
24
25
  receiverHeight: 0.042,
@@ -29,8 +30,8 @@ export const KOLMOGOROV_PISTOL = Object.freeze({
29
30
  boltStroke: 0.042,
30
31
  hasStock: false,
31
32
  hasPump: false,
32
- }),
33
- masses: Object.freeze({
33
+ },
34
+ masses: {
34
35
  receiver: 0.48,
35
36
  barrel: 0.14,
36
37
  bolt: 0.24,
@@ -38,30 +39,30 @@ export const KOLMOGOROV_PISTOL = Object.freeze({
38
39
  magazine: 0.18,
39
40
  stock: 0,
40
41
  pump: 0,
41
- }),
42
- });
43
- export const KOLMOGOROV_CARBINE = Object.freeze({
42
+ },
43
+ };
44
+ export const KOLMOGOROV_CARBINE = {
44
45
  id: "kolmogorov_carbine",
45
46
  label: "Kolmogorov 5.56 Modular Carbine",
46
47
  r2Key: "weapons/kolmogorov_carbine.glb",
47
- spec: Object.freeze({
48
+ spec: {
48
49
  id: "kolmogorov_carbine",
49
50
  ammoId: DEFAULT_AMMO_CATALOG.rifle.id,
50
51
  fireRateHz: 11.5,
51
52
  magazineCapacity: 30,
52
53
  reloadSec: 1.9,
53
- recoilImpulseNs: 4.1,
54
- sockets: Object.freeze({
54
+ recoilImpulseNs: 4.8,
55
+ sockets: {
55
56
  grip_primary: [0, -0.08, -0.07],
56
57
  grip_secondary: [0, -0.03, 0.28],
57
58
  rail_top: [0, 0.042, 0.04],
58
59
  rail_under: [0, -0.032, 0.24],
59
- muzzle: [0, 0.015, 0.56],
60
+ muzzle: [0, 0.017, 0.5],
60
61
  eject_port: [0.024, 0.018, 0.04],
61
62
  sight_align: [0, 0.062, -0.08],
62
- }),
63
- }),
64
- dims: Object.freeze({
63
+ },
64
+ },
65
+ dims: {
65
66
  receiverLength: 0.26,
66
67
  receiverWidth: 0.046,
67
68
  receiverHeight: 0.068,
@@ -72,8 +73,8 @@ export const KOLMOGOROV_CARBINE = Object.freeze({
72
73
  boltStroke: 0.075,
73
74
  hasStock: true,
74
75
  hasPump: false,
75
- }),
76
- masses: Object.freeze({
76
+ },
77
+ masses: {
77
78
  receiver: 1.35,
78
79
  barrel: 0.68,
79
80
  bolt: 0.38,
@@ -81,29 +82,29 @@ export const KOLMOGOROV_CARBINE = Object.freeze({
81
82
  magazine: 0.36,
82
83
  stock: 0.45,
83
84
  pump: 0,
84
- }),
85
- });
86
- export const KOLMOGOROV_SHOTGUN = Object.freeze({
85
+ },
86
+ };
87
+ export const KOLMOGOROV_SHOTGUN = {
87
88
  id: "kolmogorov_shotgun",
88
89
  label: "Kolmogorov 12G Pump Breacher",
89
90
  r2Key: "weapons/kolmogorov_shotgun.glb",
90
- spec: Object.freeze({
91
+ spec: {
91
92
  id: "kolmogorov_shotgun",
92
- ammoId: DEFAULT_AMMO_CATALOG.orb.id,
93
+ ammoId: DEFAULT_AMMO_CATALOG.shells_12g.id,
93
94
  fireRateHz: 1.4,
94
95
  magazineCapacity: 8,
95
96
  reloadSec: 2.6,
96
- recoilImpulseNs: 9.5,
97
- sockets: Object.freeze({
97
+ recoilImpulseNs: 14.5,
98
+ sockets: {
98
99
  grip_primary: [0, -0.07, -0.08],
99
100
  grip_secondary: [0, -0.02, 0.34],
100
101
  rail_top: [0, 0.04, 0.02],
101
- muzzle: [0, 0.018, 0.64],
102
+ muzzle: [0, 0.016, 0.58],
102
103
  eject_port: [0.025, 0.018, 0.05],
103
104
  sight_align: [0, 0.052, -0.09],
104
- }),
105
- }),
106
- dims: Object.freeze({
105
+ },
106
+ },
107
+ dims: {
107
108
  receiverLength: 0.24,
108
109
  receiverWidth: 0.048,
109
110
  receiverHeight: 0.064,
@@ -114,8 +115,8 @@ export const KOLMOGOROV_SHOTGUN = Object.freeze({
114
115
  boltStroke: 0.085,
115
116
  hasStock: true,
116
117
  hasPump: true,
117
- }),
118
- masses: Object.freeze({
118
+ },
119
+ masses: {
119
120
  receiver: 1.45,
120
121
  barrel: 0.85,
121
122
  bolt: 0.32,
@@ -123,8 +124,8 @@ export const KOLMOGOROV_SHOTGUN = Object.freeze({
123
124
  magazine: 0.22,
124
125
  stock: 0.52,
125
126
  pump: 0.28,
126
- }),
127
- });
127
+ },
128
+ };
128
129
  export const PISTOL_9MM = KOLMOGOROV_PISTOL;
129
130
  export const CARBINE_556 = KOLMOGOROV_CARBINE;
130
131
  export const SHOTGUN_12G = KOLMOGOROV_SHOTGUN;
@@ -133,8 +134,13 @@ export const LAUNCHER_RECIPES = Object.freeze([
133
134
  KOLMOGOROV_CARBINE,
134
135
  KOLMOGOROV_SHOTGUN,
135
136
  ]);
137
+ const RECIPE_ALIASES = Object.freeze({
138
+ pistol_9mm: KOLMOGOROV_PISTOL,
139
+ carbine_556: KOLMOGOROV_CARBINE,
140
+ shotgun_12g: KOLMOGOROV_SHOTGUN,
141
+ });
136
142
  export function findLauncherRecipe(id) {
137
- const hit = LAUNCHER_RECIPES.find((r) => r.id === id);
143
+ const hit = LAUNCHER_RECIPES.find((r) => r.id === id) ?? RECIPE_ALIASES[id];
138
144
  if (!hit)
139
145
  throw new RangeError(`@khr3/launchers: unknown recipe "${id}"`);
140
146
  return hit;
package/dist/runtime.js CHANGED
@@ -1,4 +1,4 @@
1
- import { validateLauncherSpec, } from "./schema.js";
1
+ import { validateLauncherSpec } from "./schema.js";
2
2
  export function createLauncherState(spec) {
3
3
  validateLauncherSpec(spec);
4
4
  return {
@@ -10,12 +10,21 @@ export function createLauncherState(spec) {
10
10
  totalFired: 0,
11
11
  };
12
12
  }
13
+ function updateCyclePhase(cooldownSec, cyclePeriod) {
14
+ if (cooldownSec <= 0)
15
+ return 0;
16
+ const ratio = Math.min(1, cooldownSec / cyclePeriod);
17
+ return 0.5 * (1 + Math.cos((1 - ratio) * Math.PI));
18
+ }
13
19
  export function stepLauncher(state, input, dt) {
14
- const stepDt = Math.max(0, dt);
15
- if (state.cooldownSec > 0)
16
- state.cooldownSec = Math.max(0, state.cooldownSec - stepDt);
20
+ if (!Number.isFinite(dt) || dt <= 0)
21
+ return null;
22
+ const prevCooldown = state.cooldownSec;
23
+ if (state.cooldownSec > 0) {
24
+ state.cooldownSec = Math.max(0, state.cooldownSec - dt);
25
+ }
17
26
  if (state.reloadRemainingSec > 0) {
18
- state.reloadRemainingSec = Math.max(0, state.reloadRemainingSec - stepDt);
27
+ state.reloadRemainingSec = Math.max(0, state.reloadRemainingSec - dt);
19
28
  if (state.reloadRemainingSec === 0)
20
29
  state.ammoInMag = state.spec.magazineCapacity;
21
30
  }
@@ -25,13 +34,13 @@ export function stepLauncher(state, input, dt) {
25
34
  state.ammoInMag = state.spec.magazineCapacity;
26
35
  }
27
36
  const cyclePeriod = 1 / state.spec.fireRateHz;
28
- state.cyclePhase = state.cooldownSec > 0 ? Math.sin((state.cooldownSec / cyclePeriod) * Math.PI) : 0;
29
37
  if (input.trigger && state.reloadRemainingSec === 0 && state.cooldownSec === 0) {
30
38
  if (state.ammoInMag > 0) {
39
+ const carry = prevCooldown > 0 ? Math.max(0, dt - prevCooldown) : 0;
31
40
  state.ammoInMag -= 1;
32
41
  state.totalFired += 1;
33
- state.cooldownSec = cyclePeriod;
34
- state.cyclePhase = 1;
42
+ state.cooldownSec = Math.max(0, cyclePeriod - carry);
43
+ state.cyclePhase = updateCyclePhase(state.cooldownSec, cyclePeriod);
35
44
  return {
36
45
  launcherId: state.spec.id,
37
46
  ammoId: state.spec.ammoId,
@@ -41,10 +50,19 @@ export function stepLauncher(state, input, dt) {
41
50
  };
42
51
  }
43
52
  state.reloadRemainingSec = state.spec.reloadSec;
53
+ if (state.reloadRemainingSec === 0) {
54
+ state.ammoInMag = state.spec.magazineCapacity;
55
+ }
44
56
  }
57
+ state.cyclePhase = updateCyclePhase(state.cooldownSec, cyclePeriod);
45
58
  return null;
46
59
  }
47
60
  export function attachModule(spec, attachment) {
61
+ if (!attachment.id)
62
+ throw new Error("AttachmentSpec: missing id");
63
+ if (!Number.isFinite(attachment.massKg) || attachment.massKg < 0) {
64
+ throw new RangeError(`AttachmentSpec(${attachment.id}): massKg must be finite and >= 0`);
65
+ }
48
66
  return {
49
67
  ...spec,
50
68
  attachments: {
package/dist/schema.js CHANGED
@@ -24,27 +24,105 @@ export const CHARACTER_SOCKETS = [
24
24
  "Socket_Head",
25
25
  "Socket_Back",
26
26
  ];
27
- export const DEFAULT_AMMO_CATALOG = {
28
- pistol: { id: "pistol", muzzleSpeedMs: 360, massKg: 0.008, casingRadiusM: 0.0049, casingLengthM: 0.019, tipRatio: 0.35, color: "#E3A83B" },
29
- rifle: { id: "rifle", muzzleSpeedMs: 880, massKg: 0.004, casingRadiusM: 0.0048, casingLengthM: 0.045, tipRatio: 0.45, color: "#D68A28" },
30
- laser: { id: "laser", muzzleSpeedMs: 1200, massKg: 0.0001, casingRadiusM: 0, casingLengthM: 0, tipRatio: 0, color: "#26E3E8" },
31
- orb: { id: "orb", muzzleSpeedMs: 42, massKg: 0.12, casingRadiusM: 0, casingLengthM: 0, tipRatio: 0, color: "#E3782A" },
32
- rocket: { id: "rocket", muzzleSpeedMs: 95, massKg: 1.4, casingRadiusM: 0.035, casingLengthM: 0.32, tipRatio: 0.3, color: "#D93832" },
33
- };
27
+ export const DEFAULT_AMMO_CATALOG = Object.freeze({
28
+ pistol: Object.freeze({
29
+ id: "pistol",
30
+ muzzleSpeedMs: 360,
31
+ massKg: 0.008,
32
+ casingRadiusM: 0.0049,
33
+ casingLengthM: 0.019,
34
+ tipRatio: 0.35,
35
+ color: "#E3A83B",
36
+ }),
37
+ rifle: Object.freeze({
38
+ id: "rifle",
39
+ muzzleSpeedMs: 880,
40
+ massKg: 0.004,
41
+ casingRadiusM: 0.0048,
42
+ casingLengthM: 0.045,
43
+ tipRatio: 0.45,
44
+ color: "#D68A28",
45
+ }),
46
+ shells_12g: Object.freeze({
47
+ id: "shells_12g",
48
+ muzzleSpeedMs: 400,
49
+ massKg: 0.032,
50
+ casingRadiusM: 0.01,
51
+ casingLengthM: 0.07,
52
+ tipRatio: 0,
53
+ color: "#C83228",
54
+ }),
55
+ laser: Object.freeze({
56
+ id: "laser",
57
+ muzzleSpeedMs: 1200,
58
+ massKg: 0.0001,
59
+ casingRadiusM: 0,
60
+ casingLengthM: 0,
61
+ tipRatio: 0,
62
+ color: "#26E3E8",
63
+ }),
64
+ orb: Object.freeze({
65
+ id: "orb",
66
+ muzzleSpeedMs: 42,
67
+ massKg: 0.12,
68
+ casingRadiusM: 0,
69
+ casingLengthM: 0,
70
+ tipRatio: 0,
71
+ color: "#E3782A",
72
+ }),
73
+ rocket: Object.freeze({
74
+ id: "rocket",
75
+ muzzleSpeedMs: 95,
76
+ massKg: 1.4,
77
+ casingRadiusM: 0.035,
78
+ casingLengthM: 0.32,
79
+ tipRatio: 0.3,
80
+ color: "#D93832",
81
+ }),
82
+ });
83
+ function isFiniteVec3(v) {
84
+ return (Array.isArray(v) &&
85
+ v.length === 3 &&
86
+ Number.isFinite(v[0]) &&
87
+ Number.isFinite(v[1]) &&
88
+ Number.isFinite(v[2]));
89
+ }
34
90
  export function validateLauncherSpec(spec) {
35
- if (!spec.id)
91
+ if (!spec.id || typeof spec.id !== "string")
36
92
  throw new Error("LauncherSpec: missing id");
37
- if (!spec.ammoId)
93
+ if (!spec.ammoId || typeof spec.ammoId !== "string") {
38
94
  throw new Error(`LauncherSpec(${spec.id}): missing ammoId`);
39
- if (!(spec.fireRateHz > 0))
40
- throw new Error(`LauncherSpec(${spec.id}): fireRateHz must be > 0`);
41
- if (!(spec.magazineCapacity >= 1 && Number.isInteger(spec.magazineCapacity))) {
42
- throw new Error(`LauncherSpec(${spec.id}): magazineCapacity must be a positive integer`);
43
- }
44
- if (!(spec.reloadSec >= 0))
45
- throw new Error(`LauncherSpec(${spec.id}): reloadSec must be >= 0`);
46
- if (!spec.sockets.grip_primary)
47
- throw new Error(`LauncherSpec(${spec.id}): missing grip_primary socket`);
48
- if (!spec.sockets.muzzle)
49
- throw new Error(`LauncherSpec(${spec.id}): missing muzzle socket`);
95
+ }
96
+ if (!Number.isFinite(spec.fireRateHz) || spec.fireRateHz <= 0) {
97
+ throw new RangeError(`LauncherSpec(${spec.id}): fireRateHz must be finite and > 0`);
98
+ }
99
+ if (!Number.isFinite(spec.magazineCapacity) ||
100
+ !Number.isInteger(spec.magazineCapacity) ||
101
+ spec.magazineCapacity < 1) {
102
+ throw new RangeError(`LauncherSpec(${spec.id}): magazineCapacity must be a finite integer >= 1`);
103
+ }
104
+ if (!Number.isFinite(spec.reloadSec) || spec.reloadSec < 0) {
105
+ throw new RangeError(`LauncherSpec(${spec.id}): reloadSec must be finite and >= 0`);
106
+ }
107
+ if (!Number.isFinite(spec.recoilImpulseNs) || spec.recoilImpulseNs < 0) {
108
+ throw new RangeError(`LauncherSpec(${spec.id}): recoilImpulseNs must be finite and >= 0`);
109
+ }
110
+ if (!spec.sockets || !isFiniteVec3(spec.sockets.grip_primary)) {
111
+ throw new Error(`LauncherSpec(${spec.id}): missing or non-finite grip_primary socket`);
112
+ }
113
+ if (!isFiniteVec3(spec.sockets.muzzle)) {
114
+ throw new Error(`LauncherSpec(${spec.id}): missing or non-finite muzzle socket`);
115
+ }
116
+ for (const [sockName, pos] of Object.entries(spec.sockets)) {
117
+ if (pos !== undefined && !isFiniteVec3(pos)) {
118
+ throw new RangeError(`LauncherSpec(${spec.id}): socket "${sockName}" must be finite [x, y, z]`);
119
+ }
120
+ }
121
+ if (spec.attachments) {
122
+ for (const [rail, att] of Object.entries(spec.attachments)) {
123
+ if (att !== undefined && (!Number.isFinite(att.massKg) || att.massKg < 0)) {
124
+ throw new RangeError(`LauncherSpec(${spec.id}): attachment on "${rail}" must have finite massKg >= 0`);
125
+ }
126
+ }
127
+ }
50
128
  }
@@ -0,0 +1,72 @@
1
+ # `@khr3/launchers` API and Configuration Guide
2
+
3
+ This guide documents the public `@khr3/launchers` API: part roles, rail/character sockets, SI ammo specs, recipes, multi-body KHR planning, and deterministic launch cycle state stepping.
4
+
5
+ ## Import Path
6
+
7
+ ```ts
8
+ import {
9
+ LAUNCHER_PART_ROLES,
10
+ LAUNCHER_SOCKETS,
11
+ RAIL_SOCKETS,
12
+ CHARACTER_SOCKETS,
13
+ DEFAULT_AMMO_CATALOG,
14
+ PISTOL_9MM,
15
+ CARBINE_556,
16
+ SHOTGUN_12G,
17
+ LAUNCHER_RECIPES,
18
+ findLauncherRecipe,
19
+ validateLauncherSpec,
20
+ createLauncherState,
21
+ stepLauncher,
22
+ attachModule,
23
+ detachModule,
24
+ buildLauncherParts,
25
+ resolveLauncherSockets,
26
+ diagonalizeInertiaTensor,
27
+ sumLauncherBoxes,
28
+ planLauncher,
29
+ } from "@khr3/launchers";
30
+ ```
31
+
32
+ ## Schema & Ammo (`schema`)
33
+
34
+ - `LAUNCHER_PART_ROLES`: `"receiver" | "bolt" | "pump" | "trigger" | "magazine" | "barrel" | "stock" | "screen_rect"`
35
+ - `LAUNCHER_SOCKETS`: `"grip_primary" | "grip_secondary" | "rail_top" | "rail_under" | "muzzle" | "eject_port" | "sight_align"`
36
+ - `RAIL_SOCKETS`: `"rail_top" | "rail_under" | "muzzle"`
37
+ - `CHARACTER_SOCKETS`: `"Socket_Hand_R" | "Socket_Hand_L" | "Socket_Head" | "Socket_Back"`
38
+
39
+ ### `DEFAULT_AMMO_CATALOG`
40
+
41
+ | ID | `muzzleSpeedMs` | `massKg` | `casingRadiusM` | `casingLengthM` | `tipRatio` | `color` |
42
+ | --- | --- | --- | --- | --- | --- | --- |
43
+ | `pistol` | `360` | `0.008` | `0.0049` | `0.019` | `0.35` | `#E3A83B` |
44
+ | `rifle` | `880` | `0.004` | `0.0048` | `0.045` | `0.45` | `#D68A28` |
45
+ | `shells_12g` | `400` | `0.032` | `0.01` | `0.07` | `0` | `#C83228` |
46
+ | `laser` | `1200` | `0.0001` | `0` | `0` | `0` | `#26E3E8` |
47
+ | `orb` | `42` | `0.12` | `0` | `0` | `0` | `#E3782A` |
48
+ | `rocket` | `95` | `1.4` | `0.035` | `0.32` | `0.3` | `#D93832` |
49
+
50
+ `validateLauncherSpec(spec)` throws `Error` / `RangeError` if `fireRateHz <= 0`, `magazineCapacity < 1` (non-int), `reloadSec < 0`, `recoilImpulseNs < 0`, or `grip_primary` / `muzzle` sockets are missing/non-finite.
51
+
52
+ ## Runtime State Machine (`runtime`)
53
+
54
+ | Function | Signature | Description |
55
+ | --- | --- | --- |
56
+ | `createLauncherState` | `(spec: LauncherSpec) => LauncherState` | Validates `spec` and initializes full magazine |
57
+ | `stepLauncher` | `(state: LauncherState, input: LauncherInput, dt: number) => LaunchEvent \| null` | Advances cooldown, reload, fractional cooldown carry, and smooth C1 `cyclePhase` |
58
+ | `attachModule` | `(spec: LauncherSpec, attachment: AttachmentSpec) => LauncherSpec` | Returns new spec with rail attachment |
59
+ | `detachModule` | `(spec: LauncherSpec, rail: RailSocketName) => LauncherSpec` | Returns new spec without attachment on `rail` |
60
+
61
+ ## Multi-Body Inertia & KHR Planner (`inertia`, `launcherParts`, `launcherKhr`)
62
+
63
+ - `boxInertiaDiagonal(massKg, size) => Vec3`
64
+ - `buildLauncherParts(recipe) => LauncherPart[]`
65
+ - `resolveLauncherSockets(recipe) => ResolvedLauncherSockets`
66
+ - `diagonalizeInertiaTensor(t00, t11, t22, t01, t02, t12) => { inertiaDiagonal, inertiaOrientation }`
67
+ - `sumLauncherBoxes(parts) => LumpedInertiaProps`
68
+ - `planLauncher(recipe, friction = 0.5) => LauncherPlan`: emits `Receiver_Root` (lumped fixed parts + rail attachment masses), articulated `Bolt` (prismatic), `Trigger` (revolute), optional `Pump` (prismatic), and `Socket_*` locator nodes.
69
+
70
+ ## Authored Recipes (`recipes`)
71
+
72
+ `KOLMOGOROV_PISTOL` (`PISTOL_9MM`), `KOLMOGOROV_CARBINE` (`CARBINE_556`), `KOLMOGOROV_SHOTGUN` (`SHOTGUN_12G`), `LAUNCHER_RECIPES`, `findLauncherRecipe(id)` (accepts recipe `id` or `"pistol_9mm"` / `"carbine_556"` / `"shotgun_12g"`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@khr3/launchers",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Zero-dependency KHR launcher moving-part schema, rail attachment sockets, data-driven ammo catalog, and deterministic cycle state machine for khr3.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,6 +16,7 @@
16
16
  },
17
17
  "files": [
18
18
  "dist",
19
+ "docs",
19
20
  "LICENSE",
20
21
  "README.md"
21
22
  ],
@@ -40,6 +41,7 @@
40
41
  "typecheck": "tsc --noEmit",
41
42
  "build": "rm -rf dist && tsc && rm -f dist/*.test.*",
42
43
  "test": "rm -rf dist && tsc && node --test dist/launchers.test.js && rm -f dist/*.test.*",
44
+ "example": "tsx example/index.ts",
43
45
  "prepack": "npm run build",
44
46
  "pack:dry": "npm pack --dry-run"
45
47
  },