@its-not-rocket-science/ananke 0.1.56 → 0.1.57

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/CHANGELOG.md CHANGED
@@ -6,6 +6,27 @@ Versioning follows [Semantic Versioning](https://semver.org/).
6
6
 
7
7
  ---
8
8
 
9
+ ## [0.1.57] — 2026-03-30
10
+
11
+ ### Added
12
+
13
+ - **PA-8 — Host Integration SDKs (complete):**
14
+ - `src/host-loop.ts` (new): stable, versioned wire-format protocol for the Ananke sidecar ↔ renderer bridge. All values on the wire are real SI units (floats, not fixed-point).
15
+ - **Wire types**: `BridgeVec3`, `BridgeCondition`, `BridgeAnimation`, `BridgePoseModifier`, `BridgeGrappleConstraint`, `BridgeEntitySnapshot`, `BridgeFrame`, `HostLoopConfig`.
16
+ - **`serializeBridgeFrame(world, config)`**: canonical serializer — converts `WorldState` to `BridgeFrame`. Replaces per-sidecar serializer duplications in Unity and Godot reference implementations.
17
+ - **`derivePrimaryState(animation)`**: maps `AnimationHints` to a single state string (`"idle"` | `"attack"` | `"flee"` | `"prone"` | `"unconscious"` | `"dead"`). Suitable for top-level renderer state machines.
18
+ - **`derivePoseOffset(segmentId, impairmentQ)`**: anatomical local-space bone offset at a given impairment level (real metres), for injury deformation blend shapes.
19
+ - Constants: `BRIDGE_SCHEMA_VERSION = "ananke.bridge.frame.v1"`, `DEFAULT_TICK_HZ = 20`, `DEFAULT_BRIDGE_PORT = 3001`, `DEFAULT_BRIDGE_HOST`, `DEFAULT_STREAM_PATH`.
20
+ - `"./host-loop"` subpath export added to `package.json`.
21
+ - **Reference sidecar updates**: both `ananke-unity-reference` and `ananke-godot-reference` sidecars updated to v0.1.57 dependency and refactored to import `serializeBridgeFrame` from `@its-not-rocket-science/ananke/host-loop` — local serialization code removed.
22
+ - **Quickstart guides** (new):
23
+ - `docs/quickstart-unity.md`: 15-minute Unity integration guide (sidecar → WebSocket → `AnankeReceiver` → `AnimationDriver` → your mesh).
24
+ - `docs/quickstart-godot.md`: 15-minute Godot 4 integration guide (GDScript and C# addon variants).
25
+ - `docs/quickstart-web.md`: Three.js browser integration guide (zero-build-step HTML example + `serializeBridgeFrame` sidecar recipe).
26
+ - 41 new tests (188 test files, 5,553 tests total). Coverage: 97.10% stmt, 88.05% branch, 95.81% func. Build: clean.
27
+
28
+ ---
29
+
9
30
  ## [0.1.56] — 2026-03-30
10
31
 
11
32
  ### Added
@@ -0,0 +1,188 @@
1
+ import type { WorldState } from "./sim/world.js";
2
+ import { type AnimationHints } from "./model3d.js";
3
+ /** Wire schema identifier — included in every BridgeFrame. */
4
+ export declare const BRIDGE_SCHEMA_VERSION: "ananke.bridge.frame.v1";
5
+ /** Default sidecar tick rate (Hz). */
6
+ export declare const DEFAULT_TICK_HZ = 20;
7
+ /** Default sidecar WebSocket/HTTP port. */
8
+ export declare const DEFAULT_BRIDGE_PORT = 3001;
9
+ /** Default sidecar host. */
10
+ export declare const DEFAULT_BRIDGE_HOST = "127.0.0.1";
11
+ /** Default WebSocket stream path. */
12
+ export declare const DEFAULT_STREAM_PATH = "/stream";
13
+ /**
14
+ * 3D vector in real metres (float).
15
+ * Converts from fixed-point SCALE.m: `x_m = x_Sm / SCALE.m`.
16
+ */
17
+ export interface BridgeVec3 {
18
+ x: number;
19
+ y: number;
20
+ z: number;
21
+ }
22
+ /**
23
+ * Entity physiological condition (Q-values as [0, 1] floats).
24
+ * Divide the underlying Q value by SCALE.Q (10 000) to get floats.
25
+ */
26
+ export interface BridgeCondition {
27
+ /** Shock intensity. q(0) = no shock; q(1.0) = incapacitating. */
28
+ shockQ: number;
29
+ /** Fear intensity. q(0) = calm; q(1.0) = panic. */
30
+ fearQ: number;
31
+ /** Consciousness level. q(0) = unconscious; q(1.0) = fully alert. */
32
+ consciousnessQ: number;
33
+ /** Cumulative fluid loss. q(0) = none; q(1.0) = lethal. */
34
+ fluidLossQ: number;
35
+ /** True if the entity is clinically dead. */
36
+ dead: boolean;
37
+ }
38
+ /**
39
+ * Animation blend weights and state flags for a renderer character controller.
40
+ * All Q-values are [0, 1] floats.
41
+ *
42
+ * Locomotive blends are mutually exclusive; typically only one is nonzero.
43
+ */
44
+ export interface BridgeAnimation {
45
+ idle: number;
46
+ walk: number;
47
+ run: number;
48
+ sprint: number;
49
+ crawl: number;
50
+ guardingQ: number;
51
+ attackingQ: number;
52
+ shockQ: number;
53
+ fearQ: number;
54
+ prone: boolean;
55
+ unconscious: boolean;
56
+ dead: boolean;
57
+ /** Dominant animation state as a single string (see `derivePrimaryState`). */
58
+ primaryState: string;
59
+ /** Max locomotion blend weight — useful for speed-parameterised blend trees. */
60
+ locomotionBlend: number;
61
+ /** Worst-case injury deformation weight across all body segments. */
62
+ injuryWeight: number;
63
+ }
64
+ /**
65
+ * Per-body-segment pose modifier — drives deformation or damage blend shapes.
66
+ * Q-values are [0, 1] floats.
67
+ */
68
+ export interface BridgePoseModifier {
69
+ segmentId: string;
70
+ /** Overall deformation blend: max(structuralQ, surfaceQ). */
71
+ impairmentQ: number;
72
+ structuralQ: number;
73
+ surfaceQ: number;
74
+ /**
75
+ * Anatomical offset for this segment at full impairment, in real metres.
76
+ * Apply to the bone's local position to show slumping/collapse.
77
+ */
78
+ localOffset_m: BridgeVec3;
79
+ }
80
+ /**
81
+ * Grapple constraint describing hold/held relationships between entities.
82
+ */
83
+ export interface BridgeGrappleConstraint {
84
+ isHolder: boolean;
85
+ holdingEntityId: number;
86
+ isHeld: boolean;
87
+ heldByIds: number[];
88
+ /** Grapple positional state. */
89
+ position: "standing" | "prone" | "pinned" | "mounted";
90
+ /** Grip strength [0, 1]. */
91
+ gripQ: number;
92
+ }
93
+ /**
94
+ * Complete per-entity snapshot for one simulation tick.
95
+ */
96
+ export interface BridgeEntitySnapshot {
97
+ entityId: number;
98
+ teamId: number;
99
+ tick: number;
100
+ /** World position in real metres. */
101
+ position_m: BridgeVec3;
102
+ /** Velocity in real m/s. */
103
+ velocity_mps: BridgeVec3;
104
+ /** Normalised facing direction (unit vector). */
105
+ facing: BridgeVec3;
106
+ /** Mass in real kg. */
107
+ massKg: number;
108
+ /** Centre-of-gravity offset from foot position (real metres). */
109
+ cogOffset_m: {
110
+ x: number;
111
+ y: number;
112
+ };
113
+ animation: BridgeAnimation;
114
+ pose: BridgePoseModifier[];
115
+ grapple: BridgeGrappleConstraint;
116
+ condition: BridgeCondition;
117
+ }
118
+ /**
119
+ * Complete serialized frame for one simulation tick.
120
+ * JSON-encoded and sent over WebSocket / HTTP.
121
+ */
122
+ export interface BridgeFrame {
123
+ /** Fixed schema identifier — check this before deserializing. */
124
+ schema: typeof BRIDGE_SCHEMA_VERSION;
125
+ scenarioId: string;
126
+ tick: number;
127
+ tickHz: number;
128
+ /** ISO 8601 generation timestamp — for latency diagnostics only. */
129
+ generatedAt: string;
130
+ entities: BridgeEntitySnapshot[];
131
+ }
132
+ /**
133
+ * Sidecar configuration — passed to `serializeBridgeFrame` and used by
134
+ * host loop implementations.
135
+ */
136
+ export interface HostLoopConfig {
137
+ /** Stable identifier for this scenario (e.g. `"knight-vs-brawler"`). */
138
+ scenarioId: string;
139
+ /** Simulation tick rate in Hz. Default: `DEFAULT_TICK_HZ` (20). */
140
+ tickHz?: number;
141
+ /** Listening port. Default: `DEFAULT_BRIDGE_PORT` (3001). */
142
+ port?: number;
143
+ /** Listening host. Default: `DEFAULT_BRIDGE_HOST`. */
144
+ host?: string;
145
+ }
146
+ /**
147
+ * Derive a single animation state string from `AnimationHints`.
148
+ *
149
+ * Priority: dead > unconscious > prone/crawl > attack > flee (run/sprint) > idle.
150
+ * Renderer character controllers use this to drive top-level state machines
151
+ * when a detailed blend tree is not available.
152
+ *
153
+ * @returns One of: `"dead"` | `"unconscious"` | `"prone"` | `"attack"` | `"flee"` | `"idle"`
154
+ */
155
+ export declare function derivePrimaryState(animation: AnimationHints): string;
156
+ /**
157
+ * Anatomical local-space offset for a body segment at maximum impairment.
158
+ *
159
+ * Applied as: `bone.localPosition += poseOffset * impairmentQ`.
160
+ * Values are in real metres (float).
161
+ *
162
+ * @param segmentId Canonical segment identifier (e.g. `"head"`, `"leftArm"`).
163
+ * @param impairmentQ Impairment blend weight [0, 1] float.
164
+ * @returns Local-space offset in real metres.
165
+ */
166
+ export declare function derivePoseOffset(segmentId: string, impairmentQ: number): BridgeVec3;
167
+ /**
168
+ * Serialize a complete simulation tick into the stable bridge wire format.
169
+ *
170
+ * This is the canonical sidecar serializer. Replaces per-project
171
+ * `serialiseFrame` implementations in Unity and Godot sidecars.
172
+ *
173
+ * @param world Current world state after `stepWorld()`.
174
+ * @param config Sidecar configuration.
175
+ * @returns A `BridgeFrame` safe to `JSON.stringify` and send over WebSocket.
176
+ *
177
+ * @example
178
+ * ```ts
179
+ * import { serializeBridgeFrame } from "@its-not-rocket-science/ananke/host-loop";
180
+ *
181
+ * function tick() {
182
+ * stepWorld(world, commands, ctx);
183
+ * const frame = serializeBridgeFrame(world, { scenarioId: "my-duel", tickHz: 20 });
184
+ * broadcast(JSON.stringify(frame));
185
+ * }
186
+ * ```
187
+ */
188
+ export declare function serializeBridgeFrame(world: WorldState, config: HostLoopConfig): BridgeFrame;
@@ -0,0 +1,185 @@
1
+ // src/host-loop.ts — PA-8: Host Integration Bridge Protocol
2
+ //
3
+ // Stable, versioned wire format for the Ananke sidecar ↔ renderer bridge.
4
+ // All values on the wire are in real SI units (floats).
5
+ //
6
+ // Usage in a sidecar:
7
+ // import { serializeBridgeFrame, HostLoopConfig } from "@ananke/host-loop";
8
+ //
9
+ // Usage in a renderer client (Unity, Godot, Web):
10
+ // const frame: BridgeFrame = JSON.parse(rawWebSocketMessage);
11
+ // // field names and types are stable across minor versions
12
+ //
13
+ // Schema version string: BRIDGE_SCHEMA_VERSION.
14
+ // Increment the version suffix (v1 → v2) only on breaking wire changes.
15
+ import { SCALE, q, clampQ, qMul } from "./units.js";
16
+ import { deriveAnimationHints, derivePoseModifiers, deriveGrappleConstraint, deriveMassDistribution, } from "./model3d.js";
17
+ // ── Protocol constants ─────────────────────────────────────────────────────────
18
+ /** Wire schema identifier — included in every BridgeFrame. */
19
+ export const BRIDGE_SCHEMA_VERSION = "ananke.bridge.frame.v1";
20
+ /** Default sidecar tick rate (Hz). */
21
+ export const DEFAULT_TICK_HZ = 20;
22
+ /** Default sidecar WebSocket/HTTP port. */
23
+ export const DEFAULT_BRIDGE_PORT = 3001;
24
+ /** Default sidecar host. */
25
+ export const DEFAULT_BRIDGE_HOST = "127.0.0.1";
26
+ /** Default WebSocket stream path. */
27
+ export const DEFAULT_STREAM_PATH = "/stream";
28
+ // ── Primary state derivation ──────────────────────────────────────────────────
29
+ /**
30
+ * Derive a single animation state string from `AnimationHints`.
31
+ *
32
+ * Priority: dead > unconscious > prone/crawl > attack > flee (run/sprint) > idle.
33
+ * Renderer character controllers use this to drive top-level state machines
34
+ * when a detailed blend tree is not available.
35
+ *
36
+ * @returns One of: `"dead"` | `"unconscious"` | `"prone"` | `"attack"` | `"flee"` | `"idle"`
37
+ */
38
+ export function derivePrimaryState(animation) {
39
+ if (animation.dead)
40
+ return "dead";
41
+ if (animation.unconscious)
42
+ return "unconscious";
43
+ if (animation.prone || animation.crawl > 0)
44
+ return "prone";
45
+ if (animation.attackingQ > 0)
46
+ return "attack";
47
+ if (animation.sprint > 0 || animation.run > 0)
48
+ return "flee";
49
+ return "idle";
50
+ }
51
+ // ── Pose offset per segment ───────────────────────────────────────────────────
52
+ /**
53
+ * Anatomical local-space offset for a body segment at maximum impairment.
54
+ *
55
+ * Applied as: `bone.localPosition += poseOffset * impairmentQ`.
56
+ * Values are in real metres (float).
57
+ *
58
+ * @param segmentId Canonical segment identifier (e.g. `"head"`, `"leftArm"`).
59
+ * @param impairmentQ Impairment blend weight [0, 1] float.
60
+ * @returns Local-space offset in real metres.
61
+ */
62
+ export function derivePoseOffset(segmentId, impairmentQ) {
63
+ // 6% of stature at full impairment (clamp to [0, SCALE.Q])
64
+ const weightQ = clampQ(Math.round(impairmentQ * SCALE.Q), q(0), SCALE.Q);
65
+ const offsetQ = qMul(weightQ, q(0.06));
66
+ const offset = offsetQ / SCALE.Q;
67
+ // `+ 0` normalises IEEE-754 negative-zero (−0) to plain 0.
68
+ switch (segmentId) {
69
+ case "head": return { x: 0, y: (-offset * 0.35) + 0, z: 0 };
70
+ case "torso":
71
+ case "thorax":
72
+ case "abdomen": return { x: 0, y: (-offset * 0.50) + 0, z: 0 };
73
+ case "leftArm": return { x: (-offset) + 0, y: 0, z: 0 };
74
+ case "rightArm": return { x: offset, y: 0, z: 0 };
75
+ case "leftLeg": return { x: (-offset * 0.45) + 0, y: (-offset) + 0, z: 0 };
76
+ case "rightLeg": return { x: offset * 0.45, y: (-offset) + 0, z: 0 };
77
+ default: return { x: 0, y: 0, z: 0 };
78
+ }
79
+ }
80
+ // ── Internal helpers ──────────────────────────────────────────────────────────
81
+ function scaleVec3(v, divisor) {
82
+ return { x: v.x / divisor, y: v.y / divisor, z: v.z / divisor };
83
+ }
84
+ function normalizeFacing(v) {
85
+ const mag = Math.hypot(v.x, v.y, v.z) || 1;
86
+ return { x: v.x / mag, y: v.y / mag, z: v.z / mag };
87
+ }
88
+ function buildBridgeAnimation(animation, pose) {
89
+ const locomotionBlend = Math.max(animation.idle, animation.walk, animation.run, animation.sprint, animation.crawl) / SCALE.Q;
90
+ const injuryWeight = pose.reduce((worst, m) => Math.max(worst, m.impairmentQ), 0) / SCALE.Q;
91
+ return {
92
+ idle: animation.idle / SCALE.Q,
93
+ walk: animation.walk / SCALE.Q,
94
+ run: animation.run / SCALE.Q,
95
+ sprint: animation.sprint / SCALE.Q,
96
+ crawl: animation.crawl / SCALE.Q,
97
+ guardingQ: animation.guardingQ / SCALE.Q,
98
+ attackingQ: animation.attackingQ / SCALE.Q,
99
+ shockQ: animation.shockQ / SCALE.Q,
100
+ fearQ: animation.fearQ / SCALE.Q,
101
+ prone: animation.prone,
102
+ unconscious: animation.unconscious,
103
+ dead: animation.dead,
104
+ primaryState: derivePrimaryState(animation),
105
+ locomotionBlend,
106
+ injuryWeight,
107
+ };
108
+ }
109
+ function buildBridgeGrapple(grapple) {
110
+ return {
111
+ isHolder: grapple.isHolder,
112
+ holdingEntityId: grapple.holdingEntityId ?? 0,
113
+ isHeld: grapple.isHeld,
114
+ heldByIds: grapple.heldByIds,
115
+ position: grapple.position,
116
+ gripQ: grapple.gripQ / SCALE.Q,
117
+ };
118
+ }
119
+ function buildBridgeCondition(entity) {
120
+ return {
121
+ shockQ: entity.injury.shock / SCALE.Q,
122
+ fearQ: (entity.condition.fearQ ?? 0) / SCALE.Q,
123
+ consciousnessQ: entity.injury.consciousness / SCALE.Q,
124
+ fluidLossQ: entity.injury.fluidLoss / SCALE.Q,
125
+ dead: entity.injury.dead,
126
+ };
127
+ }
128
+ function buildEntitySnapshot(entity, tick) {
129
+ const animation = deriveAnimationHints(entity);
130
+ const pose = derivePoseModifiers(entity);
131
+ const grapple = deriveGrappleConstraint(entity);
132
+ const mass = deriveMassDistribution(entity);
133
+ return {
134
+ entityId: entity.id,
135
+ teamId: entity.teamId,
136
+ tick,
137
+ position_m: scaleVec3(entity.position_m, SCALE.m),
138
+ velocity_mps: scaleVec3(entity.velocity_mps, SCALE.m),
139
+ facing: normalizeFacing(entity.action.facingDirQ),
140
+ massKg: mass.totalMass_kg / SCALE.kg,
141
+ cogOffset_m: mass.cogOffset_m,
142
+ animation: buildBridgeAnimation(animation, pose),
143
+ pose: pose.map(pm => ({
144
+ segmentId: pm.segmentId,
145
+ impairmentQ: pm.impairmentQ / SCALE.Q,
146
+ structuralQ: pm.structuralQ / SCALE.Q,
147
+ surfaceQ: pm.surfaceQ / SCALE.Q,
148
+ localOffset_m: derivePoseOffset(pm.segmentId, pm.impairmentQ / SCALE.Q),
149
+ })),
150
+ grapple: buildBridgeGrapple(grapple),
151
+ condition: buildBridgeCondition(entity),
152
+ };
153
+ }
154
+ // ── Public API ────────────────────────────────────────────────────────────────
155
+ /**
156
+ * Serialize a complete simulation tick into the stable bridge wire format.
157
+ *
158
+ * This is the canonical sidecar serializer. Replaces per-project
159
+ * `serialiseFrame` implementations in Unity and Godot sidecars.
160
+ *
161
+ * @param world Current world state after `stepWorld()`.
162
+ * @param config Sidecar configuration.
163
+ * @returns A `BridgeFrame` safe to `JSON.stringify` and send over WebSocket.
164
+ *
165
+ * @example
166
+ * ```ts
167
+ * import { serializeBridgeFrame } from "@its-not-rocket-science/ananke/host-loop";
168
+ *
169
+ * function tick() {
170
+ * stepWorld(world, commands, ctx);
171
+ * const frame = serializeBridgeFrame(world, { scenarioId: "my-duel", tickHz: 20 });
172
+ * broadcast(JSON.stringify(frame));
173
+ * }
174
+ * ```
175
+ */
176
+ export function serializeBridgeFrame(world, config) {
177
+ return {
178
+ schema: BRIDGE_SCHEMA_VERSION,
179
+ scenarioId: config.scenarioId,
180
+ tick: world.tick,
181
+ tickHz: config.tickHz ?? DEFAULT_TICK_HZ,
182
+ generatedAt: new Date().toISOString(),
183
+ entities: world.entities.map(e => buildEntitySnapshot(e, world.tick)),
184
+ };
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@its-not-rocket-science/ananke",
3
- "version": "0.1.56",
3
+ "version": "0.1.57",
4
4
  "type": "module",
5
5
  "description": "Deterministic lockstep-friendly SI-units RPG/physics core (fixed-point TS)",
6
6
  "license": "MIT",
@@ -193,6 +193,10 @@
193
193
  "./extended-senses": {
194
194
  "import": "./dist/src/extended-senses.js",
195
195
  "types": "./dist/src/extended-senses.d.ts"
196
+ },
197
+ "./host-loop": {
198
+ "import": "./dist/src/host-loop.js",
199
+ "types": "./dist/src/host-loop.d.ts"
196
200
  }
197
201
  },
198
202
  "workspaces": [