diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..78ef940
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,2 @@
+*.sh text eol=lf
+tests/Lodur.Core.Tests/pain-box-golden.tsv text eol=lf
diff --git a/Lodur.slnx b/Lodur.slnx
index b755d72..3a5ebc3 100644
--- a/Lodur.slnx
+++ b/Lodur.slnx
@@ -1,5 +1,6 @@
+
diff --git a/README.md b/README.md
index b079601..6639f7f 100644
--- a/README.md
+++ b/README.md
@@ -4,16 +4,24 @@ A physics character middleware for characters that **feel and react**: they
pull back from something hot, jump when poked, and, if they want their
objective badly enough, crawl toward it after losing a leg.
-**Status: design plus a first slice of layer 5.** The design is
-[`docs/lodur-target.md`](docs/lodur-target.md); read it first. What runs today is a
-PD-muscle active ragdoll on Ymir's Box3D SoA world: [`docs/first-slice.md`](docs/first-slice.md)
-(measured and unmeasured). Layers 1-4 (perception, reflex, drive, behaviour) are not
-coded.
+**Status: layers 1-3 and a layer-4 stand-in run on a PD-muscle ragdoll on Ymir.** The
+design is [`docs/lodur-target.md`](docs/lodur-target.md); read it first. `Lodur.Core`
+holds perception, the withdrawal reflex, the drive state and a hold-against-reflex
+stand-in, run per character by `Actor`; `Lodur.Body.Ymir` is the PD-muscle active ragdoll
+on Ymir's Box3D SoA world ([`docs/first-slice.md`](docs/first-slice.md), measured and
+unmeasured). Behaviour selection beyond the stand-in, impairment and the learned tracker
+are not coded.
-Entry points: `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
-`src/Lodur.Body.Ymir/HumanoidRagdoll.cs` (the ragdoll and `Drive`), `tests/Lodur.Tests`
-(stand, fall, rest, same-seed-same-hash). Needs a sibling Ymir checkout at
-`main` (the SoA joints merge, 2026-11-10, or later); `dotnet test tests/Lodur.Tests` builds its native library with cmake.
+Entry points: `src/Lodur.Core/Actor.cs` (one character's nervous state, one tick per
+physics step), `src/Lodur.Core/PdMuscle.cs` (engine-free PD law, strength per muscle),
+`src/Lodur.Core/BodyPlan.cs` (a body as data: parts, joints that are the tree, sense points, airway openings),
+`src/Lodur.Body.Ymir/Ragdoll.cs` (builds a `BodyPlan` into a Ymir world; `Drive`, `ReadSensePoints`, and `ReadAirway`, which reads the liquid sensors it places at the airway openings (live and pooled volume) and each opening's drop below the airway sumps against the caller's down),
+`tests/Lodur.Core.Tests` (the layers and parity with the pain box; builds without Ymir),
+`tests/Lodur.Tests` (stand, fall, rest, same-seed-same-hash, and the connected pain box:
+`ConnectedPainBoxTests`). The map this was cut from is
+[`docs/connect-rungs-map.md`](docs/connect-rungs-map.md). Needs a sibling Ymir checkout at
+`main` (the SoA joints merge, 2026-11-10, or later); `dotnet test tests/Lodur.Tests` builds
+its native library with cmake.
## The problem
@@ -27,10 +35,12 @@ time. Lodur is that layer.
## Shape (planned)
- **Core** (C#, no engine references): perception, reflexes, a drive state of
- pain, shock, adrenaline and resolve that evolves every tick, and behaviour
- selection that turns the drive into targets plus muscle strength.
+ pain, shock, adrenaline and resolve that evolves every tick (the will breaks
+ at zero resolve and mends as it recovers, and can break again), and behaviour
+ selection that turns the drive into targets plus muscle strength, weighted by
+ the will available to each voluntary pose.
- **Body** (per engine): follows those targets on the engine's own articulated
- physics. v1 is a PD-tracking active ragdoll in Unity; v2 adds a small learned
+ physics. v1 is a PD-tracking active ragdoll on Ymir; v2 adds a small learned
tracker for upright balance behind the same interface.
## First consumer
diff --git a/docs/bds-mvp-map.md b/docs/bds-mvp-map.md
new file mode 100644
index 0000000..6c9edf6
--- /dev/null
+++ b/docs/bds-mvp-map.md
@@ -0,0 +1,368 @@
+# Bad Day Simulator MVP on Lodur and Ymir (map)
+
+Imagination pass `bds-mvp-map`, nibu-imagination, session nibu-self-2026-11-17, 2026-11-20.
+Serves `lodur:ruling:bds-mvp-scope` and `lodur:ruling:bds-sandbox-arenas-will-economy`, under target
+`lodur:target:r3`. Committed as `Lodur/docs/bds-mvp-map.md`; the bases, probes and body facts below are as of the pass (Modeling refreshed the state columns and the cut table on 2026-11-20, see "Landed since the pass"); the target r4 text below went to
+`docs/lodur-target.md` when Self admits r4.
+
+## Bases
+
+| Repo | Base | Note |
+|---|---|---|
+| GameCult/Ymir | `0b0321a` (main) | Box3D v0.1.0 at `extern/box3d` 8441b4a |
+| GameCult/Lodur | `1491bed` (read), main now `a048827` | rung 3 sensory load merged to main during this pass (a048827); Lodur anchors below are at 1491bed and move with it |
+| GameCult/BadDaySimulator | `a218c55` (main) | |
+| Godot client | none | a parallel Imagination maps `client-ready-sim`, `godot-client-v1`; not admitted at 5566 |
+
+In-flight specs this map sequences around (no report unless noted): `rung3-sensory-load` (merged), `rung3-office-stress`, `rung4-goal-flip`, `rung4-office-flip`.
+
+## Landed since the pass (Modeling, 2026-11-20; mains: Ymir `5104b17`, Lodur `f9e302e`, BDS `bd01101`)
+
+Body facts 1 and 8-10 below describe the bases, not today. What the cuts changed; the owners' inputs, outputs, derived
+state and forbidden writers are in `docs/lodur-target.md` ("Who writes what, per tick") and BDS's README ("Who owns
+what"); rulings and specs are cited by id, not restated.
+
+- **Ymir** (ABI 8): contact and hit facts with materials, exact per-step contact impulse, grab anchor, motor joint,
+ point impulse, ray, joint handles with generations, tombstoned joint lanes, and joint origin lanes (the joint
+ frame's origin in the world, on body A). Not landed: thresholds, overload facts, removal of bodies and joints
+ (`ymir-break-and-remove`, still refused by the API).
+- **Lodur**: the drive's will breaks and mends as a recurring event (`Breaks`, `WillMendsAt`); `Will` = min(resolve x
+ attention, consciousness) is derived; every voluntary pose is written at `Will^WillCurve` (the will mix), an
+ involuntary goal onset at full weight; goals carry `EntryResolve`, `Effort`, `InvoluntarySeconds`, and `SensoryGain`,
+ `EntryArousal`, `EntrySeconds` (the Actor ramps gain and arousal over the entry, Perception gates the sense channels
+ with the gain and refuses one outside [0, 1]). Startle (the Attention writer) and physiology (the Consciousness
+ writer) are not built.
+- **BDS**: the chamber and the office are scenarios on one stepping session each; the office arc is snap, rage, calm
+ (the stress column is arousal), and each scenario's release goal is declared by id. The Godot client draws the
+ body run as one skinned SDF puppet: `PuppetField` meshes, `PuppetModel` owns bind, signature and rebuild,
+ `PuppetSkin` skins every frame and derives the surface, `Puppet` owns the Godot mesh and the build counter, the
+ shader only draws the bevel, `RenderCheck` is the windowed oracle. Not landed: a sandbox session, commands,
+ levels, runtime bodies.
+
+## Body facts (probes)
+
+All probes 2026-11-20, read-only on `F:\Projects`; the C probe is
+`scratchpad/imag-mvp/probe/probe.c`, built with StrawberryPerl gcc 13.2
+(`gcc -O1 -std=c17 -mavx2 -I extern/box3d/include -I extern/box3d/src probe.c extern/box3d/src/*.c`)
+against Ymir's pinned Box3D, sphere r 0.1 m, density 1000, 1/120 s, 4 substeps, sleep off, one worker.
+
+1. **Ymir SoA has none of what the MVP needs from physics.** `native/Ymir.Box3D/ymir_box3d_soa.c`: body kinds
+ sphere/static box/capsule/box only (42-48, check at 365); joint kinds revolute/spherical/weld only (50-55,
+ C# `Box3DSoaWorld.cs:13-18`); no remove, no kinematic body, no motor joint, no impulse, no raycast, no events;
+ `add_body` builds every shape with `b3DefaultShapeDef()` (453) whose `enableContactEvents` is **false** in
+ v0.1.0 (`extern/box3d/src/types.c:66-80`, the field is zero-initialised). Lanes are dense, append-only
+ (`count++` at 485), capacity fixed at create (289-333), views are zero-copy pointers fixed for the world's life
+ (`Box3DSoaWorld.cs:150-155`). Duplicate stable ids are refused by a linear scan (419-425). Shape `userData`
+ already carries the stable id (454).
+2. **Box3D v0.1.0 has every API the MVP needs.** Headers: `b3World_GetContactEvents` (box3d.h:69),
+ `b3World_GetJointEvents` (72), `b3DestroyBody` (490), `b3Body_SetTargetTransform` (557),
+ `b3Body_ApplyLinearImpulse` (598), `b3DestroyJoint` (1014), `b3Joint_GetConstraintForce/Torque` (1059/1062),
+ `b3Joint_SetForceThreshold/TorqueThreshold` (1080/1086), `b3CreateMotorJoint` (1219), `b3_kinematicBody`
+ (types.h:230), `b3JointDef.forceThreshold/torqueThreshold` (types.h:622/625, default `FLT_MAX`,
+ joint.c:28-29), `b3MotorJointDef` with linear/angular spring hertz, damping and max force (types.h:696-730),
+ manifold points with `normalImpulse` and `totalNormalImpulse` (types.h:2573/2577). This corrects
+ `lodur:research:mvp-prior-art.contact-events` ("no normal-impulse accessor found in the docs"): the
+ accessor is `b3Body_GetContactData` / `b3Contact_GetData` manifolds.
+3. **Contact events, run.** With `enableContactEvents` and `enableHitEvents` on both shapes, a sphere dropped
+ 1.4 m gave 1 begin, 1 hit (approach 5.25 m/s), 0 ends over 120 steps. At rest, the manifold's
+ `normalImpulse` summed to 0.0873 per step against m g dt = 0.349: it is the **last substep's** impulse
+ (0.349 / 4). Force from a contact is `totalNormalImpulse / dt`, or `normalImpulse * substeps / dt`.
+4. **End events after removal, run.** Destroying a resting body gives **no** end event in the destroy call's
+ buffer and **one** after the next step, carrying the destroyed shape's id (invalid by then).
+ `b3Body_Disable` behaves the same. So a consumer must resolve a dead shape id to the stable id it had. Ymir's
+ planar session already does this: `ymir_box3d.c:694-712` (`ymir_session_resolve_event_shape`, a
+ retired-shape table filled at removal, 1420-1437) and drains begin/hit/end with manifold details at 773-830.
+ The SoA world should reuse that pattern, not invent one.
+5. **Joint over threshold, run.** A spherical joint with `forceThreshold` 200 N under a ramped pull reported one
+ `b3JointEvent` on the step the force crossed it; `b3Joint_GetConstraintForce` read 1241.9 N on that step; the
+ joint is **not** destroyed by Box3D (event only); `b3DestroyJoint` from the event left the child falling free.
+ Joint events are only for awake joints; Ymir disables sleep (soa.c:337, 447), so every joint reports.
+6. **Grab, run.** A shapeless kinematic body moved by `b3Body_SetTargetTransform` each step, joined to a 4.19 kg
+ sphere by a motor joint (linear spring 5 Hz, damping 0.7, max spring force 50 N, angular spring off), held
+ the sphere at (0.72, 1.02) against a target of (1.0, 1.5): the max force (50 N against 41 N of weight) bounds
+ the pull, as the Box2D v3 drag sample states (`lodur:research:mvp-prior-art.grab-drag`). Destroying the
+ grabbed body destroyed the motor joint with it (`b3Joint_IsValid` 0).
+7. **Impulse at a point, run.** `b3Body_ApplyLinearImpulse` of 1 N s, 0.1 m above the centre, gave v 0.28 m/s and
+ spin -5.0 rad/s: an off-centre poke turns the part, which the force lanes (centre of mass only, soa.c:593-626)
+ cannot do.
+8. **Lodur today.** Perception senses named box volumes at points only (`Perception.cs:82-113`); regions are two
+ sense points read by `Ragdoll.ReadSensePoints`; one reflex kind (`WithdrawalReflex.cs`); drive is pain,
+ strain, resolve, `WillBroken` (`DriveState.cs`); behaviour blends two poses by leak and shake
+ (`PoseBehaviour.cs:87-115`); the body takes one strength and one joint-space target per plan joint
+ (`Ragdoll.Drive`). No IK, no clips, no physiology, no grip; the part tree is `BodyPlan` (parts, joints that are the tree,
+ sense points), without HP, coverage or vital flags. Rung 3 adds emitters and arousal; rung 4 the goal flip and `PoseBehaviour`.
+9. **BDS today.** Headless and body pain box only (`src/BadDay.Ymir/BodyPainBox.cs`); the world is built per run
+ with capacity 15 (58); the puppet is welded to a stool because the PD ragdoll cannot balance for 15 s (59-62).
+ No session type survives beyond a run, no commands, no level content.
+10. **Godot today.** Nothing; no repo under `F:\Projects` matches.
+
+## The systems, by owner
+
+`exists` cites base code; `new` is MVP work and names the cut that builds it (cut order below).
+
+### Ymir (physics facts and actuators; decides nothing about bodies' meaning)
+
+| System | State | Cut |
+|---|---|---|
+| Contact facts: begin/end/hit per step with stable ids, lanes, point, normal, approach speed, material ids; per-body contact force lane | landed (ABI 5-7; `docs/soa-world.md`: facts per step, exact per-step contact impulse per body and per hit); planar session precedent `ymir_box3d.c:694-830` | `ymir-contact-facts` |
+| Material id per body (u64, the game's), carried on hit facts | landed (the body's `material_id`, on the hit facts) | `ymir-contact-facts` |
+| Raycast (closest hit: lane, stable id, point, normal, fraction) for picking and hitscan | landed (ABI 5) | `ymir-grab-anchor` |
+| Grab anchor: shapeless kinematic body moved by target transform; motor joint (linear/angular spring, max force) | landed (ABI 5-6: grab release, joint handles with generations; probe 6) | `ymir-grab-anchor` |
+| Point impulse command | landed (ABI 5; probe 7) | `ymir-grab-anchor` |
+| Joint stress: per-joint force/torque thresholds (create and set), overload facts with measured force/torque | new; probe 5 | `ymir-break-and-remove` |
+| Runtime removal of bodies and joints; tombstoned lanes; reuse after a step; removal facts (incl. joints that die with a body); end-touch attribution for dead shapes | new; probe 4 | `ymir-break-and-remove` |
+| Placeable joint kinds for building (motor-driven revolute, prismatic, distance/rope, spring) | new | follow-up `ymir-joint-kinds` |
+| More shapes (hulls, compounds) for authored props | new | follow-up `ymir-shapes` |
+
+### Lodur (general character middleware; no gore)
+
+| System | Layer | State | Cut |
+|---|---|---|---|
+| Part tree: the body plan as content (parts, parent, side, max HP, coverage, vital flags, muscles, Ymir lane binding) | 3 data + 5 binding | `BodyPlan` holds parts, joints as the tree and sense points; HP, coverage and vital flags are new | `lodur-physiology` |
+| Touch perception per part: pressure (contact force), impact (hit speed, material), external-joint pull (grab, strap) | 1 (+5 reads Ymir) | new | `lodur-touch` |
+| Reflexes: withdrawal (exists), startle on sensory and touch onsets, flinch-from-touch, brace on impact | 2 | withdrawal exists `WithdrawalReflex.cs` and reads `Will`; rest new | `lodur-startle-attention`, `lodur-reflex-set` |
+| Physiology as drive state: per-part HP and injuries, body blood fraction, bleeding, pain sum, shock, consciousness, capacities scaling muscle strength, death | 3 | new | `lodur-physiology` |
+| Will economy: resolve (exists) times attention (new, startle drains it) is the budget every voluntary layer draws on; reflexes act against it | 3/4 | landed except attention: `Will` = min(resolve x attention, consciousness) in `DriveState`, read by the reflex and the will mix; the Attention and Consciousness slots read 1 until startle and physiology write them | `lodur-startle-attention` (open), `lodur-will-mix` (landed `afb8df3`) |
+| Voluntary motor layers: hold pose (exists as `PoseBehaviour`), clip player, IK goals (reach, look, aim), grip; mixed by will | 4 | hold exists, weighted by `Will^WillCurve` (`PoseBehaviour.Write`; an involuntary goal onset writes at weight 1); rest new | `lodur-will-mix`, `lodur-ik-goals`, `lodur-clips` |
+| Body interface: strengths + joint targets (exists) + IK goals with weights | 5 | partial `Ragdoll.Drive` | `lodur-ik-goals` |
+| Severing: physiology decides; binding removes the joint in Ymir; impairment states derived per part, mirror-symmetric | 3 decides, 5 executes | new | `lodur-sever-impair` |
+| Grip: hand holds an object by a breakable weld whose threshold follows grip strength; drop on pain, overload, unconsciousness; the tool frame is an IK end effector | 4/5 | new | `lodur-grip` |
+
+### Bad Day Simulator (content, rules, sandbox; owns the gore)
+
+| System | State | Cut |
+|---|---|---|
+| Sandbox session: one deterministic world with puppets and objects; command queue (spawn, remove, grab begin/move/end, poke, cut, place joint, wire) | new; today per-run `BodyPainBox.Run` | follow-up `bds-sandbox-session` (after `client-ready-sim`) |
+| Damage content: material ids to insult kinds and gains (blade Cut, bat Blunt, spike Pierce), tear from joint overload | new | follow-up `bds-damage-content` |
+| Gore presentation data: blood colour, bleed particle rates by wound, decal sets, stump caps, gibs | new; waits on `bds-gore-look` | follow-up `bds-gore-content` |
+| Levels and arenas as CultCache: objects, joints, stimulus volumes, emitters, triggers, signal wires; arenas are levels built with the player's commands | new | follow-up `bds-level-content` |
+| Contraption logic: signals between objects (switch, timer, sensor volume, motor, emitter) ticked in the session | new | follow-up `bds-contraption-signals` |
+| Guns and ballistics: hitscan by Ymir raycast, recoil impulse, damage content | new | follow-up `bds-guns` |
+
+### Godot client
+
+| System | State | Cut |
+|---|---|---|
+| Render bodies from Ymir lanes by stable id | landed: `BodyRenderer` draws static boxes and `Puppet` the dynamic bodies as one skinned SDF mesh (BDS README, "Who owns what") | `godot-client-v1` |
+| Bodies added and removed at runtime from Ymir lifecycle facts | new | follow-up `godot-runtime-bodies` |
+| Input to commands: ray pick, grab drag, poke, cut, place, wire | new | follow-up `godot-interaction` |
+| Blood visuals from BDS gore events (particles at wounds, decals at hits, stump caps) | new | follow-up `godot-blood` |
+| Building tools UI over the level commands | new | follow-up `godot-build-tools` |
+
+## Authority map (MVP)
+
+**Owner of each decision, one each.**
+
+- **Whether a body or joint exists in the world:** Ymir, on command only. Ymir never removes anything on its
+ own; a joint over threshold is a fact, not a removal (probe 5: Box3D itself does the same).
+- **What touched what this step, how hard:** Ymir's contact facts and contact-force lane. Nothing else derives
+ touch from geometry; the box-volume stimuli stay named game stimuli (a heat source is not a contact).
+- **What damage an insult does to a part, and whether a part is severed, disabled or dead:** Lodur physiology,
+ from insults (part, kind, magnitude) the binding builds out of Ymir facts and the game's material table.
+ **The joint break threshold is no longer an owner; it is a stress sensor** whose facts become Tear insults.
+- **What the body tries to do:** Lodur's will mix: voluntary layers weighted by available will, reflexes against
+ it (ruling `bds-sandbox-arenas-will-economy`). `PoseBehaviour`'s blend (`PoseBehaviour.cs:87-115`) is
+ no longer an owner; it becomes one voluntary layer (hold pose) inside the mix.
+- **Muscle strength ceiling:** physiology capacities times consciousness; the will mix may only scale down from
+ it. Content gains are parameters, not owners.
+- **Where the player's hand is and what it holds:** BDS sandbox session (grab handle); Ymir executes the anchor.
+- **What a material means (sharp, blunt, hot) and how gore looks:** BDS content. Lodur sees only insult kinds.
+- **What is drawn:** Godot, from Ymir lanes and lifecycle facts, BDS presentation events. Godot owns no
+ simulation state and never writes a lane.
+
+**Inputs/outputs per tick (one order, the body run's order today, `BodyPainBox.cs:106-110`, extended):**
+BDS applies queued commands (spawn/remove/grab target/impulse) → Ymir step → Ymir facts (contacts, hits,
+overloads, removals) → binding turns facts into per-part touch samples and insults → Actor tick: perception,
+reflex (gain from last tick's drive), drive and physiology, will mix → binding writes strengths, targets, IK
+solve onto torque lanes, executes severing and grip changes as commands for the next step → BDS emits
+presentation events (wound opened, part severed, death) → Godot draws.
+
+**Derived state:** impairment state per part (from HP, severed, nerve flags); capacities; consciousness;
+"dead"; blood visuals; Godot node set (from lifecycle facts); joint overload (a sensor reading).
+
+**Forbidden writers:** Godot writing any lane or calling Ymir directly; BDS setting muscle strengths or targets
+(body-one-interface); Ymir destroying a joint on threshold; any per-wound lookup choosing behaviour
+(drive-is-state); a voluntary layer writing targets outside the will weighting; the binding deciding damage.
+
+**Shared paths:** player grab, a scripted grab in an arena, and a level load all go through the session's
+command queue; arenas are levels; a player cut and a falling blade go through the same contact-to-insult path;
+a torn limb and a cut limb go through the same physiology severing decision; reload of a level replays the
+same commands as building it.
+
+**Deletion lines:** `PoseBehaviour.Blend` as the motor owner (in `lodur-will-mix`, landed: `Blend` now only mixes the hold layer's flinch pose, the strength is the will mix); hand-only `Region`
+enum and `ReadRegions` as perception's body model (landed: deleted with `Limb` and `Muscle` in `lodur:cut_spec:cut-body-plan-data.r2`; `lodur-touch` reads parts and sense points by plan label); the per-run world in
+`BodyPainBox.Run` as BDS's only world (in `bds-sandbox-session`, scenario runs become sessions,
+follow-up `scenario-session-unify`).
+
+## Model page: identity, lifecycle, authority
+
+| Kind | Named by | Lifecycle | Decides | Persisted |
+|---|---|---|---|---|
+| Ymir body lane | caller's `stable_id` (u64, unique among live bodies of a world) and its lane while alive | add → live → removed (tombstoned) → lane reusable after the next completed step | Ymir on command | no (the level persists what spawned it) |
+| Ymir joint lane | lane while alive; caller may tag | add → live → removed by command or with its body | Ymir on command | no |
+| Body part (def) | (body plan content id, part label) | authored content, immutable at runtime | content (game), schema Lodur | CultCache content |
+| Body part (state) | (actor, part label) | spawned with the actor → intact → impaired/disabled → severed or dead; never resurrected in MVP (`bds-reattach`) | Lodur physiology | no in MVP (`bds-gore-look` option persist) |
+| Wound (injury) | (actor, part, ordinal) | opened by an insult → bleeding → clotting (content rate) → closed; no tending in MVP | Lodur physiology | no |
+| Blood (body) | (actor) scalar fraction | 1.0 at spawn, falls by bleeding, recovers only while nothing bleeds (RimWorld, `rw-blood-bleeding`) | Lodur physiology | no |
+| Blood visual (pool, decal, spray) | presentation instance | emitted from wound/hit events, fades or stays per `bds-gore-look` | BDS presentation data, Godot draws | no (question) |
+| Severed part | the stable ids of its bodies (they survive; only the joint goes) | severed → loose physics prop owned by the session, grabbable, removable by the player | physiology severs; session owns the prop after | no |
+| Grab | (session, pointer) handle; anchor's stable id | begin on ray pick → target moved per tick → end on release, or ends when its body is removed (Ymir removal fact) | BDS session | no |
+| Impairment state | (actor, limb slot, side) | derived each tick from part states; closed set `Intact, Impaired, Disabled, Severed` per limb slot, mirror-symmetric | derived (physiology) | no |
+| Animation clip | content id | authored, immutable | content (BDS), schema Lodur | CultCache content |
+| IK goal | (actor, chain) for chain in the closed set `ArmL, ArmR, LegL, LegR, Look, Aim` | written every tick by a voluntary layer, weighted by will, consumed by the binding's solver | Lodur will mix | no |
+| Held object (grip) | (actor, hand side) → object stable id | grip begins on behaviour or level content → weld joint with threshold = grip strength → released by behaviour, reflex, unconsciousness or overload | Lodur grip state; Ymir weld executes | level may author "starts holding X" (content) |
+| Level / arena | content id | authored with player tools, saved, loaded by replaying commands | BDS | CultCache |
+| Contact / hit / overload / removal fact | (step, ordinal) | one step | Ymir | no |
+| Attention | (actor) scalar | 1.0, and nothing writes it yet but the test seam `Actor.SetAttention`; startle will drop it, recovering in under a second | Lodur drive | no |
+
+## Questions for the operator and Deru (one batch; admitted as `question`s)
+
+1. `bds-gore-look`: what gore looks like and whether it stays. Options: stylised (bright blood, decals and
+ spurts, capped stumps, no viscera), realistic (wound textures, exposed bone, gibs), stylised with a content
+ slider. Recommend stylised default with presentation data shaped to take a realism slider later; blood
+ visuals fade per session and are never saved in levels. Grounds: People Playground reads clearly with
+ stylised blood (`mvp-prior-art.pp-physiology`); the sim (wounds, blood fraction) is the same for every
+ option, so only BDS content and Godot change.
+2. `bds-death`: what kills a puppet and what death looks like. Options: RimWorld rules (consciousness 0,
+ blood loss 100%, lethal part destroyed: head, neck, torso, heart), then limp and permanent until reset;
+ People Playground rules (no hard line; integrity and oxygen fade, revivable by an item); no death in the
+ MVP (unconscious only). Recommend RimWorld rules with a session reset, revival items later
+ (`rw-consciousness`, `rw-body-tree`, `pp-physiology`).
+3. `bds-reattach`: can parts be put back. Options: no; prop-only (the player may weld a severed arm back with
+ the joint tool, it hangs limp and stays Severed to physiology); full heal. Recommend prop-only: it costs
+ nothing (it is the joint tool) and keeps physiology one-way.
+4. `bds-dismember-trigger`: what takes a part off. Options: blades and extreme force both (Cut insults past a
+ part's HP, and Tear from joint overload while grabbed or hit); blades only; an explicit sever tool. Recommend
+ both through one severing rule (DF: severed limbs common; Box3D thresholds as sensors, `joint-break-apis`).
+5. `bds-upright`: how the puppet stays up in the MVP. Options: seated or strapped (today's stool weld); an
+ assist pin on pelvis and torso whose strength is consciousness times will, so a fainting puppet collapses
+ (PuppetMaster pin weights, euphoria doc 10.1); hung or suspended; learned balance (v2, out of MVP per
+ `euphoria-body-layer-order`). Recommend the assist pin: it is a voluntary layer in the will mix, reads as
+ standing, and its failure is the collapse People Playground shows.
+6. `bds-mvp-clips`: which animations exist. Options: poses only (idle, guard, cower, protect-head, brace, reach,
+ aim); poses plus a few looping clips (idle sway, struggle, writhe); generated clips from Vili. Recommend poses
+ plus three loops, authored as pose keys (rung 4's `PoseBehaviour` generalised); Vili clips when its retarget to
+ this ragdoll exists.
+7. `bds-will-visible`: what failing will looks like. Options: tremor and sag (strain shake exists,
+ `PoseBehaviour.cs:89`), slower and shorter reaches, aim wander; plus an on-screen will bar; plus vocal or
+ facial cues (presentation). Recommend tremor, sag, slower reach and aim wander from the will mix, plus a
+ debug bar; voice later.
+
+## Target r4 (landed: `5d0fec8` and r5 `58c2201`; `docs/lodur-target.md` is now the text)
+
+Keep r3's invariants and add:
+
+- `one-severance-owner`: A part is damaged, disabled or severed only by Lodur's physiology; Ymir reports
+ contacts and joint stress and removes a joint only on command; no physics threshold removes anything by itself.
+- `will-is-the-budget`: Every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
+ available will (resolve times attention, capped by consciousness); reflexes act against it with their own
+ gains; nothing writes targets outside that mix.
+- `sandbox-is-content`: An arena is a level built from the commands the player has; no engine path exists only
+ for an arena; levels are CultCache.
+
+Replace r3's first not-in-scope line with: "Adapting to body topology outside the authored part tree (new
+limbs, re-rooted trees, morphology-agnostic learned control). Losing a subtree of the authored tree is in
+scope as a closed set of impairment states per limb slot, mirror-symmetric." Add to not in scope: "Weapons,
+ballistics, gore and wound presentation (Bad Day Simulator content)."
+
+This resolves the tension the MVP ruling names: severing changes topology only inside the authored tree, so
+the behaviour set compensates through a closed set of states (intact, impaired, disabled, severed per limb
+slot), as the r3 doc's open item proposed and `euphoria-stimulus-and-impairment` asks (hopping after losing a
+leg is a behaviour keyed on the state, not a re-learned controller).
+
+## Rationale
+
+- **Facts, not callbacks.** Ymir fills fixed-capacity fact buffers per step and the caller reads spans, like
+ lanes; no managed callback crosses the ABI, overflow is counted, never silent (bounded-tick).
+- **Tombstones, not compaction.** Lodur and the client cache lane indices (`Ragdoll._bodyLane`,
+ `Ragdoll.cs:16`). Swap-remove, as the planar session does (`ymir_box3d.c:1435-1436`), would move a
+ live body's lane under them. A removed lane keeps its last state and a `Removed` kind; reuse waits for a
+ completed step so end facts still name the old id.
+- **Grab is felt.** A motor joint is not a contact, so a grab produces no contact fact. The binding treats every
+ joint on a ragdoll body that the ragdoll does not own (grab, strap, grip, a player's weld) as a touch at its
+ anchor with the joint's constraint force: one rule for grabs, restraints and held tools.
+- **Poke is a body.** The poke and cut tools are small kinematic bodies on the grab anchor, so their touch
+ arrives through contacts and their damage through the material table, like a falling blade. The impulse
+ command stays for explosions, recoil and bullets.
+- **Physiology is drive state.** RimWorld's model (part tree, HP, pain sum, blood fraction, consciousness,
+ capacities; `rw-*` notes) is per-tick state with no per-wound behaviour lookup, which drive-is-state asks.
+ Numbers start from RimWorld and ATLS bands (`df-and-atls`) as content defaults.
+- **Grip and aim follow PuppetMaster's prop and IK split.** A held prop becomes part of the puppet through its
+ own joint, pick-up and drop are one assignment, and props drop when the puppet loses balance
+ (`mvp-prior-art-2.puppetmaster-prop-attachment`); aiming IK runs before the physics read so the muscles chase
+ the aimed pose and physics, pain and will degrade it (`mvp-prior-art-2.ik-after-physics-aiming`). Lodur's
+ grip is that model with the drop rule moved into drive state (pain in the hand, unconsciousness, overload
+ of the weld's threshold). Aim error is not a parameter: it is the gap between the aim IK goal and where the
+ will-weighted, tremoring, startled arm lands. Arma's suppression and fatigue sway
+ (`mvp-prior-art-2.suppression-aim-degradation`, `aim-physiology-numbers`) are the games that fake that gap
+ with a sway multiplier; here it emerges, which is what the ruling asks for.
+- **Building is props plus constraints plus signals.** Garry's Mod composes from props and a fixed set of
+ constraint tools and saves entities then constraints (`mvp-prior-art-2.gmod-constraint-duplicator`);
+ People Playground, Besiege and Algodoo add activation signals, sensors, timers and logic
+ (`mvp-prior-art-2.algodoo-ppg-besiege-signals`). BDS levels are that triple as CultCache: objects (with
+ behaviours as content), joints (Ymir kinds, `ymir-joint-kinds`), wires; load creates objects before
+ joints, as the duplicator's paste does. No source reached says how those games' shipped levels were built;
+ the ruling's "arenas with the player's tools" is ours.
+- **Startle moves up.** The new ruling makes distraction a will drain, so `lodur:follow_up:startle-reflex`
+ becomes cut `lodur-startle-attention`. It did not land right after rung 4: `lodur-will-mix` landed first (it needs only the `Will` slots, which read 1), so startle now depends on it.
+
+## Cut order
+
+Agent pace: S is one Hands session plus Soul, about 1-2 h; M about 3-4 h; L about 6 h. Ymir runs in parallel
+with the Lodur rungs (different repo); Lodur cuts serialise on `Actor.cs`; BDS waits on the client pass.
+
+| # | Cut | Repo | One line | Depends on | Size |
+|---|---|---|---|---|---|
+| 1 | `ymir-contact-facts` | Ymir | contact/hit facts, contact-force lane, material ids | ymir-shape-lanes (parallel client pass, ABI 3) | M | landed |
+| 1' | `ymir-grab-anchor` | Ymir | kinematic anchor, motor joint, impulse, raycast | ymir-shape-lanes (sibling of 1) | S-M | landed |
+| 2 | `ymir-break-and-remove` | Ymir | thresholds, overload facts, remove body/joint, tombstones, removal facts | 1 | M | open |
+| - | `rung3-sensory-load` Soul, `rung4-goal-flip`, `rung3-office-stress`, `rung4-office-flip` | Lodur/BDS | landed (rung 3 `a048827`, rung 4 the Brain `c26c15c`; the office arc and the chamber release in BDS) | as admitted | - |
+| - | `client-ready-sim`, `godot-client-v1` | BDS/Godot | landed (`BodyPainBoxSession`; the Godot client at `client/`) | its own | - |
+| 3 | `lodur-will-mix` | Lodur | voluntary layers weighted by will; PoseBehaviour demoted | rung4-goal-flip | M, landed (`afb8df3`, with the recurring break `74883f8`; goal entry effects `c93bdb7`) |
+| 4 | `lodur-physiology` | Lodur | part tree content, HP, wounds, blood, pain, shock, consciousness, capacities, death | 3 (landed) | L (split core/binding if over budget) |
+| 5 | `lodur-touch` | Lodur | per-part touch from contact facts, external-joint pull; insults from material table | 1, 2, 4 | M |
+| 6 | `lodur-startle-attention` | Lodur | startle reflex on onsets; attention scales will | 3 (it writes the Attention slot the will mix already reads) | M, open |
+| 7 | `lodur-ik-goals` | Lodur | IK goals in body interface; two-bone arm/leg, look, aim | 3 | M |
+| 8 | `lodur-reflex-set` | Lodur | flinch-from-touch, brace | 3, 5 | M |
+| 9 | `lodur-sever-impair` | Lodur | severing via binding, impairment states | 2, 4, 5; Q `bds-dismember-trigger`, `bds-reattach` | M |
+| 10 | `lodur-clips` | Lodur | pose-key clips as a voluntary layer | 3; Q `bds-mvp-clips` | S |
+| 11 | `lodur-assist-pin` | Lodur | upright assist as a voluntary layer | 3; Q `bds-upright` | S |
+| 12 | `lodur-grip` | Lodur | grip weld, drop rules, tool frame for aim | 2, 7 | M |
+| 13 | `bds-sandbox-session` | BDS | session + command queue, grab/poke/cut | client-ready-sim, 1' | M |
+| 14 | `bds-damage-content` + `bds-gore-content` | BDS | materials to insults; gore data | 5, 9; Q `bds-gore-look`, `bds-death` | M |
+| 15 | `godot-runtime-bodies`, `godot-interaction`, `godot-blood` | Godot | lifecycle, input, blood | godot-client-v1, 2, 13, 14 | M each |
+| 16 | `ymir-joint-kinds`, `bds-level-content`, `bds-contraption-signals`, `godot-build-tools` | mixed | building and arenas | 13 | M-L each |
+| 17 | `bds-guns` | BDS | gun content aimed by IK | 7, 12, 1' | M |
+
+Rough total: about 26 cuts, roughly 70-90 agent-hours; with Ymir and BDS/Godot running beside the Lodur chain,
+the critical path is the Lodur chain 3 → 4 → 5 → 9 (and 3 → 7 → 12; startle, 6, is off it), about 30 agent-hours after rung 4 lands.
+The playable MVP (grab, poke, cut, bleed, sever, reflexes, will) is cuts 1-9, 13-15.
+
+Admitted 2026-11-20 (pass `bds-mvp-map`): specs `lodur:cut_spec:cut-ymir-contact-facts.r2`,
+`cut-ymir-grab-anchor.r2` (siblings, after the parallel pass's `ymir-shape-lanes`), `cut-ymir-break-and-remove.r2` (after contact facts); every
+later cut above is a `lodur:follow_up:` of the same name (22), owner nibu; questions
+`lodur:question:bds-*` (7); ideas `lodur:idea:bds-mvp-map.*` (22, seven rejected and resolved Recorded).
+
+## Wound blood slice (pass `bds-slice-map`, 2026-11-27; mains Lodur `2359142`, Ymir `1d27114`, BDS `f26ec57`)
+
+Probe: `/nibu-imagination/probe/Program.cs` (Release, net10 roll-forward, paired interleaved medians of 9 against a no-fluid control).
+
+- **B, bleed.** One Knife cut (Skin, Fat, Muscle at 60) bleeds 78.0 mL/s at peak and kills by BloodLoss at 38.1 s; 3 cuts 234 mL/s and 11.2 s; 6 cuts 468 mL/s and 5.5 s. Every bleed-out spills 2.50 L real, 25.0 L visible at gain 10, 1600 drops of 15.625 mL.
+- **A, cost on the seated world.** Drops at three body points, settled when supported and under 0.05 m/s for 30 ticks: +0.076 ms a tick at 50 drops/s (live 42), +0.250 at 150/s (live 126), +0.562 at 300/s (live 256), at caps 512 to 2048 alike; wets 37-39, overflow 0. Cap-bound (only the cap settles): 512 live +1.49 ms, 1024 +3.9, 2048 +7.2. Settling carries the gain; the cap stays 512.
+- **A, lane reuse.** A lane freed by Settle is free only after the next Step: settling only when emission finds the cap full refuses 795 of about 2,600 drops at cap 512. Settle after the Step, down to LiveCap - MaxDropsPerTick.
+- **I, identity.** A SeatedPuppet world with particle capacities and no fluid steps byte-identically over 1200 driven ticks (hash `B3ACA960FE3B41E7` both); Ragdoll.Build places 2 airway sensors.
+
+Order: `cut-bds-wound-blood.r1`, then `cut-bds-client-office.r1`, then follow-up `bds-drown-own-blood-slice` (its Lodur part, `lodur-airway-internal-bleed`, can run beside the client cut). Idea `bds-slice-map.gain-at-circulation-boundary` holds the aspirate-cough amplification hazard for that slice.
+
+## Airway internal bleed (pass `internal-bleed-map`, 2026-11-27; mains Lodur `cb20b37`, Ymir `c635c17`, BDS `407319b`)
+
+Probe: `/imag-airway/probe` (a scratch copy of Lodur.Core at `cb20b37` with spec `cut-lodur-airway-internal-bleed.r1`'s rule; `Program.cs`, Release, net10).
+
+- **P1, conservation.** Over every run (knife on Skin, Fat, Muscle plus a Larynx core of share 1; gains 1 and 10; vascularity 0.2 and 1), blood lost = skin bleed + airway bleed exactly (2500.2 = 2166.9 + 333.4 mL), and Coughed + Drained + AirwayLiquid = gain x airway bleed exactly (3183.6 + 150.0 = 3333.6 mL at gain 10), the overflow spill included.
+- **P2, timing.** Larynx-only Cut 60 (vascularity 1): airway full (occlusion 0.99) at 0.3 s at gain 10, 31.1 s at gain 1; dies of BloodLoss at 53.7 s either way. Larynx-only Cut 20: full at 129 s (gain 10) and 147 s (gain 1), unconscious at 127.7 s both, dead 275-290 s by Consciousness: blood-loss stages, not hypoxia, take him first. With the knife's skin, fat and muscle also cut he is unconscious at 11-18 s and dead at 20-32 s, before the ruled 75 s asphyxia: a cut throat cannot drown him with today's knife (question `bds-throat-cut-bleed-band`).
+- **P3, cost.** Physiology.Step on the humanoid with two knife wounds: 2.563 us base, 2.687 us with the rule and Larynx and Trachea added (paired interleaved medians of 7, +0.17 us).
+- **Source reads.** Breathing in takes nothing from the world: `Ragdoll.ReadAirway` and `SeatedBody.ReadAirway` only read sensor lanes (idea `internal-bleed-map.drawn-liquid-stays-in-world`). Ymir creates and removes sensors at runtime (`Box3DSoaWorld.CreateSensors`, `Remove`) and destroys particles (`DestroyParticles`), but has no partial take from a wet patch. BDS's knife names Skin, Fat, Muscle and no airway tissue; the Humanoid has no larynx or trachea at `cb20b37`.
+
+Gain owner: the caller (BDS `BloodParameters.Gain`), passed to `Physiology` at construction like `slowScale`; Lodur content holds none. The airway is in world units, so bled blood enters at the gain and leaves at 1x.
+
+Order: `cut-lodur-airway-internal-bleed.r1` (beside `cut-bds-client-office.r1`), then follow-up `lodur-wound-reach` (Lodur), then `bds-throat-cut` (BDS, after client-office and question `bds-throat-cut-bleed-band`), then `bds-airway-expulsion`, then `bds-fella-air-hunger` (question `bds-air-hunger-struggle-look`). `lodur-airway-wound-openings` is off the slice's path.
diff --git a/docs/connect-rungs-map.md b/docs/connect-rungs-map.md
new file mode 100644
index 0000000..16f4e55
--- /dev/null
+++ b/docs/connect-rungs-map.md
@@ -0,0 +1,280 @@
+# Lodur: connect the rungs (map)
+
+Campaign `lodur` (Nibu's mind). Imagination pass `connect-rungs-map`, session `nibu-self-2026-11-17`,
+2026-11-19. Operator order: "A, connect the rungs" (`lodur:ruling:lodur-body-on-ymir`). This file is the prose
+map: body facts, the model page, rationale, the proposed target r3 text (committed as docs/lodur-target.md), and the
+Ymir cut draft. Committed here from the Imagination scratchpad so it is durable; the bases below are the pins it was probed at.
+
+## Bases
+
+| Repo | Base | Note |
+|---|---|---|
+| GameCult/Lodur | `18c4ffd0d598c34fc00f96c7f5d23aafdc003706` | main = origin/main |
+| GameCult/BadDaySimulator | `9f597647a608a6c6e44473cc9f1399983de14616` | main = origin/main |
+| GameCult/Ymir | `7ba31c30fc3329b84cc638646310259c663c1051` | origin/main. **`F:\Projects\Ymir` local `main` is 11 behind** (its last fetch was 2026-10-29; it has no SoA world at all). I ran `git fetch origin` only (refs, no checkout). Lodur's sibling default `..\Ymir` therefore builds against a tree without `Box3DSoaWorld` until that checkout is fast-forwarded; that is Self's call, not done. |
+
+## Body facts (probes)
+
+All probes in detached worktrees `F:\aeth-wt\connect\{Ymir,Lodur,BadDaySimulator}` at the bases above
+(Ymir submodule `extern/box3d` at pin `8441b4a`), Windows 11 workstation, 2026-11-19. Worktrees removed after.
+
+1. **Windows build of Ymir native works with MinGW, with one defect.** No MSVC/VS on the workstation
+ (`vswhere` finds nothing). `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc dotnet test tests/Lodur.Tests`
+ (gcc and ninja from StrawberryPerl, CMake 3.x in Program Files) configures "Box3D on MinGW", builds 53
+ objects, and links `bin\Debug\libymir_box3d.dll`. The build then fails MSB3030: `Ymir.Box3D.csproj`
+ expects `bin\$(Configuration)\ymir_box3d.dll` (MSVC naming; MinGW adds the `lib` prefix). After copying the
+ DLL to the unprefixed name: **Lodur.Tests 21/21 pass on Windows** (6 s), including same-seed-same-hash
+ within one process. The CultLib pin guard in Ymir's `Directory.Build.targets` did not fire for this graph.
+ Without `CMAKE_GENERATOR` set: not tried.
+2. **What Ymir's SoA world exposes for a hand in a box** (`src/Ymir.Box3D/Box3DSoaWorld.cs`, origin/main;
+ `docs/soa-world.md` "Not done"): body lanes (stable id, kind, parent, limb, position, rotation quaternion,
+ linear and angular velocity), write lanes (force, torque), joint lanes. **No contact facts, no sensor shapes,
+ no overlap or ray queries, no body removal.** Box3D compiles `sensor.c` but Ymir's SoA ABI does not
+ surface sensors. So the hand-in-box test is geometry over the body lanes: the hand point is the
+ palm body's centre (the ragdoll has palm, thumb and fingers bodies per arm).
+ The box is a game stimulus volume (layer 1 "named game stimuli"), not a physics body.
+3. **The SoA world is internal.** `Box3DSoaWorld`, `Box3DSoaView` and the kind enums are `internal`, visible to
+ `Ymir.Core`, `Ymir.Box3D.Soa.Tests`, `Lodur.Body.Ymir` and `Lodur.Tests` by `InternalsVisibleTo`
+ (`src/Ymir.Box3D/Properties/AssemblyInfo.cs:3-6`, commit 0227636 "until Ymir.Core has a public surface").
+ `Ragdoll` (Lodur.Body.Ymir) builds a `BodyPlan` into a caller-owned `Box3DSoaWorld`. **Bad Day Simulator cannot name the
+ world today**, so it cannot own its one physics world without a Ymir change.
+4. **A pelvis weld to a static body holds the ragdoll upright for 20 s.** `AddJoint(Weld, staticBox, pelvis)`
+ is accepted (native refuses only out-of-range or equal indices). Full-strength ragdoll, pelvis welded to a
+ 5 cm static box behind it: head 1.739 m and pelvis 1.110 m at every 2 s checkpoint to 20 s. Unwelded it
+ topples at about 2 s (first-slice.md), and the pain box breaks at about 15 s.
+5. **Arm reach into a box, at strength 1.** Right shoulder target `FromAxisAngle(1,0,0,-1.0)` (joint frame),
+ elbow `FromAxisAngle(0,0,1,-0.6)`: hand tip settles at about (-0.21, 1.19, 0.46). Over 2-4 s of hold its
+ range is x [-0.233, -0.191], y [1.175, 1.220], z [0.448, 0.469] (natural wobble, no tremor). Shoulder
+ `-1.2`, elbow 0.3 gives (-0.21, 1.20, 0.48). Positive shoulder angles swing the arm back (+1.0 puts the hand
+ at z -0.25). Strength 0 leaves it hanging at y 0.96.
+6. **Strength above 1 is not safe on the arm.** Strength 3 with the same targets sagged the hand to y 1.03 and
+ let it drift in x to -0.35 (explicit PD past its stable damping). Keep strength in [0, 1].
+7. **Withdrawal is fast.** Switching the arm target to shoulder +0.3, elbow 2.0 (strength 1) takes the hand out
+ of a 0.12 m half-extent box centred at (-0.21, 1.19, 0.46) in 5-6 ticks at 120 Hz (about 50 ms).
+ Shoulder -0.3 / elbow 1.5 takes 18 ticks.
+8. **Visible strain needs low frequency.** A 9 Hz shoulder-target tremor of 0.08 rad leaves the hold range
+ unchanged to the millimetre (the PD at swing gains 20/1 filters it). 3 Hz at 0.15 rad widens y to
+ [1.162, 1.230]; 4 Hz at 0.3 rad to [1.161, 1.233] and z to [0.437, 0.477]. So strain shows as a shake of a
+ few Hz, not physiological tremor frequency.
+9. **Pain-box baseline at the BDS base** (Windows, git-bash, `dotnet run --project src/BadDay.Cli -- run
+ --seed N > file`; Summary uses `WriteLine`, so CRLF on Windows and the hashes are platform-bound):
+ 13/13 tests pass; seed 1 "will broke at 14730 ms, hand out at 14830 ms, 16 flinches". sha256 run-1
+ `973603f9…dd4cc`, run-2 `cf1a6060…a4af95`, run-3 `bafc5967…20e1`. PainSweep table (scratch csproj compiling
+ `tools/PainSweep/Program.cs` against BadDay.Core; stdout) sha256 `13424cd1…7bf`; cells e.g. 0.80 x 0.95 =
+ 14.9 s, 0.20 x 0.50 = 95.4(8/9), every suppression-0 cell "never". Hands recaptures at base with one method.
+10. **Where the model's arithmetic sits** (`src/BadDay.Core/PainBoxSimulation.cs` at base): traits 22-23; box
+ stimulus 59-61; nociceptor threshold, sensitisation, conduction ring 64-69; pain 72-73; reflex suppression,
+ leak, flinch, strain 77-86; resolve drain, recovery, break 89-101; sample 104; withdrawal 106-112. Order
+ inside a tick matters: suppression reads last tick's resolve (gain set ahead of time); the Flinch row is
+ logged after pain but before strain and resolve update (lines 83, 85, 94).
+
+## Body plan authority (cut `lodur:cut_spec:cut-body-plan-data.r2`, `cut-bds-body-plan-labels.r1`)
+
+The body's structure is data in one place; the hard-coded `HumanoidRagdoll`, `Limb`, `Muscle` and `Region` enums are deleted.
+
+- **Owner:** `BodyPlan` (`src/Lodur.Core/BodyPlan.cs`), built by a plan factory (`BodyPlans.Humanoid()`, a quadruped in `QuadrupedPlanTests`). Immutable after construction.
+- **Inputs:** `PartDef` (label, side, shape, size, creation pose, density, friction), `JointDef` (label, side, kind, parent and child part ordinals, anchor, axis, limits, `MuscleGains`), `SensePointDef` (label, side, part, offset).
+- **The tree is the joint list.** No part carries a parent field. `ParentOf(part)` is derived at construction from the one joint that has the part as child; part 0 is the root. A part is the child of exactly one joint and a parent precedes its child, so the tree is acyclic and creation order is part order.
+- **Names are `(label, side)`**, unique per list (parts, joints, sense points), resolved by `PartIndex`, `JointIndex`, `SenseIndex`; an unknown name throws. Ordinals are plan order and are not a contract between repos; labels are.
+- **Validate** (in the constructor, refuses): rule 1 unique non-empty labels; 2 joint ends are parts and parent precedes child; 3 a root exists and every other part has exactly one attaching joint; 4 sense points sit on parts; 5 finite numbers, positive sizes and density, and no field the shape cannot carry (sphere rotation, box rolling resistance, unused size components), limits ordered, cone non-negative.
+- **Derived state:** `ParentOf`, the three label indexes, and in `Ragdoll` the part-to-lane and joint-to-lane maps (`BodyLane`, `JointLane`; the parent lane comes from `ParentOf`, the limb lane is the part ordinal). Nothing derived is persisted.
+- **Output:** `Ragdoll.Build(world, plan, origin, firstStableId)` adds bodies in part order, then joints in joint order, to the caller's world; `Drive` takes one strength and one target per plan joint; `ReadSensePoints` writes one point per plan sense point. The binding holds no body numbers.
+- **Forbidden writers:** the binding, perception, reflex and BDS never add, reorder or alter parts, joints or labels after construction; no code outside `BodyPlan` derives a part's parent; no consumer hard-codes a part or joint ordinal (resolve by label at build).
+- **Consumers:** `Ragdoll` (Lodur.Body.Ymir); BDS `SeatedPuppet.Plan` is the one plan instance, passed to `Ragdoll.Build` and therefore the same object as `ragdoll.Plan`; `OfficeBody` and `BodyPainBox` resolve joint, part and sense-point labels against it once at build and index arrays by the resulting ordinals thereafter.
+- **Verification layer:** `tests/Lodur.Core.Tests/BodyPlanTests.cs` (each Validate rule, label resolution, derived tree), `tests/Lodur.Tests/QuadrupedPlanTests.cs` (a second morphology builds through the same binding), `RagdollTests.cs` (stand, fall, per-joint strength, torque equal and opposite), BDS tests against the label-resolved humanoid.
+
+## The model page (step 0b)
+
+No persistent content is introduced by these cuts: every parameter stays a code default or a CLI argument,
+so `content-is-cultcache` is not engaged yet (follow-up `lodur:follow_up:drive-profiles-as-content`).
+
+| Kind | What names it | Lifecycle | Who decides |
+|---|---|---|---|
+| Nerve, reflex and drive parameters (`NerveParameters`, `WithdrawalParameters`, `DriveParameters`) | Nothing persistent: C# records with defaults in Lodur.Core; a per-actor instance is a value | Built once when the consumer creates an actor (per-seed traits folded in as `Gain`, `DrainTrait`), immutable for the actor's life | Lodur owns the schema and defaults; the consumer (BDS scenario) owns per-actor values and the trait draw |
+| Actor (nervous state: afferent rings, drive state, goal) | The consumer's handle; no id inside Lodur | Created with the scenario, ticked once per physics step, never persisted, dies with the scenario | Lodur.Core alone writes it; nothing else writes drive state |
+| Puppet definition (the 19-body humanoid: shapes, joints, gains, sense points) | `BodyPlan` data in Lodur.Core (`BodyPlans.Humanoid()`), built by `Ragdoll` in Lodur.Body.Ymir; world stable ids `firstStableId + part ordinal` passed by the caller | Built into the caller's world once; no removal (Ymir has none) | `BodyPlan` owns geometry, joints, gains and labels, `Ragdoll` builds them; BDS owns placement and stable-id allocation (see "Body plan authority") |
+| Stimulus source (the pain box) | BDS object, scenario-local; not a world body | Placed by the scenario; intensity written every tick from its schedule (ramp, noise, disable time) | BDS writes intensity and on/off; Lodur perception only reads it and decides containment and transduction |
+| Restraint (stool weld) | BDS scene object: one static box + one weld joint in the world | Created with the scenario | BDS (a game object acting on the body through the world, like a grab; not a layer above Lodur) |
+| Scenario run | (seed, parameters) | One run, headless or on the body | BDS; the timeline is output, not content |
+
+## Rationale
+
+- **Wrong owner, now.** The pain box is perception, reflex and drive flattened into the consumer. Lodur.Core
+ holds only the PD law. The cut moves layers 1-3 and a layer-4 stand-in into Lodur.Core and leaves BDS with
+ the things a game owns: the box schedule, the seed and trait draw, the restraint, the world, the recorder.
+- **Move first, retune never in the same cut.** The layers keep the pain box's double arithmetic and the order
+ of operations, so seed 1 still breaks at 14730 ms and the sweep table is byte-identical. The only planned
+ difference: every timeline row becomes end-of-tick state, which changes the strain and resolve columns of
+ Flinch rows (they were logged mid-tick). Any retune (latencies, `[M]` figures) is a later, separately
+ falsifiable cut.
+- **The game owns the world** (`one-physics-world`, `lodur-body-on-ymir`): BDS creates the Ymir world and Lodur
+ adds its bodies to it. That needs Ymir's SoA world to be nameable outside Ymir, hence the Ymir cut. A Lodur
+ facade that creates and hides the world would make Lodur the world's owner, which is the split this invariant
+ forbids.
+- **Headless stays engine-free.** BadDay.Core references only Lodur.Core, so the sweep and the headless tests
+ build with `dotnet` alone; the body scenario lives in a new BadDay.Ymir project. One more csproj buys a
+ measure that does not need cmake.
+- **Posture.** The PD ragdoll cannot balance for 15 s; the puppet sits strapped at the pelvis (body fact 4).
+ The learned tracker (v2) is what lets it stand later.
+- **Visible strain** is a 3-4 Hz shake along the withdraw direction, scaled by strain (body fact 8), plus the
+ flinch blend. Sweat is a render concern; there is no renderer.
+
+## Cut order
+
+1. `ymir-soa-public` (GameCult/Ymir): **not admitted**, because Ymir is not in the lodur repo set (target r2:
+ Lodur, BadDaySimulator). Recommended: target r3 adds GameCult/Ymir; then admit the draft below. Tracked as
+ `lodur:follow_up:ymir-soa-public-surface`. Ymir is Nibu's stewardship (`nibu:stewardship:gamecult_-ymir.n1`).
+2. `nervous-layers` (GameCult/Lodur), `lodur:cut_spec:cut-nervous-layers.r1`. Its Core commits need nothing
+ from Ymir; its body-binding commit needs cut 1 on Ymir main.
+3. `pain-box-on-lodur` (GameCult/BadDaySimulator), `lodur:cut_spec:cut-pain-box-on-lodur.r1`, depends on 2;
+ blocked on `lodur:question:bds-consumes-lodur`.
+
+### Draft cut spec: ymir-soa-public (admit after target r3 names GameCult/Ymir)
+
+- repo GameCult/Ymir, branch `nibu/soa-public`, base `7ba31c30fc3329b84cc638646310259c663c1051`.
+- deletes: `src/Ymir.Box3D/Properties/AssemblyInfo.cs:5-6` (2 lines, the Lodur friend grants).
+- file_changes: `src/Ymir.Box3D/Box3DSoaWorld.cs:5` `Box3DSoaKind`, `:13` `Box3DSoaJointKind`, `:151`
+ `Box3DSoaView`, `:223` `Box3DSoaWorld` become `public`; the native desc/view structs and
+ `Box3DSoaNative` stay internal; the `Box3DSoaView` constructor stays internal. `native/Ymir.Box3D/CMakeLists.txt`
+ `:22` `set_target_properties(ymir_box3d ...)` gains `PREFIX ""` so MinGW emits `ymir_box3d.dll` (body fact 1).
+ `docs/soa-world.md` "Managed (... internal)" and "Not done ... public typed surface" lines: say the SoA world
+ is public in Ymir.Box3D. Ymir.Core keeps its own surface.
+- verification: `dotnet test tests/Ymir.Box3D.Soa.Tests` green; Lodur at 18c4ffd with `YMIR_ROOT` at the head
+ builds and its 21 tests pass with the friend grants gone; on Windows,
+ `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc` builds with no DLL rename. Negative: `InternalsVisibleTo\("Lodur`
+ in `src/` finds nothing.
+- estimate: about +10 / -4 lines, no targets.
+
+## Proposed target r3 text for `Lodur/docs/lodur-target.md`
+
+Hands commits this in `nervous-layers`; Self admits the typed `lodur:target:r3` (invariants as below, repos
+GameCult/Lodur, GameCult/BadDaySimulator, GameCult/Ymir; doc at that commit) with the superseding resolution
+of r2.
+
+```markdown
+# Lodur: target
+
+Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
+workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
+ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
+ruling disagree, the ruling wins and this file is stale.
+
+## What it is for
+
+A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
+back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
+objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
+
+The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
+characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
+follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
+nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
+latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
+`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
+`15d9a4e`).
+
+Named after the god in Voluspa who gives the first humans blood, warmth and good colour
+(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
+
+## Layers
+
+Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
+(`netstandard2.1`, no references); layer 5 is a body binding.
+
+1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`). Contacts, impulses, temperature,
+ proximity and named game stimuli become typed signals on body regions. Input: one point per body region
+ (from the body binding, read-only) and the game's stimulus sources. Today one channel (noxious) and one
+ source kind: a box volume with an intensity the game writes each tick. Output per region: the stimulus, and
+ the afferent signal after threshold, sensitisation and conduction delay. A poke that barely moves the body
+ is still a stimulus.
+2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
+ (withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
+ Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
+ (the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
+ Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
+ flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
+ (figures `[M]` in the research doc; verify before they become constants).
+3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
+ afferent input, strain from suppressed reflexes, resolve drained by both and scaled by the objective's pull;
+ later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
+ breaks the will, which releases every suppression. Static per-character values are this state with its
+ dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
+4. **Behaviour.** The drive selects and weights behaviours (hold against a reflex, withdraw, writhe, crawl to
+ the objective, pass out, get up) that emit targets and per-muscle strength into caller-owned arrays, and
+ nothing else. Today one stand-in: hold a pose against the withdrawal reflex, blended toward a withdraw pose
+ by the reflex leak, shaking with strain, and withdrawing once the will breaks.
+5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
+ PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
+ Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
+ the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
+ learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
+ policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
+
+`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
+caller-owned outputs, and reports its events (flinch, will broke, goal changed) as flags.
+
+## Invariants
+
+- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
+ core is a defect, not a convenience. The core's tests build without Ymir.
+- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
+ never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
+ no layer above.
+- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
+ world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
+ through that world.
+- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
+ never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
+ the pull of the objective) sets each reflex's gain, so a resolved character can hold its hand in the box.
+ Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
+ until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
+ (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
+- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
+ per-wound lookup.
+- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
+ inputs give the same outputs. A middleware that hitches is unusable in a game.
+- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
+ in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
+ Parameters that are only code defaults are not yet content.
+
+## First consumer
+
+Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
+not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
+behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
+`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
+separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
+the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
+`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
+
+## Not in scope
+
+- Adapting to arbitrary changes of body topology. The operator called it too ambitious; impairment is handled
+ through the drive and the behaviour set.
+- A Rust port of the core.
+- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
+- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
+ section 10.1).
+- Hand-tuned balance controllers of the SIMBICON family as the upright path.
+
+## Open
+
+- **Impairment states.** Self's proposal, not ruled: a closed set of named body states (intact, missing a leg,
+ missing an arm, both legs), with mirror symmetry; crawling as the first locomotion after any leg loss.
+- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
+- **The pain measure** (`lodur:question:pain-sweep-measure`).
+- **Ymir gaps Lodur needs next**: contact facts for pain from impacts, body removal, joint springs for stiff
+ ankles (`nibu-body:follow_up:ymir-soa-lodur-needs`).
+- **Renderer and rig** for Bad Day Simulator: nothing draws the puppet yet.
+- **Training host for v2.** Raven trains only when the household's GPU allows
+ (`motion-pipeline:ruling:raven-gpu-defers-to-household`).
+- **Trademark search** on "Bad Day Simulator" before anything public is announced.
+```
+
+Changes against r2: header names Nibu's mind; layer 5 binds to Ymir (Unity ArticulationBody wording gone, it
+was replaced by `lodur-body-on-ymir`); layers carry their first type names and the tick order; `one-physics-world`
+restated with the game as the world's owner; `core-engine-free` adds "core tests build without Ymir";
+`bounded-tick` adds same-inputs-same-outputs (it was implicit in every test); `content-is-cultcache` says code
+defaults are not content; the Rust-port line drops "until a first consumer outside Unity exists" (Unity is no
+longer the first host); Open drops the Unity version and UPM items (moot under Ymir) and the rig licence item
+becomes renderer and rig.
diff --git a/docs/first-slice.md b/docs/first-slice.md
index 361e474..a06692f 100644
--- a/docs/first-slice.md
+++ b/docs/first-slice.md
@@ -7,9 +7,9 @@ Ymir's structure-of-arrays world. Nothing above layer 5 exists yet.
- `Lodur.Core` (`netstandard2.1`, no references): `Quat`, `MuscleGains`, `PdMuscle.Torque`. A PD law on one
joint: the child's rotation relative to the parent and their relative angular velocity in, a torque out.
- Strength is a multiplier on every gain; zero is limp and returns exactly zero. Swing (joint frame x, y) and
+ Strength is a multiplier on every gain; zero is limp and returns exactly zero, except that a muscle with `Passive` keeps that fraction of its damping (tissue viscosity). Swing (joint frame x, y) and
twist (z) have separate gains.
-- `Lodur.Body.Ymir` (`net8.0`, references Ymir.Box3D): `HumanoidRagdoll` builds 13 bodies and 12 joints in a
+- `Lodur.Body.Ymir` (`net8.0`, references Ymir.Box3D): `Ragdoll` builds a `BodyPlan` (here `BodyPlans.Humanoid`: 19 bodies, palm, thumb and fingers per arm, and 18 joints) in a
caller-owned `Box3DSoaWorld`: capsule limbs, box pelvis, torso and feet, a sphere head, ball joints at
spine, neck, shoulders and hips, hinges at elbows, knees and ankles. `Drive(strengths, targets)` writes
each muscle's torque onto the world's torque lanes (equal and opposite on child and parent). The strength
@@ -33,7 +33,7 @@ Ymir's structure-of-arrays world. Nothing above layer 5 exists yet.
## Not measured, or limits found
-- Cross-platform bit-identity: unclaimed. Windows build and Unity consumption: unrun. One machine, Debug
+- Cross-platform bit-identity: unclaimed. Windows (2026-11-19, no MSVC): builds and passes with MinGW gcc, `CMAKE_GENERATOR="Ninja Multi-Config" CC=gcc`; Ymir 0b0321a emits `ymir_box3d.dll` under MinGW, so no rename is needed, and its world create/destroy lock makes test classes safe to run in parallel (before it, two live worlds crashed the host). Unity consumption: unrun. One machine, Debug
native build only; no Release run, no run in a second process.
- Explicit PD through torque lanes limits stiffness and damping: damping times the step must stay under the
inertia it acts on. Hips and spine went unstable at damping 15 and 20 and are set to 3 and 4; the gains
diff --git a/docs/flesh-map.md b/docs/flesh-map.md
new file mode 100644
index 0000000..bc447e6
--- /dev/null
+++ b/docs/flesh-map.md
@@ -0,0 +1,136 @@
+# Flesh on the bones: map
+
+Pass `flesh-bones-map` (Imagination, 2026-11-25). Pinned to Lodur fbc3501, Ymir d82da6d, BadDaySimulator 3d6e735.
+Rests on rulings bds-particle-tissues, bds-flesh-at-rest, bds-body-skeleton-particle-flesh-rough, bds-skeleton-19-for-mvp,
+bds-cut-location, bds-gut-length, bds-gut-rope-tension, bend-limit-stiffness, ymir-sheet-sieve-at-budget-substeps,
+particles-are-constraint-graphs, and on the ideas of pass bds-body-flesh-map (2026-11-23), which this map measures and corrects.
+
+## Target shape
+
+Fella is 19 Ymir rigid bones (the plan's parts). Each part's flesh is one skin sheet and, on the six muscled parts, one muscle
+sheet: Ymir particles, distances and bends, each particle attached to its own bone at its rest point. Sheets of neighbouring
+parts are stitched across each joint by distances. At rest a part's flesh is dormant: in no Ymir loop at all, drawn from the
+bone pose. Lodur's binding wakes one part when that part is disturbed and pins it again when it settles. A wound removes the
+sheet edges it crosses; a sever at a joint removes that joint's stitches with the joint. Fat and bone are thicknesses in the
+part's tissue stack, not particles. Internal tubes and organs stay meshes until released (follow-ups lodur-organ-release-rope,
+lodur-exposed-tube-chains).
+
+### Tissue layers per part (plan data)
+
+| Part (label, side) | Skin sheet | Muscle sheet | Stack only |
+| --- | --- | --- | --- |
+| Pelvis, Torso | yes | yes | fat, bone; organs contained |
+| Head | yes | no (scalp over skull) | fat, bone; brain contained |
+| UpperArm, LowerArm, Thigh, Shin (L, R) | yes | yes | fat, bone; vessels, tendons contained |
+| Foot, Palm, Thumb, Fingers (L, R) | yes | no | bone, tendons contained |
+
+Authority: `PhysiologyPlan.Parts` owns each part's tissue stack (`PartTissuesDef`: `TissueDef` Thickness and `SheetDef`: spacing,
+edge and attachment compliance, tensile strength), joined to the `BodyPlan` only by `PhysiologyPlan.Resolve`, the one
+(label, side) join. The sheet builder reads (`BodyPlan`, `PhysiologyPlan`). Lodur.Core derives the sheet geometry (rest points
+in the part frame, edges, bends, joint stitches) from the part's shape and stack, deterministically, at build. Derived
+geometry is never stored: a stored copy would be a cache that could disagree with the stack. The content lives in
+`PhysiologyPlans.Humanoid` until lodur-body-plan-cultcache.
+
+## Authority map
+
+- Owner of flesh meaning (which part, which layer, awake or dormant, wound, sever): Lodur's binding (Lodur.Body.Ymir), from
+ plan data and physiology insults.
+- Owner of flesh physics (positions, constraint solve, tension and attachment-force sensors, components): Ymir.
+- Inputs to the binding's wake rule: contact impulse lanes on the part's bone, insults on the part, wounds, severs,
+ evisceration; for re-pinning, attachment force times compliance (the deviation; no new lane).
+- Outputs: Ymir commands (create in batches, set pinned, remove distances, destroy particles); Tear insults from DistanceTension.
+- Derived: sheet geometry (from the stack), render embedding weights (BDS client, at load), components and tethers (Ymir),
+ the active lists of the pin cut (Ymir, at command time), the per-particle held-body list and limb skip (Ymir, at command time).
+- Forbidden writers: Ymir never wakes, pins, tears or splits on its own; BDS never commands flesh except through the session;
+ no per-tick writes of dormant particles.
+- Demotions: "pinned = inverse mass 0 in every constraint" (follow-up ymir-particle-pinning as admitted) is no longer the
+ mechanism; dormant particles leave the loops. held_by's scan over every attachment is no longer an owner; the held list is
+ derived at command time.
+
+## Body facts (probes)
+
+Probe sources: `/imag-flesh/fella.c`, `sieve.c`, and a copy of Ymir d82da6d `ymir_particles.c` with opt-in probe
+patches (pinned skip flags, a body group filter in place of held_by, flesh out of the solid contact grid, phase timers; the
+unpatched paths are byte-for-byte the shipped code). gcc 13.2 -O2 -ffp-contract=off, one core, 120 Hz x 4 substeps. Bones are
+kinematic proxies driven by forward kinematics of BodyPlans.Humanoid (sways at 3 rad/s); Box3D's own step is not included.
+
+P1 Counts per Fella, sampler at skin 10 cm / muscle 14 cm with a ring floor of 4: 397 skin + 264 muscle = 661 particles,
+3,123 distances (383 joint stitches), 434 bends, 661 attachments. At 8 / 10 cm with a ring floor of 6: 619 + 414 = 1,033,
+4,742 distances (527 stitches), 736 bends. Torso skin 110 and pelvis 54 at 8 cm; hands 76 together.
+
+P2 Per-tick cost, median of 5 interleaved runs of 600 ticks (`matrix2.sh`, 10/14 cm config):
+
+| Scene | Live particles | ms/tick |
+| --- | --- | --- |
+| A 1 Fella pinned as mass 0 in the solve (shipped code) | 0 | 4.918 |
+| B 1 Fella pinned by skip flags | 0 | 0.255 |
+| H 4 Fellas pinned by skip flags | 0 | 1.023 |
+| D 1 live forearm, rest dormant (absent) | 40 | 0.204 |
+| E 1 Fella live, flesh out of particle contact, limb skip | 661 | 1.036 |
+| F E plus a released 8 m gut (300 particles, self-colliding) | 961 | 2.359 |
+| G E with flesh in the solid contact walk | 661 | 5.441 |
+| I E with held_by's attachment scan instead of the limb skip | 661 | 5.280 |
+| J 4 Fellas' bones and capacity, 1 Fella live, rest absent | 661 | 2.271 |
+| K J plus the gut | 961 | 4.262 |
+
+Phase split (fella_prof): a live Fella in the contact walk spends 4.4 of 5.4 ms in particle_contacts walking pairs of its
+own group that never collide. With nothing live, 0.6 ms of 4 Fellas' 1.2 ms is grid_sort clearing a bucket table sized 2x
+particle capacity (32,768 buckets). body_contacts is live particles x every body: 0.49 ms for 232 particles x 77 bodies.
+
+P3 Command cost (one call each, 4 Fellas + gut, 8/10 cm): remove 24 skin edges 0.59-0.65 ms, remove 32 elbow stitches
+0.61-0.66 ms (one outlier 10.3 ms); 1 Fella + gut at 10/14 cm: 0.12-0.47 and 0.11-0.17 ms. Every remove, attach and
+create_distances runs rederive_topology over the whole world. Waking a part (restoring inverse mass) 2-10 us.
+
+P4 Spawn with one attach per call (the only attach Ymir has): 1 Fella 147 ms, 4 Fellas 2.3 s (quadratic in world size).
+
+P5 Joint rings: with held_by, neighbouring bones of the same Fella push flesh at the joints: max live deviation from the
+attachment point 0.064 m against 0.023 m with the limb skip (8/10 cm, all live).
+
+P6 Sieve (`sieve.c`): a skin sheet at 8 cm (36 particles, r 0.036, 96 edges) attached along a static capsule (r 0.07,
+half 0.18, horizontal) under a 7x7x7 fluid pour or a 4x4x4 solid block, 3 s at 4 substeps:
+
+| Load, rate | Worst edge stretch | Deep tick x pairs | Load inside the bone | Skin mean axis distance |
+| --- | --- | --- | --- | --- |
+| fluid 60 Hz | 0.0204 | 35 | 0 | 0.0700 |
+| fluid 120 Hz | 0.0221 | 2 | 0 | 0.0700 |
+| solid 60 Hz | 0.0275 | 2 | 0 | 0.0700 |
+| solid 120 Hz | 0.0321 | 0 | 0 | 0.0700 |
+| mutant: attachments off (compliance 1e3), fluid 120 Hz | 0.0566 | 0 | 0 | 0.4016 |
+
+The body-backed skin does not sieve: it holds its place within 0.1 mm and stretches 2-3%. 96 of 343 fluid particles reach the
+bone surface between skin particles, which is where the drawn skin is; none enters the bone. The corner-pinned tarp's sieve
+is a limit of loose cloth, not of BDS skin.
+
+P7 Solid grid sized by its members (pass ymir-dormant-map; `probes/flesh/grid-mask.probe.patch` on top of the P2 probe,
+`grid-mask.fella.patch` adds `MASKSIZED` and an FNV hash of the pos_x, pos_y and vel_z lanes; runs `grid-mask-h.out`,
+`grid-mask-k.out`). grid_sort's solid pass uses a mask from the member count (16 or more buckets, at least twice the count,
+capped at the table) and walk_half hashes with the same mask. The hash is equal with and without it on a live Fella plus
+self-colliding gut (961 live) and on 4 skip-flag Fellas, because walk_half reads a cell's particles in lane order whatever
+the bucket count. The fluid grid is left full size: fluid_density sums in bucket order. Paired interleaved medians, 5 runs of
+600 ticks:
+
+| Scene | Full table | Sized | Particle-free (bones only) |
+| --- | --- | --- | --- |
+| 4 Fellas pinned by skip flags | 0.988 | 0.486 | 0.096 |
+| 1 live Fella out of contact + gut, 3 Fellas' bones (K) | 3.975 | 3.464 | |
+
+Phase split of the sized 4-Fella run, ms per tick: grid 0.056, particle contacts 0.087, attachments 0.021, distances 0.123,
+bends 0.028, bodies 0.014. Those are walks over dormant lanes that active lists remove.
+
+## Cut order
+
+1. cut-ymir-skin-sieve-test (Ymir, test and doc). Beside it: 2. cut-ymir-particle-limb-contact (Ymir: held list derived at
+ command time, LIMB attachment flag skips the attached body's limb tree) and 3. cut-ymir-flesh-no-particle-contact
+ (NO_PARTICLE_CONTACT phase bit, solid grid sized by its members; no ABI number).
+4. cut-ymir-attach-batch (ABI 17): attach takes n descs and ends in one derivation; the ONE_WAY attachment flag. After
+ ymir-break-and-remove (ABI 16) and limb-contact.
+5. cut-ymir-particle-pinning-dormant (ABI 18): set_pinned; dormant particles out of every substep walk through command-time
+ active lists and a derived solve inverse mass; pinned particles bordering live ones are kinematic per substep; wake writes
+ position and velocity from the anchor. After 2, 3 and 4.
+6. lodur-tissue-sheet-material (stack material in PhysiologyPlan, Resolve), then lodur-sheet-builder (the deterministic sheet builder).
+7. lodur-body-sheets-graph (binding: build dormant, wake per part, re-pin, wounds and severs as commands), after lodur-physiology and lodur-sheet-builder.
+8. bds-flesh-render-embedding; then lodur-organ-release-rope and lodur-exposed-tube-chains.
+
+Budget reading: at rest flesh must cost nothing per tick (P2 B, H); one hurt part costs about 0.2 ms; a whole live Fella about
+1 ms alone and 2.3 ms in a 4-Fella world; an eviscerated gut adds 1.3 to 2 ms. The rope scene already takes about 2 ms, so a
+whole-body event on top of it overruns: question bds-flesh-live-budget.
diff --git a/docs/goal-ai-map.md b/docs/goal-ai-map.md
new file mode 100644
index 0000000..1fedb09
--- /dev/null
+++ b/docs/goal-ai-map.md
@@ -0,0 +1,491 @@
+# Fella's goal-following AI (map)
+
+Campaign `lodur`, pass `goal-ai-map`, 2026-11-25. Serves `lodur:ruling:bds-fella-needs-goal-ai`: Fella follows
+simple goals, moving towards or away from things and interacting with objects. Read with
+`lodur:ruling:bds-hallucination-shown` (hallucinations alter his reality and drive behaviour by type),
+`lodur:ruling:bds-graft-control-by-wiring`, `lodur:ruling:npc-brain-authors-goals`,
+`lodur:ruling:lodur-locomotion-rosen-style` and `lodur:ruling:bds-mvp-clips`. Where this file and a ruling
+disagree, the ruling wins.
+
+## Bases
+
+Lodur `fbc3501`, BDS `3d6e735`, Ymir `d82da6d` (origin mains, fetched 2026-11-25).
+
+## Body facts (probes and reads at base)
+
+1. `Brain` (`src/Lodur.Core/Brain.cs`) is goals selected by eligibility (conditions over `DriveState`) then
+ priority, committed by the Actor after the deliberate latency. A goal has exactly one behaviour, a
+ `PoseBehaviour`, and **no target**: nothing in a goal names a thing in the world.
+2. `Perception` (`src/Lodur.Core/Perception.cs`) reduces the world to intensities: noxious boxes per region, and
+ point `Emitter`s (channel, position, radius, intensity) reduced to one stimulus per channel at the sense
+ region, then one `Load`. An emitter has **no identity**: the puppet cannot tell two sounds apart, or know
+ where anything is. There is no percept of an object.
+3. No IK exists in the code (`grep -rniE "\bIK\b|reach|two-bone" src` finds nothing); `lodur-ik-goals` is a
+ follow-up. The body interface is per-joint strength plus target rotation (`Ragdoll.Drive`).
+4. The puppet cannot stand: every BDS body run builds through `SeatedPuppet.Build`, which welds the pelvis to a
+ stool (`BDS src/BadDay.Ymir/SeatedPuppet.cs:24-30`). `lodur-assist-pin` (the will-scaled upright assist the
+ Rosen ruling names) is a follow-up, unbuilt.
+5. BDS authors two Brains, `OfficeBrain` and `ChamberBrain`; neither has a target. Emitters are built in BDS
+ `Setting.cs` and `StressSession.cs` with no id.
+6. `dotnet test tests/Lodur.Core.Tests` at base: 188 passed, 0 failed (2026-11-25).
+
+Pass `goal-targets-ik-map`, Lodur `4118b47` (percepts landed), Ymir `d82da6d`, 2026-11-25. Probes in the
+scratch project `imag-goals/probe` (not committed); humanoid, 120 Hz, 4 substeps.
+
+7. **Joint target convention (probe).** Ymir's joint frame lane at build is the shortest arc from +z to the
+ plan's axis: Shoulder `(-0.707, 0, 0, 0.707)` (z to up), Elbow `(0, 0.707, 0, 0.707)` (z to across). A target
+ q makes the child's rotation relative to the parent, from the creation pose, `F q F^-1`: at gravity 0 the
+ measured upper-arm direction in the torso frame for shoulder `x -1.0` was `(0.14, -0.55, 0.83)` against
+ predicted `(0, -0.54, 0.84)`, the forearm for elbow `z -1.2` `(0.00, -0.36, 0.93)` against `(0, -0.36, 0.93)`.
+ Spherical Lower/Upper bound twist (about frame z, the bone axis) and Cone bounds swing (Ymir
+ `AddJoint` summary). Shoulder twist tracks weakly: a combined target `z +0.6` then `x -0.8` reached joint
+ rotation `(-0.385, -0.065, 0.157, 0.907)` against `(-0.372, -0.115, 0.272, 0.880)` (twist kp 1, swing kp 20).
+ Swinging the right arm toward +x hits the torso: the arm collides with its own trunk.
+8. **Zero-twist two-bone solve (probe).** Choosing the elbow swivel so the shoulder target has no twist is
+ closed form: `R = Rot(v, phi) * Arc(p, v)`, `phi/2 = atan2(-Q.y, w v.y + (v x Q).y)` with `(Q, w) = Arc(p, v)`
+ and y the creation-pose bone axis; the result is unique. Arm lengths: L1 0.310 m, L2 0.265 m (anchors).
+ That swivel can push the swing past the shoulder cone where another swivel reaches: the seated ward-off goals at
+ head height (`(0.30, 1.74, 0.26)` left, `(0.00, 1.74, 0.26)` right) clamp 20.5 and 22.6 cm short at zero twist and
+ are reached at twist 0.27 and 0.52 inside the [-1, 1] limits. At gravity 0 the twist muscle holds those to 0.54
+ and 0.44 and the wrists land 7.0 and 2.8 cm off (probe, cut `lodur-orient-goals` s1 fix).
+ Across the body, a goal the zero-twist swivel reaches can still be missed: the right arm swinging toward
+ `(-0.04, 1.60, 0.24)` drives its forearm into the side of the trunk and wedges there, 45 cm short at gravity 0
+ (two forearm contacts, swing 0.20 against 1.50); a forward via point for 0.6 s first brings it to 9.8 cm.
+9. **Reach on the ragdoll (probe).** Solving each step from the measured torso frame, wrist error after 4 s,
+ right arm, targets at shoulder plus an offset. Gravity 0, free-floating: `(0,-0.25,0.35)` 3.0 cm,
+ `(0.12,-0.1,0.4)` 11.1 cm (swing 1.22 near the 1.5 cone, across the body), `(-0.15,-0.3,0.25)` 2.3 cm,
+ `(0,0.05,0.45)` 1.0 cm. Gravity on, pelvis welded to a static box: 13.6, 17.9, 10.2 and 23.9 cm: PD sag
+ under gravity, not IK error. A naive task-space integrator on the target (2 and 4 per second, 0.3 m cap)
+ made it worse (2 to 38 cm, swing past the cone); see follow-up `lodur-reach-tracking`.
+10. **Select's one caller** is `Actor.Tick` (`Actor.cs:173`); BDS never calls it (grep at BDS origin/main).
+ Every authored priority is >= 0 (BDS OfficeBrain 0, 1, 2; ChamberBrain 0, 1; PainBoxBrain 0).
+11. **Percept slots are reused** by another id after eviction (`Perception.Admit`), so a target is tracked by
+ Id. Sense runs before Select within a tick (`Actor.cs:145`, `:173`).
+12. **In-flight overlap.** `lodur-physiology-core.r1` changes `Actor.cs` 5-16, 46-90, 100-105, 131-140 and
+ 207-213, `DriveState.cs`, `WillTests.cs`, `CalmSensesTests.cs`; `lodur-airway-openings` changes `BodyPlan.cs`,
+ `BodyPlans.cs`, `Ragdoll.cs`. `brain-goal-targets` touches `Actor.cs` only at 36-40, 126-129 and 169-194;
+ `lodur-ik-goals` touches none of these files.
+
+Pass `goal-planner-map`, Lodur `997b1fe`, 2026-11-25, after `lodur:ruling:bds-intelligence-is-planning-depth`.
+Probe: a scratch C# replica (not committed), net10 Release on the workstation, 41 rounds of 200 calls in shuffled
+order per round, paired medians against a utility-only Select in the same round.
+
+13. **Planner cost (probe).** World: 16 percept slots (the `Perception` default capacity), 48 grounded verbs (go to
+ each slot, grab and drop four portable things, unlock with either key on either door, open, cut the strap,
+ switch off, eat, two filler verbs on each of eight other things), facts as a 128-bit set; Fella starts strapped
+ down with a knife in reach. Six planned wants per Select (open either door, 8 steps; pain off, 4; fed, 6; hold
+ the knife, 1; a filler, 5). Iterative-deepening regression to the depth limit, plus the utility pass over six
+ goals by 16 slots. Paired median extra cost per Select over utility alone (3.75 us):
+
+ | Depth | Regressive (F.E.A.R.) | Forward | Wants planned | Regressive nodes |
+ |---|---|---|---|---|
+ | 1 | 0.47 us | 0.59 us | 1/6 | 18 |
+ | 2 | 1.33 us | 1.56 us | 1/6 | 41 |
+ | 3 | 3.30 us | 4.06 us | 1/6 | 97 |
+ | 4 | 8.52 us | 16.07 us | 2/6 | 244 |
+
+ Nodes, untimed, beyond 4: 516, 1118, 2744, 5860 at depths 5 to 8 (all six wants planned at 8); forward search
+ visits 15035 at depth 5. Regression grows about 2.2x a level, forward about 10x. At depth 4 the planner costs
+ about 1 ms of CPU per second per puppet at 120 Hz, so it can run every Select: no planning cadence, no plan cache.
+14. **Where depth bites.** In the probe world a depth-3 Fella plans nothing but grabbing the knife; depth 4 finds
+ "grab knife, cut strap, go to switch, switch off"; the door needs 8. Depth is visible in play exactly as the
+ ruling wants: the same room, the same wants, a different number of things he can work out.
+15. **What exists to plan over.** Percepts carry id, kind, position, salience and age (`Perception.cs:111-131`);
+ nothing carries a fact about the thing (open, locked, on). Interactions do not exist (follow-up
+ `lodur-interactions`); a verb today has neither preconditions nor effects.
+
+Pass `goal-planner-cut`, Lodur `419d454` (`nibu/brain-goal-targets` head, in Soul review), 2026-11-25.
+
+16. **Baseline.** `dotnet test tests/Lodur.Core.Tests -c Release` at `419d454`: 278 tests. The first run after a
+ fresh build failed one test in a reflection-invoked path; four reruns passed 278/278. The failing test was not
+ named in the output kept; a Hands pass that sees it names it.
+17. **Facts have no home at base.** `Emitter` carries channel, position, radius, intensity, `Id`, `Kind`;
+ `Percept` carries id, kind, position, salience, seconds since sensed (`Perception.cs` `Emitter`, `Percept`).
+ A thing's kind may change between ticks (`PerceptTests` "takes the new kind"), so facts follow the same rule:
+ the slot takes what it was last sensed with, and `Sense` refuses two emitters of one id that disagree.
+18. **Overlap.** Cut 2b is split. Part 1 (`lodur:cut_spec:cut-lodur-goal-planner.r1`) touches only
+ `Perception.cs`, a new `Planner.cs`, tests and `docs/lodur-target.md` (its row lands after line 115, not
+ adjacent to `lodur-tissue-sheet-material`'s edit at 112). Part 2 (follow-up `lodur-planner-select`) edits
+ `Brain.Select` and `Actor`, where `lodur-orient-goals` (ctor `BodyPlan?`, Tick `parts`, the commit block) and
+ the oxygen cut (`Physiology.Step` input, the ceiling loop) also edit; it runs after whichever of them is in
+ flight and adds only trailing optional parameters.
+
+Pass `planner-select-cut`, Lodur `77d00d3` (main: goal targets, planner part 1, airway, orient goals), 2026-11-26.
+Probes in the scratch project `nibu-imagination-select/probe` (not committed): `Lodur.Core` at `77d00d3` with
+`NodeBudget` made settable and a `MoveRule` switch in `Regress` only; net10 Release on the workstation.
+
+19. **Baseline.** `dotnet test tests/Lodur.Core.Tests -c Release` at `77d00d3`: 377 passed.
+20. **Reach and the oracle.** `Planner.Plan` sets bit 63 once per call from distance to the observer
+ (`Planner.cs:177-181`) and no verb takes it away (finding `reach-is-monotone`). The forward oracle in
+ `PlannerEquivalenceTests` places things only at x 0.5 or 5 and its `Apply` has no reach rule, so it cannot see the
+ rule either way: with the Regress half of the move rule on, the 17 planner tests (equivalence included) passed.
+21. **Crowded worlds (probe).** Rooms of 16, 48 and 64 things (a strap at 0.3 m; knives, keys, doors 70% locked,
+ switches, tools and four junk kinds within 12 m), verbs of the test catalogue plus `Pry` (strap with a tool) and
+ junk `Fiddle`/`Stack` decoys, wants on every door, switch, knife and the strap; 100 seeds. Plan calls exhausting the
+ 4096 budget while an unbounded search finds a plan within depth: none at depth <= 5; at depth 6, 23 of 1200 calls
+ (48 things) and 96 of 1800 (64); at 7-8, 62/1200 and 127/1800. The move rule removed 2-3 plans per 600-1800 calls at
+ depth 4 (plans holding two far things in reach) and cut nodes slightly. **Decisions** (300 seeds, the best pair by
+ `raw x (1 - 0.08 len)`, direct `raw x 0.5 x (1 - 0.08 (d + 1))`): per-plan budget, exhaustive or best-first, chose
+ as unbounded search in every room; one 4096 budget per decision spent best-first differed in 0 rooms at depth 4,
+ 11-20 of 300 at depths 5-8 for 48-64 things, and 16 of 300 at depth 8 for 16 things.
+22. **Cost per Select (probe).** Paired interleaved medians, 31 rounds, us per Select (all want pairs):
+
+ | Things | Depth | Every pair | Best-first, budget per plan | Best-first, budget per decision |
+ |---|---|---|---|---|
+ | 16 | 4 | 25.8 | 10.9 | 11.1 |
+ | 16 | 8 | 937.6 | 578.7 | 233.0 |
+ | 48 | 4 | 239.0 | 59.3 | 65.5 |
+ | 48 | 6 | 1989.9 | 525.1 | 213.4 |
+ | 48 | 8 | 3169.1 | 1114.2 | 237.7 |
+ | 64 | 4 | 526.8 | 105.0 | 101.1 |
+ | 64 | 8 | 3539.3 | 905.2 | 172.6 |
+
+ A grounding costs about 0.2 us here, not the 35 ns fact 13's world implied, and pairs multiply it: the 8.5 us of
+ fact 13 was six wants, not a want per thing. At 120 Hz, 1.1 ms per Select is 13% of a core per Fella.
+
+Pass `reach-tracking-map` (its records cite these facts as 19-23; here they are 23-27), Lodur `77d00d3`, Ymir `e51cf76`, 2026-11-26. Probes in a scratch test class (not committed)
+in `F:\aeth-wt\imag-reach-lodur`, net8 Release; humanoid, 120 Hz, 4 substeps; errors after 2 s (seated) or 4 s (reach).
+
+23. **Gravity sag is PD sag, and feedforward removes it (probe).** At base the seated head-height wards read 16.0-17.8
+ cm under gravity against 2.8-7.0 cm without; the welded reach targets 10.2-24.0 cm against 0.25-0.89 cm. Adding,
+ after `Ragdoll.Drive`, each joint's subtree gravity load times the muscle's strength (`-(sum m_b (x_b - a_j)) x g`,
+ masses from the plan's shape and density, which Box3D also uses) brings the reach targets to 0.88, 0.11, 0.55 cm and
+ the seated wards to 3.95-5.51 cm. At half strength it still sags (12.0-22.9 cm), as a weak will must: the torque
+ and the stiffness scale together. Cost, an O(parts) bottom-up form, 41 paired interleaved rounds: +0.79 us per
+ `Drive` (0.89 to 1.66 us) against 89.4 us per `world.Step`.
+24. **Feedforward on every muscle moves 13 of 60 `Lodur.Tests` (probe, also projected onto each muscle's gain
+ axes).** ConnectedPainBoxTests (5): the held arm no longer sags into the box, the will never breaks, the replay
+ golden changes; HandTests (7): thumbs keep turning at rest (0.2-1.2 rad/s), the wrist overshoots its cone to
+ 1.069, the finger rest reads 0.29 against 0.35; RagdollTests hinge-axis torque (1). Content and tuning were set
+ against sagging muscles. Question `gravity-feedforward-scope`.
+25. **The far-arm wedge is cleared by a via point ahead of the wrist's own side (probe).** Seated low sound, right
+ wrist from (-0.21, 0.975, 0) to its ward goal (-0.04, 1.60, 0.24) in the torso's creation frame: the straight
+ wrist segment touches the trunk (distance 0.0 to the torso and pelvis boxes); for the head-height sound on the
+ right it clears by 6.6 cm, on the left it touches (0.0). Minimum-jerk path, two 0.3 s segments, via point
+ `(wrist x, mid y, trunk front + c)`, under gravity with feedforward: low far arm 9.9, 7.6, 6.0 cm at c = 0.15,
+ 0.2, 0.3 (zero gravity, c 0.2: 7.8); the left head-height sound's right arm 2.2-3.2 cm. A via point at the
+ midpoint's x needs c 0.3 and fails at 0.15-0.2 (38-40 cm); at the goal's or shoulder's height 8.2-16.6 cm. A
+ straight path with no via: 47.5 cm.
+26. **A hand path costs where nothing blocks (probe).** The straight minimum-jerk path on the unblocked right-side
+ ward ends 12.8 cm off (gravity, feedforward) against 5.5 cm for the direct solve; on the left-side ward without a
+ via, 9.7 against 3.95 (zero gravity 28.2 against 2.8). The final IK targets are the same; the shoulder twist is
+ not: 0.84 rad off its target after the path against 0.06 direct, no contacts at the end. The twist muscle (kp 1,
+ fact 7) cannot pull the twist back once the path leaves it elsewhere. Question `reach-path-unblocked`.
+27. **The hand-off jump.** `OrientRig.Compose` runs only while the goal in force has layers (`Actor.Tick`,
+ `PoseBehaviour.Write`), and an arm not driven keeps its slewed output, so engaging slews from stale targets and
+ disengaging writes the base pose at once (Soul s4 on `lodur-orient-goals`: 0.65 rad in a tick).
+28. **Feedforward on a supported body makes it weightless (probe, pass `gravity-cuts-map`).** The hand-rest bodies
+ that keep turning (fact 24) belong to a fallen body: `RagdollScenario` lies on the ground after 5 s (head at
+ 0.11 m). Feedforward cancels the weight that gave the floor contact its friction, so palm, thumb and fingers
+ drift at 0.07-0.80, 0.21-1.20 and 0.12-0.94 rad/s (off: 0.000-0.012). Skipping feedforward on the hand joints
+ leaves them drifting (thumb 0.13-2.88): the load comes from the arms and trunk. Reading the anchor from Ymir's
+ `JointOrigin` lane instead of the plan changes nothing measurable. A gate that gives a body touching anything
+ (`ContactCount > 0`) no load settles every hand body (0.000-0.007 rad/s) and passes all five hand-rest tests.
+ A continuous gate (load minus `ContactImpulse / dt`) is worse than none (thumb 1.5-1.9 rad/s): the one-step
+ lag rings. The count gate also counts self-contact: thumb against fingers, a forearm on its own thigh.
+29. **The pain-box hold re-solved, and its survival curve (probe).** At the base pose (shoulder -1.0, elbow -0.6)
+ feedforward lifts the palm from (-0.207, 1.121, 0.446) to (-0.174, 1.395, 0.572), out of the box, and no seed
+ of 20 breaks in 60 s. A grid fit of the two hold angles to put the settled palm (seed 1, 3-4 s, box at
+ intensity 0) at the box centre gives shoulder -0.66, elbow -0.28 (0.49 cm) without the gate and -0.70, -0.36
+ (0.34 cm) with it. Seeds 1-20, 60 s limit, break / first flinch in s: at base 14.12-19.23 / 6.86-9.34, median
+ break 15.9 s, every seed breaks by 19.3 s (no censoring); re-solved pose with gate within +0.03 s of base on
+ every seed's break and first flinch within 0.11 s (seed 13; the rest equal). Hand in the box after 2 s: 99-100% at
+ base, 94-98% gated.
+30. **What moves with the gate and the re-solved pose (probe, gravity hard-coded so the two zero-gravity tests are
+ probe artefacts).** `Lodur.Tests`: 5 of 60 (13 ungated): the seed-1 replay golden; the leak test, whose hand
+ now leaves the box at tick 1756, 18 ticks before the break at 1774 (box half 0.125 was sized against sag); the
+ wrist cone, 1.0616 against the 1.06 bound both sides; the hinge-torque test (the wrist's feedforward reaches the
+ forearm). BDS `3d6e735` against it: 69 of 71 (70 of 71 ungated): the body hand-in-box test (one excursion
+ before the break) and, gated only, the flinch control (tracks 5.5 cm apart before the first flinch, 6.0 after).
+ Office body tests, the CLI goldens and `tools/PainSweep` (engine-free, no body) do not move. Probe:
+ `F:\aeth-wt\imag-gravity-probe\` (patch, harness, logs).
+31. **The built gate in a crowded room (probe, `PlannerSelectTests`).** The first build planned pairs best raw first, a whole
+ depth each. Room of 48 things (a strap at 0.3 m, a knife at
+ 0.5 m, then knives, keys, doors 70% locked, switches and four junk kinds within 12 m; the test catalogue plus `Pry`,
+ `Fiddle`, `Stack`; wants on every door, switch, knife and the strap; doors outrank the strap), 100 seeds, ThinkBudget
+ 4096 against `int.MaxValue`: decisions that differ were 0 at depth 4, 37 at 5, 59 at 6 and 62 at 8 (at 64 things, 8
+ at depth 4). This is far above fact 21's 4-7%: the first pair in raw order is a locked door no plan within depth 6
+ reaches, it spends the whole budget searching, and the strap he could cut is starved to a direct try. The count is
+ a property of the world's priorities (a crowd of high-raw unplannable wants), not of the gate; fact 21's room did
+ not have it. Paired interleaved medians (20 seeds, 20 measured ticks each after 12 settling ticks, net10 Release,
+ workstation): `Brain.Select` alone, budget 4096, 406 us at depth 4 and 766 us at depth 6 (unbounded: 259 us and
+ 13.3 ms); `Actor.Tick` over a utility-only Brain, extra 441 us at depth 4 and 924 us at depth 6, the difference
+ from Select being the committed pair's plan, a second Plan call with the full budget every tick. A grounding costs
+ about 0.1-0.2 us. Deepening across pairs, with the plan made by the Select that chooses the pair and carried with
+ it, as built: decisions that differ are a rate, about 0.5% at 48 things and 3% at 64, at every depth (400 seeds, 5000-5399: 1 and 11;
+ seeds 0-399: 1 and 13; seeds 9000-9399: 3 and 23; the first 100 seeds gave 0 and 2, a property of those seeds). Paired interleaved medians, 48 things, budget 4096, net10 Release: `Brain.Select` 206, 205 and 206 us at depths 4, 6 and 8
+ (unbounded 205, 208, 206; a Select spends 1592 groundings at the median, 4096 at most), `Actor.Tick` extra over a
+ utility-only Brain 68 us at depth 4 and 79 us at depth 6: a tick spends at most one `ThinkBudget`. At depth 4 the move rule's plan cost
+ is about 2x on movers and 1.0x elsewhere (Soul s1 on `lodur-planner-moves`, paired medians, 6 wants); the budget
+ bounds it, so no work on it here.
+32. **Self-contact under the count gate, and the subtree-external gate (probe, pass `gravity2-map`).** At `63444f0` the
+ count gate's self-contact cost shows in tests: the gravity reach reads 3.01, 3.16, 3.97 cm (ungated 0.89, 0.13,
+ 0.54) because the right thumb and fingers touch. Probed gate: each body's load is deposited at the lowest common
+ ancestor of it and every body it touches (a body touching nothing deposits at itself; a touch outside the ragdoll
+ deposits nowhere, as the count gate), then summed bottom-up as at `63444f0`, so a joint carries a body unless a
+ touch outside the joint's subtree supports it. Touching pairs were kept in the probe from Ymir's Begin/End facts
+ and equal `ContactCount` on every body every step (2,614,540 body-steps, 0 mismatches). Readings: gravity reach
+ 0.77, 0.16, 0.72 cm; half strength 19.00, 13.85, 22.79 cm; seated ward under gravity 7.03 cm worst (count 6.00,
+ ungated 7.59, zero gravity 8.11: the ward is not gravity-limited); hand-rest tests pass (ungated: 5 fail). In
+ the chamber hold at 3 s, 5 of the 7 touching pairs are self-contacts. Cost per `Drive` from a per-step pair list
+ (lanes mapped by offset, LCA by depth walk), 20000 calls x 41 paired interleaved rounds, net10 Release: +0.227,
+ +0.230, +0.255 us over the count gate's 1.58-1.93 us. Probe: `F:\aeth-wt\imag-gravity2-probe-lodur.patch`
+ (scratch modes `LODUR_GATE=count|subtree|none`), logs `F:\aeth-wt\imag-gravity2-*.txt`.
+33. **The pain-box hold under the subtree-external gate (probe).** The count-gate pose -0.70, -0.36 settles the palm
+ 4.74 cm from Box (count 0.24). Grid 0.04 then 0.01: -0.68, -0.25 at 0.15 cm (count-gate refit -0.73, -0.30 at
+ 0.15 cm: the fit is a ridge). Seeds 1-20, 60 s: median break 15.90 s (14.16-19.26), holding at 10/15/20 s
+ 1.00/0.70/0.00, censored 0, median first flinch 7.55 s (`63444f0`: 15.88 s, 1.00/0.70/0.00, 7.55). Box half by
+ the shipped-run rule (seed 1, ticks out from 2 s to the break): 0.145 3, 0.150 2, 0.155 0. `Lodur.Tests` then
+ fail 2: the seed-1 replay golden and the strain shake (shipped 2.68 cm in second 8, bound 3 cm).
+34. **BDS `c55770f` against the gravity feedforward (probe).** Against `63444f0`: 66 of 81 (the report's 15). With
+ Lodur's pose -0.70, -0.36 and box half 0.145 only: 79 of 81, left the flinch control (seed 1 gap before the
+ first flinch 5.50 cm, after 6.15) and office settle (seed 100 hand 0.0292 m/s). The same content under the
+ subtree-external gate: 80 of 81 (only the idle drift, 5.7 cm: the pose was fit for the count gate). With the
+ subtree refit (-0.68, -0.25, half 0.155): 80 of 81, the flinch control on seed 3 (before 2.06 cm, after 3.98;
+ rule before < after / 2). The pre-flinch gap is the leak, not a contact: in the Lodur fixture full and
+ flinch-gain-0 runs part at tick 39-40 (the box ramp), first flinch at 843-1043, and forcing the feedforward's
+ strength factor to 1 leaves the gap (seeds 1-3 before 1.70-2.69 cm). BDS's world is Lodur's fixture (same
+ ground, stool, weld, lane order). Probe: `F:\aeth-wt\imag-gravity2-probe-bds.patch`.
+
+## Prior art (research pass `goal-ai-prior-art`)
+
+- The Sims: needs-based utility; objects advertise what they offer, so the data lives on the object and new
+ objects need no character code. Fits "interact with objects in various ways" and `sandbox-is-content`.
+- F.E.A.R. (Orkin, GDC 2006): three states (Goto, Animate, UseSmartObject) plus a STRIPS-like A* planner over
+ actions. The three states are the motor vocabulary we need. The planner was rejected in the first pass and is
+ taken now (pass `goal-planner-map`): its depth is plan length, which is what the intelligence ruling names.
+ Read from the paper's text: the world state is a fixed array of variables, effects and preconditions are
+ entries in it, search regresses from the goal, and **target and weapon selection run outside the planner**,
+ which reasons about the one target in focus. That is the split this map keeps: utility picks (goal, target),
+ the planner finds how.
+- HTN (Killzone 2 bots, SHOP-like; Horizon's Decima planner, which backtracks over preconditions as Prolog does):
+ depth there is the decomposition depth of authored methods. Capping it does not make a duller character, it
+ truncates a method into a broken one; a dim NPC is one with fewer methods, which is authoring, not a stat.
+ No published cost figures (Guerrilla's pages give none).
+- The Sims: objects advertise and selection is one step; no lookahead (Forbus's lecture notes mention only
+ routing A*). Wright said the early autonomy was too good and Sims were made dumber for play: the precedent for
+ intelligence as a tunable limit rather than a fixed competence.
+- MCTS (Total War: Rome II campaign AI, Champandard 2014): depth is rollout length and iterations, it needs a
+ forward simulator of the world, and it is stochastic per decision; built for turn-based campaigns.
+- Dave Mark (gamedev.net) on GOAP: long plans in a dynamic world are invalidated each think and replanned
+ whole. Fella's plans are short (the depth cap) and replanning is the measured 0.5-8.5 us, so the cost he
+ names is paid and affordable.
+- RimWorld: a priority think tree picks a job; a job driver runs a fixed list of toils (go to, reserve, wait,
+ interact). The tree is what `Brain` already is (priority plus conditions); toils are the shape of an
+ interaction.
+- Utility AI (Dave Mark's infinite-axis system): normalised considerations through response curves, multiplied.
+ The way `Brain` grows (`lodur:idea:brain-map.brain-extends-to-utility-and-will-mix`), now over (goal, target).
+- Gang Beasts: virtual balancing forces not tied to ground contact, and a developer note that the control
+ mixes the Overgrowth talk with IK and PID on a fully physical ragdoll. Precedent for the will-scaled assist
+ carrying the body while gait poses and foot IK supply the look.
+- Euphoria (GTA IV): behaviours run on a simulated body; reachable sources give no behaviour API. Nothing to
+ copy below the behaviour level beyond what Lodur already has.
+
+## Target shape
+
+Signal per tick stays one way: perception → reflex → drive → Brain → motor layers → body.
+
+**Percepts (layer 1).** An emitter gains an `Id` (the game's stable id; 0 is anonymous and only loads the
+nerve) and a `Kind` (the game's tag; Lodur never interprets it). Perception keeps a bounded percept memory:
+one slot per thing sensed (id, kind, last position, salience, seconds since sensed), forgotten after a memory
+time. Real and phantom things are **one stream**: a hallucination is a thing in the puppet's reality, sensed
+like any other, and nothing the Brain reads tells them apart. Phantom ids carry the top bit, reserved to
+Lodur; `Sense` refuses a caller emitter that sets it, so the game cannot forge one and Lodur's hallucination
+owner (physiology and substances, `lodur-phantom-perception`) is the only writer.
+
+**Goals with targets (layer 4).** A goal may name a target: a kind filter over percepts. Selection scores each
+(goal, percept) pair, Priority times response-curve considerations (distance, salience, drive quantities),
+with a commitment bonus on the current pair. Conditions stay eligibility gates. A goal with no target scores
+its Priority alone, so OfficeBrain and ChamberBrain select exactly as now.
+
+**The planner (layer 4, between selection and the motor layers).** A goal may name a want: a fact about its
+target (open, off, held) or about himself (free, fed). Objects advertise verbs (BDS content, keyed by kind);
+each verb carries preconditions and effects as facts over the acting slot, a second slot, or himself, plus the
+toil step list that performs it. An emitter carries the thing's facts as the game sees them, and the percept
+remembers the facts as last sensed, so a remembered door is still locked to him after it was opened out of
+sight. Lodur never interprets a fact key, as it never interprets a kind.
+
+Search is regressive and depth-first with iterative deepening, as F.E.A.R.'s, over verbs grounded on the
+percept slots, to a depth limit that is the intelligence stat; it returns the shallowest plan, ties to the
+lowest verb order, and allocates nothing. Selection stays utility (`brain-goal-targets`), and the planner is a gate
+on its pairs, built in `Brain.Select` and the Actor's `Deliberation`: a pair whose want already holds is not offered;
+a pair planned within `PlanDepth` steps scores raw times the `PlanSteps` responses at its length; a pair with no
+plan (none within the depth, or the think budget gone) is tried direct at `DirectDiscount`, reading `PlanSteps`
+at depth + 1 (ruling `bds-unplannable-tries-direct`, which answers `bds-unplannable-goal`: he goes at the target
+and fails where the player can see it; a direct try that reads `PlanLength` -1 for `FrustrationSeconds` bars that pair's
+direct try, reports `TickEvents.Frustrated` and decides again past the dwell, and the bar lifts on forgetting the target or
+`RetrySeconds`; a changed fact does not lift it, since his own try can change one, and a change that makes the goal
+achievable shows as a plannable pair offered through the bar, ruling `frustration-lifts-without-fact-changes`). One `ThinkBudget` serves a whole Select, spent by deepening
+across the pairs (Korf's iterative deepening, anytime): round k asks every live pair for a plan of exactly k steps,
+by a bound on what the pair can still score, so short plans are found first and one pair's dead end cannot starve the
+rest; a want about himself is planned once per goal. The plan is the decision's: made by the Select that chose or
+re-chose the pair and carried with it to the Actor's commit (`PlanLength`, `PlanStep(i)`), checked against the
+percepts on a tick that decides nothing (its want holds, or a thing it names left memory), and made again for the
+pair in force when the dwell refuses a Select, from what is left of that Select's budget. Select never reads it;
+the pair's commitment keeps the choice stable. A plan step is a verb on a percept, and a phantom
+percept advertises as its kind does: a clever Fella plans through a hallucinated door and fails at it as a dim one
+fails at a real one. Intelligence 0 is the Fella of `brain-goal-targets`: no plans, every want pair direct. With no
+pair offered the goal in force stays and lets go of its target.
+
+**Mind stats.** Four sim stats per `lodur:ruling:bds-intelligence-is-planning-depth`, each derived each step as
+a physiology capacity is (base from the character content, then the offsets and factors of live afflictions,
+so a potion is an affliction whose effects target a stat): intelligence (planner depth, rounded down),
+quickness (scales the deliberate latency and the dwell), judgment (temperature of a seeded softmax over pair
+scores; perfect judgment is the argmax of `brain-goal-targets`), memory (percept memory seconds). Player-facing
+stats, if fewer, map onto these four and own nothing.
+
+**Motor layers (layer 4 to 5).** A goal's behaviour becomes a set of voluntary layers, each weighted by will:
+pose (exists), look (head IK at the target), reach (arm IK to the target), ward off (arms between head and
+target), lean or recoil (pose blend by the target's side), and, once the body can stand, locomotion (a desired
+ground velocity toward or away from the target). The hallucination behaviours of the ruling are Brain data
+over phantom kinds: flee is avoid, the attractive phantom is approach, fight is approach plus strike, ward
+off is a layer, stare at hands is look plus reach at a phantom attached to his own hand, fetal is a pose goal
+eligible when threat salience is high and no avoid target is reachable.
+
+**Locomotion is its own chain**, after the orienting goals: the assist pin (pelvis and torso, will times
+consciousness), standing (BDS drops the stool weld), a Rosen walk gait (pose keys timed by speed, foot IK),
+then steering (seek, flee, arrive) that writes the desired velocity the assist carries. Crawl and hop follow
+as impairment gaits.
+
+**Interactions** are advertised by objects (BDS content): a verb, an interaction point and a short step list
+in the RimWorld toil shape (go to, face, reach, grip, pose, wait, release). Lodur runs the steps; BDS authors
+them.
+
+**Grafts.** Every motor layer writes per joint, so a wired brain's authority is a per-joint mask; two brains on
+one joint contest by will. Nothing in the cuts below may write a body-wide output that a mask could not split.
+
+## Authority map
+
+- Owner of what the puppet perceives: `Perception` (the game supplies emitters; Lodur decides what is sensed
+ and remembered). Owner of what is real to him: the same; phantom-ness is not an input the Brain reads.
+- Owner of which goal and which target: `Brain` data, committed by the `Actor`.
+- Owner of how a goal is reached: the planner, reading percept facts and advertised verbs to the depth the
+ intelligence stat gives it. The plan belongs to the decision: written by the Select that chooses or re-chooses the
+ pair (or by its refusal), carried with it, checked on carried ticks; Select never reads it; nothing outside the Actor writes it.
+- Owner of the four mind stats' current values: physiology, from character base and live afflictions. Brain,
+ planner and Perception read them; a potion, a session or BDS never writes a depth, a latency or a memory time.
+- Owner of motion: the will mix over voluntary layers; reflexes act against it.
+- Forbidden writers: the game writing a phantom (top-bit id), a Brain reading phantom-ness, BDS setting a goal
+ or target from outside, any layer writing a joint or force (`body-one-interface`), a kinematic root move,
+ the planner reading phantom-ness or a kind's meaning, BDS handing Lodur a plan or a depth.
+- Derived: salience, the target slot, the thought-bubble type (from the phantoms in memory), desired velocity,
+ the plan, the mind stats.
+- Shared paths: a phantom and a real thing go through the same `Sense`; a scenario Brain and a sandbox Brain
+ are the same data; a player-placed lure and an arena's lure are the same object content.
+
+## Cut order
+
+| # | Cut | Repo | Builds | Waits on | Size |
+|---|---|---|---|---|---|
+| 1 | `lodur-percepts` | Lodur | emitter id and kind, percept memory, phantom id bit | none | S, specced |
+| 2 | `brain-goal-targets` | Lodur | target filters, (goal, percept) utility, commitment | 1 | M |
+| 2b | `lodur-goal-planner` | Lodur | percept facts, verbs with needs and gives, depth-limited regressive planner (core, no caller) | 2 | M, specced |
+| 2c | `lodur-planner-moves`, `lodur-planner-select` (built), `lodur-planner-frustration` | Lodur | the move rule and a budget per Plan call; wants, the Select gate, direct tries at a discount (`bds-unplannable-tries-direct`), one think budget per Select, the plan on the Actor; the frustration that ends a futile direct try | 2b | S, M, S |
+| 3 | `lodur-ik-goals` | Lodur | Look, ArmL, ArmR as a Core producer of joint targets (legs later) | none (parallel to 2) | M |
+| 3b | `lodur-reach-path` | Lodur | hand path through a clearance via point when blocked; arm hand-off slewed both ways | 3, 4 | M, landed |
+| 3c | `ymir-world-gravity`, then `lodur-gravity-feedforward` | Ymir, Lodur (+ BDS content) | the world reports its gravity; muscles carry their subtree's weight times strength | Q `gravity-feedforward-scope` | S, M |
+| 3d | `ymir-touching-pairs`, then `lodur-gravity-subtree-support`, then `bds-gravity-feedforward-content` | Ymir, Lodur, BDS | the world publishes each step's touching pairs (ABI 20); only a touch outside a joint's subtree supports it (facts 32-33); the chamber re-authored against it (fact 34); Lodur and BDS land in one sitting | 3c | S, S, S |
+| 4 | `lodur-orient-goals` | Lodur + BDS | look, reach, ward off and recoil as layers; fetal (a key-pose goal) and stare-at-hands (Look and Reach on a phantom) are data; seated Fella demo | 2, 3 | M |
+| 5 | `lodur-phantom-percepts` + `bds-thought-bubble` | Lodur, BDS | phantom things by hallucination type; the bubble reads their kinds | 1, 4 | M, S |
+| 6 | `lodur-assist-pin` | Lodur | upright assist | none | S |
+| 7 | `lodur-stand` | Lodur + BDS | standing puppet scene, stool weld dropped | 6 | S |
+| 8 | `lodur-walk-gait` | Lodur | Rosen walk, leg IK | 3, 7 | M |
+| 9 | `lodur-steering` | Lodur | approach, avoid, arrive into desired velocity | 2, 8 | M |
+| 10 | `lodur-grip`, then `lodur-interaction-steps` | Lodur + BDS | a verb's toil steps run the plan's current step | 2b, 9, Q `bds-sandbox-lures` | M each |
+| 11 | `lodur-mind-stats` | Lodur | intelligence, quickness, judgment, memory as derived stats; potions drive them | 2b, `lodur-physiology-core` | S-M |
+
+Cut 1 is `lodur:cut_spec:cut-lodur-percepts.r1` (landed). Cuts 2 and 3 are
+`lodur:cut_spec:cut-brain-goal-targets.r1` and `lodur:cut_spec:cut-lodur-ik-goals.r1`; they touch disjoint files.
+The rest are follow-ups. `brain-goal-targets.r1` stands unchanged under the planner: its (goal, target) pair is the
+planner's unit, F.E.A.R.'s split of target selection from planning; cut 2b adds one admission gate and one
+consideration input to its Select.
+
+**IK rationale (pass `goal-targets-ik-map`, research `ik-prior-art`).** IK is a producer of joint targets in
+Lodur.Core, as Final IK feeds PuppetMaster's target pose, not a solver in the binding: the binding stays the
+muscle layer and the will mix and graft mask see IK like any other layer. Arms are two-bone with a hinge elbow,
+so the analytic solve is exact; FABRIK and CCD wait for graft chains that are not two-bone. The elbow swivel is
+the one needing no shoulder twist, because the shoulder's twist muscle tracks a twist weakly (fact 7); what this
+gives up is an authored elbow direction. Where that swivel leaves the cone, the swivel is the nearest one inside
+the cone and the twist limits, the feasible swivel range of Tolani, Goswami and Badler (2000) (fact 8). When no
+swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus twist past its range) is
+least, with swing and twist clamped to the limits: at the edge of the feasible set that is the last feasible swivel,
+so a goal crossing the edge moves the targets continuously (the zero-twist clamp it replaces jumped 1.4 rad there).
+That choice is stateless, and mirrored swivels tie under it (at the shoulder's sagittal plane, unreached or reached),
+so it must jump somewhere on the tie set. Ruling `ik-swivel-temporal-coherence` makes each `ArmChain` the arm's solver
+across ticks: it holds the previous swivel's basin, takes the stateless choice only when that is better by
+`BasinMargin` (less violation, or less twist when both are feasible), and turns the swivel no faster than
+`SwivelRate`; the first solve after construction or `Reset` is stateless. Both constants are placeholders. What it
+gives up: IK is no longer a pure function of the goal. Near a half-turn swing the swing-twist split in the clamp is
+singular, so the clamped solution can still jump; ruling `ik-output-slew-limit` covers it at the output: the returned
+shoulder and elbow targets move toward the solution no faster than `MaxAngularRate` (a placeholder near human peak
+arm speed), everywhere, and the singular-band special case is deleted. What that gives up: a leaping goal is followed
+at the rate, not at once. The slew holds across the hand-off too (cut `lodur-reach-path`, fact 27): an arm that engages
+slews from the base pose, one the layer stops driving slews back to it, and `OrientRig.Compose` runs on every tick of an
+Actor with a rig, so the arm layer's own contribution to the written arm targets moves at most `MaxAngularRate` times the tick across engage
+and disengage while the base pose is constant. A goal switch to a different key pose steps the base itself, and the written arm targets
+with it by the base difference (0.2-0.4 rad measured at weights 0.2-0.5), as every other joint's target steps by its key difference;
+that step is not slewed. Reach under gravity
+lands short by PD sag (facts 9, 23); that is follow-up `lodur-gravity-feedforward`.
+
+**Reach rationale (pass `reach-tracking-map`, ruling `reach-clears-body-by-via-point`).** One owner of an arm's motion
+across ticks: `ArmChain` holds the held swivel, the slewed output and now the hand path and the hand-off state, so a
+teleport's `Reset` forgets all of it at once. The path is minimum-jerk (Flash and Hogan 1985) in the arm parent's creation
+frame, where the chain already solves; it starts at the measured wrist when the arm engages or the Actor commits a (goal,
+target) pair, and it is taken only when the straight wrist segment is blocked by the trunk (fact 25). An unblocked reach
+solves the goal directly each tick, slewed (ruling `reach-path-blocked-only`; a path there ends further off, fact 26;
+it gives up the bell-shaped hand speed of an unobstructed human reach). The via point sits ahead of the wrist's own side,
+not of the midpoint (`ArmChain.ViaClearance` 0.2 m and `PathSegmentSeconds` 0.3 s are placeholders; blocked is decided once per
+path start, against the trunk bounds the chain derives from the arm's parent part and its ancestors): the arm comes forward first, then across, as a person reaching across their body does. Gravity is a
+muscle-layer term, not a reach-layer correction (fact 23): computed-torque practice (PD plus gravity compensation,
+Takegaki and Arimoto 1981; Coros et al. 2010 for simulated characters) puts it in the torque, scaled here by strength so a
+failing will still sags; a task-space loop on the target was unstable (fact 9) and fights a weak will. PuppetMaster's
+alternative, pin forces pulling bodies to the target pose, is an external force and breaks `body-one-interface`.
+
+**Goal-target rationale.** A target is tracked by percept Id (fact 11), selection scores (goal, percept) pairs,
+and a retarget inside the goal waits the deliberate latency but not the dwell, held only by the commitment
+multiplier. No `TargetChanged` event: nothing reads one.
+
+**Planner rationale (pass `goal-planner-map`).** The ruling makes intelligence the lookahead, and utility
+selection has none, so a planner exists. Regression over verbs (F.E.A.R.) is taken because its depth is plan
+length, the ruling's own words, and because it visits about a tenth of forward search's nodes at depth 4
+(fact 13). HTN is not taken: its depth is authored decomposition, so lowering it breaks methods rather than
+dulling the puppet. MCTS is not taken: it needs a forward simulator and is stochastic per decision. What this
+gives up: verbs now need preconditions and effects authored as facts (the cost the first pass named), a failed
+plan has to be read by a debug view of the plan, and facts on emitters widen the game's interface to Lodur by
+one field.
+
+**Planner cut rationale (pass `goal-planner-cut`).** Facts are one `ulong` per thing, the game's bits; bit 63 is
+Lodur's in-reach, derived per call from the sense point and the percept's position and refused from the game, as
+`PhantomIdBit` is (idea `goal-planner-cut.rejected-reach-as-game-fact`: a game-supplied near goes stale as soon as
+he moves; what it gives up is one bit). Verbs are the world's list, given to the planner, not each Brain's
+(`rejected-verbs-on-brain`, ruling `bds-lures-tagged-props`). Verbs carry only needs and gives now; the interaction
+point and toil steps join the same record in `lodur-interaction-steps`, which waits on locomotion
+(`rejected-interaction-steps-first`). Plan steps name percept ids, not slots. A verb that gives its This in-reach is a move
+(no Verb field marks it; the give is the mark): after it every other thing is in reach exactly when it is within reach
+of that This, by the percepts' remembered positions, so a plan cannot hold two far things in reach (finding
+`reach-is-monotone`). A carried thing is reached through a game fact, not reach, so a give of in-reach on a Tool or a
+false one is a plain literal. A Plan call takes a budget, defaulting to `NodeBudget`, and `LastExhausted` says it spent
+it; a spent budget drops legitimate plans (finding `budget-drops-legit-plans`), and not worked out is tried direct
+(ruling `bds-unplannable-tries-direct`).
+Intelligence 0 is read as: want goals go direct at the discount and still end in frustration, and every Brain
+without wants selects exactly as `brain-goal-targets` (idea `depth-zero-is-direct-with-frustration`, in force for
+the part-2 mapper).
+
+**Planner-select rationale (pass `planner-select-cut`).** Cut 2c is three cuts: `lodur-planner-moves` (Planner only:
+a This give of in-reach is a move, so after it another thing is in reach only if near the move's target; a budget per
+Plan call and `LastExhausted`), `lodur-planner-select` (wants, the gate, the plan on the Actor) and follow-up
+`lodur-planner-frustration`. The gate: a satisfied want is not offered; a planned pair scores through `PlanSteps`; an
+unplanned or not-worked-out pair is tried direct at `DirectDiscount`, reading `PlanSteps` at depth + 1 so a futile try
+never outranks an equal pair he can plan. Pairs are planned by deepening across them (round k, a bound per pair, a round
+ends when no bound can win; with an unbounded budget this chooses exactly as planning every pair), so a pair that no plan
+reaches cannot spend the budget before a cheap plan is found; fact 31 measures best raw first starving at 59 of 100
+decisions at depth 6 and deepening at 0. One `ThinkBudget` per Select bounds cost (fact 22) at the price of 4-7% of choices in crowds at depth 5 and up (fact 21), and 0-2% in fact 31's room:
+question `bds-think-budget-per-decision` (Deru). With no pair offered, the goal in force stays and lets go of its
+target (finding `stale-target-without-pair`); the orient layers then rest. The pair's plan is made with the decision (the
+Select that chose it, or re-chose it, or was refused and plans the pair in force) and carried; it is not derived each tick, which cost a
+second Plan call per tick (fact 31).
+
+## Mind stats
+
+`lodur:ruling:bds-intelligence-is-planning-depth` answers the withdrawn `bds-intelligence-in-goal-ai`: four
+stats, not one scalar. Follow-up `lodur-mind-stats` holds them (see Target shape).
diff --git a/docs/lodur-target.md b/docs/lodur-target.md
index 06a5381..508413f 100644
--- a/docs/lodur-target.md
+++ b/docs/lodur-target.md
@@ -1,123 +1,190 @@
# Lodur: target
-Campaign `lodur`. The operator's rulings live in the eureka-state mind under
-root `motion-pipeline` (the workshop ran there); this document holds the
-rationale and the design truths the campaign will produce. Where it and a
+Campaign `lodur`. The operator's rulings live in Nibu's mind under roots `lodur` and `motion-pipeline` (the
+workshop ran under `motion-pipeline`; some of those show as moved in Eureka's mind, and Nibu's copies are the
+ones in force). This document holds the rationale and the design truths the campaign produces. Where it and a
ruling disagree, the ruling wins and this file is stale.
## What it is for
-A character that reacts to forces and stimuli, and compensates for injury,
-the way a person would: it pulls back from something hot, jumps when poked,
-and crawls toward its objective on one leg if it wants that objective badly
-enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
+A character that reacts to forces and stimuli, and compensates for injury, the way a person would: it pulls
+back from something hot, jumps when poked, and crawls toward its objective on one leg if it wants that
+objective badly enough. (`motion-pipeline:ruling:euphoria-stimulus-and-impairment`.)
-The field has the physics and the balance. NaturalMotion's Euphoria shipped
-active, physically simulated characters in GTA IV through Red Dead Redemption
-2, and learned trackers (DReCon, ProtoMotions, MaskedMimic) follow arbitrary
-motion while keeping their feet. What the field does not have, per the prior-art
-pass, is the nervous system on top: senses that are not forces, reflexes layered
-under deliberate behaviour with their own latencies, and a character whose will
-competes with its pain. Euphoria's reactions are whole-body behaviours a game
-starts; nothing in the record senses heat or a light touch, and nothing models
-the twenty seconds in which a wounded character crawls, slows, and passes out.
-That layer is Lodur. Evidence: `gamecult-ops/docs/research/euphoria-at-home-prior-art.md`
-(sections 1-9 at `8320c18`, section 10 at `15d9a4e`).
+The field has the physics and the balance. NaturalMotion's Euphoria shipped active, physically simulated
+characters in GTA IV through Red Dead Redemption 2, and learned trackers (DReCon, ProtoMotions, MaskedMimic)
+follow arbitrary motion while keeping their feet. What the field does not have, per the prior-art pass, is the
+nervous system on top: senses that are not forces, reflexes layered under deliberate behaviour with their own
+latencies, and a character whose will competes with its pain. That layer is Lodur. Evidence:
+`gamecult-ops/docs/research/euphoria-at-home-prior-art.md` (sections 1-9 at `8320c18`, section 10 at
+`15d9a4e`).
-Named after the god in Voluspa who gives the first humans blood, warmth and
-good colour (`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
+Named after the god in Voluspa who gives the first humans blood, warmth and good colour
+(`motion-pipeline:ruling:euphoria-middleware-named-lodur`).
## Layers
-Signal flows one way per tick; each layer has one owner.
+Signal flows one way per tick, in this order; each layer has one owner. Layers 1-4 are `Lodur.Core`
+(`netstandard2.1`, no references); layer 5 is a body binding.
-1. **Perception.** Contacts, impulses, temperature, proximity and named game
- stimuli become typed stimuli on body regions. A poke that barely moves the
- body is still a stimulus.
-2. **Reflex.** Fast, local responses to stimuli (withdrawal, startle,
- bracing), each with a latency, overlaid on whatever the body is doing.
- Their gain is set from above by the drive, the way descending pathways
- modulate spinal reflexes: the Gom Jabbar case. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary
- reaction about 200 ms (figures `[M]` in the research doc; verify before
- they become constants).
-3. **Drive.** Per-character state that evolves every tick: pain accumulates
- and decays, shock runs on a clock that blood loss speeds, adrenaline spikes
- on threat and fades; resolve is a trait, and the objective pulls. Static
- per-character values are this state with its dynamics frozen.
- (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
-4. **Behaviour.** The drive selects and weights behaviours (writhe, crawl to
- the objective, pass out, get up, the reflex overlay) that emit targets.
-5. **Body.** Follows targets (poses, IK goals) with per-muscle strength on the
- host engine's articulated physics. v1 is GameCult's own PD-tracking active
- ragdoll and ships the ground behaviours; v2 is a small learned tracker
- (DReCon scale: 340 us per character per frame measured, 60 us of it the
- policy) for upright states, behind the same interface.
- (`motion-pipeline:ruling:euphoria-body-layer-order`.)
+1. **Perception** (`Perception`, `NerveParameters`, `BoxStimulus`, `Emitter`). Contacts, impulses, temperature,
+ proximity and named game stimuli become typed signals on body regions. Input: one point per body region
+ (from the body binding, read-only) and the game's stimulus sources. Two source kinds today: noxious box
+ volumes with an intensity the game writes each tick, and point emitters on the audio, visual and interrupt
+ channels (position, radius and intensity written each tick, falling off linearly to the radius), sensed at
+ one region and combined into one load, `1 - prod(1 - afferent)`. An emitter may carry an `Id` (the game's
+ stable id; 0 is anonymous and only loads the nerve) and a `Kind` (the game's tag, never interpreted by Lodur).
+ Perception keeps a bounded percept memory (`PerceptParameters`, `Percept`): one slot per identified thing
+ strictly inside an emitter's radius, with its kind, the position of the emitter that reached it hardest,
+ salience (that reach times the sensory gain) and seconds since sensed, forgotten after a memory time. The top
+ id bit (`PhantomIdBit`) is reserved to Lodur's phantoms and `Sense` refuses it from the game. Percepts also remember the thing's `Facts`
+ (a `ulong`, bit i is fact i) as last sensed; the game owns every bit but 63 (`InReachFact`), which is Lodur's and which `Sense` refuses, like `PhantomIdBit`. Output per region: the stimulus, and
+ the afferent signal after threshold, sensitisation and conduction delay; and the load, and the percepts. A poke that barely moves the body
+ is still a stimulus.
+2. **Reflex** (`WithdrawalReflex`, `WithdrawalParameters`). Fast, local responses to afferent signals
+ (withdrawal now; startle and bracing later), each with a latency, overlaid on whatever the body is doing.
+ Each reflex's gain is set ahead of time by the drive, the way descending pathways modulate spinal reflexes
+ (the Gom Jabbar case): a reflex reads the drive state of the previous tick, never waits for behaviour.
+ Output: the reflex command that leaks past suppression, the strain load of holding the rest down, and
+ flinch events. Physiology sets the scale: withdrawal roughly 60-150 ms, voluntary reaction about 200 ms
+ (figures `[M]` in the research doc; verify before they become constants).
+3. **Drive** (`DriveState`, `DriveParameters`). Per-character state that evolves every tick: pain from
+ afferent input, strain from suppressed reflexes, arousal from sensory load; resolve drained by all three and
+ scaled by the active goal's pull, recovering only when pain and arousal are both low;
+ later shock on a clock that blood loss speeds and adrenaline that spikes on threat. Resolve reaching zero
+ breaks the will, which releases every suppression; the break is an event that counts (`Breaks`) and recurs:
+ the will mends when resolve climbs back to `WillMendsAt`. `Will` is what is available to hold a reflex down
+ and to power a voluntary layer: resolve times `Attention`, capped by `Consciousness` (both slots that read 1
+ until startle and physiology fill them). Static per-character values are this state with its
+ dynamics frozen. (`motion-pipeline:ruling:euphoria-drive-is-dynamic-state`.)
+4. **The Brain.** The consumer's authored goals (a behaviour, a priority, a pull in [0, 1] that defaults to 0, no pull (the former objective pull
+ defaulted to 0.5), an optional minimum dwell, conditions over the drive
+ state), selected after a deliberate latency: the eligible goal of highest priority is wanted, and the
+ Actor commits it. Lodur has no flip rule of its own; every rule is Brain data
+ (`lodur:ruling:npc-brain-authors-goals`). One behaviour, `PoseBehaviour`: a pose held or a loop of pose keys,
+ blended toward a flinch pose by the reflex leak and shaking with strain, emitting targets and per-muscle
+ strength into caller-owned arrays and nothing else. Commitment is soft: a goal with a minimum dwell, counted
+ in ticks from the tick it took over, is left for a goal that ties or ranks below it only once the dwell has
+ passed, while a strictly higher-priority goal preempts during the dwell (after the deliberate latency); the
+ return trip from an entered goal is gated by that goal's own dwell, which is what bounds chatter at a threshold.
+ A goal also carries an entry effect on the drive (`EntryResolve`: the tick it takes over, resolve is set, which
+ is how rage resets the will), an `Effort` (resolve drained per second to sustain it) and `InvoluntarySeconds`
+ (an onset that runs without will and without paying the effort; +infinity is involuntary throughout)
+ (`lodur:ruling:rage-involuntary-onset-then-voluntary`). The will mix: a voluntary goal writes each muscle at
+ `HoldStrength x min(1, Will^WillCurve + leak x FlinchGain)` (the Actor passes `Will^WillCurve` as the weight), an involuntary one at `HoldStrength`, so a failing
+ will slackens the layer while a reflex that gets past it still moves the muscle
+ (`lodur:ruling:bds-sandbox-arenas-will-economy`).
+ A goal can also carry a sensory gain and an arousal target (`SensoryGain`, `EntryArousal`), reached linearly over `EntrySeconds`
+ from their values at takeover (0, the default, is at the takeover tick; the Start goal's apply at construction). The gain multiplies the sense
+ channels' afferents as they leave the conduction delay, so sensitisation still follows the world; `Load` is built from the gated afferents and
+ `ChannelStimulus` stays the world's. Sense reads the gain at the start of each tick, so a change of gain reaches `Load` one tick after the Actor sets it;
+ the ramp's last tick assigns the targets exactly. The nociceptive region afferents, the withdrawal reflex and its flinch are never gated. The Actor owns the gain
+ in force (`DriveState.SensoryGain`) and, through the ramp, arousal; after it the drive owns arousal again. Calm uses it to silence the office's
+ stressors and drain the stress bar, tailing off over a few seconds rather than cutting
+ (`lodur:ruling:stress-bar-shows-arousal-calm-silences`, `lodur:ruling:flinch-tail-after-stimulus`).
+ A built Brain owns copies of its data and reads back as read-only views. Considerations extend it.
+5. **Body.** Follows targets with per-muscle strength in the game's physics world. v1 is GameCult's own
+ PD-tracking active ragdoll on **Ymir**, GameCult's boundary around a pinned Box3D, read and driven through
+ Ymir's structure-of-arrays world in place (`lodur:ruling:lodur-body-on-ymir`): `Lodur.Body.Ymir`. It owns
+ the puppet's shapes, joints and gains and reports body-region points upward to perception. v2 is a small
+ learned tracker for upright states (DReCon scale: 340 us per character per frame measured, 60 us of it the
+ policy) behind the same interface. (`motion-pipeline:ruling:euphoria-body-layer-order`.)
-Layers 1-4 are the core: C# with no engine references, testable without an
-engine. Layer 5 binds to the host: Unity `ArticulationBody` first; v2 inference
-through the engine's runner (Unity Inference Engine, ONNX Runtime).
-(`motion-pipeline:ruling:euphoria-first-consumer-sandbox-csharp-core`.)
+`Actor` runs layers 1-4 for one character in that order once per physics step, from caller-owned inputs into
+caller-owned outputs, and reports its events (flinch, will broke, goal changed, died) as flags.
+
+### Who writes what, per tick
+
+One order inside `Actor.Tick`: the Physiology steps and writes Consciousness (an actor with a physiology; a dead one
+goes limp and ends the tick) → Perception senses (with the sensory gain in force) → each reflex steps on its
+afferent (gain from the previous tick's drive) → the drive steps (pain, strain, arousal, resolve, the break and
+the mend; the goal's effort is paid here) → the Brain decides (a decision is pending for the deliberate latency)
+and a due decision commits (entry resolve is set) → the entry ramp assigns gain and arousal → the goal's
+behaviour writes strengths and targets at the will's weight (the key pose, then the orient layers (recoil, look, arms) toward the committed target from the caller's part poses, then the flinch blend over every joint), and the strengths are scaled by the motor ceiling. The tick that
+commits a goal already writes under it.
+
+| Owner | Inputs | Outputs | Derived state | Forbidden writers |
+|---|---|---|---|---|
+| `Perception` | region points, the game's stimulus sources and emitters, the sensory gain passed in | per-region stimulus and afferent, per-channel stimulus and afferent, `Load`, the percept slots | sensitisation, the conduction rings, percept salience and slot occupancy; the channel afferents are gated, the stimuli are not | the drive or a goal writing an afferent; the game setting `PhantomIdBit` (`Sense` refuses it); the Brain or a session writing a percept; a gain outside [0, 1] (`Sense` refuses it, NaN and infinity included); gating a region (nociceptive) afferent |
+| Reflex (`WithdrawalReflex`) | its region's afferent and the drive's `Will` (the pull acts through resolve's drain, not here) | leak, strain load, flinch | none beyond its latency ring | the Brain or the behaviour setting a reflex gain |
+| Drive (`DriveState`) | afferent sum, strain load, `Load`, the goal's pull and effort | pain, strain, arousal, resolve, `Breaks`, `Will` (= min(resolve x attention, consciousness)), the break and mend events | `Will` is derived and never stored; the break recurs (it mends at `WillMendsAt`) | the Brain, a session or the body writing resolve, arousal or `Will`; the one sanctioned jumps are `Enter` (a goal's entry resolve) and the Actor's entry ramp (arousal) |
+| Attention slot | nothing yet: reads 1 (startle is the writer to come) | a factor of `Will` | none | anything but the startle reflex (`lodur-startle-attention`); the Actor's test seam `SetAttention` is internal |
+| Consciousness slot | `Physiology.Consciousness`, written by the Actor each tick; 1 for an actor with no physiology | the cap of `Will` | derived from the physiology each tick | anything but the Actor reading its Physiology; no test seam: tests lower it through a Physiology |
+| `Physiology` | its `BodyPlan` and `PhysiologyPlan` (tissue stacks, joined to the `BodyPlan` by `PhysiologyPlan.Resolve`, the one (label, side) join; a stack also carries thickness and sheet material that Physiology does not read; afflictions with data effects, blood) at construction; `Afflict` (the one entry for harm); `Step(dt)` from the Actor; the slow scale at construction | capacities (`Consciousness`, `BloodPumping`), `Bleed` per part, `BloodVolume` and `BloodLoss`, `MotorCeiling` per joint, `Integrity` per tissue, `Dead`, `Cause`, `Refused` | integrity (from Injures afflictions: part HP is never stored), capacities, bleed and the ceiling, recomputed each step; death is judged once at the end of a step (vital tissue, blood loss, consciousness: `lodur:ruling:bds-death`) and is permanent | anything else writing tissue, blood or the slot; a game writing integrity, volume or severity (harm enters through `Afflict`); an effect writing state; an affliction killing by its own severity; tissue, organ or affliction labels outside content (`PhysiologyPlans`) |
+| Brain (`Brain`, `GoalSpec`) | the drive state it reads through conditions | the wanted goal; each goal's pull, priority, dwell, entry effects (`EntryResolve`, `EntryArousal`, `SensoryGain`, `EntrySeconds`), `Effort`, `InvoluntarySeconds` and behaviour | none: it is data, copied at build and read back read-only | a flip rule anywhere else (`lodur:ruling:npc-brain-authors-goals`) |
+| `Actor` | all of the above, one tick | the committed goal; `DriveState.SensoryGain`; arousal during a goal's `EntrySeconds`; the events | the pending decision and its tick, the dwell, the ramp's start values, the onset in whole ticks | a consumer setting the goal or the gain from outside |
+| Behaviour (`PoseBehaviour`) | the weight (the will's `Will^WillCurve` once the goal's involuntary onset is over, else 1), the leak, strain, time | strengths and targets into caller arrays: `HoldStrength x min(1, weight + leak x FlinchGain)` | none | writing a joint or a force (`body-one-interface`); any strength not under the will mix |
+| Orient layers (`LookLayer`, `ArmLayer`, `RecoilLayer` on the goal's `PoseBehaviour`; solved by the Actor's `OrientRig`) | the committed target (`Actor.Target`), the caller's part poses (`Ragdoll.ReadPartPoses`), the `BodyPlan` at construction | joint targets only: the neck, the shoulders and elbows, and the recoil poses' joints, blended in before the flinch | the Nearer arm side, set when a (goal, target) pair commits and held until the next commit; layer targets are recomputed each tick and never stored | a layer writing strength; the game solving IK around the Actor or overwriting targets after `Tick`; IK in the Ymir binding; a layer reading `PhantomIdBit`; a mid-pair arm-side flip; an arm the closed form cannot solve (bent at creation, an elbow range straddling zero) is refused at construction, naming the goal and side |
+| `Planner` | percept facts and positions, self facts, the verb list (`Verb`: kind filters, needs, gives), a depth, the reach | `Plan`'s length (0 holds, n steps, -1 none within depth or within the 4096-grounding `NodeBudget`, a counter) and the steps as (verb index, This id, Tool id) in the caller's buffer | reach (bit 63) from distance, per call; the plan, per call | reading phantom-ness or a kind's or fact's meaning; storing a plan; the game supplying bit 63; allocating after construction |
## Invariants
-- `core-engine-free`: the core assemblies reference no engine. A Unity type in
- the core is a defect, not a convenience.
-- `body-one-interface`: the body consumes only targets and per-muscle strength.
- Drive, behaviour and reflex never set a joint, force or physics property
- directly; swapping the PD ragdoll for a learned tracker changes no layer above.
-- `one-physics-world`: the body simulates in the host's physics world. No
- second world that the game's objects cannot touch.
-- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and
- overlays the running behaviour; it never waits for behaviour selection. Will
- acts on reflexes ahead of time, not after: drive state (resolve, the pull of
- the objective) sets each reflex's gain, so a resolved character can hold its
- hand in the box. Suppression is never free: the stimulus still feeds pain,
- and holding a reflex down shows as visible strain until resolve breaks.
- Deliberate behaviour takes over a fired reflex only after its own, longer
- latency. (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
-- `drive-is-state`: what a hurt character does is decided by drive state
- evolving over time, never by a per-wound lookup.
-- `bounded-tick`: per-character work per tick is bounded and allocates nothing
- in steady state. A middleware that hitches is unusable in a game.
-- `content-is-cultcache`: persistent content (puppet and object definitions,
- drive parameters, saved levels in Bad Day Simulator) is CultCache, per the
- GameCult substrate doctrine. JSON is schema publication only.
+- `core-engine-free`: the core assemblies reference no engine and no physics. A Unity or Ymir type in the
+ core is a defect, not a convenience. The core's tests build without Ymir.
+- `body-one-interface`: the body consumes only targets and per-muscle strength. Drive, behaviour and reflex
+ never set a joint, force or physics property directly; swapping the PD ragdoll for a learned tracker changes
+ no layer above.
+- `one-physics-world`: the game creates and owns one physics world, Ymir's; Lodur adds its bodies to that
+ world and never creates one of its own. Game objects (a restraint, a box, a thrown chair) act on a puppet
+ through that world.
+- `reflex-gain-from-drive`: a reflex fires on its own shorter latency and overlays the running behaviour; it
+ never waits for behaviour selection. Will acts on reflexes ahead of time, not after: drive state (resolve,
+ the pull of the active goal) sets each reflex's gain, so a resolved character can hold its hand in the box.
+ Suppression is never free: the stimulus still feeds pain, and holding a reflex down shows as visible strain
+ until resolve breaks. Deliberate behaviour takes over a fired reflex only after its own, longer latency.
+ (`motion-pipeline:ruling:lodur-reflexes-suppressible-by-will`.)
+- `drive-is-state`: what a hurt character does is decided by drive state evolving over time, never by a
+ per-wound lookup.
+- `bounded-tick`: per-character work per tick is bounded and allocates nothing in steady state, and the same
+ inputs give the same outputs. A middleware that hitches is unusable in a game.
+- `content-is-cultcache`: persistent content (puppet and object definitions, drive parameters, saved levels
+ in Bad Day Simulator) is CultCache, per the GameCult substrate doctrine. JSON is schema publication only.
+ Parameters that are only code defaults are not yet content.
+- `one-severance-owner`: a part is damaged, disabled or severed only by Lodur's physiology. Ymir reports
+ contacts and joint stress and removes a joint only on command; no physics threshold removes anything by
+ itself.
+- `will-is-the-budget`: every voluntary motor layer (hold, clip, IK reach, look, aim, grip) is weighted by
+ available will (resolve times attention, capped by consciousness); reflexes act against it with their own
+ gains; nothing writes targets outside that mix. A distraction such as a startle lowers attention, and so the
+ will every layer can spend (`lodur:ruling:bds-sandbox-arenas-will-economy`).
+- `sandbox-is-content`: in Bad Day Simulator an arena is a level built from the commands the player has; no
+ engine path exists only for an arena; levels are CultCache.
## First consumer
-Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of
-how People Playground plays, not its camera or UI. The player gets a level and
-places puppets of various sorts and objects with set behaviours and
-interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
-`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) It is a
-separate repo so that Lodur's boundary has a real consumer from the first cut.
+Bad Day Simulator (`GameCult/BadDaySimulator`): a 3D sandbox in the spirit of how People Playground plays,
+not its camera or UI. The player gets a level and places puppets of various sorts and objects with set
+behaviours and interactions. (`motion-pipeline:ruling:euphoria-sandbox-shape`,
+`motion-pipeline:ruling:euphoria-sandbox-named-bad-day-simulator`.) Its one physics world is Ymir's. It is a
+separate repo so that Lodur's boundary has a real consumer from the first cut. Its first item is the pain box,
+the Synaptic Induction Chamber (`lodur:ruling:bds-pain-box-item`,
+`lodur:ruling:bds-pain-box-named-synaptic-induction-chamber`).
## Not in scope
-- Adapting to arbitrary changes of body topology. The operator called it too
- ambitious; impairment is handled through the drive and the behaviour set.
-- A Rust port of the core, until a first consumer outside Unity exists.
+- Adapting to body topology outside the authored part tree (new limbs, re-rooted trees, morphology-agnostic
+ learned control). Losing a subtree of the authored tree is in scope as a closed set of impairment states per
+ limb slot (intact, impaired, disabled, severed), mirror-symmetric; the behaviour set compensates for each
+ (`lodur:ruling:bds-mvp-scope`).
+- Weapons, ballistics, gore and wound presentation: Bad Day Simulator content, not Lodur.
+- A Rust port of the core.
- The StreamPixels overlay as a consumer before StreamPixels M1 ships.
-- Depending on RootMotion PuppetMaster (paid, not redistributable, and no
- balance control: research section 10.1).
-- Hand-tuned balance controllers of the SIMBICON family as the upright path.
+- Depending on RootMotion PuppetMaster (paid, not redistributable, and no balance control: research
+ section 10.1).
+- A hand-tuned balance controller of the SIMBICON family as the upright path. What holds the body up is the PD
+ muscles plus a will-scaled assist (and later a learned tracker). Stepping strategies that only re-plan targets
+ (capture-point foot placement after a shove, stumble, brace, get up) are in scope as behaviours.
-## Open before the first cut is mapped
+## Open
-The identity, lifecycle and authority table (one row per persistent kind) is
-written before any cut; these feed it.
-
-- **Impairment states.** Self's proposal, not ruled: impairment as a closed set
- of named body states (intact, missing a leg, missing an arm, both legs), with
- mirror symmetry; crawling as the first locomotion after any leg loss; one-leg
- hopping a stretch goal.
-- **Rig.** Which humanoid the sandbox ships with, and its licence for a public
- repo. The StreamPixels Little Heroes Mega Pack is a paid asset and cannot be
- committed to a public repo.
-- **Unity version** for Bad Day Simulator, and how Lodur's core is consumed
- (UPM package from the Lodur repo, or a built assembly).
+- **The MVP map** (`docs/bds-mvp-map.md`): systems by owner, authority map, model page and cut order for
+ grab, poke, physiology, dismemberment, will-weighted animation and IK, and sandbox levels.
+- **How Bad Day Simulator consumes Lodur** (`lodur:question:bds-consumes-lodur`).
+- **The pain measure** (`lodur:question:pain-sweep-measure`).
+- **Ymir gaps Lodur needs next**: contact facts, joint stress and removal, a grab anchor and impulses are
+ specced (`lodur:cut_spec:cut-ymir-contact-facts`, `cut-ymir-grab-anchor`, `cut-ymir-break-and-remove`);
+ joint springs for stiff ankles remain (`nibu-body:follow_up:ymir-soa-lodur-needs`).
+- **Renderer**: a Godot client (`lodur:ruling:bds-client-godot`), specced as `lodur:cut_spec:cut-godot-client-v1`.
- **Training host for v2.** Raven trains only when the household's GPU allows
(`motion-pipeline:ruling:raven-gpu-defers-to-household`).
-- **Trademark search** on "Bad Day Simulator" before anything public is
- announced.
+- **Trademark search** on "Bad Day Simulator" before anything public is announced.
diff --git a/docs/notes/motionbricks-fit.md b/docs/notes/motionbricks-fit.md
new file mode 100644
index 0000000..088ea84
--- /dev/null
+++ b/docs/notes/motionbricks-fit.md
@@ -0,0 +1,250 @@
+# MotionBricks fit survey
+
+Question: can NVIDIA MotionBricks (arXiv 2604.24833, `NVlabs/motionbricks`,
+Hugging Face weights) serve as an intent layer for Lodur: characters with
+nervous systems on Ymir, headless, state read as a structure-of-arrays view?
+
+Sources were read on 2026-11-06 at `NVlabs/motionbricks` commit `54fc563`
+(2026-10-23) unless stated. This is a survey; nothing was run. Items not
+established are listed in the last section.
+
+## Verdict
+
+**Optional tier, off by default, never core.** Keep the licence question out of
+the repo (weights are fetched by the user, not committed). Do not adopt now.
+
+- The licence is not the blocker. The NVIDIA Open Model Agreement carries no
+ field-of-use limit and no no-training clause (quoted below). One clause
+ (indemnity) needs a human to rule on it against the always-open-source rule.
+- The runtime is the blocker. The shipped runtime is Python plus TensorRT and
+ needs an NVIDIA GPU. Lodur's core is engine-free C# with a headless,
+ deterministic Ymir world. A CPU ONNX path is documented only as an example
+ snippet; its speed and determinism are unmeasured.
+- The output is a kinematic pose stream on a fixed human skeleton. It does not
+ claim to be physically feasible, which is the right shape for a *target*, and
+ the wrong shape for a body.
+
+Revisit when (a) a CPU ONNX run of the SOMA model is measured, and (b) Lodur has
+a body with a humanoid rig to track poses at all (Ymir's SoA world has spheres
+and static boxes only today).
+
+## 1. Licences
+
+| Part | Licence | Source |
+|---|---|---|
+| Code | Apache-2.0 | README "License" |
+| Docs and media | CC-BY-4.0 | README "License" |
+| Models (SOMA and G1 checkpoints, bundled ONNX) | NVIDIA Open Model Agreement (v. March 9, 2026; release date April 2, 2026) | README; `motionbricks/assets/onnx/LICENSE.md`; SOMA model card |
+| Sample BVH/CSV motions | NVIDIA Sample Data Evaluation License | `assets/motions/LICENSE.txt` |
+| Python runtime's TensorRT wheels | NVIDIA TensorRT Software License Agreement (proprietary, distributed with the packages) | README "License" |
+
+Agreement text: .
+Section numbers did not survive the page; clauses are cited by heading.
+
+### Open Model Agreement, against the questions asked
+
+- **Field of use.** None. The preamble: "Works are commercially usable. You are
+ free to create and distribute Derivative Works. NVIDIA does not claim
+ ownership to any outputs generated using the Works or Derivative Works."
+ No clause restricts a domain or use case.
+- **Training on outputs or on the model.** No clause restricts it. The only
+ termination trigger is: "If You institute patent or copyright litigation
+ against any entity ... alleging that the Work or an output from the Work
+ constitutes direct or contributory patent or copyright infringement, then any
+ licenses granted to You under this License for that Work shall terminate."
+- **Grant.** "a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+ irrevocable license to reproduce, prepare Derivative Works of, publicly
+ display, publicly perform, sublicense, and distribute the Work and such
+ Derivative Works in source or object form." (Irrevocable, subject to the
+ litigation clause above.)
+- **Derivatives.** "Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of, the
+ Work." Lodur calling the model through ONNX is therefore not a Derivative
+ Work of it. Fine-tuned or re-exported weights would be.
+- **Redistribution.** Allowed "with or without modifications, in source or
+ object form" on three conditions: give recipients a copy of the licence;
+ retain copyright, patent, trademark and attribution notices in the source
+ form of distributed Derivative Works; and, "If the Work includes a 'NOTICE'
+ text file", Derivative Works must carry "Licensed by NVIDIA Corporation under
+ the NVIDIA Open Model Agreement." (The repo has no `NOTICE` file at this
+ commit, so the attribution clause has nothing to trigger on in the code
+ repo; the Hugging Face checkpoint repos were not checked.) You may add
+ "additional or different license terms" to your own modifications.
+- **Other terms.** Trademarks not granted. As-is warranty and liability
+ disclaimers. Delaware law, Santa Clara County courts. Export and sanctions
+ compliance.
+- **Indemnity (the clause to rule on).** Under "Accepting Warranty or
+ Additional Liability": "You will indemnify and hold harmless NVIDIA from and
+ against any claim by any third party arising out of or related to your use or
+ distribution of the Works, Derivative Works thereof, or output from the Works
+ or Derivative Works." It sits in a section about offering warranties, but the
+ sentence is not limited to that case on its face. OSI-approved licences do not
+ carry an unconditional user indemnity. Whether that counts against "always
+ open source" is a legal and operator call, not an engineering one.
+
+### Fit with GameCult's always-open-source rule
+
+- Code (Apache-2.0): compatible.
+- Weights: permissive, redistributable and sublicensable, no field-of-use
+ limit. This is not an OSI licence and the indemnity sentence is unusual, so
+ "compatible" is not established until someone rules on it.
+- Cleanest posture, if ever adopted: Lodur's repo contains no weights. The
+ tier is a documented optional download that the user fetches themselves
+ under NVIDIA's terms. Lodur's own code stays open and separable (the
+ Derivative Works carve-out above). Do not commit the sample motions: they
+ are internal evaluation only and may not be redistributed.
+- Not a lawyer's reading. Nothing here is legal advice.
+
+## 2. Training data
+
+- Trained on Bones RigPlay 1 (RP1): 313,526 clips selected from about 350,000
+ clips / 700 hours, a 4,881-clip validation subset disjoint from training
+ (SOMA model card, "Training Dataset", "Testing Dataset").
+- Captured by Bones in a studio ("Automatic/Sensors"), processed by NVIDIA into
+ the 30-joint SOMA skeleton at 30 Hz. The corpus is not distributed with the
+ model: "Access to the dataset is governed separately from the model weights."
+- Bones' own page () describes RP01 as
+ "Enterprise-grade · IP-clean · Ready to license" and "full IP clearance",
+ optical Vicon mocap at 120 fps, 170+ performers. That is a commercial
+ product. **No public RP1 licence text was found**, so the terms binding
+ NVIDIA's weights to RP1 are unread.
+- The separate BONES-SEED dataset (HF `bones-studio/seed`, gated, licence at
+ ) is a different licence from RP1 and
+ is not what the weights were trained on, so it does not bind Lodur. It
+ matters only if Lodur wanted to fine-tune on it: SEED is restricted to
+ "Academic User" or "Qualifying Startup" (under $1,000,000 gross revenue),
+ forbids public mirrors, and forbids using it "to train, fine-tune, or
+ condition any generative model whose primary purpose ... is to generate
+ motion capture data", which excludes fine-tuning MotionBricks on it. (Models
+ that "consume the Dataset ... and produce non-data outputs", such as
+ control policies, are expressly allowed.) Closed data, so it fails the
+ open-source rule for anything Lodur ships.
+- The model's outputs are motion, not recordings; the model card says nothing
+ on whether generated motion can reproduce training clips. Unverified.
+
+## 3. Runtime
+
+- **Official runtime**: Python on NVIDIA Warp, Newton (viewer and scene) and
+ TensorRT. README: "The runtime uses TensorRT, which requires an NVIDIA GPU."
+ Tested on Windows and Linux x86-64 with an RTX 4090 only. `runtime_api.md`:
+ "Engines need a CUDA device." The first launch of each model builds a
+ TensorRT plan, which takes minutes, cached in `.trt-cache/`.
+- **Headless**: `runtime_api.md` ships "two short scripts in `examples` that
+ call the library without a viewer or the apps". Headless in the sense of
+ no window: yes by the doc. Headless in the sense of no GPU: no.
+- **Model**: SOMA is about 200M parameters (VQ-VAE 23.4M, pose predictor
+ 136.5M, root predictor 40.4M), ONNX opset 17, FP32 and mixed FP16 files,
+ variable batch N. Interface (`onnx_inference.md`): inputs `global_root_values`
+ [N,8,5], `local_root_values` [N,8,4], `local_poses` [N,8,267], three int32
+ masks [N,8] and `allowed_pred_num_tokens` [N,11]; outputs
+ `pred_global_motions` [N,64,366] and `pred_num_tokens` [N]. Files use Git LFS.
+- **Latency** (`onnx_inference.md`, TensorRT plan alone, RTX 4090, Windows,
+ inputs already on the GPU): SOMA FP32 2.50 ms at N=1 and 5.28 ms at N=32
+ (6,063 requests/s); mixed FP16 1.28 ms at N=1 and 3.93 ms at N=32. Input
+ preparation, decoding and endpoint correction are excluded. The 15,000 FPS /
+ 2 ms figures in the paper abstract are consistent with this. Starfire's GTX
+ 1070 (8 GB, shared) has no tensor-core FP16 path and is untested.
+- **CPU path**: `onnx_inference.md` shows an `onnxruntime` session with
+ `providers=["CPUExecutionProvider"]`, but the example loads the G1 model, not
+ SOMA. The SOMA card says "A CPU-versus-GPU inference comparison is not
+ provided." CPU speed for a 200M-parameter model is unmeasured here.
+- **ONNX leaves work undone**: the ONNX output "includes the boundary frames
+ and has no endpoint correction. The SOMA and G1 engines remove the boundary
+ frames and apply endpoint correction." The SOMA engine also decodes the
+ foot contacts packed in the output, and finds the model's 30 joints from the
+ input rig. A C# consumer would reimplement all of that against Python
+ reference code. Real cost, not estimated.
+- **Determinism**: not documented. The card warns "Mixed FP16 and FP32 can
+ produce different motion ... Differences can accumulate when generated
+ motion is fed back." Ymir's own stance is byte-equal lanes on the same
+ build, not across CPUs. A model whose output differs across precision and
+ backend, and which is fed its own output, cannot be replayed from a
+ command stream unless its outputs are recorded. Whether the graph itself is
+ free of sampling randomness is unverified.
+- **Platforms**: Windows and Linux x86-64 only; no macOS or ARM claim.
+
+## 4. Pose format and skeleton
+
+SOMA card ("Model Space", "Inference"):
+
+- 30-joint SOMA skeleton, 30 Hz, Y-up, metres. One output frame is 366 floats:
+ root position and heading (5), joint positions (87), 6D rotations (180),
+ joint velocities (90), foot contacts (4). 6D means the first two columns of
+ a rotation matrix.
+- One generation returns 18 to 58 valid frames (the ONNX tensor carries 24 to
+ 64 raw frames, between boundary frames), conditioned on 4 context poses and
+ 1 to 4 target poses; generations chain by feeding the last four poses back.
+ Conditioning is poses and constraints only: no text, no scene geometry.
+- The skeleton is fixed. Another rig needs retargeting (a SOMA Retargeter
+ exists; not read).
+- Stated limit, verbatim from the card: "Kinematic motion generation does not
+ establish dynamic feasibility, physical robot tracking, collision avoidance,
+ or safe contact. Physical execution requires a separate controller." And:
+ "Evaluate generated motion in the intended application. Physical execution
+ requires a separate tracking and safety system."
+
+## 5. How a tracker over Ymir's SoA world would follow it
+
+Today (`Ymir/docs/soa-world.md`): headless Box3D world, lanes for stable id,
+kind, position, rotation, linear and angular velocity, spheres and static boxes
+only. Its own "needed next" list is joints, capsule/box bodies, a torque write
+path, joint state lanes and contact facts. Lodur's `body-one-interface` says the
+body consumes only targets and per-muscle strength.
+
+Reading, not tested:
+
+1. A MotionBricks tier would sit under *behaviour*. Behaviour picks a target
+ pose set (a few SOMA poses placed ahead of the character) plus per-muscle
+ strength; the model fills the in-between frames at 30 Hz.
+2. The body maps SOMA joint rotations (6D to quaternion) onto the Ymir
+ ragdoll's joints, retargeted if the ragdoll is not the SOMA 30-joint rig,
+ and drives each joint's PD or motor target toward the frame for the current
+ tick. Strength scales the torque limit. A limb with strength loss lags or
+ misses the target; that is the "motor system that may fail".
+3. The measured ragdoll state (the SoA lanes plus joint state) feeds back as
+ perception, and, once the character is no longer on the kinematic path (fall,
+ impairment), the context poses for the next generation come from the *real*
+ body, not the previous output (the runtime's `MotionRecorder` / history
+ already takes context from "the last four played frames"). A body that is
+ on the floor is out of distribution for a model trained on upright studio
+ mocap; expect garbage targets then and fall back to Lodur's own ground
+ behaviours (design target: v1 ships those).
+4. The model runs per character, not per physics tick: 30 Hz targets,
+ one generation per 18 to 58 frames. It is intent, below the nervous system
+ and above the tracker; reflexes overlay it and never wait for it.
+
+Missing for this to run at all: a jointed humanoid in Ymir's SoA world, a
+joint motor write path, and a SOMA-to-ragdoll rig mapping. All three are Ymir
+or Lodur work that exists whether or not MotionBricks is used.
+
+## 6. Fit
+
+- Fit: target poses for a motor system that may fail. Kinematic, human-only,
+ upright-trained, poses in and poses out. Not a replacement for the physical
+ body, and the card says as much.
+- Competing options already in the design target: Lodur's own
+ behaviours emit targets directly (crawl, writhe); a small learned tracker
+ (DReCon scale) is v2. MotionBricks is the only one that supplies natural
+ locomotion and transitions between authored pose targets, and it is the
+ heaviest by orders of magnitude.
+- Lodur's characters are meant to be hurt, not graceful. Whether upright
+ mocap-derived targets help the interesting 20 seconds (crawl, shock, pass
+ out) is doubtful. They would help locomotion before injury.
+
+## Unverified
+
+- Whether the Open Model Agreement's indemnity sentence is acceptable under
+ GameCult's open-source rule (needs a ruling, and likely a lawyer).
+- RP1 licence text and what it says, if anything, about models trained on it.
+- Whether the Hugging Face checkpoint repos ship a `NOTICE` file (none in the
+ GitHub repo at `54fc563`), which would trigger the attribution clause.
+- SOMA ONNX on CPU: speed, memory, and agreement with TensorRT output.
+- Bit determinism of one backend across runs; any sampling randomness inside
+ the graph.
+- Behaviour on a GTX 1070 (no tensor-core FP16) and under GPU sharing.
+- Quality of targets when the body is off the training distribution (prone,
+ one-legged).
+- SOMA Retargeter licence and fit for Lodur's rig; Lodur has no rig yet.
+- Effort to port boundary-frame trimming, endpoint correction and foot-contact
+ decoding to C#.
+- The paper (arXiv 2604.24833) was read at abstract level only.
diff --git a/docs/probes/flesh/README.md b/docs/probes/flesh/README.md
new file mode 100644
index 0000000..19caf8e
--- /dev/null
+++ b/docs/probes/flesh/README.md
@@ -0,0 +1,18 @@
+# Flesh cost probes
+
+Probes behind `docs/flesh-map.md` and the Nibu research notes
+`lodur:research:flesh-bones-map.probe-flesh-cost`, `.probe-flesh-commands` and
+`.probe-skin-sieve`.
+
+- `ymir_particles.probe.patch`: the probe's changes to Ymir's
+ `native/Ymir.Box3D/ymir_particles.{c,h}` at GameCult/Ymir d82da6d (pin
+ skipping by flag, a no-contact phase switch). Probe only; not a Ymir change.
+- `fella.c`: one or more Fellas of skin and muscle sheets on rigid bones,
+ stepped at 120 Hz x 4 substeps. `matrix.sh` / `matrix2.sh` run the
+ configurations interleaved, five repetitions; `matrix*.out` are the runs the
+ notes cite.
+- `sieve.c`: a skin sheet attached along a bone under fluid and solid load at
+ 4 substeps.
+
+Build against a patched copy of the two Ymir files with the same flags Ymir
+uses (`-O2 -std=c17 -ffp-contract=off`).
diff --git a/docs/probes/flesh/fella.c b/docs/probes/flesh/fella.c
new file mode 100644
index 0000000..4c2bdbb
--- /dev/null
+++ b/docs/probes/flesh/fella.c
@@ -0,0 +1,502 @@
+// Probe: Fella flesh on Ymir's particle solver (ymir_particles.c at d82da6d, scratch copy with two opt-in patches:
+// probe_pinned excludes pinned particles from grid and constraints; probe_body_group replaces held_by with a group filter).
+// Bones are kinematic proxies animated by FK (one-way coupling). 120 Hz x 4 substeps.
+// usage: fella F skin_m muscle_m live pinmode filter gut ticks [cut]
+// live: 0 none, 1 left forearm of each Fella, 2 all of Fella 0, 3 everything
+// pinmode: 0 pinned = mass 0 in the solve (shipped code), 1 pinned excluded (patch)
+// filter: 0 held_by (shipped), 1 body group filter (patch)
+#include "ymir_particles.h"
+#include
+#include
+#include
+#include
+#include
+
+extern uint8_t* probe_pinned;
+extern int32_t* probe_body_group;
+extern double probe_t[8];
+extern int probe_nocontact;
+
+typedef struct { float x, y, z; } v3;
+typedef struct { float x, y, z, w; } q4;
+static v3 V(float x, float y, float z) { return (v3){x, y, z}; }
+static v3 add(v3 a, v3 b) { return V(a.x + b.x, a.y + b.y, a.z + b.z); }
+static v3 sub(v3 a, v3 b) { return V(a.x - b.x, a.y - b.y, a.z - b.z); }
+static v3 mul(v3 a, float s) { return V(a.x * s, a.y * s, a.z * s); }
+static float dot(v3 a, v3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
+static float len(v3 a) { return sqrtf(dot(a, a)); }
+static v3 cross(v3 a, v3 b) { return V(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); }
+static q4 qmul(q4 a, q4 b)
+{
+ return (q4){a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
+ a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z};
+}
+static v3 qrot(q4 q, v3 v)
+{
+ v3 u = V(q.x, q.y, q.z);
+ v3 t = mul(cross(u, v), 2.0f);
+ return add(add(v, mul(t, q.w)), cross(u, t));
+}
+static q4 qaxis(v3 a, float ang) { float s = sinf(ang / 2); return (q4){a.x * s, a.y * s, a.z * s, cosf(ang / 2)}; }
+
+// The 19-part humanoid of Lodur BodyPlans.Humanoid (fbc3501), rotations taken as identity.
+enum { BOX, CAP, SPH };
+typedef struct { int shape; v3 size, pos; } part;
+typedef struct { int parent, child; v3 anchor, axis; float amp, phase; } joint;
+static part P[19];
+static joint J[18];
+static int np = 0, nj = 0;
+static int addp(int sh, v3 sz, v3 pos) { P[np] = (part){sh, sz, pos}; return np++; }
+static void addj(int pa, int ch, v3 an, v3 ax, float amp) { J[nj] = (joint){pa, ch, an, ax, amp, 0.7f * nj}; nj++; }
+static int LOWERARM_L;
+static void humanoid(void)
+{
+ int pelvis = addp(BOX, V(.15f, .08f, .09f), V(0, 1.11f, 0));
+ int torso = addp(BOX, V(.15f, .22f, .09f), V(0, 1.41f, 0));
+ int head = addp(SPH, V(.11f, 0, 0), V(0, 1.74f, 0));
+ int ua[2], la[2], th[2], sh[2], ft[2], pa[2], tb[2], fg[2];
+ for (int k = 0; k < 2; k++)
+ {
+ float sx = k == 0 ? 1.f : -1.f;
+ ua[k] = addp(CAP, V(.045f, .11f, 0), V(sx * .21f, 1.395f, 0));
+ la[k] = addp(CAP, V(.04f, .10f, 0), V(sx * .21f, 1.10f, 0));
+ th[k] = addp(CAP, V(.07f, .18f, 0), V(sx * .09f, .79f, 0));
+ sh[k] = addp(CAP, V(.06f, .17f, 0), V(sx * .09f, .31f, 0));
+ ft[k] = addp(BOX, V(.05f, .04f, .12f), V(sx * .09f, .04f, .05f));
+ }
+ for (int k = 0; k < 2; k++)
+ {
+ float sx = k == 0 ? 1.f : -1.f;
+ pa[k] = addp(BOX, V(.014f, .045f, .040f), V(sx * .21f, .930f, 0));
+ tb[k] = addp(CAP, V(.011f, .03f, 0), V(sx * .206f, .93f, .055f));
+ fg[k] = addp(BOX, V(.011f, .0425f, .038f), V(sx * .21f - sx * .0145f, .845f, 0));
+ }
+ LOWERARM_L = la[0];
+ v3 up = V(0, 1, 0), ac = V(1, 0, 0);
+ addj(pelvis, torso, V(0, 1.19f, 0), ac, .15f);
+ addj(torso, head, V(0, 1.63f, 0), ac, .2f);
+ for (int k = 0; k < 2; k++)
+ {
+ float sx = k == 0 ? 1.f : -1.f;
+ addj(torso, ua[k], V(sx * .21f, 1.55f, 0), ac, .6f);
+ addj(ua[k], la[k], V(sx * .21f, 1.24f, 0), ac, .7f);
+ addj(pelvis, th[k], V(sx * .09f, 1.04f, 0), ac, .5f);
+ addj(th[k], sh[k], V(sx * .09f, .54f, 0), ac, .6f);
+ addj(sh[k], ft[k], V(sx * .09f, .08f, 0), ac, .3f);
+ }
+ for (int k = 0; k < 2; k++)
+ {
+ float sx = k == 0 ? 1.f : -1.f;
+ addj(la[k], pa[k], V(sx * .21f, .975f, 0), ac, .4f);
+ addj(pa[k], tb[k], V(sx * .206f, .955f, .03f), ac, .3f);
+ addj(pa[k], fg[k], V(sx * .21f, .885f, 0), ac, .5f);
+ }
+ (void)up;
+}
+
+// signed distance to a part's shape in its local frame
+static float sdf(const part* p, v3 x)
+{
+ if (p->shape == SPH) return len(x) - p->size.x;
+ if (p->shape == CAP)
+ {
+ float y = x.y < -p->size.y ? -p->size.y : x.y > p->size.y ? p->size.y : x.y;
+ return len(V(x.x, x.y - y, x.z)) - p->size.x;
+ }
+ v3 q = V(fabsf(x.x) - p->size.x, fabsf(x.y) - p->size.y, fabsf(x.z) - p->size.z);
+ v3 m = V(q.x > 0 ? q.x : 0, q.y > 0 ? q.y : 0, q.z > 0 ? q.z : 0);
+ float in = fmaxf(q.x, fmaxf(q.y, q.z));
+ return len(m) + (in < 0 ? in : 0);
+}
+
+// surface samples of a part at spacing s, inset d (local frame)
+static int sample(const part* p, float s, float d, v3* out)
+{
+ int n = 0;
+ if (p->shape == SPH || p->shape == CAP)
+ {
+ float r = p->size.x - d;
+ if (r < 0.005f) r = 0.005f;
+ float half = p->shape == CAP ? p->size.y : 0;
+ int rings = (int)ceilf(2 * half / s);
+ for (int i = 0; i <= rings && half > 0; i++)
+ {
+ float y = -half + 2 * half * i / (rings ? rings : 1);
+ int m = (int)fmaxf(getenv("MINRING") ? atoi(getenv("MINRING")) : 6, roundf(2 * 3.14159f * r / s));
+ for (int k = 0; k < m; k++)
+ {
+ float a = 2 * 3.14159f * (k + 0.5f * (i & 1)) / m;
+ out[n++] = V(r * cosf(a), y, r * sinf(a));
+ }
+ }
+ // caps (whole sphere for SPH): latitude rings
+ int lat = (int)fmaxf(2, roundf(3.14159f * r / 2 / s));
+ for (int c = 0; c < 2; c++)
+ for (int i = (half > 0 ? 1 : 0); i <= lat; i++)
+ {
+ if (half == 0 && c == 1 && i == 0) continue;
+ float phi = 3.14159f / 2 * i / lat; // 0 at equator
+ float rr = r * cosf(phi), yy = r * sinf(phi) * (c ? -1 : 1);
+ int m = i == lat ? 1 : (int)fmaxf(3, roundf(2 * 3.14159f * rr / s));
+ for (int k = 0; k < m; k++)
+ {
+ float a = 2 * 3.14159f * (k + 0.5f * (i & 1)) / m;
+ out[n++] = V(rr * cosf(a), (c ? -half : half) + yy, rr * sinf(a));
+ }
+ }
+ return n;
+ }
+ v3 h = V(fmaxf(p->size.x - d, .004f), fmaxf(p->size.y - d, .004f), fmaxf(p->size.z - d, .004f));
+ for (int ax = 0; ax < 3; ax++)
+ for (int sg = -1; sg <= 1; sg += 2)
+ {
+ float hu = ax == 0 ? h.y : h.x, hv = ax == 2 ? h.y : h.z;
+ int nu = (int)fmaxf(1, ceilf(2 * hu / s)), nv = (int)fmaxf(1, ceilf(2 * hv / s));
+ for (int i = 0; i <= nu; i++)
+ for (int k = 0; k <= nv; k++)
+ {
+ // skip the shared edges of faces already done
+ float u = -hu + 2 * hu * i / nu, v = -hv + 2 * hv * k / nv;
+ v3 x = ax == 0 ? V(sg * h.x, u, v) : ax == 1 ? V(u, sg * h.y, v) : V(u, v, sg * h.z);
+ int dup = 0;
+ for (int q = 0; q < n; q++) if (len(sub(out[q], x)) < 0.3f * s) { dup = 1; break; }
+ if (!dup) out[n++] = x;
+ }
+ }
+ return n;
+}
+
+// ---- world ----
+static ymir_particles* W;
+static int F; // Fellas
+static uint64_t stepc = 1;
+typedef struct { int fella, part, layer; v3 local; } pinfo;
+static pinfo* PI;
+static float* pmass;
+static int nparticles = 0;
+static ymir_handle* PH;
+static int ndist = 0, nbend = 0, natt = 0, nstitch = 0;
+static ymir_handle* DH; static int* Dlayer; static int* Dpart; static int* Dfella;
+static int nfloor;
+static v3 bonepos[64][19]; static q4 bonerot[64][19];
+
+static void pose(int f, float t, v3* pos, q4* rot)
+{
+ v3 off = V(1.2f * f, 0, 0);
+ q4 R[19]; v3 X[19];
+ R[0] = qaxis(V(0, 1, 0), 0.3f * sinf(1.3f * t));
+ X[0] = add(add(P[0].pos, off), V(0, 0.02f * sinf(6 * t), 0));
+ for (int j = 0; j < nj; j++)
+ {
+ joint* J0 = &J[j];
+ int a = J0->parent, c = J0->child;
+ q4 rj = qaxis(J0->axis, J0->amp * sinf(3.0f * t + J0->phase + f));
+ R[c] = qmul(R[a], rj);
+ v3 an = add(X[a], qrot(R[a], sub(J0->anchor, P[a].pos)));
+ X[c] = add(an, qrot(R[c], sub(P[c].pos, J0->anchor)));
+ }
+ for (int i = 0; i < 19; i++) { pos[i] = X[i]; rot[i] = R[i]; }
+}
+
+static void fill_proxies(float t, float h)
+{
+ for (int f = 0; f < F; f++)
+ {
+ v3 x0[19], x1[19]; q4 r0[19], r1[19];
+ pose(f, t, x0, r0);
+ pose(f, t + h, x1, r1);
+ for (int i = 0; i < 19; i++)
+ {
+ ymir_particle_proxy* b = W->proxies + f * 19 + i;
+ memset(b, 0, sizeof *b);
+ b->shape = P[i].shape == SPH ? YMIR_PROXY_SPHERE : P[i].shape == CAP ? YMIR_PROXY_CAPSULE : YMIR_PROXY_BOX;
+ b->size[0] = P[i].size.x; b->size[1] = P[i].size.y; b->size[2] = P[i].size.z;
+ b->position[0] = x0[i].x; b->position[1] = x0[i].y; b->position[2] = x0[i].z;
+ b->rotation[0] = r0[i].x; b->rotation[1] = r0[i].y; b->rotation[2] = r0[i].z; b->rotation[3] = r0[i].w;
+ v3 v = mul(sub(x1[i], x0[i]), 1 / h);
+ b->velocity[0] = v.x; b->velocity[1] = v.y; b->velocity[2] = v.z;
+ q4 inv0 = {-r0[i].x, -r0[i].y, -r0[i].z, r0[i].w};
+ q4 dq = qmul(r1[i], inv0);
+ if (dq.w < 0) { dq.x = -dq.x; dq.y = -dq.y; dq.z = -dq.z; dq.w = -dq.w; }
+ b->angular_velocity[0] = 2 * dq.x / h; b->angular_velocity[1] = 2 * dq.y / h; b->angular_velocity[2] = 2 * dq.z / h;
+ bonepos[f][i] = x0[i]; bonerot[f][i] = r0[i];
+ }
+ }
+ ymir_particle_proxy* fl = W->proxies + F * 19;
+ memset(fl, 0, sizeof *fl);
+ fl->shape = YMIR_PROXY_BOX; fl->size[0] = 50; fl->size[1] = 0.5f; fl->size[2] = 50; fl->position[1] = -0.5f; fl->rotation[3] = 1;
+ W->body_count = F * 19 + 1;
+}
+
+static double now_ms(void)
+{
+ LARGE_INTEGER c, fq; QueryPerformanceCounter(&c); QueryPerformanceFrequency(&fq);
+ return 1000.0 * (double)c.QuadPart / (double)fq.QuadPart;
+}
+
+int main(int argc, char** argv)
+{
+ F = argc > 1 ? atoi(argv[1]) : 1;
+ float s = argc > 2 ? (float)atof(argv[2]) : 0.08f, sm = argc > 3 ? (float)atof(argv[3]) : 0.10f;
+ int live = argc > 4 ? atoi(argv[4]) : 0, pinmode = argc > 5 ? atoi(argv[5]) : 0, filter = argc > 6 ? atoi(argv[6]) : 0;
+ int gut = argc > 7 ? atoi(argv[7]) : 0, ticks = argc > 8 ? atoi(argv[8]) : 600, cut = argc > 9 ? atoi(argv[9]) : 0;
+ humanoid();
+ int cap = 4000 * F + 400;
+ ymir_particle_capacities c = {cap, cap * 6, cap * 4, cap * 2, cap * 2, 4, 0, 0, 0};
+ W = ymir_particles_create(&c, F * 19 + 1);
+ PI = calloc(cap, sizeof *PI); pmass = calloc(cap, sizeof *pmass); PH = calloc(cap, sizeof *PH);
+ DH = calloc(cap * 6, sizeof *DH); Dlayer = calloc(cap * 6, sizeof(int)); Dpart = calloc(cap * 6, sizeof(int)); Dfella = calloc(cap * 6, sizeof(int));
+ uint8_t* pinned = calloc(cap, 1);
+ int32_t* bgroup = calloc(F * 19 + 1, sizeof(int32_t));
+ for (int f = 0; f < F; f++) for (int i = 0; i < 19; i++) bgroup[f * 19 + i] = f + 1;
+ bgroup[F * 19] = -1;
+ fill_proxies(0, 1.f / 480);
+ double build0 = now_ms();
+ v3* tmp = malloc(sizeof(v3) * 4000);
+ int per_layer[2] = {0, 0};
+ for (int f = 0; f < F; f++)
+ {
+ int first[2][19], cnt[2][19];
+ for (int layer = 0; layer < 2; layer++)
+ {
+ float sp = layer == 0 ? s : sm, d = layer == 0 ? 0 : 0.012f;
+ float mass = layer == 0 ? 0.012f * (sp * sp / 0.0064f) : 0.05f, rad = 0.45f * sp;
+ for (int i = 0; i < 19; i++)
+ {
+ first[layer][i] = nparticles; cnt[layer][i] = 0;
+ if (layer == 1 && (P[i].shape == BOX && P[i].size.x < 0.02f)) continue; // no muscle sheet in palm/fingers
+ if (layer == 1 && P[i].size.x < 0.02f) continue;
+ int n = sample(&P[i], sp, d, tmp);
+ for (int k = 0; k < n; k++)
+ {
+ v3 w = add(P[i].pos, tmp[k]);
+ int inside = 0;
+ for (int o = 0; o < 19; o++) if (o != i && sdf(&P[o], sub(w, P[o].pos)) < -0.25f * sp) { inside = 1; break; }
+ if (inside) continue;
+ v3 wp = add(bonepos[f][i], qrot(bonerot[f][i], tmp[k]));
+ int live_p = live == 3 || (live == 2 && f == 0) || (live == 1 && i == LOWERARM_L);
+ if (!live_p && getenv("ABSENT")) continue;
+ ymir_particle_desc pd = {{wp.x, wp.y, wp.z}, {w.x + 1.2f * f, w.y, w.z}, {0, 0, 0}, mass, rad, (uint32_t)(f + 1), 0};
+ pd.mass = live_p ? mass : 0.0f;
+ if (ymir_particles_create_particles(W, 1, &pd, stepc, &PH[nparticles]) != 0) { printf("create failed\n"); return 1; }
+ PI[nparticles] = (pinfo){f, i, layer, tmp[k]};
+ pmass[nparticles] = mass;
+ pinned[PH[nparticles].lane] = !live_p;
+ nparticles++; cnt[layer][i]++; if (f == 0) per_layer[layer]++;
+ }
+ }
+ }
+ if (f == 0 && getenv("PARTS")) { for (int i = 0; i < 19; i++) printf("part %d skin %d muscle %d;", i, cnt[0][i], cnt[1][i]); }
+ // edges within a part and layer: 6 nearest within 1.6 spacing; bends over near-opposite pairs
+ for (int layer = 0; layer < 2; layer++)
+ {
+ float sp = layer == 0 ? s : sm;
+ for (int i = 0; i < 19; i++)
+ {
+ int a0 = first[layer][i], n = cnt[layer][i];
+ int* nb = calloc((size_t)n * 6, sizeof(int)); int* nbe = calloc((size_t)n * 6, sizeof(int)); int* nn = calloc(n, sizeof(int));
+ for (int a = 0; a < n; a++)
+ {
+ int best[6]; float bd[6]; int nb6 = 0;
+ for (int b = 0; b < n; b++)
+ {
+ if (b == a) continue;
+ float dd = len(sub(PI[a0 + a].local, PI[a0 + b].local));
+ if (dd > 1.6f * sp) continue;
+ int q;
+ if (nb6 < 6) q = nb6++;
+ else { if (bd[5] <= dd) continue; q = 5; }
+ best[q] = b; bd[q] = dd;
+ for (int z = q; z > 0 && bd[z] < bd[z - 1]; z--) { float t = bd[z]; bd[z] = bd[z - 1]; bd[z - 1] = t; int u = best[z]; best[z] = best[z - 1]; best[z - 1] = u; }
+ }
+ for (int q = 0; q < nb6; q++)
+ {
+ int b = best[q];
+ if (b < a) { int seen = 0; for (int z = 0; z < nn[b]; z++) if (nb[b * 6 + z] == a) seen = 1; if (seen) continue; }
+ ymir_distance_desc dd = {PH[a0 + a], PH[a0 + b], -1.0f, layer == 0 ? 2e-4f : 1e-4f};
+ { int rc = ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]); if (rc) { printf("dist failed rc %d layer %d part %d a %d b %d n %d lanes %d %d\n", rc, layer, i, a, b, n, PH[a0+a].lane, PH[a0+b].lane); return 1; } }
+ Dlayer[ndist] = layer; Dpart[ndist] = i; Dfella[ndist] = f;
+ if (nn[a] < 6) { nb[a * 6 + nn[a]] = b; nbe[a * 6 + nn[a]] = ndist; nn[a]++; }
+ if (nn[b] < 6) { nb[b * 6 + nn[b]] = a; nbe[b * 6 + nn[b]] = ndist; nn[b]++; }
+ ndist++;
+ }
+ }
+ for (int b = 0; b < n; b++)
+ for (int x = 0; x < nn[b]; x++)
+ for (int y = x + 1; y < nn[b]; y++)
+ {
+ v3 u = sub(PI[a0 + nb[b * 6 + x]].local, PI[a0 + b].local), v = sub(PI[a0 + nb[b * 6 + y]].local, PI[a0 + b].local);
+ if (dot(u, v) / (len(u) * len(v)) > -0.85f) continue;
+ ymir_bend_desc bd = {DH[nbe[b * 6 + x]], DH[nbe[b * 6 + y]], 1e-3f, -1.0f};
+ ymir_handle hb;
+ if (ymir_particles_create_bends(W, 1, &bd, stepc, &hb) == 0) nbend++;
+ }
+ free(nb); free(nbe); free(nn);
+ }
+ }
+ // stitches across each joint (skin and muscle): child particles within 1.5 sp of the anchor to the nearest parent particle within 2 sp
+ for (int layer = 0; layer < 2; layer++)
+ {
+ float sp = layer == 0 ? s : sm;
+ for (int j = 0; j < nj; j++)
+ {
+ int pa = J[j].parent, ch = J[j].child;
+ for (int a = first[layer][ch]; a < first[layer][ch] + cnt[layer][ch]; a++)
+ {
+ v3 wa = add(P[ch].pos, PI[a].local);
+ if (len(sub(wa, J[j].anchor)) > 1.5f * sp + P[ch].size.x) continue;
+ int best = -1; float bd = 2.0f * sp;
+ for (int b = first[layer][pa]; b < first[layer][pa] + cnt[layer][pa]; b++)
+ {
+ float dd = len(sub(wa, add(P[pa].pos, PI[b].local)));
+ if (dd < bd) { bd = dd; best = b; }
+ }
+ if (best < 0) continue;
+ ymir_distance_desc dd = {PH[a], PH[best], -1.0f, 2e-4f};
+ if (ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]) != 0) { printf("stitch failed\n"); return 1; }
+ Dlayer[ndist] = 2 + layer; Dpart[ndist] = ch; Dfella[ndist] = f; ndist++; nstitch++;
+ }
+ }
+ }
+ // skin to nearest muscle of the same part
+ for (int i = 0; i < 19; i++)
+ for (int a = first[0][i]; a < first[0][i] + cnt[0][i]; a++)
+ {
+ int best = -1; float bd = 1e9f;
+ for (int b = first[1][i]; b < first[1][i] + cnt[1][i]; b++) { float dd = len(sub(PI[a].local, PI[b].local)); if (dd < bd) { bd = dd; best = b; } }
+ if (best < 0) continue;
+ ymir_distance_desc dd = {PH[a], PH[best], -1.0f, 5e-4f};
+ if (ymir_particles_create_distances(W, 1, &dd, stepc, &DH[ndist]) != 0) { printf("sm failed\n"); return 1; }
+ Dlayer[ndist] = 4; Dpart[ndist] = i; Dfella[ndist] = f; ndist++;
+ }
+ }
+ // attachments: every flesh particle to its bone point
+ for (int k = 0; k < nparticles; k++)
+ {
+ ymir_attachment_desc ad = {YMIR_ATTACH_BODY, 0, PH[k], PI[k].fella * 19 + PI[k].part, {PI[k].local.x, PI[k].local.y, PI[k].local.z}, PI[k].layer == 0 ? 1e-3f : 1e-4f, 0};
+ ymir_handle ha;
+ if (ymir_particles_attach(W, &ad, W->body_count, stepc, &ha) != 0) { printf("attach failed\n"); return 1; }
+ natt++;
+ }
+ int flesh = nparticles;
+ double build_ms = now_ms() - build0;
+ // gut: a released real-length rope of 300 particles hanging from the pelvis of Fella 0
+ int gut0 = nparticles, ngut = gut ? 300 : 0;
+ ymir_handle* GE = calloc(400, sizeof *GE);
+ for (int k = 0; k < ngut; k++)
+ {
+ float a = k * 0.18f, r = 0.05f + 0.0012f * k;
+ v3 x = V(r * cosf(a), 0.9f, 0.25f + r * sinf(a));
+ ymir_particle_desc pd = {{x.x, x.y, x.z}, {0.0267f * k, 0, 0}, {0, 0, 0}, 0.0267f * 0.0003f * 1050.0f / 0.0267f * 0.0267f, 0.0125f, 99u | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER, 0};
+ pd.mass = 0.008f;
+ ymir_particles_create_particles(W, 1, &pd, stepc, &PH[nparticles]);
+ PI[nparticles] = (pinfo){0, -1, 9, x}; nparticles++;
+ }
+ int ngutd = 0;
+ for (int k = 1; k < ngut; k++)
+ {
+ ymir_distance_desc dd = {PH[gut0 + k - 1], PH[gut0 + k], 0.0267f, 0};
+ ymir_particles_create_distances(W, 1, &dd, stepc, &GE[k - 1]); ngutd++;
+ }
+ for (int k = 1; k + 1 < ngut; k++) { ymir_bend_desc bd = {GE[k - 1], GE[k], 1e-2f, -1}; ymir_handle hb; ymir_particles_create_bends(W, 1, &bd, stepc, &hb); }
+ if (ngut)
+ {
+ for (int e = 0; e < 2; e++)
+ {
+ int k = e ? ngut - 1 : 0;
+ ymir_attachment_desc ad = {YMIR_ATTACH_BODY, YMIR_ATTACH_FLAG_TETHER, PH[gut0 + k], 0, {0.02f * (e ? 1 : -1), -0.02f, 0.09f}, 0, 0};
+ ymir_handle ha; ymir_particles_attach(W, &ad, W->body_count, stepc, &ha);
+ }
+ }
+ if (pinmode) probe_pinned = pinned;
+ if (getenv("NOCONTACT")) probe_nocontact = 1;
+ if (filter) probe_body_group = bgroup;
+ if (filter && ngut) bgroup[0] = 0; // the gut (group 99) collides with every bone; nothing to do
+ // per-Fella counts
+ int fd = 0, fs = 0;
+ for (int e = 0; e < ndist; e++) if (Dfella[e] == 0) { fd++; if (Dlayer[e] >= 2 && Dlayer[e] <= 3) fs++; }
+ float h = 1.0f / 480.0f;
+ double* tk = malloc(sizeof(double) * (ticks + 240));
+ float t = 0;
+ int warm = 120;
+ double cut_ms = -1, sever_ms = -1, wake_ms = -1;
+ float maxdev = 0;
+ for (int n = 0; n < warm + ticks; n++)
+ {
+ // pinned particles are written from their bone at the tick's start (Ymir's pin write, one per tick)
+ double t0 = now_ms();
+ fill_proxies(t, h);
+ for (int k = 0; k < flesh; k++)
+ {
+ int l = PH[k].lane;
+ if (!pinned[l]) continue;
+ v3 w = add(bonepos[PI[k].fella][PI[k].part], qrot(bonerot[PI[k].fella][PI[k].part], PI[k].local));
+ W->pos_x[l] = w.x; W->pos_y[l] = w.y; W->pos_z[l] = w.z;
+ }
+ ymir_particles_begin(W);
+ for (int sstep = 0; sstep < 4; sstep++)
+ {
+ if (sstep) fill_proxies(t + sstep * h, h);
+ ymir_particles_substep(W, h, 0, -9.81f, 0);
+ }
+ ymir_particles_end(W, 4);
+ double t1 = now_ms();
+ t += 4 * h;
+ stepc++;
+ if (n >= warm) tk[n - warm] = t1 - t0;
+ if (cut && n == warm + ticks / 2)
+ {
+ // wound: remove the skin edges of Fella 0's left forearm within 6 cm of its front point; then sever at the left elbow (stitches)
+ ymir_handle hs[64]; int m = 0;
+ for (int e = 0; e < ndist && m < 64; e++)
+ if (Dfella[e] == 0 && Dpart[e] == LOWERARM_L && Dlayer[e] == 0)
+ {
+ int a = W->dist_a[DH[e].lane];
+ v3 x = V(W->pos_x[a], W->pos_y[a], W->pos_z[a]);
+ v3 c0 = add(bonepos[0][LOWERARM_L], qrot(bonerot[0][LOWERARM_L], V(0, 0, .04f)));
+ if (len(sub(x, c0)) < 0.06f) hs[m++] = DH[e];
+ }
+ double c0 = now_ms();
+ ymir_particles_remove(W, YMIR_LANES_DISTANCE, m, hs, stepc);
+ cut_ms = now_ms() - c0;
+ printf("cut: %d skin edges\n", m);
+ m = 0;
+ for (int e = 0; e < ndist && m < 64; e++) if (Dfella[e] == 0 && Dpart[e] == LOWERARM_L && (Dlayer[e] == 2 || Dlayer[e] == 3)) hs[m++] = DH[e];
+ c0 = now_ms();
+ ymir_particles_remove(W, YMIR_LANES_DISTANCE, m, hs, stepc);
+ sever_ms = now_ms() - c0;
+ printf("sever: %d stitches; forearm skin component %d, upper arm skin component %d\n", m,
+ W->component[PH[0].lane], 0);
+ // wake Fella 0's thigh flesh: pinned -> live (mass back, velocity of the bone point)
+ c0 = now_ms();
+ for (int k = 0; k < flesh; k++)
+ if (PI[k].fella == 0 && PI[k].part == 7)
+ {
+ int l = PH[k].lane;
+ if (!pinned[l]) continue;
+ pinned[l] = 0; W->inv_mass[l] = 1.0f / pmass[k];
+ }
+ wake_ms = now_ms() - c0;
+ }
+ if (n == warm + ticks - 1)
+ for (int k = 0; k < flesh; k++)
+ {
+ int l = PH[k].lane;
+ if (pinned[l]) continue;
+ v3 w = add(bonepos[PI[k].fella][PI[k].part], qrot(bonerot[PI[k].fella][PI[k].part], PI[k].local));
+ float dv = len(sub(V(W->pos_x[l], W->pos_y[l], W->pos_z[l]), w));
+ if (dv > maxdev) maxdev = dv;
+ }
+ }
+ // median and mean
+ int nt = ticks;
+ for (int a = 1; a < nt; a++) { double v = tk[a]; int b = a - 1; while (b >= 0 && tk[b] > v) { tk[b + 1] = tk[b]; b--; } tk[b + 1] = v; }
+ double mean = 0; for (int a = 0; a < nt; a++) mean += tk[a]; mean /= nt;
+ int livec = 0; for (int k = 0; k < nparticles; k++) livec += !pinned[PH[k].lane] || k >= flesh;
+ printf("FELLA F=%d skin=%.3f muscle=%.3f live=%d pinmode=%d filter=%d gut=%d | per Fella: skin %d muscle %d particles, %d distances (%d stitches), bends total %d, attachments total %d | live particles %d | ms/tick median %.3f mean %.3f p95 %.3f max %.3f | max live deviation %.3f m",
+ F, s, sm, live, pinmode, filter, gut, per_layer[0], per_layer[1], fd, fs, nbend, natt, livec, tk[nt / 2], mean, tk[(int)(nt * 0.95)], tk[nt - 1], maxdev);
+ printf(" | phases ms/tick grid %.3f pcontact %.3f att %.3f dist %.3f bend %.3f tether %.3f body %.3f", probe_t[0]/(warm+ticks), probe_t[1]/(warm+ticks), probe_t[2]/(warm+ticks), probe_t[3]/(warm+ticks), probe_t[4]/(warm+ticks), probe_t[5]/(warm+ticks), probe_t[6]/(warm+ticks));
+ if (cut) printf(" | cut %.3f ms sever %.3f ms wake %.4f ms", cut_ms, sever_ms, wake_ms);
+ printf("\n");
+ printf("BUILD %.1f ms;", build_ms); return 0;
+}
diff --git a/docs/probes/flesh/grid-mask-h.out b/docs/probes/flesh/grid-mask-h.out
new file mode 100644
index 0000000..cbc196b
--- /dev/null
+++ b/docs/probes/flesh/grid-mask-h.out
@@ -0,0 +1,15 @@
+1 full median 0.980 HASH ce534bd202fabaca
+1 sized median 0.476 HASH ce534bd202fabaca
+1 empty median 0.094 HASH 14650fb0739d0383
+2 full median 0.991 HASH ce534bd202fabaca
+2 sized median 0.456 HASH ce534bd202fabaca
+2 empty median 0.095 HASH 14650fb0739d0383
+3 full median 0.987 HASH ce534bd202fabaca
+3 sized median 0.496 HASH ce534bd202fabaca
+3 empty median 0.097 HASH 14650fb0739d0383
+4 full median 1.011 HASH ce534bd202fabaca
+4 sized median 0.488 HASH ce534bd202fabaca
+4 empty median 0.097 HASH 14650fb0739d0383
+5 full median 0.988 HASH ce534bd202fabaca
+5 sized median 0.486 HASH ce534bd202fabaca
+5 empty median 0.096 HASH 14650fb0739d0383
diff --git a/docs/probes/flesh/grid-mask-k.out b/docs/probes/flesh/grid-mask-k.out
new file mode 100644
index 0000000..04bd318
--- /dev/null
+++ b/docs/probes/flesh/grid-mask-k.out
@@ -0,0 +1,20 @@
+1 H X median 0.096 HASH 14650fb0739d0383
+1 H MASKSIZED median 0.095 HASH 14650fb0739d0383
+1 K X median 3.980 HASH 7c43ed61a4d7e339
+1 K MASKSIZED median 3.464 HASH 7c43ed61a4d7e339
+2 H X median 0.094 HASH 14650fb0739d0383
+2 H MASKSIZED median 0.094 HASH 14650fb0739d0383
+2 K X median 4.025 HASH 7c43ed61a4d7e339
+2 K MASKSIZED median 3.519 HASH 7c43ed61a4d7e339
+3 H X median 0.093 HASH 14650fb0739d0383
+3 H MASKSIZED median 0.094 HASH 14650fb0739d0383
+3 K X median 3.883 HASH 7c43ed61a4d7e339
+3 K MASKSIZED median 3.424 HASH 7c43ed61a4d7e339
+4 H X median 0.096 HASH 14650fb0739d0383
+4 H MASKSIZED median 0.096 HASH 14650fb0739d0383
+4 K X median 3.975 HASH 7c43ed61a4d7e339
+4 K MASKSIZED median 3.378 HASH 7c43ed61a4d7e339
+5 H X median 0.096 HASH 14650fb0739d0383
+5 H MASKSIZED median 0.096 HASH 14650fb0739d0383
+5 K X median 3.946 HASH 7c43ed61a4d7e339
+5 K MASKSIZED median 3.565 HASH 7c43ed61a4d7e339
diff --git a/docs/probes/flesh/grid-mask.fella.patch b/docs/probes/flesh/grid-mask.fella.patch
new file mode 100644
index 0000000..1230e15
--- /dev/null
+++ b/docs/probes/flesh/grid-mask.fella.patch
@@ -0,0 +1,27 @@
+--- fella.c
++++ fella.c
+@@ -15,7 +15,7 @@
+ extern uint8_t* probe_pinned;
+ extern int32_t* probe_body_group;
+ extern double probe_t[8];
+-extern int probe_nocontact;
++extern int probe_nocontact; extern int probe_mask_sized;
+
+ typedef struct { float x, y, z; } v3;
+ typedef struct { float x, y, z, w; } q4;
+@@ -410,6 +410,7 @@
+ }
+ if (pinmode) probe_pinned = pinned;
+ if (getenv("NOCONTACT")) probe_nocontact = 1;
++ if (getenv("MASKSIZED")) probe_mask_sized = 1;
+ if (filter) probe_body_group = bgroup;
+ if (filter && ngut) bgroup[0] = 0; // the gut (group 99) collides with every bone; nothing to do
+ // per-Fella counts
+@@ -496,6 +497,7 @@
+ printf("FELLA F=%d skin=%.3f muscle=%.3f live=%d pinmode=%d filter=%d gut=%d | per Fella: skin %d muscle %d particles, %d distances (%d stitches), bends total %d, attachments total %d | live particles %d | ms/tick median %.3f mean %.3f p95 %.3f max %.3f | max live deviation %.3f m",
+ F, s, sm, live, pinmode, filter, gut, per_layer[0], per_layer[1], fd, fs, nbend, natt, livec, tk[nt / 2], mean, tk[(int)(nt * 0.95)], tk[nt - 1], maxdev);
+ printf(" | phases ms/tick grid %.3f pcontact %.3f att %.3f dist %.3f bend %.3f tether %.3f body %.3f", probe_t[0]/(warm+ticks), probe_t[1]/(warm+ticks), probe_t[2]/(warm+ticks), probe_t[3]/(warm+ticks), probe_t[4]/(warm+ticks), probe_t[5]/(warm+ticks), probe_t[6]/(warm+ticks));
++ { uint64_t hh = 1469598103934665603ull; for (int i = 0; i < W->particle_count; i++) { const unsigned char* b; b=(const unsigned char*)&W->pos_x[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} b=(const unsigned char*)&W->pos_y[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} b=(const unsigned char*)&W->vel_z[i]; for(int c=0;c<4;c++){hh^=b[c];hh*=1099511628211ull;} } printf(" | HASH %016llx", (unsigned long long)hh); }
+ if (cut) printf(" | cut %.3f ms sever %.3f ms wake %.4f ms", cut_ms, sever_ms, wake_ms);
+ printf("\n");
+ printf("BUILD %.1f ms;", build_ms); return 0;
diff --git a/docs/probes/flesh/grid-mask.probe.patch b/docs/probes/flesh/grid-mask.probe.patch
new file mode 100644
index 0000000..6ea3310
--- /dev/null
+++ b/docs/probes/flesh/grid-mask.probe.patch
@@ -0,0 +1,135 @@
+--- ymir_particles.c
++++ ymir_particles.c
+@@ -5,6 +5,16 @@
+ // every sum in a fixed order. See ymir_particles.h.
+
+ #include "ymir_particles.h"
++#include
++uint8_t* probe_pinned = 0; int32_t* probe_body_group = 0;
++#include
++double probe_t[8];
++static double pnow(void){LARGE_INTEGER c,f;QueryPerformanceCounter(&c);QueryPerformanceFrequency(&f);return 1000.0*(double)c.QuadPart/(double)f.QuadPart;}
++#define T(k,x) do{double _t=pnow(); x; probe_t[k]+=pnow()-_t;}while(0)
++int probe_nocontact = 0;
++#define PIN(i) ((probe_pinned && probe_pinned[i]) || (probe_nocontact && !(p->phase[i] & (YMIR_PHASE_SELF_COLLIDE|YMIR_PHASE_FLUID)) && grid_ctx))
++static int grid_ctx = 0;
++
+
+ #include
+ #include
+@@ -1358,20 +1368,24 @@
+
+ // Counting sort into a hash grid of cell 1 / inv_cell: the live particles' predicted positions, fluid lanes left out when
+ // `solids` is set. Within a bucket particles keep index order, so every neighbour walk is the same on every run.
++int probe_mask_sized = 0; static uint32_t g_mask;
+ static void grid_sort(ymir_particles* p, float inv_cell, int solids)
+ {
+- int32_t buckets = (int32_t)p->table_mask + 1;
++ uint32_t mask = p->table_mask;
++ if (solids && probe_mask_sized) { int32_t n = 0; for (int32_t i = 0; i < p->particle_count; ++i) n += p->particle_live[i] && !PIN(i) && !(p->phase[i] & YMIR_PHASE_FLUID); uint32_t t = 16; while (t < 2u * (uint32_t)n) t <<= 1; if (t - 1 < mask) mask = t - 1; }
++ g_mask = mask;
++ int32_t buckets = (int32_t)mask + 1;
+ memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1));
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (!p->particle_live[i] || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
++ if (!p->particle_live[i] || PIN(i) || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ {
+ continue;
+ }
+ p->cell_x[i] = cell_of(p->pp_x[i], inv_cell);
+ p->cell_y[i] = cell_of(p->pp_y[i], inv_cell);
+ p->cell_z[i] = cell_of(p->pp_z[i], inv_cell);
+- p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask) + 1]++;
++ p->cell_start[cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask) + 1]++;
+ }
+ for (int32_t c = 0; c < buckets; ++c)
+ {
+@@ -1380,9 +1394,9 @@
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (p->particle_live[i] && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
++ if (p->particle_live[i] && !PIN(i) && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ {
+- uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask);
++ uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], mask);
+ p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i;
+ }
+ }
+@@ -1461,7 +1475,7 @@
+ {
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (!p->particle_live[i] || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
++ if (!p->particle_live[i] || PIN(i) || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
+ {
+ continue;
+ }
+@@ -1469,7 +1483,7 @@
+ {
+ int32_t o = cell == 0 ? 13 : 13 + cell, da = o / 9 - 1, db = o / 3 % 3 - 1, dc = o % 3 - 1;
+ int32_t ca = p->cell_x[i] + da, cb = p->cell_y[i] + db, cc = p->cell_z[i] + dc;
+- uint32_t bucket = cell_hash(ca, cb, cc, p->table_mask);
++ uint32_t bucket = cell_hash(ca, cb, cc, g_mask);
+ for (int32_t q = p->cell_start[bucket]; q < p->cell_start[bucket + 1]; ++q)
+ {
+ int32_t j = p->sorted[q];
+@@ -1979,7 +1993,7 @@
+ {
+ continue;
+ }
+- if (held_by(p, i, k))
++ if (probe_body_group ? probe_body_group[k] == (int32_t)(p->phase[i] & YMIR_PHASE_GROUP_MASK) : held_by(p, i, k))
+ {
+ continue;
+ }
+@@ -2056,6 +2070,7 @@
+ continue;
+ }
+ int32_t i = p->att_particle[a];
++ if (PIN(i)) continue;
+ v3 at = end_point(p, a);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at);
+ float len = vlen(d);
+@@ -2088,6 +2103,7 @@
+ continue;
+ }
+ int32_t i = p->dist_a[e], j = p->dist_b[e];
++ if (PIN(i) && PIN(j)) continue;
+ float wi = p->inv_mass[i], wj = p->inv_mass[j], alpha = p->dist_compliance[e] / (f->h * f->h);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i));
+ float len = vlen(d);
+@@ -2117,6 +2133,7 @@
+ continue;
+ }
+ int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
++ if (PIN(a) && PIN(b) && PIN(c)) continue;
+ float wa = p->inv_mass[a], wb = p->inv_mass[b], wc = p->inv_mass[c];
+ v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f};
+ for (int pass = 0; pass < 2; ++pass)
+@@ -2320,17 +2337,17 @@
+ }
+ put(p->pp_x, p->pp_y, p->pp_z, i, x);
+ }
+- build_grid(p);
+- particle_contacts(p);
++ grid_ctx = 1; T(0, build_grid(p););
++ T(1, particle_contacts(p);); grid_ctx = 0;
+ if (p->live_fluid > 0)
+ {
+ fluid_density(p);
+ }
+- solve_attachments(&f);
+- solve_distances(&f);
+- solve_bends(&f);
+- solve_tethers(&f);
+- body_contacts(&f);
++ T(2, solve_attachments(&f););
++ T(3, solve_distances(&f););
++ T(4, solve_bends(&f););
++ T(5, solve_tethers(&f););
++ T(6, body_contacts(&f););
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i])
diff --git a/docs/probes/flesh/matrix.out b/docs/probes/flesh/matrix.out
new file mode 100644
index 0000000..d30bc62
--- /dev/null
+++ b/docs/probes/flesh/matrix.out
@@ -0,0 +1,50 @@
+1 ship_1pin median 5.345
+1 ship_4pin median 21.693
+1 pin_1 median 0.242
+1 pin_4 median 1.167
+1 nc_4_forearms median 1.358
+1 nc_4_one_live median 3.038
+1 nc_4_one_live_gut median 3.572
+1 c_4_one_live median 6.990
+1 nc_4_all_live median 7.416
+1 nc_1_live median 1.127
+2 ship_1pin median 4.701
+2 ship_4pin median 20.071
+2 pin_1 median 0.245
+2 pin_4 median 1.026
+2 nc_4_forearms median 1.397
+2 nc_4_one_live median 2.712
+2 nc_4_one_live_gut median 3.827
+2 c_4_one_live median 6.973
+2 nc_4_all_live median 7.499
+2 nc_1_live median 1.135
+3 ship_1pin median 5.612
+3 ship_4pin median 24.192
+3 pin_1 median 0.248
+3 pin_4 median 1.268
+3 nc_4_forearms median 1.667
+3 nc_4_one_live median 3.134
+3 nc_4_one_live_gut median 4.969
+3 c_4_one_live median 8.860
+3 nc_4_all_live median 9.238
+3 nc_1_live median 1.132
+4 ship_1pin median 5.626
+4 ship_4pin median 23.291
+4 pin_1 median 0.249
+4 pin_4 median 1.271
+4 nc_4_forearms median 1.809
+4 nc_4_one_live median 3.429
+4 nc_4_one_live_gut median 4.777
+4 c_4_one_live median 8.777
+4 nc_4_all_live median 8.990
+4 nc_1_live median 1.128
+5 ship_1pin median 4.790
+5 ship_4pin median 23.049
+5 pin_1 median 0.247
+5 pin_4 median 1.282
+5 nc_4_forearms median 1.684
+5 nc_4_one_live median 3.326
+5 nc_4_one_live_gut median 4.850
+5 c_4_one_live median 8.675
+5 nc_4_all_live median 9.965
+5 nc_1_live median 1.578
diff --git a/docs/probes/flesh/matrix.sh b/docs/probes/flesh/matrix.sh
new file mode 100644
index 0000000..f4174d4
--- /dev/null
+++ b/docs/probes/flesh/matrix.sh
@@ -0,0 +1,18 @@
+#!/bin/sh
+# name|env|args
+CONF='ship_1pin||1 0.08 0.10 0 0 0 0 600
+ship_4pin||4 0.08 0.10 0 0 0 0 600
+pin_1||1 0.08 0.10 0 1 1 0 600
+pin_4||4 0.08 0.10 0 1 1 0 600
+nc_4_forearms|NOCONTACT=1|4 0.08 0.10 1 1 1 0 600
+nc_4_one_live|NOCONTACT=1|4 0.08 0.10 2 1 1 0 600
+nc_4_one_live_gut|NOCONTACT=1|4 0.08 0.10 2 1 1 1 600
+c_4_one_live|CONTACT=1|4 0.08 0.10 2 1 1 0 600
+nc_4_all_live|NOCONTACT=1|4 0.08 0.10 3 1 1 0 600
+nc_1_live|NOCONTACT=1|1 0.08 0.10 3 1 1 0 600'
+for rep in 1 2 3 4 5; do
+ echo "$CONF" | while IFS='|' read name env args; do
+ if [ -n "$env" ]; then out=$(env $env ./fella.exe $args); else out=$(./fella.exe $args); fi
+ echo "$rep $name $(echo "$out" | grep -o 'median [0-9.]*' )"
+ done
+done
diff --git a/docs/probes/flesh/matrix2.out b/docs/probes/flesh/matrix2.out
new file mode 100644
index 0000000..7778e5a
--- /dev/null
+++ b/docs/probes/flesh/matrix2.out
@@ -0,0 +1,50 @@
+1 A_ship_pinned_1 median 4.271 live particles 0
+1 B_skipflag_pinned_1 median 0.252 live particles 0
+1 D_forearm_live_1 median 0.204 live particles 40
+1 E_fella_live_1 median 1.025 live particles 661
+1 F_fella_live_gut_1 median 2.244 live particles 961
+1 G_fella_live_contact_1 median 5.117 live particles 661
+1 I_fella_live_heldby_1 median 6.433 live particles 661
+1 H_skipflag_pinned_4 median 1.021 live particles 0
+1 J_4_one_live_absent median 2.266 live particles 661
+1 K_4_one_live_gut_absent median 4.334 live particles 961
+2 A_ship_pinned_1 median 4.918 live particles 0
+2 B_skipflag_pinned_1 median 0.253 live particles 0
+2 D_forearm_live_1 median 0.205 live particles 40
+2 E_fella_live_1 median 1.036 live particles 661
+2 F_fella_live_gut_1 median 2.428 live particles 961
+2 G_fella_live_contact_1 median 12.285 live particles 661
+2 I_fella_live_heldby_1 median 5.280 live particles 661
+2 H_skipflag_pinned_4 median 1.014 live particles 0
+2 J_4_one_live_absent median 2.270 live particles 661
+2 K_4_one_live_gut_absent median 4.166 live particles 961
+3 A_ship_pinned_1 median 5.341 live particles 0
+3 B_skipflag_pinned_1 median 0.256 live particles 0
+3 D_forearm_live_1 median 0.204 live particles 40
+3 E_fella_live_1 median 1.046 live particles 661
+3 F_fella_live_gut_1 median 2.349 live particles 961
+3 G_fella_live_contact_1 median 5.441 live particles 661
+3 I_fella_live_heldby_1 median 5.310 live particles 661
+3 H_skipflag_pinned_4 median 1.046 live particles 0
+3 J_4_one_live_absent median 2.317 live particles 661
+3 K_4_one_live_gut_absent median 4.218 live particles 961
+4 A_ship_pinned_1 median 5.124 live particles 0
+4 B_skipflag_pinned_1 median 0.255 live particles 0
+4 D_forearm_live_1 median 0.204 live particles 40
+4 E_fella_live_1 median 1.028 live particles 661
+4 F_fella_live_gut_1 median 2.359 live particles 961
+4 G_fella_live_contact_1 median 5.683 live particles 661
+4 I_fella_live_heldby_1 median 5.232 live particles 661
+4 H_skipflag_pinned_4 median 1.023 live particles 0
+4 J_4_one_live_absent median 2.271 live particles 661
+4 K_4_one_live_gut_absent median 4.319 live particles 961
+5 A_ship_pinned_1 median 4.507 live particles 0
+5 B_skipflag_pinned_1 median 0.257 live particles 0
+5 D_forearm_live_1 median 0.205 live particles 40
+5 E_fella_live_1 median 1.050 live particles 661
+5 F_fella_live_gut_1 median 2.369 live particles 961
+5 G_fella_live_contact_1 median 5.268 live particles 661
+5 I_fella_live_heldby_1 median 5.052 live particles 661
+5 H_skipflag_pinned_4 median 1.039 live particles 0
+5 J_4_one_live_absent median 2.284 live particles 661
+5 K_4_one_live_gut_absent median 4.262 live particles 961
diff --git a/docs/probes/flesh/matrix2.sh b/docs/probes/flesh/matrix2.sh
new file mode 100644
index 0000000..715448d
--- /dev/null
+++ b/docs/probes/flesh/matrix2.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+CONF='A_ship_pinned_1|MINRING=4|1 0.10 0.14 0 0 0 0 600
+B_skipflag_pinned_1|MINRING=4|1 0.10 0.14 0 1 1 0 600
+D_forearm_live_1|MINRING=4 NOCONTACT=1 ABSENT=1|1 0.10 0.14 1 1 1 0 600
+E_fella_live_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 1 0 600
+F_fella_live_gut_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 1 1 600
+G_fella_live_contact_1|MINRING=4|1 0.10 0.14 3 1 1 0 600
+I_fella_live_heldby_1|MINRING=4 NOCONTACT=1|1 0.10 0.14 3 1 0 0 600
+H_skipflag_pinned_4|MINRING=4|4 0.10 0.14 0 1 1 0 600
+J_4_one_live_absent|MINRING=4 NOCONTACT=1 ABSENT=1|4 0.10 0.14 2 1 1 0 600
+K_4_one_live_gut_absent|MINRING=4 NOCONTACT=1 ABSENT=1|4 0.10 0.14 2 1 1 1 600'
+for rep in 1 2 3 4 5; do
+ echo "$CONF" | while IFS='|' read name env args; do
+ out=$(env $env ./fella.exe $args)
+ echo "$rep $name $(echo "$out" | grep -o 'median [0-9.]*') $(echo "$out" | grep -o 'live particles [0-9]*')"
+ done
+done
diff --git a/docs/probes/flesh/sieve.c b/docs/probes/flesh/sieve.c
new file mode 100644
index 0000000..f4fb07c
--- /dev/null
+++ b/docs/probes/flesh/sieve.c
@@ -0,0 +1,142 @@
+// Sieve probe: a skin sheet attached along its length to a horizontal static capsule (a BDS thigh: r 0.07, half 0.18) at spacing s,
+// under a fluid pour (7x7x7, r 0.0125, 15.6 g) and a dropped solid block (4x4x4 solid particles, r 0.02) at 4 substeps, 60 Hz as the
+// Ymir pour test and 120 Hz as BDS. Readings: worst edge stretch, deep overlaps (pairs within half a contact distance), fluid and
+// solid particles that reach the bone surface through the skin (centre within r_cap + 1.5 r of the axis segment), and fallen below.
+// usage: sieve s hz substeps attach_compliance dropped(0 fluid,1 solid)
+#include "ymir_particles.h"
+#include
+#include
+#include
+#include
+
+static float seglen(float x, float y, float z, float half) // distance from the capsule axis segment (along x here)
+{
+ float cx = x < -half ? -half : x > half ? half : x;
+ return sqrtf((x - cx) * (x - cx) + y * y + z * z);
+}
+
+int main(int argc, char** argv)
+{
+ float s = argc > 1 ? (float)atof(argv[1]) : 0.08f;
+ float hz = argc > 2 ? (float)atof(argv[2]) : 120.f;
+ int sub = argc > 3 ? atoi(argv[3]) : 4;
+ float ac = argc > 4 ? (float)atof(argv[4]) : 1e-3f;
+ int solid = argc > 5 ? atoi(argv[5]) : 0;
+ const float R = 0.07f, HALF = 0.18f, Y = 0.5f;
+ ymir_particle_capacities c = {2048, 8192, 8192, 1024, 2048, 2, 512, 0, 0};
+ ymir_particles* W = ymir_particles_create(&c, 2);
+ ymir_material_desc m = {0.3f, 0.01f, 0, 0, 1};
+ ymir_particles_set_material(W, 0, &m);
+ // the capsule lies along x: Ymir capsules run along local y, so rotate y onto x (90 degrees about z)
+ float q[4] = {0, 0, sinf(-0.785398f), cosf(-0.785398f)};
+ ymir_particle_proxy* b = W->proxies;
+ memset(b, 0, 2 * sizeof *b);
+ b[0].shape = YMIR_PROXY_CAPSULE; b[0].size[0] = R; b[0].size[1] = HALF; b[0].position[1] = Y; memcpy(b[0].rotation, q, sizeof q);
+ b[1].shape = YMIR_PROXY_BOX; b[1].size[0] = 5; b[1].size[1] = 0.5f; b[1].size[2] = 5; b[1].position[1] = -0.5f; b[1].rotation[3] = 1;
+ W->body_count = 2;
+ // skin: rings along the capsule at spacing s, staggered, centres on the bone surface; caps left open (a limb continues at its joints)
+ int rings = (int)ceilf(2 * HALF / s), per = (int)fmaxf(6, roundf(2 * 3.14159f * R / s));
+ int n = (rings + 1) * per;
+ ymir_handle* ph = calloc(n, sizeof *ph);
+ float* lx = calloc(n, sizeof(float)); float* ly = calloc(n, sizeof(float)); float* lz = calloc(n, sizeof(float));
+ for (int i = 0, k = 0; i <= rings; i++)
+ for (int j = 0; j < per; j++, k++)
+ {
+ float a = 2 * 3.14159f * (j + 0.5f * (i & 1)) / per;
+ float x = -HALF + 2 * HALF * i / rings;
+ lx[k] = x; ly[k] = R * cosf(a); lz[k] = R * sinf(a);
+ // local frame of the body is y along the axis: local = (-world y, world x, z) rotated; keep world-space rest and compute the body point
+ ymir_particle_desc d = {{x, Y + ly[k], lz[k]}, {x, Y + ly[k], lz[k]}, {0, 0, 0}, 0.012f * (s * s / 0.0064f), 0.45f * s, 1u, 0};
+ ymir_particles_create_particles(W, 1, &d, 1, &ph[k]);
+ }
+ // edges: ring neighbours, next ring's two nearest; bends along rings and along the axis
+ ymir_handle* eh = calloc(n * 4, sizeof *eh);
+ int ne = 0;
+ int* ringe = calloc(n, sizeof(int)); int* axe = calloc(n, sizeof(int));
+ for (int i = 0; i <= rings; i++)
+ for (int j = 0; j < per; j++)
+ {
+ int k = i * per + j;
+ ymir_distance_desc d = {ph[k], ph[i * per + (j + 1) % per], -1, 2e-4f};
+ ymir_particles_create_distances(W, 1, &d, 1, &eh[ne]); ringe[k] = ne++;
+ if (i < rings)
+ {
+ int j2 = (i & 1) ? (j + 1) % per : j, j3 = (i & 1) ? j : (j + per - 1) % per;
+ ymir_distance_desc d2 = {ph[k], ph[(i + 1) * per + j2], -1, 2e-4f}, d3 = {ph[k], ph[(i + 1) * per + j3], -1, 2e-4f};
+ ymir_particles_create_distances(W, 1, &d2, 1, &eh[ne]); axe[k] = ne++;
+ ymir_particles_create_distances(W, 1, &d3, 1, &eh[ne]); ne++;
+ }
+ }
+ for (int i = 0; i <= rings; i++)
+ for (int j = 0; j < per; j++)
+ {
+ int k = i * per + j, kp = i * per + (j + per - 1) % per;
+ ymir_bend_desc bd = {eh[ringe[kp]], eh[ringe[k]], 1e-3f, -1};
+ ymir_handle hb; ymir_particles_create_bends(W, 1, &bd, 1, &hb);
+ }
+ for (int k = 0; k < n; k++)
+ {
+ // the body frame: rotation q maps local y onto world x; local = q^-1 (world - centre): (x, y', z) world -> local (y', -x ... ) computed numerically
+ float wx = lx[k], wy = ly[k], wz = lz[k];
+ // inverse of a -90 degree turn about z: local x = -wy? Use the exact inverse: rotate by +90 about z: (x, y) -> (-y, x)
+ float px = -wy, py = wx, pz = wz;
+ (void)px;
+ ymir_attachment_desc ad = {YMIR_ATTACH_BODY, 0, ph[k], 0, {-wy * -1.0f * 0 + (-wy) * 0 + wy * 0 + (-wy) , py, pz}, ac, 0};
+ ad.point[0] = -wy; ad.point[1] = wx; ad.point[2] = wz;
+ // check: q (y-axis -> x-axis) applied to (px, py, pz) must give (wx, wy, wz)
+ ad.point[0] = -wy; ad.point[1] = wx; ad.point[2] = wz;
+ ymir_handle ha; ymir_particles_attach(W, &ad, 2, 1, &ha);
+ }
+ // the load: a 7x7x7 block 0.25 m above the capsule's top, centred on it
+ int nl = solid ? 64 : 343, side = solid ? 4 : 7;
+ float lr = solid ? 0.02f : 0.0125f, sp = 2 * lr;
+ ymir_handle* lh = calloc(nl, sizeof *lh);
+ for (int a = 0; a < side; a++) for (int bb = 0; bb < side; bb++) for (int cc = 0; cc < side; cc++)
+ {
+ int k = (a * side + bb) * side + cc;
+ float x = -0.5f * (side - 1) * sp + a * sp, y = Y + R + 0.25f + bb * sp, z = -0.5f * (side - 1) * sp + cc * sp;
+ ymir_particle_desc d = {{x, y, z}, {x, y, z}, {0, 0, 0}, solid ? 0.06f : 0.015625f, lr, solid ? (6u | YMIR_PHASE_SELF_COLLIDE) : (6u | YMIR_PHASE_FLUID), 0};
+ ymir_particles_create_particles(W, 1, &d, 1, &lh[k]);
+ }
+ float h = 1.0f / hz / sub, worst = 0;
+ int deep = 0, through = 0, inside = 0, ticks = (int)(3 * hz);
+ char* hit = calloc(nl, 1);
+ for (int t = 0; t < ticks; t++)
+ {
+ ymir_particles_begin(W);
+ for (int ss = 0; ss < sub; ss++)
+ {
+ for (int k = 0; k < 2; k++) { /* static: pose fixed, velocities zero */ }
+ ymir_particles_substep(W, h, 0, -9.81f, 0);
+ b[0].position[1] = Y; b[0].position[0] = 0; b[0].position[2] = 0; memcpy(b[0].rotation, q, sizeof q);
+ b[1].position[1] = -0.5f; b[1].position[0] = b[1].position[2] = 0; b[1].rotation[0] = b[1].rotation[1] = b[1].rotation[2] = 0; b[1].rotation[3] = 1;
+ }
+ ymir_particles_end(W, sub);
+ for (int e = 0; e < ne; e++)
+ {
+ int i = W->dist_a[eh[e].lane], j = W->dist_b[eh[e].lane];
+ float dx = W->pos_x[i] - W->pos_x[j], dy = W->pos_y[i] - W->pos_y[j], dz = W->pos_z[i] - W->pos_z[j];
+ float st = sqrtf(dx * dx + dy * dy + dz * dz) / W->dist_rest[eh[e].lane] - 1;
+ if (st > worst) worst = st;
+ }
+ for (int k = 0; k < nl; k++)
+ {
+ int l = lh[k].lane;
+ for (int s2 = 0; s2 < n; s2++)
+ {
+ int i = ph[s2].lane;
+ float dx = W->pos_x[i] - W->pos_x[l], dy = W->pos_y[i] - W->pos_y[l], dz = W->pos_z[i] - W->pos_z[l];
+ if (sqrtf(dx * dx + dy * dy + dz * dz) < 0.5f * (W->radius[i] + lr)) deep++;
+ }
+ if (fabsf(W->pos_x[l]) < HALF && seglen(W->pos_x[l], W->pos_y[l] - Y, W->pos_z[l], HALF) < R) inside++;
+ if (!hit[k] && fabsf(W->pos_x[l]) < HALF && seglen(W->pos_x[l], W->pos_y[l] - Y, W->pos_z[l], HALF) < R + 1.5f * lr) { hit[k] = 1; through++; }
+ }
+ }
+ // a sanity read of the skin's place: mean distance of skin centres from the axis (R when held)
+ float md = 0;
+ for (int k = 0; k < n; k++) { int i = ph[k].lane; md += seglen(W->pos_x[i], W->pos_y[i] - Y, W->pos_z[i], HALF); }
+ int below = 0; for (int k = 0; k < nl; k++) below += W->pos_y[lh[k].lane] < 0.05f;
+ printf("SIEVE s=%.3f %gHz x%d attach_c=%g load=%s: skin %d particles r %.3f, %d edges | worst stretch %.4f | deep (tick x pair) %d | load reaching the bone through the skin %d of %d | inside the bone (tick x particle) %d | on the floor at 3 s %d | skin mean axis distance %.4f (R %.3f)\n",
+ s, hz, sub, ac, solid ? "solid" : "fluid", n, 0.45f * s, ne, worst, deep, through, nl, inside, below, md / n, R);
+ return 0;
+}
diff --git a/docs/probes/flesh/ymir_particles.probe.patch b/docs/probes/flesh/ymir_particles.probe.patch
new file mode 100644
index 0000000..e005493
--- /dev/null
+++ b/docs/probes/flesh/ymir_particles.probe.patch
@@ -0,0 +1,691 @@
+--- /tmp/base_ymir_particles.c 2026-11-25 20:46:03.839493800 +0100
++++ /c/Users/Meta/AppData/Local/Temp/claude/a3c197df03062ea3/0d8e833d-7cf1-4193-ba8c-8babeaf48eda/scratchpad/imag-flesh/ymir_particles.c 2026-11-25 20:14:24.880958500 +0100
+@@ -5,6 +5,16 @@
+ // every sum in a fixed order. See ymir_particles.h.
+
+ #include "ymir_particles.h"
++#include
++uint8_t* probe_pinned = 0; int32_t* probe_body_group = 0;
++#include
++double probe_t[8];
++static double pnow(void){LARGE_INTEGER c,f;QueryPerformanceCounter(&c);QueryPerformanceFrequency(&f);return 1000.0*(double)c.QuadPart/(double)f.QuadPart;}
++#define T(k,x) do{double _t=pnow(); x; probe_t[k]+=pnow()-_t;}while(0)
++int probe_nocontact = 0;
++#define PIN(i) ((probe_pinned && probe_pinned[i]) || (probe_nocontact && !(p->phase[i] & (YMIR_PHASE_SELF_COLLIDE|YMIR_PHASE_FLUID)) && grid_ctx))
++static int grid_ctx = 0;
++
+
+ #include
+ #include
+@@ -1364,7 +1374,7 @@
+ memset(p->cell_start, 0, sizeof(int32_t) * (size_t)(buckets + 1));
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (!p->particle_live[i] || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
++ if (!p->particle_live[i] || PIN(i) || (solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ {
+ continue;
+ }
+@@ -1380,7 +1390,7 @@
+ }
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (p->particle_live[i] && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
++ if (p->particle_live[i] && !PIN(i) && !(solids && (p->phase[i] & YMIR_PHASE_FLUID)))
+ {
+ uint32_t c = cell_hash(p->cell_x[i], p->cell_y[i], p->cell_z[i], p->table_mask);
+ p->sorted[p->cell_start[c] + p->cell_fill[c]++] = i;
+@@ -1461,7 +1471,7 @@
+ {
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+- if (!p->particle_live[i] || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
++ if (!p->particle_live[i] || PIN(i) || (p->phase[i] & YMIR_PHASE_FLUID)) // the grid holds no fluid lane
+ {
+ continue;
+ }
+@@ -1979,7 +1989,7 @@
+ {
+ continue;
+ }
+- if (held_by(p, i, k))
++ if (probe_body_group ? probe_body_group[k] == (int32_t)(p->phase[i] & YMIR_PHASE_GROUP_MASK) : held_by(p, i, k))
+ {
+ continue;
+ }
+@@ -2056,6 +2066,7 @@
+ continue;
+ }
+ int32_t i = p->att_particle[a];
++ if (PIN(i)) continue;
+ v3 at = end_point(p, a);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, i), at);
+ float len = vlen(d);
+@@ -2088,6 +2099,7 @@
+ continue;
+ }
+ int32_t i = p->dist_a[e], j = p->dist_b[e];
++ if (PIN(i) && PIN(j)) continue;
+ float wi = p->inv_mass[i], wj = p->inv_mass[j], alpha = p->dist_compliance[e] / (f->h * f->h);
+ v3 d = vsub(P(p, p->pp_x, p->pp_y, p->pp_z, j), P(p, p->pp_x, p->pp_y, p->pp_z, i));
+ float len = vlen(d);
+@@ -2117,6 +2129,7 @@
+ continue;
+ }
+ int32_t a = p->bend_a[k], b = p->bend_b[k], c = p->bend_c[k];
++ if (PIN(a) && PIN(b) && PIN(c)) continue;
+ float wa = p->inv_mass[a], wb = p->inv_mass[b], wc = p->inv_mass[c];
+ v3 ja = {0.0f, 0.0f, 0.0f}, jc = {0.0f, 0.0f, 0.0f};
+ for (int pass = 0; pass < 2; ++pass)
+@@ -2320,17 +2333,17 @@
+ }
+ put(p->pp_x, p->pp_y, p->pp_z, i, x);
+ }
+- build_grid(p);
+- particle_contacts(p);
++ grid_ctx = 1; T(0, build_grid(p););
++ T(1, particle_contacts(p);); grid_ctx = 0;
+ if (p->live_fluid > 0)
+ {
+ fluid_density(p);
+ }
+- solve_attachments(&f);
+- solve_distances(&f);
+- solve_bends(&f);
+- solve_tethers(&f);
+- body_contacts(&f);
++ T(2, solve_attachments(&f););
++ T(3, solve_distances(&f););
++ T(4, solve_bends(&f););
++ T(5, solve_tethers(&f););
++ T(6, body_contacts(&f););
+ for (int32_t i = 0; i < p->particle_count; ++i)
+ {
+ if (!p->particle_live[i])
+--- /tmp/base_ymir_particles.h 2026-11-25 20:46:03.949325900 +0100
++++ /c/Users/Meta/AppData/Local/Temp/claude/a3c197df03062ea3/0d8e833d-7cf1-4193-ba8c-8babeaf48eda/scratchpad/imag-flesh/ymir_particles.h 2026-11-25 20:09:57.828286700 +0100
+@@ -1,292 +1,292 @@
+-// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
+-// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
+-// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
+-// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
+-// See docs/soa-world.md.
+-//
+-// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
+-// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
+-// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
+-// topology command ends in and which is their only writer.
+-//
+-// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
+-// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
+-// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
+-// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
+-// on MSVC) so no fused multiply-add changes a byte.
+-//
+-// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
+-// No code of PhysX 5.6.0 or any other solver is adapted here.
+-
+-#ifndef YMIR_PARTICLES_H
+-#define YMIR_PARTICLES_H
+-
+-#include
+-
+-enum
+-{
+- YMIR_PARTICLES_OK = 0,
+- YMIR_PARTICLES_INVALID_ARGUMENT = 1,
+- YMIR_PARTICLES_DUPLICATE_ID = 2,
+- YMIR_PARTICLES_FULL = 3,
+- YMIR_PARTICLES_OUT_OF_MEMORY = 4
+-};
+-
+-// Phase word: bits 0-19 are the group; the three flags below are the only other bits.
+-enum
+-{
+- YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
+- YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
+- YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
+- YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
+- // the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
+- YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID
+-};
+-
+-// Lane sets a command names (a type for remove, a set for free_slots).
+-enum
+-{
+- YMIR_LANES_PARTICLE = 0,
+- YMIR_LANES_DISTANCE = 1,
+- YMIR_LANES_BEND = 2,
+- YMIR_LANES_ATTACHMENT = 3,
+- YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
+- YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
+-};
+-
+-enum
+-{
+- YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
+- YMIR_ATTACH_STATIC = 1, // particle to a world point
+- YMIR_ATTACH_REMOVED = 2
+-};
+-
+-enum
+-{
+- YMIR_ATTACH_FLAG_TETHER = 1u // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
+-};
+-
+-enum
+-{
+- YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
+- YMIR_PROXY_SPHERE = 1,
+- YMIR_PROXY_CAPSULE = 2, // segment along local Y
+- YMIR_PROXY_BOX = 3
+-};
+-
+-// A lane and the generation it had when the handle was made.
+-typedef struct ymir_handle
+-{
+- int32_t lane;
+- uint32_t generation;
+-} ymir_handle;
+-
+-typedef struct ymir_particle_capacities
+-{
+- int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
+-} ymir_particle_capacities;
+-
+-// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
+-// the self-collision filter read it); `material` indexes the material table.
+-typedef struct ymir_particle_desc
+-{
+- float position[3];
+- float rest[3];
+- float velocity[3];
+- float mass;
+- float radius;
+- uint32_t phase;
+- uint32_t material;
+-} ymir_particle_desc;
+-
+-// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
+-typedef struct ymir_distance_desc
+-{
+- ymir_handle a, b;
+- float rest;
+- float compliance;
+-} ymir_distance_desc;
+-
+-// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
+-// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
+-typedef struct ymir_bend_desc
+-{
+- ymir_handle e1, e2;
+- float compliance;
+- float max_angle;
+-} ymir_bend_desc;
+-
+-// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
+-// or the world (static).
+-typedef struct ymir_attachment_desc
+-{
+- uint32_t kind;
+- uint32_t flags;
+- ymir_handle particle;
+- int32_t body;
+- float point[3];
+- float compliance; // m/N, >= 0
+- uint32_t reserved;
+-} ymir_attachment_desc;
+-
+-// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
+-typedef struct ymir_sensor_desc
+-{
+- int32_t body;
+- float point[3];
+- float radius;
+-} ymir_sensor_desc;
+-
+-typedef struct ymir_material_desc
+-{
+- float friction; // >= 0
+- float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
+- float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
+- uint32_t pad;
+- uint64_t material_id;
+-} ymir_material_desc;
+-
+-// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
+-// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
+-typedef struct ymir_particle_proxy
+-{
+- uint32_t shape;
+- float size[3];
+- float position[3];
+- float rotation[4]; // x y z w
+- float velocity[3];
+- float angular_velocity[3];
+- float inv_mass; // 0 for static, kinematic and anchor bodies
+- float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
+- float impulse[3]; // N s, world: the tick's total, the sum of every substep's
+- float angular_impulse[3];
+- float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
+- float sub_angular[3];
+-} ymir_particle_proxy;
+-
+-typedef struct ymir_particles
+-{
+- int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
+- int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
+- int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
+- int32_t tether_count; // derived: the live tethers
+- int32_t body_count; // bodies filled in `proxies` this step
+- int32_t live_particles;
+- int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
+- int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
+- int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
+- int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
+- int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
+- ymir_particle_proxy* proxies;
+-
+- // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
+- float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
+- float *rest_x, *rest_y, *rest_z;
+- uint32_t *phase, *material, *particle_live, *particle_generation;
+- uint64_t* particle_removed_at;
+- int32_t* component; // derived: the lowest lane of the particle's distance-connected component
+- int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
+- int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
+- float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
+-
+- // wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
+- // one of the two is -1, and a free lane holds -1 in both. Written by settle, remove and destroy_particles only; the step never touches them.
+- int32_t *wet_body, *wet_particle;
+- float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
+- uint32_t *wet_material, *wet_live, *wet_generation;
+- uint64_t* wet_removed_at;
+- int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
+- float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
+- float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
+- float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
+- int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
+- float *wu_x, *wu_y, *wu_z, *wu_volume;
+-
+- // sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
+- // remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
+- // and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
+- int32_t* sensor_body;
+- float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
+- uint32_t *sensor_live, *sensor_generation;
+- uint64_t* sensor_removed_at;
+-
+- // distance lanes
+- int32_t *dist_a, *dist_b;
+- float *dist_rest, *dist_compliance;
+- float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
+- uint32_t *dist_live, *dist_generation;
+- uint64_t* dist_removed_at;
+-
+- // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
+- int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
+- float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
+- uint32_t *bend_live, *bend_generation;
+- uint64_t* bend_removed_at;
+-
+- // attachment lanes
+- uint32_t *att_kind, *att_flags, *att_generation;
+- int32_t *att_particle, *att_body;
+- float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
+- float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
+- uint64_t* att_removed_at;
+-
+- // tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
+- // lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
+- // among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
+- // booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
+- // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
+- int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
+- float* tether_bound;
+-
+- // material table
+- float *mat_friction, *mat_viscosity, *mat_wet_friction;
+- uint64_t* mat_id;
+-
+- // solver scratch, allocated once at create
+- float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
+- float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
+- int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
+- float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
+- uint32_t* sphase; // the sorted lanes' phase
+- int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
+- float *heap_key, *path, *near_path;
+- uint8_t* done;
+- uint32_t table_mask;
+- void* arena;
+-} ymir_particles;
+-
+-// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
+-ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
+-void ymir_particles_free(ymir_particles* p);
+-
+-// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
+-float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
+-
+-// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
+-// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
+-// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command ends in the one rederive_topology.
+-int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
+-int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
+-int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
+-int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
+-int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
+-int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
+-// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
+-// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
+-// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no patch to merge into, before any
+-// change. `out` (NULL or n handles) receives the patch each drop landed in.
+-int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count, ymir_handle* out);
+-// Creates liquid sensors in the lowest free lanes. Refuses whole (INVALID_ARGUMENT) a body outside [0, body_count), a radius that is not finite and > 0, or a
+-// non-finite point; FULL when there are not n free lanes; nothing changes. A sensor only reads: its volume moves nothing.
+-int32_t ymir_particles_create_sensors(ymir_particles* p, int32_t n, const ymir_sensor_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
+-int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d);
+-int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count);
+-
+-// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
+-// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
+-// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
+-int32_t ymir_particles_begin(ymir_particles* p);
+-void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
+-void ymir_particles_end(ymir_particles* p, int32_t substeps);
+-
+-#endif
++// Particles and the constraints between them: Ymir's own position-based solver, stepped inside Box3D's substeps
++// (see ymir_box3d_soa.c, the only Box3D caller). This module knows nothing of Box3D. soa.c fills one proxy per body
++// (pose, velocity, shape, inverse mass and inertia) before each substep, the solver moves those proxies by the
++// constraints it solves, and the impulse each body accumulated comes back in the proxy for soa.c to apply.
++// See docs/soa-world.md.
++//
++// There is no object above the lanes: particles are one lane set with a phase word, and every constraint type
++// (distance, bend, attachment) is a lane set of its own. A thing made of particles is whatever constraints a
++// caller emitted. Tethers and components are derived from the distance graph by rederive_topology, which every
++// topology command ends in and which is their only writer.
++//
++// Determinism: single thread; constraints are Gauss-Seidel in lane order; the one Jacobi pass (particle-particle
++// contact) accumulates and applies after the walk (each pair once, from the lower of its two cells, neighbours read in cell then index order
++// from a stable counting-sort grid, a pair weighted the same at both ends); proxy impulses are summed per body
++// in lane order; heap and breadth-first orders break ties by lane. Compiled with -ffp-contract=off (/fp:precise
++// on MSVC) so no fused multiply-add changes a byte.
++//
++// Licence note: the formulas come from the papers (Kelager 2010 bend, Kim 2012 tethers, Macklin 2014, 2016, 2019).
++// No code of PhysX 5.6.0 or any other solver is adapted here.
++
++#ifndef YMIR_PARTICLES_H
++#define YMIR_PARTICLES_H
++
++#include
++
++enum
++{
++ YMIR_PARTICLES_OK = 0,
++ YMIR_PARTICLES_INVALID_ARGUMENT = 1,
++ YMIR_PARTICLES_DUPLICATE_ID = 2,
++ YMIR_PARTICLES_FULL = 3,
++ YMIR_PARTICLES_OUT_OF_MEMORY = 4
++};
++
++// Phase word: bits 0-19 are the group; the three flags below are the only other bits.
++enum
++{
++ YMIR_PHASE_GROUP_MASK = 0xFFFFFu,
++ YMIR_PHASE_SELF_COLLIDE = 1u << 20, // particles of one group collide (both must set it)
++ YMIR_PHASE_SELF_FILTER = 1u << 21, // ... except pairs closer than 1.5 (ri + rj) in the rest pose (either sets it)
++ YMIR_PHASE_FLUID = 1u << 22, // a fluid particle: number density, not contact, with other fluid; contact with solids. Group and
++ // the SELF_* flags are ignored between two fluid particles (all fluid shares one density field)
++ YMIR_PHASE_VALID = YMIR_PHASE_GROUP_MASK | YMIR_PHASE_SELF_COLLIDE | YMIR_PHASE_SELF_FILTER | YMIR_PHASE_FLUID
++};
++
++// Lane sets a command names (a type for remove, a set for free_slots).
++enum
++{
++ YMIR_LANES_PARTICLE = 0,
++ YMIR_LANES_DISTANCE = 1,
++ YMIR_LANES_BEND = 2,
++ YMIR_LANES_ATTACHMENT = 3,
++ YMIR_LANES_WET = 4, // a wet patch: settled liquid on a body or a solid particle
++ YMIR_LANES_SENSOR = 5 // a liquid sensor: a sphere fixed in a body that reads the liquid volume inside it
++};
++
++enum
++{
++ YMIR_ATTACH_BODY = 0, // particle to a point fixed in a body (its lane)
++ YMIR_ATTACH_STATIC = 1, // particle to a world point
++ YMIR_ATTACH_REMOVED = 2
++};
++
++enum
++{
++ YMIR_ATTACH_FLAG_TETHER = 1u // bounds each particle by the rest path to the nearest point of its two nearest islands of tether attachments
++};
++
++enum
++{
++ YMIR_PROXY_NONE = 0, // no shape (an anchor): attachments reach it, particles never touch it
++ YMIR_PROXY_SPHERE = 1,
++ YMIR_PROXY_CAPSULE = 2, // segment along local Y
++ YMIR_PROXY_BOX = 3
++};
++
++// A lane and the generation it had when the handle was made.
++typedef struct ymir_handle
++{
++ int32_t lane;
++ uint32_t generation;
++} ymir_handle;
++
++typedef struct ymir_particle_capacities
++{
++ int32_t particles, distances, bends, attachments, tethers, materials, fluid, wets, sensors; // fluid: the most live particles with the FLUID phase; wets: the most wet patches; sensors: the most liquid sensors
++} ymir_particle_capacities;
++
++// A particle to create. `mass` kg (0 = immovable); `velocity` m/s; `rest` is its place in the rest pose (rest lengths, bends and
++// the self-collision filter read it); `material` indexes the material table.
++typedef struct ymir_particle_desc
++{
++ float position[3];
++ float rest[3];
++ float velocity[3];
++ float mass;
++ float radius;
++ uint32_t phase;
++ uint32_t material;
++} ymir_particle_desc;
++
++// A distance constraint. `rest` < 0 takes the rest-pose length. `compliance` m/N, >= 0.
++typedef struct ymir_distance_desc
++{
++ ymir_handle a, b;
++ float rest;
++ float compliance;
++} ymir_distance_desc;
++
++// A bend over two distance constraints that share one particle. `compliance` < 0 switches the soft pass off;
++// `max_angle` (radians, the deflection from straight) < 0 switches the hard limit off.
++typedef struct ymir_bend_desc
++{
++ ymir_handle e1, e2;
++ float compliance;
++ float max_angle;
++} ymir_bend_desc;
++
++// An attachment of `particle`. `body` is the body lane (body kind) or -1. `point` is in the body's frame (body)
++// or the world (static).
++typedef struct ymir_attachment_desc
++{
++ uint32_t kind;
++ uint32_t flags;
++ ymir_handle particle;
++ int32_t body;
++ float point[3];
++ float compliance; // m/N, >= 0
++ uint32_t reserved;
++} ymir_attachment_desc;
++
++// A liquid sensor to create: a sphere of `radius` m (> 0) centred on `point` in the frame of body lane `body`.
++typedef struct ymir_sensor_desc
++{
++ int32_t body;
++ float point[3];
++ float radius;
++} ymir_sensor_desc;
++
++typedef struct ymir_material_desc
++{
++ float friction; // >= 0
++ float viscosity; // >= 0, XSPH c (dimensionless): a fluid pair's velocities relax toward each other by c W / n0 per substep; mean of the pair's two
++ float wet_friction; // >= 0: what settled liquid of this material does to friction where it lands; stored for the friction cut, read by nothing here
++ uint32_t pad;
++ uint64_t material_id;
++} ymir_material_desc;
++
++// A body as the particle phase sees it. Filled by the caller before a step; `impulse` and `angular_impulse`
++// (N s, world, about the body position) are the totals the particle phase delivered, written by it.
++typedef struct ymir_particle_proxy
++{
++ uint32_t shape;
++ float size[3];
++ float position[3];
++ float rotation[4]; // x y z w
++ float velocity[3];
++ float angular_velocity[3];
++ float inv_mass; // 0 for static, kinematic and anchor bodies
++ float inv_inertia[6]; // world inverse inertia, symmetric: xx xy xz yy yz zz
++ float impulse[3]; // N s, world: the tick's total, the sum of every substep's
++ float angular_impulse[3];
++ float sub_impulse[3]; // N s: this substep's, applied by the caller before the body's positions integrate
++ float sub_angular[3];
++} ymir_particle_proxy;
++
++typedef struct ymir_particles
++{
++ int32_t particle_capacity, distance_capacity, bend_capacity, attachment_capacity, tether_capacity, material_capacity;
++ int32_t body_capacity, fluid_capacity; // fluid_capacity: the most live fluid particles; it sizes the neighbour arena
++ int32_t particle_count, distance_count, bend_count, attachment_count; // high-water marks
++ int32_t tether_count; // derived: the live tethers
++ int32_t body_count; // bodies filled in `proxies` this step
++ int32_t live_particles;
++ int32_t fluid_rings; // derived by fluid_density: rings of kernel cells (4 rfmax) that hold a kernel pair, 0 without fluid
++ int32_t fluid_overflow; // kernel neighbours past a fluid particle's list in the last step, summed over substeps: a sensor
++ int32_t wet_capacity, wet_count; // wet patches: the capacity and the high-water mark
++ int32_t sensor_capacity, sensor_count; // liquid sensors: the capacity and the high-water mark
++ int32_t live_fluid; // derived: the live particles with the FLUID phase bit; the create and destroy commands are its only writers
++ ymir_particle_proxy* proxies;
++
++ // particle lanes; a free lane reads live 0 and every other lane 0 except generation and removed_at
++ float *pos_x, *pos_y, *pos_z, *vel_x, *vel_y, *vel_z, *radius, *inv_mass;
++ float *rest_x, *rest_y, *rest_z;
++ uint32_t *phase, *material, *particle_live, *particle_generation;
++ uint64_t* particle_removed_at;
++ int32_t* component; // derived: the lowest lane of the particle's distance-connected component
++ int32_t *nbr, *nbr_start, *nbr_count; // scratch: the fluid rows' kernel neighbours in walk order, packed (CSR) in an arena of fluid_capacity * YMIR_FLUID_NEIGHBOURS; row i holds nbr_count[i] from nbr_start[i], this substep's
++ int32_t *support_body, *support_particle; // sensor: what a fluid particle touched in the last substep, the highest body lane / the first solid lane its row listed touching it; -1 for none, and always -1 for a solid or free lane
++ float* density; // sensor: a fluid particle's number density over its rest density n_i / n0 in the last substep it ran, else 0
++
++ // wet lanes: a patch of settled liquid on one support, a body (wet_body, its point in the body frame) or a solid particle (wet_particle, point 0);
++ // one of the two is -1, and a free lane holds -1 in both. Written by settle, remove and destroy_particles only; the step never touches them.
++ int32_t *wet_body, *wet_particle;
++ float *wet_x, *wet_y, *wet_z, *wet_radius, *wet_volume; // wet_volume m^3; wet_radius = sqrt(volume / (pi YMIR_WET_FILM))
++ uint32_t *wet_material, *wet_live, *wet_generation;
++ uint64_t* wet_removed_at;
++ int32_t *wet_order, *wet_body_start, *wet_body_count; // derived lookup index (rederive_wet): live body patches by body then centre x; each body's slice
++ float* wet_body_box; // derived, 7 per body: min xyz and max xyz of its discs' boxes, then its largest radius
++ float* particle_wet_mu; // derived, per particle lane: the wet friction of the lowest live patch on that solid particle, +inf when dry (rederive_wet)
++ float* wet_volume_body; // derived, per body lane: the sum of the live patches on it in wet lane order (rederive_wet, at command time only)
++ int32_t* wu_code; // settle's undo log, one entry per distinct drop: a patch lane (merged: its old lanes below) or -(lane + 1) (created)
++ float *wu_x, *wu_y, *wu_z, *wu_volume;
++
++ // sensor lanes: a sphere fixed in a body; a free lane reads live 0, body -1 and 0 elsewhere except generation and removed_at. Written by create_sensors and
++ // remove; sensor_liquid_volume and sensor_wet_volume are written by end alone, at the step's end (m^3): the sum of (2 r)^3 over the live fluid particles whose centre is inside,
++ // and the sum of the volumes of the live wet patches whose centre is inside, on any body or solid particle
++ int32_t* sensor_body;
++ float *sensor_x, *sensor_y, *sensor_z, *sensor_radius, *sensor_liquid_volume, *sensor_wet_volume;
++ uint32_t *sensor_live, *sensor_generation;
++ uint64_t* sensor_removed_at;
++
++ // distance lanes
++ int32_t *dist_a, *dist_b;
++ float *dist_rest, *dist_compliance;
++ float* dist_tension; // N, the load the constraint carries, mean over the substeps: a sensor
++ uint32_t *dist_live, *dist_generation;
++ uint64_t* dist_removed_at;
++
++ // bend lanes: e1 and e2 are distance lanes; a, b, c the particles (b shared)
++ int32_t *bend_e1, *bend_e2, *bend_a, *bend_b, *bend_c;
++ float *bend_rest, *bend_limit, *bend_compliance; // offsets of b from the centroid; limit < 0 is off
++ uint32_t *bend_live, *bend_generation;
++ uint64_t* bend_removed_at;
++
++ // attachment lanes
++ uint32_t *att_kind, *att_flags, *att_generation;
++ int32_t *att_particle, *att_body;
++ float *att_point_x, *att_point_y, *att_point_z, *att_compliance;
++ float *att_force_x, *att_force_y, *att_force_z; // N, the force the attachment exerts on its particles (mean): a sensor
++ uint64_t* att_removed_at;
++
++ // tether lanes: derived: grouped by island in lane order (an island: tether particles joined by live distances, named by its
++ // lowest tether attachment), settle order within; per island one for each particle that is not a tether particle and holds the island
++ // among its two nearest, to the attachment point it is nearest; then per attachment pair with a body among them a route of
++ // booking lanes (attachment -1, edge only) along their rest path and the pair tether; parents come first;
++ // other >= 0 makes the tether a bound between two attachment points (edge -1) instead of a particle and a point
++ int32_t *tether_att, *tether_particle, *tether_parent, *tether_edge, *tether_other;
++ float* tether_bound;
++
++ // material table
++ float *mat_friction, *mat_viscosity, *mat_wet_friction;
++ uint64_t* mat_id;
++
++ // solver scratch, allocated once at create
++ float *pp_x, *pp_y, *pp_z, *dp_x, *dp_y, *dp_z, *dist_acc, *tacc_x, *tacc_y, *tacc_z, *lambda;
++ float fluid_k; // n0(h) = fluid_k / h^3: the Poly6 sum over the simple-cubic lattice of spacing h / 2, a create-time constant
++ int32_t *lane_list, *cell_x, *cell_y, *cell_z, *cell_start, *cell_fill, *sorted, *contacts;
++ float *sx, *sy, *sz, *sw; // the fluid grid's lanes in sorted order (predicted position, inverse mass): scratch, only fluid_density reads them
++ uint32_t* sphase; // the sorted lanes' phase
++ int32_t *adj_start, *adj_edge, *heap_node, *heap_edge, *via, *owner, *tether_of, *queue, *comp_size, *isle, *near_isle;
++ float *heap_key, *path, *near_path;
++ uint8_t* done;
++ uint32_t table_mask;
++ void* arena;
++} ymir_particles;
++
++// Creates the state for the capacities (all >= 0) and `body_capacity` proxies; NULL on failure.
++ymir_particles* ymir_particles_create(const ymir_particle_capacities* capacities, int32_t body_capacity);
++void ymir_particles_free(ymir_particles* p);
++
++// The friction on body lane `body` at body-frame point (x, y, z): the wet friction of the lowest live patch whose disc holds it, never above mu.
++float ymir_particles_wet_mu(const ymir_particles* p, int32_t body, float x, float y, float z, float mu);
++
++// Commands. `step_count` is the world's completed steps: a removed lane is reused once a step has passed, lowest
++// lane first. Every refusal happens before anything changes; a command that would need more tethers than the
++// capacity is refused whole (tether capacity: up to two per particle reached, plus the pair routes). Every topology command ends in the one rederive_topology.
++int32_t ymir_particles_create_particles(ymir_particles* p, int32_t n, const ymir_particle_desc* d, uint64_t step_count, ymir_handle* out);
++int32_t ymir_particles_destroy_particles(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count);
++int32_t ymir_particles_create_distances(ymir_particles* p, int32_t n, const ymir_distance_desc* d, uint64_t step_count, ymir_handle* out);
++int32_t ymir_particles_create_bends(ymir_particles* p, int32_t n, const ymir_bend_desc* d, uint64_t step_count, ymir_handle* out);
++int32_t ymir_particles_attach(ymir_particles* p, const ymir_attachment_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
++int32_t ymir_particles_remove(ymir_particles* p, uint32_t type, int32_t n, const ymir_handle* h, uint64_t step_count);
++// Settles the named fluid particles into wet patches and destroys them. Each reads its support from the last step (support_body, else
++// support_particle) and its contact point from the proxies the caller has just filled; a drop's volume is (2 r)^3. Refuses whole
++// (INVALID_ARGUMENT) a dead or non-fluid particle or one with no support, FULL when a drop finds no lane and no patch to merge into, before any
++// change. `out` (NULL or n handles) receives the patch each drop landed in.
++int32_t ymir_particles_settle(ymir_particles* p, int32_t n, const ymir_handle* h, uint64_t step_count, ymir_handle* out);
++// Creates liquid sensors in the lowest free lanes. Refuses whole (INVALID_ARGUMENT) a body outside [0, body_count), a radius that is not finite and > 0, or a
++// non-finite point; FULL when there are not n free lanes; nothing changes. A sensor only reads: its volume moves nothing.
++int32_t ymir_particles_create_sensors(ymir_particles* p, int32_t n, const ymir_sensor_desc* d, int32_t body_count, uint64_t step_count, ymir_handle* out);
++int32_t ymir_particles_set_material(ymir_particles* p, int32_t index, const ymir_material_desc* d);
++int32_t ymir_particles_free_slots(const ymir_particles* p, uint32_t lane_set, uint64_t step_count);
++
++// The particle phase runs inside the rigid solver's substeps: begin once per tick (after the caller filled the
++// proxies' shape, size, inverse mass and inertia), substep once per rigid substep (after the caller refreshed each
++// proxy's pose and velocity; it then applies each proxy's sub_impulse before positions integrate), end once.
++int32_t ymir_particles_begin(ymir_particles* p);
++void ymir_particles_substep(ymir_particles* p, float h, float gx, float gy, float gz);
++void ymir_particles_end(ymir_particles* p, int32_t substeps);
++
++#endif
diff --git a/docs/probes/planner/Program.cs b/docs/probes/planner/Program.cs
new file mode 100644
index 0000000..887e8e1
--- /dev/null
+++ b/docs/probes/planner/Program.cs
@@ -0,0 +1,60 @@
+using System; using System.Diagnostics; using System.Collections.Generic;
+// Facts: 128 bits. Self: Near(s)=s (0..15), Holding(s)=16+s, HandFree=32, Free=33, Fed=34.
+// Per slot: Unlocked(s)=64+s, Open(s)=80+s, Off(s)=96+s.
+struct F { public ulong A, B;
+ public static F Bit(int i){ var f=new F(); if(i<64) f.A=1UL<new F{A=x.A|y.A,B=x.B|y.B};
+ public static F operator&(F x,F y)=>new F{A=x.A&y.A,B=x.B&y.B};
+ public static F operator~(F x)=>new F{A=~x.A,B=~x.B};
+ public bool Any=>(A|B)!=0; }
+struct Act { public F Pre, Add, Del; public float Cost; }
+static class P {
+ const int N=16; static Act[] acts; static int nActs; static F start;
+ // per goal: want fact per target slot
+ static int[] doors={0,1}, keys={2,3}; const int knife=4, strap=5, sw=6, food=7;
+ static int HB(int s)=>16+s;
+ static void Build(){
+ var l=new List(); F nearAll=new F{A=0xFFFF};
+ for(int s=0;s((r.A&~s.A)|(r.B&~s.B))==0;
+ static long nodes;
+ // regressive DFS: required set r, depth left d
+ static bool Reg(F r,int d){ nodes++; if(Sub(r,start)) return true; if(d==0) return false;
+ for(int i=0;ibest) best=y; } sink+=best; }
+ static void Main(string[] args){ Build(); wants=new[]{F.Bit(80+0),F.Bit(80+1),F.Bit(96+sw),F.Bit(34),F.Bit(HB(knife)),F.Bit(80+9)};
+ Console.WriteLine($"grounded actions {nActs}");
+ for(int d=1;d<=8;d++){ nodes=0; int f=Plan(d,false); long rn=nodes; nodes=0; int ff= d<=5? Plan(d,true):-1; Console.WriteLine($"depth {d}: plans found {f}/6, regressive nodes {rn}, forward nodes {(d<=5?nodes:-1)} found {ff}"); }
+ // timing: paired interleaved medians, rounds x conditions in shuffled order
+ var conds=new List<(string,Action)>{("utility-only",()=>Utility())};
+ for(int d=1;d<=4;d++){int dd=d; conds.Add(($"reg d{d}",()=>{Utility();Plan(dd,false);})); }
+ for(int d=1;d<=4;d++){int dd=d; conds.Add(($"fwd d{d}",()=>{Utility();Plan(dd,true);})); }
+ int rounds=41, reps=200; var t=new double[conds.Count,rounds]; var rng=new Random(7); var sw2=new Stopwatch();
+ for(int w=0;w<3;w++) foreach(var c in conds) for(int i=0;i0;i--){int j=rng.Next(i+1);(order[i],order[j])=(order[j],order[i]);}
+ foreach(int c in order){ sw2.Restart(); for(int i=0;i0?"":"."); } }
diff --git a/docs/probes/planner/probe.csproj b/docs/probes/planner/probe.csproj
new file mode 100644
index 0000000..9532288
--- /dev/null
+++ b/docs/probes/planner/probe.csproj
@@ -0,0 +1,3 @@
+
+ Exe net10.0 disable true true
+
diff --git a/src/Lodur.Body.Ymir/AssemblyInfo.cs b/src/Lodur.Body.Ymir/AssemblyInfo.cs
deleted file mode 100644
index 4b4cdac..0000000
--- a/src/Lodur.Body.Ymir/AssemblyInfo.cs
+++ /dev/null
@@ -1 +0,0 @@
-[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Lodur.Tests")]
diff --git a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs b/src/Lodur.Body.Ymir/HumanoidRagdoll.cs
deleted file mode 100644
index eaa28f0..0000000
--- a/src/Lodur.Body.Ymir/HumanoidRagdoll.cs
+++ /dev/null
@@ -1,139 +0,0 @@
-using System;
-using Ymir.Box3D;
-
-namespace Lodur.Body.Ymir
-{
- /// The ragdoll's joints, in strength-array and target-array order.
- internal enum Muscle
- {
- Spine, Neck, ShoulderL, ShoulderR, ElbowL, ElbowR, HipL, HipR, KneeL, KneeR, AnkleL, AnkleR
- }
-
- /// The ragdoll's bodies, also the limb label written into the world's limb lane.
- internal enum Limb
- {
- Pelvis, Torso, Head, UpperArmL, UpperArmR, LowerArmL, LowerArmR, ThighL, ThighR, ShinL, ShinR, FootL, FootR
- }
-
- ///
- /// A 13-body humanoid built in a caller-owned Ymir SoA world (invariant one-physics-world): capsule limbs,
- /// box pelvis, torso and feet, a sphere head, spherical joints at spine, neck, shoulders and hips, hinges at
- /// elbows, knees and ankles. Facing +z, left is +x, standing on y = 0 at the creation pose, which is also
- /// every joint's zero. is the muscle layer: it turns caller-owned strengths and target
- /// rotations into torques on the world's torque lanes and does nothing else to the physics.
- ///
- internal sealed class HumanoidRagdoll
- {
- public const int MuscleCount = 12;
- public const int LimbCount = 13;
-
- private const float Density = 1000f;
- private const float Friction = 0.8f;
- private const float HeadRolling = 0.1f; // a bare sphere on the ground rolls on, so the fallen head never settles
-
- private readonly Box3DSoaWorld _world;
- private readonly int[] _bodyLane = new int[LimbCount];
- private readonly int[] _jointLane = new int[MuscleCount];
- private readonly MuscleGains[] _gains = new MuscleGains[MuscleCount];
-
- private HumanoidRagdoll(Box3DSoaWorld world) => _world = world;
-
- /// World lane index of a limb's body.
- public int BodyLane(Limb limb) => _bodyLane[(int)limb];
-
- /// World lane index of a muscle's joint.
- public int JointLane(Muscle muscle) => _jointLane[(int)muscle];
-
- /// Body and joint capacity a world needs to hold one ragdoll (plus whatever else the caller adds).
- public static (int Bodies, int Joints) Needs => (LimbCount, MuscleCount);
-
- /// Builds the ragdoll standing with its feet on y = 0 at (x, z used). Stable ids are firstStableId.. + 12.
- public static HumanoidRagdoll Build(Box3DSoaWorld world, (float X, float Z) origin, ulong firstStableId)
- {
- var r = new HumanoidRagdoll(world);
- var ox = origin.X;
- var oz = origin.Z;
- ulong id = firstStableId;
-
- int Box(Limb limb, int parent, float x, float y, float z, float hx, float hy, float hz) =>
- r._bodyLane[(int)limb] = world.AddBox(id++, (ox + x, y, oz + z), (hx, hy, hz), Density,
- friction: Friction, parent: parent, limb: (int)limb);
- int Capsule(Limb limb, int parent, float x, float y, float radius, float half) =>
- r._bodyLane[(int)limb] = world.AddCapsule(id++, (ox + x, y, oz), radius, half, Density,
- friction: Friction, parent: parent, limb: (int)limb);
-
- var pelvis = Box(Limb.Pelvis, -1, 0f, 1.11f, 0f, 0.15f, 0.08f, 0.09f);
- var torso = Box(Limb.Torso, pelvis, 0f, 1.41f, 0f, 0.15f, 0.22f, 0.09f);
- var head = r._bodyLane[(int)Limb.Head] = world.AddSphere(id++, (ox, 1.74f, oz), 0.11f, Density,
- friction: Friction, parent: torso, limb: (int)Limb.Head, rollingResistance: HeadRolling);
- foreach (var (side, sx) in new[] { (0, 1f), (1, -1f) })
- {
- var upperArm = Capsule(Limb.UpperArmL + side, torso, sx * 0.21f, 1.395f, 0.045f, 0.11f);
- var lowerArm = Capsule(Limb.LowerArmL + side, upperArm, sx * 0.21f, 1.10f, 0.04f, 0.10f);
- var thigh = Capsule(Limb.ThighL + side, pelvis, sx * 0.09f, 0.79f, 0.07f, 0.18f);
- var shin = Capsule(Limb.ShinL + side, thigh, sx * 0.09f, 0.31f, 0.06f, 0.17f);
- Box(Limb.FootL + side, shin, sx * 0.09f, 0.04f, 0.05f, 0.05f, 0.04f, 0.12f);
- }
-
- void Joint(Muscle m, Box3DSoaJointKind kind, Limb parent, Limb child, float x, float y, float z,
- (float, float, float) axis, MuscleGains gains, float lower = 0f, float upper = 0f, float cone = 0f)
- {
- r._jointLane[(int)m] = world.AddJoint(kind, r._bodyLane[(int)parent], r._bodyLane[(int)child],
- (ox + x, y, oz + z), axis, limit: true, lower: lower, upper: upper, coneAngle: cone);
- r._gains[(int)m] = gains;
- }
-
- var up = (0f, 1f, 0f);
- var across = (1f, 0f, 0f);
- // Gains are tuned against measured stand/fall runs at 120 Hz (see the tests), not derived: explicit PD on
- // light limbs is stable only while damping * dt stays under the inertia it acts on.
- Joint(Muscle.Spine, Box3DSoaJointKind.Spherical, Limb.Pelvis, Limb.Torso, 0f, 1.19f, 0f, up, new MuscleGains(500f, 4f, 200f, 8f), -0.4f, 0.4f, 0.5f);
- Joint(Muscle.Neck, Box3DSoaJointKind.Spherical, Limb.Torso, Limb.Head, 0f, 1.63f, 0f, up, new MuscleGains(30f, 0.8f, 20f, 0.6f), -0.6f, 0.6f, 0.6f);
- for (var side = 0; side < 2; side++)
- {
- var sx = side == 0 ? 1f : -1f;
- Joint(Muscle.ShoulderL + side, Box3DSoaJointKind.Spherical, Limb.Torso, Limb.UpperArmL + side, sx * 0.21f, 1.55f, 0f, up, new MuscleGains(20f, 1f, 1f, 0.02f), -1f, 1f, 1.5f);
- Joint(Muscle.ElbowL + side, Box3DSoaJointKind.Revolute, Limb.UpperArmL + side, Limb.LowerArmL + side, sx * 0.21f, 1.24f, 0f, across, new MuscleGains(0f, 0f, 12f, 0.6f), -2.4f, 0f);
- Joint(Muscle.HipL + side, Box3DSoaJointKind.Spherical, Limb.Pelvis, Limb.ThighL + side, sx * 0.09f, 1.04f, 0f, up, new MuscleGains(600f, 3f, 10f, 0.15f), -0.5f, 0.5f, 1.2f);
- Joint(Muscle.KneeL + side, Box3DSoaJointKind.Revolute, Limb.ThighL + side, Limb.ShinL + side, sx * 0.09f, 0.54f, 0f, across, new MuscleGains(0f, 0f, 300f, 8f), 0f, 2.4f);
- Joint(Muscle.AnkleL + side, Box3DSoaJointKind.Revolute, Limb.ShinL + side, Limb.FootL + side, sx * 0.09f, 0.08f, 0f, across, new MuscleGains(0f, 0f, 100f, 0.5f), -0.6f, 0.6f);
- }
- return r;
- }
-
- ///
- /// Writes this tick's muscle torques onto the world's torque lanes: for each joint a PD torque toward
- /// [joint] (the child's rotation relative to the parent in the joint frame, whose z axis is a hinge's axis; a hinge has no swing gains, so it takes torque about that axis only) scaled by [joint], applied to the child
- /// and, equal and opposite, to the parent. Both arrays are the caller's, one entry per ;
- /// nothing is copied or retained. Allocates nothing. Call once per step, before world.Step ; the
- /// world clears the lanes when it applies them.
- ///
- public void Drive(ReadOnlySpan strengths, ReadOnlySpan targets)
- {
- if (strengths.Length != MuscleCount || targets.Length != MuscleCount)
- {
- throw new ArgumentException($"strengths and targets need {MuscleCount} entries, one per muscle.");
- }
-
- var v = _world.View;
- for (var m = 0; m < MuscleCount; m++)
- {
- if (!(strengths[m] > 0f))
- {
- continue; // limp (or NaN): no torque
- }
-
- var j = _jointLane[m];
- var rotation = new Quat(v.JointRotationX[j], v.JointRotationY[j], v.JointRotationZ[j], v.JointRotationW[j]);
- PdMuscle.Torque(rotation, v.JointAngularVelocityX[j], v.JointAngularVelocityY[j], v.JointAngularVelocityZ[j],
- targets[m], _gains[m], strengths[m], out var tx, out var ty, out var tz);
- new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j])
- .Rotate(tx, ty, tz, out var wx, out var wy, out var wz);
- var child = v.JointBodyB[j];
- var parent = v.JointBodyA[j];
- v.TorqueX[child] += wx; v.TorqueY[child] += wy; v.TorqueZ[child] += wz;
- v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
- }
- }
- }
-}
diff --git a/src/Lodur.Body.Ymir/Ragdoll.cs b/src/Lodur.Body.Ymir/Ragdoll.cs
new file mode 100644
index 0000000..dac829d
--- /dev/null
+++ b/src/Lodur.Body.Ymir/Ragdoll.cs
@@ -0,0 +1,408 @@
+using System;
+using Ymir.Box3D;
+
+namespace Lodur.Body.Ymir
+{
+ ///
+ /// A built in a caller-owned Ymir SoA world (invariant one-physics-world): parts in plan order, then joints
+ /// in plan order, the stable id firstStableId + part ordinal, the limb lane the part ordinal, the parent lane the lane of the part's
+ /// parent in the plan. The game owns the physics world: Build adds bodies to the caller's world and Lodur never creates or steps one.
+ /// is the muscle layer: it turns caller-owned strengths and target rotations into torques on the world's
+ /// torque lanes and does nothing else to the physics. Each muscle's torque is a PD term toward its target plus the gravity load of the
+ /// muscle's unsupported subtree times its strength, projected on the axes it has gains for (ruling gravity-feedforward-all-muscles), so
+ /// sag comes only from weakness. Each body's weight is carried from the lowest common ancestor of it and every body it touches, and by
+ /// no joint when it touches anything outside this ragdoll: only a touch outside a joint's subtree supports that joint's load (ruling
+ /// gravity-support-subtree-external, superseding gravity-feedforward-count-gate). The load reads Ymir's Mass, Facts.Touching, JointOrigin and
+ /// Gravity. The binding holds no body numbers; the plan owns them.
+ /// In a world with a particle system Build also places one liquid sensor per plan airway opening, and reads them.
+ ///
+ public sealed class Ragdoll
+ {
+ private readonly Box3DSoaWorld _world;
+ private readonly int[] _bodyLane;
+ private readonly int[] _jointLane;
+ // The airway sensors, one per plan opening, when Build created them (a world with no particle system has none); Ragdoll is their one owner. Ask and taken are TakeDrawn's scratch.
+ private readonly Box3DSoaConstraintHandle[] _sensors;
+ private readonly float[] _ask, _taken;
+ private bool _hasSensors;
+ // LowestOpening's last answer (-1 before the first): the opening it keeps until another's rim lies LowestHysteresis lower.
+ private int _lowest = -1;
+ private readonly MuscleGains[] _gains;
+ // Subtree mass and mass-weighted position per part: scratch rebuilt every Drive, never read across ticks.
+ private readonly float[] _mass, _momentX, _momentY, _momentZ;
+ // Depth in the plan's tree, fixed at construction, and the part each part's weight is deposited at (-1: carried from outside): the deposit is scratch rebuilt every Drive.
+ private readonly int[] _depth, _deposit;
+ private ulong _firstStableId;
+
+ private Ragdoll(Box3DSoaWorld world, BodyPlan plan)
+ {
+ _world = world;
+ Plan = plan;
+ _bodyLane = new int[plan.Parts.Count];
+ _jointLane = new int[plan.Joints.Count];
+ _sensors = new Box3DSoaConstraintHandle[plan.AirwayOpenings.Count];
+ _ask = new float[plan.AirwayOpenings.Count];
+ _taken = new float[plan.AirwayOpenings.Count];
+ _gains = new MuscleGains[plan.Joints.Count];
+ _mass = new float[plan.Parts.Count];
+ _momentX = new float[plan.Parts.Count];
+ _momentY = new float[plan.Parts.Count];
+ _momentZ = new float[plan.Parts.Count];
+ _depth = new int[plan.Parts.Count];
+ _deposit = new int[plan.Parts.Count];
+ for (var i = 1; i < _depth.Length; i++) _depth[i] = plan.ParentOf(i) < 0 ? 0 : _depth[plan.ParentOf(i)] + 1; // parent before child
+ }
+
+ /// The plan this ragdoll was built from.
+ public BodyPlan Plan { get; }
+
+ /// World lane index of a part's body, by plan part ordinal.
+ public int BodyLane(int part) => _bodyLane[part];
+
+ /// World lane index of a joint, by plan joint ordinal.
+ public int JointLane(int joint) => _jointLane[joint];
+
+ ///
+ /// Body and joint capacity a world needs to hold one ragdoll of (plus whatever else the caller adds), and the sensor
+ /// capacity: a world with a particle system must hold Sensors sensor lanes (a world without one needs none).
+ ///
+ public static (int Bodies, int Joints, int Sensors) Needs(BodyPlan plan) => (plan.Parts.Count, plan.Joints.Count, plan.AirwayOpenings.Count);
+
+ /// Builds at (x, z used). Stable ids are firstStableId + part ordinal.
+ public static Ragdoll Build(Box3DSoaWorld world, BodyPlan plan, (float X, float Z) origin, ulong firstStableId)
+ {
+ var r = new Ragdoll(world, plan);
+ r._firstStableId = firstStableId;
+ var ox = origin.X;
+ var oz = origin.Z;
+ for (var i = 0; i < plan.Parts.Count; i++)
+ {
+ var p = plan.Parts[i];
+ var id = firstStableId + (ulong)i;
+ var position = (ox + p.Position.X, p.Position.Y, oz + p.Position.Z);
+ var parent = plan.ParentOf(i) < 0 ? -1 : r._bodyLane[plan.ParentOf(i)];
+ switch (p.Shape)
+ {
+ case PartShape.Box:
+ r._bodyLane[i] = world.AddBox(id, position, p.Size, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
+ friction: p.Friction, parent: parent, limb: i);
+ break;
+ case PartShape.Capsule:
+ r._bodyLane[i] = world.AddCapsule(id, position, p.Size.X, p.Size.Y, p.Density, (p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W),
+ friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
+ break;
+ default:
+ r._bodyLane[i] = world.AddSphere(id, position, p.Size.X, p.Density,
+ friction: p.Friction, parent: parent, limb: i, rollingResistance: p.RollingResistance);
+ break;
+ }
+ }
+
+ for (var j = 0; j < plan.Joints.Count; j++)
+ {
+ var d = plan.Joints[j];
+ var kind = d.Kind == JointKind.Spherical ? Box3DSoaJointKind.Spherical : Box3DSoaJointKind.Revolute;
+ r._jointLane[j] = world.AddJoint(kind, r._bodyLane[d.Parent], r._bodyLane[d.Child],
+ (ox + d.Anchor.X, d.Anchor.Y, oz + d.Anchor.Z), d.Axis, limit: true, lower: d.Lower, upper: d.Upper, coneAngle: d.Cone);
+ r._gains[j] = d.Gains;
+ }
+
+ if (plan.AirwayOpenings.Count > 0 && world.View.ParticleCapacity > 0)
+ {
+ // Ymir refuses the whole batch when it lacks lanes: a particle world that cannot hold the airway fails here, never silently.
+ var sensors = new (int Body, (float X, float Y, float Z) Point, float Radius)[plan.AirwayOpenings.Count];
+ for (var k = 0; k < sensors.Length; k++)
+ {
+ var a = plan.AirwayOpenings[k];
+ sensors[k] = (r._bodyLane[a.Part], a.Offset, a.Radius);
+ }
+
+ world.CreateSensors(sensors, r._sensors);
+ r._hasSensors = true;
+ }
+
+ return r;
+ }
+
+ ///
+ /// Writes this tick's muscle torques onto the world's torque lanes: for each joint a PD torque toward
+ /// [joint] (the child's rotation relative to the parent in the joint frame, whose z axis is a hinge's axis; a hinge has no swing gains, so it takes torque about that axis only) scaled by [joint], applied to the child
+ /// and, equal and opposite, to the parent, plus the gravity feedforward: the torque about the joint origin that holds up the weight of the child's
+ /// subtree, except each body in it that touches something outside the subtree (the floor, an object, another body: ruling
+ /// gravity-support-subtree-external), times the strength and kept to the joint frame axes the muscle has gains for. A world with no gravity skips it.
+ /// Both arrays are the caller's, one entry per plan joint; nothing is copied or retained. Allocates nothing. Throws when the world dropped
+ /// touching pairs for want of fact capacity: a load from a partial list is wrong without a trace. Call once per step, before world.Step ; the
+ /// world clears the lanes when it applies them.
+ ///
+ public void Drive(ReadOnlySpan strengths, ReadOnlySpan targets)
+ {
+ if (strengths.Length != _gains.Length || targets.Length != _gains.Length)
+ {
+ throw new ArgumentException($"strengths and targets need {_gains.Length} entries, one per plan joint.");
+ }
+
+ var v = _world.View;
+ for (var m = 0; m < _gains.Length; m++)
+ {
+ var j = _jointLane[m];
+ var rotation = new Quat(v.JointRotationX[j], v.JointRotationY[j], v.JointRotationZ[j], v.JointRotationW[j]);
+ PdMuscle.Torque(rotation, v.JointAngularVelocityX[j], v.JointAngularVelocityY[j], v.JointAngularVelocityZ[j],
+ targets[m], _gains[m], strengths[m], out var tx, out var ty, out var tz);
+ new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j])
+ .Rotate(tx, ty, tz, out var wx, out var wy, out var wz);
+ var child = v.JointBodyB[j];
+ var parent = v.JointBodyA[j];
+ v.TorqueX[child] += wx; v.TorqueY[child] += wy; v.TorqueZ[child] += wz;
+ v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
+ }
+
+ var (gx, gy, gz) = _world.Gravity;
+ if (gx == 0f && gy == 0f && gz == 0f) return;
+ var n = _mass.Length;
+ var facts = _world.Facts;
+ if (facts.Dropped.Touching > 0)
+ {
+ throw new InvalidOperationException("The world dropped touching pairs past its fact capacity; the gravity load needs every pair. Raise the world's fact capacity.");
+ }
+
+ for (var p = 0; p < n; p++) _deposit[p] = p;
+ foreach (var t in facts.Touching)
+ {
+ var a = PartOf(t.LaneA, t.StableIdA);
+ var b = PartOf(t.LaneB, t.StableIdB);
+ if (a >= 0 && b >= 0)
+ {
+ if (_deposit[a] >= 0) _deposit[a] = CommonAncestor(_deposit[a], b);
+ if (_deposit[b] >= 0) _deposit[b] = CommonAncestor(_deposit[b], a);
+ }
+ else if (a >= 0) _deposit[a] = -1;
+ else if (b >= 0) _deposit[b] = -1;
+ }
+
+ Array.Clear(_mass);
+ Array.Clear(_momentX);
+ Array.Clear(_momentY);
+ Array.Clear(_momentZ);
+ for (var p = 0; p < n; p++)
+ {
+ var d = _deposit[p];
+ if (d < 0) continue;
+ var b = _bodyLane[p];
+ var load = v.Mass[b];
+ _mass[d] += load;
+ _momentX[d] += load * v.PositionX[b];
+ _momentY[d] += load * v.PositionY[b];
+ _momentZ[d] += load * v.PositionZ[b];
+ }
+
+ for (var p = n - 1; p > 0; p--) // BodyPlan puts every parent before its child
+ {
+ var q = Plan.ParentOf(p);
+ if (q < 0) continue;
+ _mass[q] += _mass[p];
+ _momentX[q] += _momentX[p];
+ _momentY[q] += _momentY[p];
+ _momentZ[q] += _momentZ[p];
+ }
+
+ for (var m = 0; m < _gains.Length; m++)
+ {
+ var j = _jointLane[m];
+ var c = Plan.Joints[m].Child;
+ var rx = _momentX[c] - _mass[c] * v.JointOriginX[j];
+ var ry = _momentY[c] - _mass[c] * v.JointOriginY[j];
+ var rz = _momentZ[c] - _mass[c] * v.JointOriginZ[j];
+ var k = MathF.Max(strengths[m], 0f);
+ // The muscle holds the load up: minus the gravity torque of the subtree's weight about the joint origin.
+ var tx = -k * (ry * gz - rz * gy);
+ var ty = -k * (rz * gx - rx * gz);
+ var tz = -k * (rx * gy - ry * gx);
+ var frame = new Quat(v.JointFrameX[j], v.JointFrameY[j], v.JointFrameZ[j], v.JointFrameW[j]);
+ frame.Conjugate().Rotate(tx, ty, tz, out var lx, out var ly, out var lz);
+ if (_gains[m].SwingStiffness <= 0f) { lx = 0f; ly = 0f; }
+ if (_gains[m].TwistStiffness <= 0f) lz = 0f;
+ frame.Rotate(lx, ly, lz, out var wx, out var wy, out var wz);
+ var child = v.JointBodyB[j];
+ var parent = v.JointBodyA[j];
+ v.TorqueX[child] += wx; v.TorqueY[child] += wy; v.TorqueZ[child] += wz;
+ v.TorqueX[parent] -= wx; v.TorqueY[parent] -= wy; v.TorqueZ[parent] -= wz;
+ }
+ }
+
+ /// The plan part a touch end is, or -1 when the body is not this ragdoll's (its stable id is outside the range, or its lane is not the part's).
+ private int PartOf(int lane, ulong stableId)
+ {
+ var part = stableId - _firstStableId;
+ return stableId >= _firstStableId && part < (ulong)_bodyLane.Length && _bodyLane[(int)part] == lane ? (int)part : -1;
+ }
+
+ private int CommonAncestor(int a, int b)
+ {
+ while (_depth[a] > _depth[b]) a = Plan.ParentOf(a);
+ while (_depth[b] > _depth[a]) b = Plan.ParentOf(b);
+ while (a != b) { a = Plan.ParentOf(a); b = Plan.ParentOf(b); }
+ return a;
+ }
+
+ ///
+ /// Writes each plan sense point's world position into the caller's arrays, one entry per sense point: its part's position plus
+ /// the part's rotation applied to the point's offset. Allocates nothing.
+ ///
+ public void ReadSensePoints(Span x, Span y, Span z)
+ {
+ var points = Plan.SensePoints;
+ if (x.Length != points.Count || y.Length != points.Count || z.Length != points.Count)
+ {
+ throw new ArgumentException($"x, y and z need {points.Count} entries, one per sense point.");
+ }
+
+ var v = _world.View;
+ for (var s = 0; s < points.Count; s++)
+ {
+ var i = _bodyLane[points[s].Part];
+ var o = points[s].Offset;
+ new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(o.X, o.Y, o.Z, out var rx, out var ry, out var rz);
+ x[s] = v.PositionX[i] + rx;
+ y[s] = v.PositionY[i] + ry;
+ z[s] = v.PositionZ[i] + rz;
+ }
+ }
+
+ /// Writes each plan part's world rotation and centre into the caller's span, one entry per part, for the Actor's orient layers. Allocates nothing.
+ public void ReadPartPoses(Span poses)
+ {
+ var count = Plan.Parts.Count;
+ if (poses.Length != count)
+ {
+ throw new ArgumentException($"poses needs {count} entries, one per part.");
+ }
+
+ var v = _world.View;
+ for (var p = 0; p < count; p++)
+ {
+ var i = _bodyLane[p];
+ poses[p] = new PartPose(new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]), v.PositionX[i], v.PositionY[i], v.PositionZ[i]);
+ }
+ }
+
+ ///
+ /// Writes, per plan airway opening, the end-of-step volume (m^3) of live fluid and of settled (wet patch) liquid inside its sphere
+ /// (zeros in a world with no particle system), and the opening's drop in m: with d the normalised , how far the opening's lowest rim point
+ /// lies below the deepest plan airway sump along d (positive below, negative above). The rim is the opening's circle of Radius in the plane across its outward normal
+ /// (its part's rotation applied to the normalised offset), so a mouth turned to the side still has its half-width of drop. Drop comes from the body's pose and is written in
+ /// every world. Refuses spans not one per opening and a zero . Allocates nothing.
+ ///
+ public void ReadAirway(Span live, Span pooled, Span drop, (float X, float Y, float Z) down)
+ {
+ var n = _sensors.Length;
+ if (live.Length != n || pooled.Length != n || drop.Length != n) throw new ArgumentException($"live, pooled and drop need {n} entries, one per airway opening.");
+ var (dx, dy, dz) = Unit(down);
+ var deepest = DeepestSump(dx, dy, dz);
+ var v = _world.View;
+ for (var k = 0; k < n; k++)
+ {
+ live[k] = _hasSensors ? v.SensorLiquidVolume[_sensors[k].Lane] : 0f;
+ pooled[k] = _hasSensors ? v.SensorWetVolume[_sensors[k].Lane] : 0f;
+ drop[k] = OpeningDrop(k, dx, dy, dz, deepest);
+ }
+ }
+
+ ///
+ /// Takes what a breath drew from the pool: (Physiology's DrawnPooled, world m^3) split over the openings by each one's pooled reading at the last step's end
+ /// (exact, because Physiology's weighted sum is linear in the openings), and removed from the wet patches each opening reads. Returns the summed volume that left the world's patches, m^3:
+ /// 0 for a of 0 or less, a world with no sensors or no pooled reading; float rounding can leave it below the ask. Readings change at the next step's end. Allocates nothing.
+ ///
+ public double TakeDrawn(double drawnPooled)
+ {
+ if (!_hasSensors || !(drawnPooled > 0d)) return 0d;
+ var v = _world.View;
+ var sum = 0d;
+ for (var k = 0; k < _sensors.Length; k++) sum += v.SensorWetVolume[_sensors[k].Lane];
+ if (!(sum > 0d)) return 0d;
+ for (var k = 0; k < _sensors.Length; k++) _ask[k] = (float)(drawnPooled * v.SensorWetVolume[_sensors[k].Lane] / sum);
+ _world.TakeWet(_sensors, _ask, _taken);
+ var taken = 0d;
+ for (var k = 0; k < _taken.Length; k++) taken += _taken[k];
+ return taken;
+ }
+
+ /// The margin (m) by which another opening's rim must lie below the current lowest one's before changes its answer: face down the two rims are 0.2 mm apart and a few degrees of head pitch would swap them.
+ public const float LowestHysteresis = 0.005f;
+
+ ///
+ /// The plan airway opening whose rim lies lowest along (the largest drop of , the first on a tie): where liquid leaves
+ /// (ruling bds-drain-head-decides, the head's pose alone decides). The answer keeps the previous call's opening until another's drop exceeds that opening's by , so a head lying face down
+ /// does not swap nose and mouth with every degree of pitch; the first call (or a ragdoll with no previous answer) takes the largest drop. Refuses a zero . Allocates nothing.
+ ///
+ public int LowestOpening((float X, float Y, float Z) down)
+ {
+ var (dx, dy, dz) = Unit(down);
+ var deepest = DeepestSump(dx, dy, dz);
+ var best = 0;
+ var bestDrop = float.NegativeInfinity;
+ var keptDrop = float.NegativeInfinity;
+ for (var k = 0; k < _sensors.Length; k++)
+ {
+ var drop = OpeningDrop(k, dx, dy, dz, deepest);
+ if (k == _lowest) keptDrop = drop;
+ if (drop > bestDrop)
+ {
+ bestDrop = drop;
+ best = k;
+ }
+ }
+
+ if (_lowest >= 0 && bestDrop <= keptDrop + LowestHysteresis) best = _lowest;
+ _lowest = best;
+ return best;
+ }
+
+ private static (float X, float Y, float Z) Unit((float X, float Y, float Z) down)
+ {
+ var dl = MathF.Sqrt(down.X * down.X + down.Y * down.Y + down.Z * down.Z);
+ if (!(dl > 0f) || !float.IsFinite(dl)) throw new ArgumentException("down needs a nonzero finite direction.", nameof(down));
+ return (down.X / dl, down.Y / dl, down.Z / dl);
+ }
+
+ /// The deepest plan airway sump's position along the unit direction d.
+ private float DeepestSump(float dx, float dy, float dz)
+ {
+ var v = _world.View;
+ var deepest = float.NegativeInfinity;
+ for (var m = 0; m < Plan.AirwaySumps.Count; m++)
+ {
+ var s = Plan.AirwaySumps[m];
+ var i = _bodyLane[s.Part];
+ new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]).Rotate(s.Offset.X, s.Offset.Y, s.Offset.Z, out var rx, out var ry, out var rz);
+ deepest = MathF.Max(deepest, (v.PositionX[i] + rx) * dx + (v.PositionY[i] + ry) * dy + (v.PositionZ[i] + rz) * dz);
+ }
+
+ return deepest;
+ }
+
+ /// Opening k's lowest rim point's drop below along the unit direction d.
+ private float OpeningDrop(int k, float dx, float dy, float dz, float deepest)
+ {
+ var v = _world.View;
+ var a = Plan.AirwayOpenings[k];
+ var i = _bodyLane[a.Part];
+ var o = a.Offset;
+ var q = new Quat(v.RotationX[i], v.RotationY[i], v.RotationZ[i], v.RotationW[i]);
+ q.Rotate(o.X, o.Y, o.Z, out var cx, out var cy, out var cz);
+ var centre = (v.PositionX[i] + cx) * dx + (v.PositionY[i] + cy) * dy + (v.PositionZ[i] + cz) * dz;
+ var ol = MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z);
+ var rim = a.Radius;
+ if (ol > 0f)
+ {
+ q.Rotate(o.X / ol, o.Y / ol, o.Z / ol, out var nx, out var ny, out var nz);
+ var along = dx * nx + dy * ny + dz * nz;
+ var px = dx - along * nx;
+ var py = dy - along * ny;
+ var pz = dz - along * nz;
+ rim *= MathF.Sqrt(px * px + py * py + pz * pz);
+ }
+
+ return centre + rim - deepest;
+ }
+ }
+}
diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs
new file mode 100644
index 0000000..feb8807
--- /dev/null
+++ b/src/Lodur.Core/Actor.cs
@@ -0,0 +1,540 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// What happened on one tick.
+ [Flags]
+ public enum TickEvents
+ {
+ None = 0,
+ /// A reflex leaked past the suppression the will still held. With no will nothing is suppressed, so there is no flinch.
+ Flinch = 1,
+ /// Resolve reached zero this tick: the will broke (again, if it had mended).
+ WillBroke = 2,
+ /// The Brain's chosen goal took over, its deliberate latency after the choice.
+ GoalChanged = 4,
+ /// The physiology died this tick (reported once, on the tick it died).
+ Died = 8,
+ /// An involuntary breath ended a held breath: the breath reflex leaked past the will, or the will gave out while the breath was wanted held.
+ Gasp = 16,
+ /// A futile direct try was given up this tick: its (goal, target) pair is barred from being tried direct, and the next decision is made past the goal's dwell.
+ Frustrated = 32,
+ }
+
+ ///
+ /// One character's nervous state and the per-tick order: perception, reflex, drive, the Brain's goal, behaviour. The caller
+ /// supplies one point per body region, the game's stimulus sources, and the spans the behaviour writes its
+ /// strengths and targets into; the Actor writes nothing else of the caller's and never touches physics.
+ /// Everything is allocated in the constructor, and the same inputs give the same outputs.
+ ///
+ public sealed class Actor
+ {
+ private readonly double _dt;
+ private readonly DriveParameters _driveP;
+ private readonly Brain _brain;
+ private readonly long _latency;
+ private readonly long[] _dwell;
+ private readonly long[] _onset;
+ private readonly long[] _entryTicks;
+ private readonly Perception _perception;
+ private readonly WithdrawalReflex[] _reflexes;
+ private readonly Physiology? _physiology;
+ // The breath-hold's contest with air hunger (null without a physiology), the gasp's length in ticks, the tick of the last gasp, and whether the breath is held for the next step.
+ private readonly WithdrawalReflex? _breath;
+ private readonly long _gaspTicks;
+ private long _lastGasp = long.MinValue / 2;
+ private bool _held;
+ private bool _diedReported;
+ // The mean of the strengths written on the last tick, after the ceiling, 0..1: the exertion the physiology is told about.
+ private double _effort;
+ private DriveState _drive = DriveState.Fresh;
+ private long _tick;
+ private int _goal;
+ private int _pending = -1;
+ private ulong _target;
+ private ulong _pendingTarget;
+ private long _switchTick;
+ private long _goalSince;
+ // The entry ramp of the goal in force: its length in ticks (-1: none, as for the Start goal) and the gain and arousal it started from.
+ private long _rampTicks = -1;
+ private double _rampGain0;
+ private double _rampArousal0;
+ // The orient layers' solvers (null when no goal has a layer) and the arm the Nearer mode holds, set when a (goal, target) pair commits.
+ private readonly OrientRig? _rig;
+ private readonly bool _layered;
+ private Side _arm = Side.Right;
+ // The want gate's thinking space (null when no goal has a want), which also holds the plan of the decision in force, and its length as read.
+ private readonly Deliberation? _deliberation;
+ private int _planLength;
+ // Frustration (ruling bds-unplannable-tries-direct): the ticks a direct try may last and a bar lasts, the tick from which the committed pair has read PlanLength -1 without a break (-1: not), and whether the next Select is accepted past the dwell.
+ private readonly long _frustrationTicks;
+ private readonly long _retryTicks;
+ private long _directSince = -1;
+ private bool _impatient;
+
+ public Actor(
+ double tickSeconds, int regionCount,
+ NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, Brain brain,
+ NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null, Physiology? physiology = null,
+ WithdrawalParameters? breath = null, BodyPlan? body = null, IReadOnlyList? verbs = null)
+ {
+ brain.Validate();
+ drive.Validate();
+ Body = body;
+ foreach (var goal in brain.Goals)
+ {
+ if (!goal.Behaviour.HasLayers)
+ {
+ continue;
+ }
+
+ if (body == null)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a behaviour with orient layers needs the Actor's BodyPlan.");
+ }
+
+ if (goal.Behaviour.MuscleCount != body.Joints.Count)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a behaviour with orient layers needs one muscle per joint of the body ({body.Joints.Count}), not {goal.Behaviour.MuscleCount}.");
+ }
+
+ _layered = true;
+ }
+
+ if (_layered)
+ {
+ _rig = new OrientRig(body!, brain, tickSeconds);
+ }
+
+ if (physiology != null && !physiology.TryBind())
+ {
+ throw new ArgumentException("this physiology is already bound to an actor; one actor steps one physiology.");
+ }
+
+ _physiology = physiology;
+
+ _dt = tickSeconds;
+ _driveP = drive;
+ _brain = brain;
+ _goal = brain.Start;
+ _drive.SensoryGain = brain.Goals[brain.Start].SensoryGain;
+ if (brain.Goals[brain.Start].EntryArousal is double startArousal)
+ {
+ _drive.Arousal = startArousal;
+ }
+ // The Start goal takes over at construction: its entry effect applies like any other goal's.
+ if (brain.Goals[brain.Start].EntryResolve is double startEntry)
+ {
+ _drive.Enter(drive, startEntry);
+ }
+ _latency = Math.Max(1, (long)Math.Round(brain.DeliberateLatencySeconds / tickSeconds));
+ _dwell = new long[brain.Goals.Count];
+ _onset = new long[brain.Goals.Count];
+ _entryTicks = new long[brain.Goals.Count];
+ for (var g = 0; g < _dwell.Length; g++)
+ {
+ _dwell[g] = (long)Math.Round(brain.Goals[g].MinDwellSeconds / tickSeconds);
+ // Rounded to whole ticks once, like the dwell, so the onset is the same number of ticks whatever the tick length does to a product.
+ // A quotient past the long range (+infinity included) is involuntary throughout: the cast of an out-of-range double is not defined across runtimes.
+ var onsetTicks = brain.Goals[g].InvoluntarySeconds / tickSeconds;
+ _onset[g] = onsetTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(onsetTicks);
+ // The entry ramp is rounded once as well; EntrySeconds is finite, but its quotient can still pass the long range.
+ var entryTicks = brain.Goals[g].EntrySeconds / tickSeconds;
+ _entryTicks[g] = entryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(entryTicks);
+ }
+
+ // Rounded once to ticks like the dwell; a quotient past the long range (+infinity included) is never reached.
+ var frustrationTicks = brain.FrustrationSeconds / tickSeconds;
+ _frustrationTicks = frustrationTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(frustrationTicks);
+ var retryTicks = brain.RetrySeconds / tickSeconds;
+ _retryTicks = retryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(retryTicks);
+
+ if (physiology != null)
+ {
+ var breathP = breath ?? new WithdrawalParameters();
+ _breath = new WithdrawalReflex(breathP, tickSeconds);
+ _gaspTicks = (long)Math.Round(breathP.FlinchRefractorySeconds / tickSeconds);
+ }
+
+ _perception = new Perception(nerve, tickSeconds, regionCount, senses, senseRegion, percepts);
+ if (brain.HasWants)
+ {
+ if (_perception.PerceptCount == 0)
+ {
+ throw new ArgumentException("A Brain with a want needs percepts: the planner reads the percepts' facts.");
+ }
+
+ _deliberation = new Deliberation(brain, verbs ?? Array.Empty(), _perception.PerceptCount);
+ }
+
+ _reflexes = new WithdrawalReflex[regionCount];
+ for (var r = 0; r < regionCount; r++)
+ {
+ _reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds);
+ }
+ }
+
+ public int RegionCount => _reflexes.Length;
+
+ /// The body the orient layers solve against; null when the actor was built without one.
+ public BodyPlan? Body { get; }
+
+ /// Ticks run so far.
+ public long TickCount => _tick;
+
+ /// A snapshot of the drive; nothing but writes it.
+ public DriveState Drive => _drive;
+
+ /// The physiology this actor steps and reads, null for an actor with none.
+ public Physiology? Physiology => _physiology;
+
+ /// Sets the drive's Attention slot; a seam for the tests until lodur-startle-attention writes it.
+ internal void SetAttention(double attention)
+ {
+ _drive.Attention = attention;
+ }
+
+ ///
+ /// Forgets the arms' history: each arm's next solve is the stateless rule, as on the first tick. For a caller that moves the body
+ /// discontinuously (a teleport, a respawn) so the arms neither carry a swivel from the old place nor slew from its targets. Nothing for an actor without arms.
+ ///
+ public void ResetArms() => _rig?.ResetArms();
+
+ public Brain Brain => _brain;
+
+ /// The index in 's goals of the goal in force; it changes only on the tick that reports .
+ public int GoalIndex => _goal;
+
+ /// How long the goal in force will have been in force at the next tick; 0 on the tick it took over.
+ public double SecondsInGoal => (_tick - _goalSince) * _dt;
+
+ public double Stimulus(int region) => _perception.Stimulus(region);
+
+ public double Afferent(int region) => _perception.Afferent(region);
+
+ /// The sensory load this tick: the channels' afferents combined, 0..1.
+ public double Load => _perception.Load;
+
+ public double ChannelStimulus(Channel channel) => _perception.ChannelStimulus(channel);
+
+ public double ChannelAfferent(Channel channel) => _perception.ChannelAfferent(channel);
+
+ /// The number of percept slots (0 with no senses); a free slot reads as Id 0.
+ public int PerceptCount => _perception.PerceptCount;
+
+ public Percept Percept(int slot) => _perception.Percept(slot);
+
+ /// The id of the percept the committed goal targets; 0 for an untargeted goal. Only the Brain's choice, committed after the latency, writes it.
+ public ulong TargetId => _target;
+
+ ///
+ /// The length of the plan of the decision in force, made by the Select that chose or re-chose the pair and carried with it (a tick that decides nothing only checks it): n steps,
+ /// -1 when he goes at it direct (no plan within , the think budget gone, or a step's thing forgotten), 0 when the goal has no want, the want holds,
+ /// or its target is no longer in memory. A -1 that lasts ends in .
+ ///
+ public int PlanLength => _planLength;
+
+ /// Step of the plan of the decision in force, for i below : a verb of the Actor's list and the percept ids it is grounded on.
+ public PlanStep PlanStep(int i)
+ {
+ if ((uint)i >= (uint)Math.Max(_planLength, 0))
+ {
+ throw new ArgumentOutOfRangeException(nameof(i), "There is no such step in the plan.");
+ }
+
+ return _deliberation!.Step(i);
+ }
+
+ /// The slot whose Id equals ; default (Id 0) when the target is 0 or forgotten.
+ public Percept Target
+ {
+ get
+ {
+ if (_target != 0UL)
+ {
+ for (var s = 0; s < _perception.PerceptCount; s++)
+ {
+ var p = _perception.Percept(s);
+ if (p.Id == _target)
+ {
+ return p;
+ }
+ }
+ }
+
+ return default;
+ }
+ }
+
+ ///
+ /// Runs one physics step's worth of nervous system. The point spans hold one entry per region; the strengths
+ /// and targets spans one entry per muscle, written for the body to follow. The emitters are the game's point
+ /// sources, sensed at the sense region's point. The airway is what the caller finds at the body's airway openings; nothing by default.
+ /// The parts are the body's part poses (one per plan part), read when the goal in force has orient layers and ignored otherwise.
+ /// are the actor's own facts for the planner (the game's; bit 63 is refused), read only by a Brain with wants.
+ ///
+ public TickEvents Tick(
+ ReadOnlySpan regionX, ReadOnlySpan regionY, ReadOnlySpan regionZ,
+ ReadOnlySpan sources, Span strengths, Span targets,
+ ReadOnlySpan emitters = default, in AirwaySample airway = default, ReadOnlySpan parts = default, ulong selfFacts = 0UL)
+ {
+ if ((selfFacts & Perception.InReachFact) != 0UL)
+ {
+ throw new ArgumentException("Bit 63 is Lodur's reach; the actor's own facts have none.", nameof(selfFacts));
+ }
+
+ // The goal that will write this tick: a decision due now commits before the behaviour runs, and one made now cannot (the latency is a tick at least).
+ if (_layered && _brain.Goals[_pending >= 0 && _tick == _switchTick ? _pending : _goal].Behaviour.HasLayers && parts.Length != Body!.Parts.Count)
+ {
+ throw new ArgumentException($"parts needs one pose per part of the body ({Body.Parts.Count}).");
+ }
+
+ var events = TickEvents.None;
+ if (_physiology != null)
+ {
+ if (strengths.Length != _physiology.JointCount)
+ {
+ throw new ArgumentException("strengths must have one entry per joint of the physiology's body.");
+ }
+
+ // The physiology steps first, on the drive as the last tick left it, and its consciousness is the slot's only writer.
+ // A dead physiology is stepped too: that step zeroes its flows, so they stand only on the tick it died.
+ var wasDead = _physiology.Dead;
+ _physiology.Step(_dt, new PhysiologyInput(_drive.Arousal, _effort, _held, airway));
+ if (!wasDead)
+ {
+ _drive.Consciousness = _physiology.Consciousness;
+ _drive.AirHunger = _physiology.BreathUrge;
+ }
+
+ if (_physiology.Dead)
+ {
+ // Limp and permanent: the drive, goal and perception never change again; targets are left as they were.
+ strengths.Clear();
+ _tick++;
+ if (_diedReported) return events;
+ _diedReported = true;
+ return TickEvents.Died;
+ }
+ }
+
+ // A flinch is the leak of a suppressed reflex; with no will nothing is suppressed, so none is reported.
+ var holding = _drive.Will > 0.0;
+
+ _perception.Sense(regionX, regionY, regionZ, sources, emitters, _drive.SensoryGain);
+
+ double afferent = 0.0, strainLoad = 0.0, leak = 0.0;
+ for (var r = 0; r < _reflexes.Length; r++)
+ {
+ var a = _perception.Afferent(r);
+ var flinch = _reflexes[r].Step(a, _drive);
+ afferent += a;
+ strainLoad += _reflexes[r].StrainLoad;
+ leak += _reflexes[r].Leak;
+ if (flinch && holding)
+ {
+ events |= TickEvents.Flinch;
+ }
+ }
+
+ // The breath is held on will while liquid is at the airway, in contest with air hunger as a reflex is with pain: it ends in a gasp when the hunger leaks past the will, or
+ // when the will gives out. The breath's leak is not the limbs' leak; its strain joins the drive's.
+ if (_physiology != null)
+ {
+ var wanted = _physiology.LiquidAtAirway;
+ var willing = wanted && _drive.Will > 0.0;
+ if (willing)
+ {
+ if (_breath!.Step(_drive.AirHunger, _drive))
+ {
+ events |= TickEvents.Gasp;
+ _lastGasp = _tick;
+ }
+
+ strainLoad += _breath.StrainLoad;
+ }
+ else if (wanted && _held)
+ {
+ events |= TickEvents.Gasp;
+ _lastGasp = _tick;
+ }
+
+ _held = willing && _tick - _lastGasp >= _gaspTicks;
+ }
+
+ // Effort is paid only once the goal is voluntary: the onset (InvoluntarySeconds) runs without will, and without cost.
+ var inForce = _brain.Goals[_goal];
+ var effort = _tick - _goalSince >= _onset[_goal] ? inForce.Effort : 0.0;
+ if (_drive.Step(_driveP, _dt, afferent, strainLoad, _perception.Load, inForce.Pull, effort))
+ {
+ events |= TickEvents.WillBroke;
+ }
+
+ // A decision in flight commits at its tick even if the condition that chose it has lapsed; none is made while one is
+ // pending. Within the goal in force's minimum dwell only a strictly higher-priority goal is decided on.
+ // Order: the bars lift on time or a forgotten target, then a direct try that has lasted its time is barred (and the next decision made impatient), then the decision.
+ if (_deliberation != null)
+ {
+ _deliberation.Lift(_perception, _tick);
+ if (_directSince >= 0 && _tick - _directSince >= _frustrationTicks && !_deliberation.Barred(_goal, _target))
+ {
+ _deliberation.Bar(_goal, _target, _retryTicks > long.MaxValue - _tick ? long.MaxValue : _tick + _retryTicks);
+ events |= TickEvents.Frustrated;
+ _directSince = -1;
+ _impatient = true;
+ }
+ }
+
+ var planned = false;
+ if (_pending < 0)
+ {
+ var sr = _perception.SenseRegion;
+ var now = new Choice(_goal, _target);
+ if (_deliberation != null)
+ {
+ _deliberation.SelfFacts = selfFacts;
+ }
+
+ var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], now, _deliberation);
+ var impatient = _impatient;
+ _impatient = false; // one Select is impatient, whatever it returns
+ if (wanted != new Choice(_goal, _target)
+ && (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority || impatient))
+ {
+ _pending = wanted.Goal;
+ _pendingTarget = wanted.Target;
+ _switchTick = _tick + _latency;
+ }
+ else if (_deliberation != null)
+ {
+ // The Select re-chose the pair in force, or was refused by the dwell and the pair in force is planned again with what is left of its budget.
+ if (wanted == now)
+ {
+ _deliberation.Refresh();
+ planned = true;
+ }
+ else if (_brain.Goals[_goal].Want is { } inForceWant)
+ {
+ planned = _deliberation.ReplanInForce(_perception, regionX[sr], regionY[sr], regionZ[sr], inForceWant, _target);
+ }
+ }
+ }
+
+ if (_pending >= 0 && _tick == _switchTick)
+ {
+ var changed = _pending != _goal;
+ if (changed || _pendingTarget != _target)
+ {
+ _directSince = -1;
+ }
+
+ _goal = _pending;
+ _target = _pendingTarget;
+ _pending = -1;
+ _rig?.Commit();
+ if (_deliberation != null)
+ {
+ _deliberation.Refresh(); // the pending decision's plan, made up to a latency ago: checked below like any carried plan
+ }
+
+ if (_layered && _brain.Goals[_goal].Behaviour.Arms is { Side: ArmSide.Nearer } && _target != 0UL)
+ {
+ var committed = Target;
+ if (committed.Id != 0UL)
+ {
+ _arm = _rig!.NearerArm(parts, committed);
+ }
+ }
+
+ if (changed)
+ {
+ _goalSince = _tick;
+ events |= TickEvents.GoalChanged;
+ _rampTicks = _entryTicks[_goal];
+ _rampGain0 = _drive.SensoryGain;
+ _rampArousal0 = _drive.Arousal;
+ if (_brain.Goals[_goal].EntryResolve is double entry)
+ {
+ _drive.Enter(_driveP, entry);
+ }
+ }
+ }
+
+ // The plan of the decision in force was written above by the Select that chose it, or is carried: a tick that wrote none only checks it against the percepts.
+ _planLength = 0;
+ if (_deliberation != null && _brain.Goals[_goal].Want is { } committedWant)
+ {
+ if (!planned)
+ {
+ var sr = _perception.SenseRegion;
+ _deliberation.SelfFacts = selfFacts;
+ _deliberation.CheckCarried(_perception, regionX[sr], regionY[sr], regionZ[sr], committedWant, _target);
+ }
+
+ _planLength = _deliberation.InForceLength;
+ if (_planLength < 0)
+ {
+ if (_directSince < 0)
+ {
+ _directSince = _tick;
+ }
+ }
+ else
+ {
+ _directSince = -1;
+ }
+ }
+ else
+ {
+ _directSince = -1;
+ }
+
+ // For EntrySeconds after a takeover the Actor, not the drive, takes the gain (and the arousal, if the goal declares one) from their values at
+ // takeover to the goal's targets, linearly; its last tick assigns the targets themselves (a lerp need not land on a nonzero target), and after it the drive
+ // owns arousal again. Sense reads the gain at the start of the next tick, so a change of gain reaches Load one tick after the Actor sets it.
+ var sinceGoal = _tick - _goalSince;
+ if (sinceGoal <= _rampTicks)
+ {
+ var goal = _brain.Goals[_goal];
+ var last = sinceGoal == _rampTicks; // also the takeover tick of a zero-length ramp
+ var k = last ? 1.0 : (double)sinceGoal / _rampTicks;
+ _drive.SensoryGain = last ? goal.SensoryGain : _rampGain0 + (goal.SensoryGain - _rampGain0) * k;
+ if (goal.EntryArousal is double target)
+ {
+ _drive.Arousal = last ? target : _rampArousal0 + (target - _rampArousal0) * k;
+ }
+ }
+
+ // Every voluntary layer is held by will, in contest with the reflex; an involuntary one (the onset of a goal) is not.
+ var secondsInGoal = (_tick - _goalSince) * _dt;
+ var weight = _tick - _goalSince >= _onset[_goal] ? Math.Pow(_drive.Will, _driveP.WillCurve) : 1.0;
+ var behaviour = _brain.Goals[_goal].Behaviour;
+ if (_rig != null)
+ {
+ behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets, new OrientInput(_rig, parts, Target, _arm));
+ }
+ else
+ {
+ behaviour.Write(weight, leak, _drive.Strain, _tick * _dt, secondsInGoal, strengths, targets);
+ }
+
+ if (_physiology != null)
+ {
+ // The only scaling of strength: each muscle (plan joint m) is held to its ceiling.
+ var sum = 0.0;
+ for (var m = 0; m < strengths.Length; m++)
+ {
+ strengths[m] *= (float)_physiology.MotorCeiling(m);
+ sum += strengths[m];
+ }
+
+ var mean = strengths.Length > 0 ? sum / strengths.Length : 0.0;
+ _effort = mean < 0.0 ? 0.0 : mean > 1.0 ? 1.0 : mean;
+ }
+
+ _tick++;
+ return events;
+ }
+ }
+}
diff --git a/src/Lodur.Core/BodyPlan.cs b/src/Lodur.Core/BodyPlan.cs
new file mode 100644
index 0000000..37a8d90
--- /dev/null
+++ b/src/Lodur.Core/BodyPlan.cs
@@ -0,0 +1,243 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// Which side of the body a part, joint or sense point is on; Center for the midline.
+ public enum Side { Center, Left, Right }
+
+ /// A part's collision shape.
+ public enum PartShape { Box, Capsule, Sphere }
+
+ /// A joint's degrees of freedom: a ball (swing cone and twist) or a hinge about its axis.
+ public enum JointKind { Spherical, Revolute }
+
+ ///
+ /// One rigid part. is (x, y, z): half extents for a box; radius, half length, 0 for a capsule;
+ /// radius, 0, 0 for a sphere. is the creation pose relative to the build origin.
+ /// The part tree is not a field here: it is the joint list.
+ ///
+ public readonly record struct PartDef(
+ string Label, Side Side, PartShape Shape, (float X, float Y, float Z) Size, (float X, float Y, float Z) Position,
+ Quat Rotation, float Density, float Friction, float RollingResistance);
+
+ /// A joint from to (part ordinals); the child's only joint is the one that attaches it.
+ public readonly record struct JointDef(
+ string Label, Side Side, JointKind Kind, int Parent, int Child, (float X, float Y, float Z) Anchor,
+ (float X, float Y, float Z) Axis, float Lower, float Upper, float Cone, MuscleGains Gains);
+
+ /// A point on a part that perception senses at: the part's position plus its rotation applied to .
+ public readonly record struct SensePointDef(string Label, Side Side, int Part, (float X, float Y, float Z) Offset);
+
+ ///
+ /// Where the airway opens to the outside: a sphere of m centred at in the part's frame; liquid inside it is liquid
+ /// at the airway. The sphere must reach outside the part's shape, since liquid never enters a body. Its Radius is also its rim: the opening's half-width.
+ ///
+ public readonly record struct AirwayOpeningDef(string Label, Side Side, int Part, (float X, float Y, float Z) Offset, float Radius);
+
+ /// A point inside the airway, at in the part's frame, where liquid pools behind the openings (the oropharynx, the glottis). Nothing reads one by label.
+ public readonly record struct AirwaySumpDef(string Label, int Part, (float X, float Y, float Z) Offset);
+
+ ///
+ /// A body as data: parts, the joints that are also its tree, sense points, airway openings and the sumps behind them, each named by label and side.
+ /// Engine-free; a physics binding builds it into a world. Validated at construction.
+ ///
+ public sealed class BodyPlan
+ {
+ private readonly int[] _parentOf;
+ private readonly Dictionary<(string, Side), int> _parts = new Dictionary<(string, Side), int>();
+ private readonly Dictionary<(string, Side), int> _joints = new Dictionary<(string, Side), int>();
+ private readonly Dictionary<(string, Side), int> _senses = new Dictionary<(string, Side), int>();
+ private readonly Dictionary<(string, Side), int> _airway = new Dictionary<(string, Side), int>();
+
+ public BodyPlan(IReadOnlyList parts, IReadOnlyList joints, IReadOnlyList sensePoints,
+ IReadOnlyList? airwayOpenings = null, IReadOnlyList? airwaySumps = null)
+ {
+ Parts = new List(parts).AsReadOnly();
+ Joints = new List(joints).AsReadOnly();
+ SensePoints = new List(sensePoints).AsReadOnly();
+ AirwayOpenings = new List(airwayOpenings ?? Array.Empty()).AsReadOnly();
+ AirwaySumps = new List(airwaySumps ?? Array.Empty()).AsReadOnly();
+ _parentOf = Validate();
+ }
+
+ public IReadOnlyList Parts { get; }
+ public IReadOnlyList Joints { get; }
+ public IReadOnlyList SensePoints { get; }
+ public IReadOnlyList AirwayOpenings { get; }
+ public IReadOnlyList AirwaySumps { get; }
+
+ /// The part ordinal a part hangs from (the parent of the one joint that attaches it), -1 for the root.
+ public int ParentOf(int part) => _parentOf[part];
+
+ public int PartIndex(string label, Side side = Side.Center) => Find(_parts, "part", label, side);
+ public int JointIndex(string label, Side side = Side.Center) => Find(_joints, "joint", label, side);
+ public int SenseIndex(string label, Side side = Side.Center) => Find(_senses, "sense point", label, side);
+ public int AirwayIndex(string label, Side side = Side.Center) => Find(_airway, "airway opening", label, side);
+
+ private static int Find(Dictionary<(string, Side), int> index, string what, string label, Side side) =>
+ index.TryGetValue((label, side), out var i) ? i : throw new ArgumentException($"no {what} labelled '{label}' on side {side}.");
+
+ private static bool IsFinite(float f) => !float.IsNaN(f) && !float.IsInfinity(f);
+ private static bool Finite((float X, float Y, float Z) v) => IsFinite(v.X) && IsFinite(v.Y) && IsFinite(v.Z);
+
+ private int[] Validate()
+ {
+ // 1. (Label, Side) unique per list, labels non-empty.
+ Unique(Parts.Count, i => (Parts[i].Label, Parts[i].Side), _parts, "part");
+ Unique(Joints.Count, i => (Joints[i].Label, Joints[i].Side), _joints, "joint");
+ Unique(SensePoints.Count, i => (SensePoints[i].Label, SensePoints[i].Side), _senses, "sense point");
+ Unique(AirwayOpenings.Count, i => (AirwayOpenings[i].Label, AirwayOpenings[i].Side), _airway, "airway opening");
+
+ // 2. Joint ends in range and ordered, so the tree is acyclic and parts are created parent first.
+ foreach (var d in Joints)
+ {
+ if (d.Parent < 0 || d.Parent >= Parts.Count || d.Child < 0 || d.Child >= Parts.Count)
+ {
+ throw new ArgumentException($"joint '{d.Label}' {d.Side}: parent {d.Parent} or child {d.Child} is not a part.");
+ }
+
+ if (d.Parent >= d.Child)
+ {
+ throw new ArgumentException($"joint '{d.Label}' {d.Side}: parent {d.Parent} must precede child {d.Child}.");
+ }
+ }
+
+ // 3. Part 0 is the root (rule 2 already leaves it no joint to be the child of); every other part is the child of exactly one joint.
+ if (Parts.Count == 0) throw new ArgumentException("a body plan needs a root part.");
+ var parentOf = new int[Parts.Count];
+ var attached = new int[Parts.Count];
+ for (var p = 0; p < parentOf.Length; p++) parentOf[p] = -1;
+ foreach (var d in Joints)
+ {
+ parentOf[d.Child] = d.Parent;
+ attached[d.Child]++;
+ }
+
+ for (var p = 1; p < attached.Length; p++)
+ {
+ if (attached[p] != 1)
+ {
+ throw new ArgumentException($"part '{Parts[p].Label}' {Parts[p].Side} is the child of {attached[p]} joints, needs 1.");
+ }
+ }
+
+ // 4. Sense points sit on parts.
+ foreach (var s in SensePoints)
+ {
+ if (s.Part < 0 || s.Part >= Parts.Count) throw new ArgumentException($"sense point '{s.Label}' {s.Side}: part {s.Part} is not a part.");
+ }
+
+ foreach (var a in AirwayOpenings)
+ {
+ if (a.Part < 0 || a.Part >= Parts.Count) throw new ArgumentException($"airway opening '{a.Label}' {a.Side}: part {a.Part} is not a part.");
+ }
+
+ foreach (var a in AirwaySumps)
+ {
+ if (a.Part < 0 || a.Part >= Parts.Count) throw new ArgumentException($"airway sump '{a.Label}': part {a.Part} is not a part.");
+ }
+
+ // An opening's drop is measured below the deepest sump: openings with none would have nothing to fall below.
+ if (AirwayOpenings.Count > 0 && AirwaySumps.Count == 0) throw new ArgumentException("airway openings need at least one airway sump to drain below.");
+
+ // 5. Numbers a physics world can take.
+ foreach (var p in Parts)
+ {
+ var r = p.Rotation;
+ var finite = Finite(p.Size) && Finite(p.Position) && IsFinite(r.X) && IsFinite(r.Y) && IsFinite(r.Z) && IsFinite(r.W)
+ && IsFinite(p.Density) && IsFinite(p.Friction) && IsFinite(p.RollingResistance);
+ if (!finite) throw new ArgumentException($"part '{p.Label}' {p.Side} has a non-finite number.");
+ var sz = p.Size;
+ var sized = p.Shape == PartShape.Box ? sz.X > 0f && sz.Y > 0f && sz.Z > 0f
+ : p.Shape == PartShape.Capsule ? sz.X > 0f && sz.Y > 0f : sz.X > 0f;
+ if (!sized) throw new ArgumentException($"part '{p.Label}' {p.Side}: a size its shape uses is not positive.");
+
+ // A binding has no destination for what the shape cannot carry (sphere rotation, box rolling resistance, size components
+ // beyond the shape's own), so the plan may not say it.
+ var spare = p.Shape == PartShape.Box ? 0f : p.Shape == PartShape.Capsule ? sz.Z : Math.Abs(sz.Y) + Math.Abs(sz.Z);
+ if (spare != 0f) throw new ArgumentException($"part '{p.Label}' {p.Side}: a size its shape does not use is not zero.");
+ if (p.Shape == PartShape.Sphere && (r.X != 0f || r.Y != 0f || r.Z != 0f || r.W != 1f))
+ {
+ throw new ArgumentException($"part '{p.Label}' {p.Side}: a sphere carries no rotation.");
+ }
+
+ if (p.Shape == PartShape.Box && p.RollingResistance != 0f) throw new ArgumentException($"part '{p.Label}' {p.Side}: a box carries no rolling resistance.");
+ if (!(p.Density > 0f)) throw new ArgumentException($"part '{p.Label}' {p.Side}: density is not positive.");
+ }
+
+ foreach (var d in Joints)
+ {
+ var g = d.Gains;
+ var finite = Finite(d.Anchor) && Finite(d.Axis) && IsFinite(d.Lower) && IsFinite(d.Upper) && IsFinite(d.Cone)
+ && IsFinite(g.SwingStiffness) && IsFinite(g.SwingDamping) && IsFinite(g.TwistStiffness) && IsFinite(g.TwistDamping) && IsFinite(g.Passive);
+ if (!finite) throw new ArgumentException($"joint '{d.Label}' {d.Side} has a non-finite number.");
+ if (d.Lower > d.Upper) throw new ArgumentException($"joint '{d.Label}' {d.Side}: lower limit exceeds upper.");
+ if (d.Cone < 0f) throw new ArgumentException($"joint '{d.Label}' {d.Side}: cone is negative.");
+ }
+
+ foreach (var s in SensePoints)
+ {
+ if (!Finite(s.Offset)) throw new ArgumentException($"sense point '{s.Label}' {s.Side} has a non-finite number.");
+ }
+
+ foreach (var a in AirwayOpenings)
+ {
+ if (!Finite(a.Offset) || !IsFinite(a.Radius)) throw new ArgumentException($"airway opening '{a.Label}' {a.Side} has a non-finite number.");
+ if (!(a.Radius > 0f)) throw new ArgumentException($"airway opening '{a.Label}' {a.Side}: radius is not positive.");
+ }
+
+ foreach (var a in AirwaySumps)
+ {
+ if (!Finite(a.Offset)) throw new ArgumentException($"airway sump '{a.Label}' has a non-finite number.");
+ }
+
+ // 6. An opening's sphere reaches outside its part: liquid never enters a body, so a sphere wholly inside reads nothing.
+ foreach (var a in AirwayOpenings)
+ {
+ if (SignedDistance(Parts[a.Part], a.Offset) <= -a.Radius)
+ {
+ throw new ArgumentException($"airway opening '{a.Label}' {a.Side} lies inside its part.");
+ }
+ }
+
+ return parentOf;
+ }
+
+ /// Signed distance from a point in the part's frame to the part's shape: negative inside.
+ private static float SignedDistance(PartDef p, (float X, float Y, float Z) o)
+ {
+ var sz = p.Size;
+ switch (p.Shape)
+ {
+ case PartShape.Sphere:
+ return MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z) - sz.X;
+ case PartShape.Capsule:
+ {
+ var dy = o.Y - Math.Clamp(o.Y, -sz.Y, sz.Y);
+ return MathF.Sqrt(o.X * o.X + dy * dy + o.Z * o.Z) - sz.X;
+ }
+ default:
+ {
+ var qx = Math.Abs(o.X) - sz.X;
+ var qy = Math.Abs(o.Y) - sz.Y;
+ var qz = Math.Abs(o.Z) - sz.Z;
+ var ox = Math.Max(qx, 0f);
+ var oy = Math.Max(qy, 0f);
+ var oz = Math.Max(qz, 0f);
+ return MathF.Sqrt(ox * ox + oy * oy + oz * oz) + Math.Min(Math.Max(qx, Math.Max(qy, qz)), 0f);
+ }
+ }
+ }
+
+ private static void Unique(int count, Func key, Dictionary<(string, Side), int> index, string what)
+ {
+ for (var i = 0; i < count; i++)
+ {
+ var (label, side) = key(i);
+ if (string.IsNullOrEmpty(label)) throw new ArgumentException($"a {what} has an empty label.");
+ if (!index.TryAdd((label, side), i)) throw new ArgumentException($"two {what}s are labelled '{label}' on side {side}.");
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/BodyPlans.cs b/src/Lodur.Core/BodyPlans.cs
new file mode 100644
index 0000000..f2f803f
--- /dev/null
+++ b/src/Lodur.Core/BodyPlans.cs
@@ -0,0 +1,128 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// Body plans in code, until they live in a store (follow-up lodur-body-plan-cultcache).
+ public static class BodyPlans
+ {
+ private const float Density = 1000f;
+ private const float Friction = 0.8f;
+ /// The fingers' creation curl at the knuckle, radians: the relaxed resting hand (question hand-rest-curl).
+ private const float RestCurl = 0.35f;
+ private const float Thumb30 = 30f * MathF.PI / 180f; // the thumb's metacarpal, out of the palm plane
+ private const float HeadRolling = 0.1f; // a bare sphere on the ground rolls on, so the fallen head never settles
+
+ ///
+ /// A 19-part humanoid: capsule limbs, box pelvis, torso, feet and palms, a sphere head, a thumb capsule and a fingers box per hand,
+ /// 18 joints: spherical at spine, neck, shoulders, hips, wrists and thumbs, hinges at elbows, knees, ankles and knuckles.
+ /// Facing +z, left is +x, standing on y = 0 at the creation pose, which is also every joint's zero. Parts and joints are in
+ /// build order: the trunk, then per side (left, right) the limbs, then per side the hand.
+ ///
+ public static BodyPlan Humanoid()
+ {
+ var parts = new List();
+ var joints = new List();
+
+ int Box(string label, Side side, float x, float y, float z, float hx, float hy, float hz) =>
+ Add(parts, new PartDef(label, side, PartShape.Box, (hx, hy, hz), (x, y, z), Quat.Identity, Density, Friction, 0f));
+ int Capsule(string label, Side side, float x, float y, float radius, float half) =>
+ Add(parts, new PartDef(label, side, PartShape.Capsule, (radius, half, 0f), (x, y, 0f), Quat.Identity, Density, Friction, 0f));
+
+ var pelvis = Box("Pelvis", Side.Center, 0f, 1.11f, 0f, 0.15f, 0.08f, 0.09f);
+ var torso = Box("Torso", Side.Center, 0f, 1.41f, 0f, 0.15f, 0.22f, 0.09f);
+ var head = Add(parts, new PartDef("Head", Side.Center, PartShape.Sphere, (0.11f, 0f, 0f), (0f, 1.74f, 0f), Quat.Identity, Density, Friction, HeadRolling));
+ var sides = new[] { (Side.Left, 1f), (Side.Right, -1f) };
+ var upperArm = new int[2]; var lowerArm = new int[2]; var thigh = new int[2]; var shin = new int[2]; var foot = new int[2];
+ for (var k = 0; k < 2; k++)
+ {
+ var (side, sx) = sides[k];
+ upperArm[k] = Capsule("UpperArm", side, sx * 0.21f, 1.395f, 0.045f, 0.11f);
+ lowerArm[k] = Capsule("LowerArm", side, sx * 0.21f, 1.10f, 0.04f, 0.10f);
+ thigh[k] = Capsule("Thigh", side, sx * 0.09f, 0.79f, 0.07f, 0.18f);
+ shin[k] = Capsule("Shin", side, sx * 0.09f, 0.31f, 0.06f, 0.17f);
+ foot[k] = Box("Foot", side, sx * 0.09f, 0.04f, 0.05f, 0.05f, 0.04f, 0.12f);
+ }
+
+ // Hands, appended after the base parts. The palm faces -sx with the thumb forward (+z); the thumb capsule
+ // lies along its metacarpal axis, 30 degrees out of the palm plane; the fingers are created at the rest curl.
+ var cmcAxis = (0f, -MathF.Cos(Thumb30), MathF.Sin(Thumb30));
+ var palm = new int[2]; var thumb = new int[2]; var fingers = new int[2];
+ for (var k = 0; k < 2; k++)
+ {
+ var (side, sx) = sides[k];
+ palm[k] = Box("Palm", side, sx * 0.21f, 0.930f, 0f, 0.014f, 0.045f, 0.040f);
+ var thumbSpin = Quat.FromAxisAngle(1f, 0f, 0f, -Thumb30);
+ thumb[k] = Add(parts, new PartDef("Thumb", side, PartShape.Capsule, (0.011f, 0.03f, 0f),
+ (sx * 0.206f + 0.05f * cmcAxis.Item1, 0.955f + 0.05f * cmcAxis.Item2, 0.03f + 0.05f * cmcAxis.Item3),
+ thumbSpin, Density, Friction, 0f));
+ var curl = Quat.FromAxisAngle(0f, 0f, sx, -RestCurl);
+ fingers[k] = Add(parts, new PartDef("Fingers", side, PartShape.Box, (0.011f, 0.0425f, 0.038f),
+ (sx * 0.21f - sx * MathF.Sin(RestCurl) * 0.0425f, 0.885f - MathF.Cos(RestCurl) * 0.0425f, 0f),
+ curl, Density, Friction, 0f));
+ }
+
+ void Joint(string label, Side side, JointKind kind, int parent, int child, float x, float y, float z,
+ (float, float, float) axis, MuscleGains gains, float lower = 0f, float upper = 0f, float cone = 0f) =>
+ joints.Add(new JointDef(label, side, kind, parent, child, (x, y, z), axis, lower, upper, cone, gains));
+
+ var up = (0f, 1f, 0f);
+ var across = (1f, 0f, 0f);
+ // Gains are tuned against measured stand/fall runs at 120 Hz (see the tests), not derived: explicit PD on
+ // light limbs is stable only while damping * dt stays under the inertia it acts on.
+ Joint("Spine", Side.Center, JointKind.Spherical, pelvis, torso, 0f, 1.19f, 0f, up, new MuscleGains(500f, 4f, 200f, 8f), -0.4f, 0.4f, 0.5f);
+ Joint("Neck", Side.Center, JointKind.Spherical, torso, head, 0f, 1.63f, 0f, up, new MuscleGains(30f, 0.8f, 20f, 0.6f), -0.6f, 0.6f, 0.6f);
+ for (var k = 0; k < 2; k++)
+ {
+ var (side, sx) = sides[k];
+ Joint("Shoulder", side, JointKind.Spherical, torso, upperArm[k], sx * 0.21f, 1.55f, 0f, up, new MuscleGains(20f, 1.5f, 1f, 0.02f), -1f, 1f, 1.5f); // damping carries the hand's mass (hands-gains: 1 and 0.6 before)
+ Joint("Elbow", side, JointKind.Revolute, upperArm[k], lowerArm[k], sx * 0.21f, 1.24f, 0f, across, new MuscleGains(0f, 0f, 12f, 0.9f), -2.4f, 0f);
+ Joint("Hip", side, JointKind.Spherical, pelvis, thigh[k], sx * 0.09f, 1.04f, 0f, up, new MuscleGains(600f, 3f, 10f, 0.15f), -0.5f, 0.5f, 1.2f);
+ Joint("Knee", side, JointKind.Revolute, thigh[k], shin[k], sx * 0.09f, 0.54f, 0f, across, new MuscleGains(0f, 0f, 300f, 8f), 0f, 2.4f);
+ Joint("Ankle", side, JointKind.Revolute, shin[k], foot[k], sx * 0.09f, 0.08f, 0f, across, new MuscleGains(0f, 0f, 100f, 0.5f), -0.6f, 0.6f);
+ }
+
+ // Hand gains are bounded by each body's own inertia, not the arm subtree's (explicit PD is stable only while
+ // damping * dt stays under the inertia it acts on; a wrist kd sized for the arm limit-cycles at once), and
+ // every hand joint keeps passive damping when limp so loose hands settle instead of ringing.
+ for (var k = 0; k < 2; k++)
+ {
+ var (side, sx) = sides[k];
+ Joint("Wrist", side, JointKind.Spherical, lowerArm[k], palm[k], sx * 0.21f, 0.975f, 0f, up, new MuscleGains(1f, 0.012f, 0.3f, 0.005f, 1f), -1.2f, 1.2f, 1.0f);
+ Joint("Thumb", side, JointKind.Spherical, palm[k], thumb[k], sx * 0.206f, 0.955f, 0.03f, cmcAxis, new MuscleGains(0.06f, 0.001f, 0f, 0f, 1f), 0f, 0f, 0.7f); // twist locked: a free thumb spins
+ Joint("Fingers", side, JointKind.Revolute, palm[k], fingers[k], sx * 0.21f, 0.885f, 0f, (0f, 0f, sx), new MuscleGains(0f, 0f, 0.3f, 0.004f, 1f), -1.6f + RestCurl, 0.35f + RestCurl);
+ }
+
+ var senses = new[]
+ {
+ new SensePointDef("Hand", Side.Left, palm[0], (0f, 0f, 0f)),
+ new SensePointDef("Hand", Side.Right, palm[1], (0f, 0f, 0f)),
+ new SensePointDef("Head", Side.Center, head, (0f, 0f, 0f)),
+ };
+
+ // The airway opens at the face, facing +z, each centred on the head sphere's surface (|offset| 0.110, head r 0.11): fluid never enters
+ // a body, so a sensor wholly inside the head reads 0 (probe, 512-drop pour: inside 0.0 mL; centred on the surface at the nose up to
+ // 46.9 mL). Radius 0.025 holds one drop centre (r 1.25 cm) outside the solid; centres 5.05 cm apart, so the spheres do not overlap.
+ var airway = new[]
+ {
+ new AirwayOpeningDef("Mouth", Side.Center, head, (0f, -0.04f, 0.1025f), 0.025f),
+ new AirwayOpeningDef("Nose", Side.Center, head, (0f, 0.01f, 0.1095f), 0.025f),
+ };
+ // Liquid pools behind the openings at the airway's deepest points: the oropharynx 8 cm behind the lips lying on the back, the glottis 7 cm below the mouth upright (placeholders).
+ // An opening drains by gravity when its lowest rim point lies below the deepest of them: the principle of the recovery position, the mouth dependent so fluid runs out
+ // (ERC 2021 BLS, Resuscitation 161:98-114), and of postural drainage, the outlet below the reservoir.
+ var sumps = new[]
+ {
+ new AirwaySumpDef("Pharynx", head, (0f, -0.06f, 0.02f)),
+ new AirwaySumpDef("Glottis", head, (0f, -0.11f, 0.04f)),
+ };
+ return new BodyPlan(parts, joints, senses, airway, sumps);
+ }
+
+ private static int Add(List parts, PartDef part)
+ {
+ parts.Add(part);
+ return parts.Count - 1;
+ }
+ }
+}
diff --git a/src/Lodur.Core/Brain.cs b/src/Lodur.Core/Brain.cs
new file mode 100644
index 0000000..5185da8
--- /dev/null
+++ b/src/Lodur.Core/Brain.cs
@@ -0,0 +1,675 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// A number the drive carries, as a condition reads it.
+ public enum DriveQuantity
+ {
+ Pain,
+ Strain,
+ Arousal,
+ Resolve,
+ /// 1 while the will is broken now (it mends), else 0.
+ WillBroken,
+ /// How many times the will has broken: the one-way latch, for a goal that must hold after a mend.
+ Breaks,
+ /// Air hunger, 0..1: the physiology's urge to breathe, carried by the Actor.
+ AirHunger,
+ }
+
+ public enum ConditionOp
+ {
+ AtLeast,
+ Below,
+ }
+
+ internal static class DriveReads
+ {
+ internal static double Read(in DriveState drive, DriveQuantity quantity) => quantity switch
+ {
+ DriveQuantity.Pain => drive.Pain,
+ DriveQuantity.Strain => drive.Strain,
+ DriveQuantity.Arousal => drive.Arousal,
+ DriveQuantity.Resolve => drive.Resolve,
+ DriveQuantity.Breaks => (double)drive.Breaks,
+ DriveQuantity.AirHunger => drive.AirHunger,
+ _ => drive.WillBroken ? 1.0 : 0.0,
+ };
+ }
+
+ ///
+ /// What a consideration reads: a percept's distance from the observer, its salience, the seconds since it was sensed, a drive quantity, or the length of
+ /// the plan to a want goal's pair.
+ ///
+ public enum ConsiderationInput
+ {
+ Distance,
+ Salience,
+ SecondsSinceSensed,
+ Drive,
+ ///
+ /// Only on a goal with a : x is the pair's plan length (1.. ) for a planned pair and
+ /// + 1 for a direct try. Read by the gate in Brain.Select, never by the raw score.
+ ///
+ PlanSteps,
+ }
+
+ ///
+ /// One response curve over an input, in [0, 1]: t = clamp01((x - X0) / (X1 - X0)), y = Y0 + (Y1 - Y0) * t^Exponent, clamped. A goal's pair
+ /// score is its Priority times every consideration's response. Drive reads off the drive state.
+ ///
+ public readonly record struct Consideration(ConsiderationInput Input, double X0, double X1, double Y0, double Y1, double Exponent = 1.0, DriveQuantity Quantity = default)
+ {
+ public double Response(double x)
+ {
+ var t = Math.Clamp((x - X0) / (X1 - X0), 0.0, 1.0);
+ return Math.Clamp(Y0 + (Y1 - Y0) * Math.Pow(t, Exponent), 0.0, 1.0);
+ }
+ }
+
+ /// The game's kinds a targeted goal accepts; Lodur never interprets them.
+ public sealed record TargetFilter
+ {
+ private IReadOnlyList _kinds = Array.AsReadOnly(Array.Empty());
+
+ /// Copied when set; read back as a read-only view.
+ public IReadOnlyList Kinds
+ {
+ get => _kinds;
+ init
+ {
+ var copy = new uint[value.Count];
+ for (var i = 0; i < copy.Length; i++)
+ {
+ copy[i] = value[i];
+ }
+
+ _kinds = Array.AsReadOnly(copy);
+ }
+ }
+
+ internal bool Accepts(uint kind)
+ {
+ for (var i = 0; i < _kinds.Count; i++)
+ {
+ if (_kinds[i] == kind)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+
+ /// The Brain's choice: a goal index and the id of the percept it targets (0: untargeted).
+ public readonly record struct Choice(int Goal, ulong Target);
+
+ /// One test of the drive state: the quantity against a threshold.
+ public readonly record struct Condition(DriveQuantity Quantity, ConditionOp Op, double Threshold)
+ {
+ public bool Holds(in DriveState drive)
+ {
+ var v = DriveReads.Read(drive, Quantity);
+ return Op == ConditionOp.AtLeast ? v >= Threshold : v < Threshold;
+ }
+ }
+
+ /// One thing the consumer wants a character to be doing, and when it is eligible to be.
+ public sealed record GoalSpec
+ {
+ /// The consumer's name for it; Lodur never reads it.
+ public string Id { get; init; } = "";
+
+ /// The eligible goal of the highest priority is wanted.
+ public double Priority { get; init; }
+
+ /// How hard the goal pulls, in [0, 1], default 0 (no pull): resolve drain is scaled by (1 - pull) while it is active. It is not a second resolve bar.
+ public double Pull { get; init; }
+
+ ///
+ /// Commitment, soft: until this goal has been active this long (rounded to whole ticks like the latency, counted
+ /// from the tick it took over), a goal that does not strictly outrank it cannot be decided on; a strictly
+ /// higher-priority goal preempts at once, after the deliberate latency. 0 (the default) never holds a goal. It keeps
+ /// a condition hovering at its threshold from making the Brain chatter: the return trip from an entered goal is
+ /// gated by that goal's own dwell. The dwell holds the decision to leave; a decision already in flight commits.
+ ///
+ public double MinDwellSeconds { get; init; }
+
+ ///
+ /// The resolve the character has the tick this goal takes over (for the Start goal, at construction), in [0, 1]; null leaves resolve as it is. Rage is what
+ /// the will breaking leads to, and it resets the will (lodur:ruling:rage-involuntary-onset-then-voluntary).
+ ///
+ public double? EntryResolve { get; init; }
+
+ /// Resolve drained per second to sustain this goal, finite and not negative, default 0; it is not paid during and is scaled by (1 - Pull) like the rest of the drain.
+ public double Effort { get; init; }
+
+ ///
+ /// The gain on the sense channels (not the nociceptive region afferents) while this goal is in force, in [0, 1], default 1; 0 is deaf and blind to the
+ /// world's stimuli, which keep sounding (lodur:ruling:stress-bar-shows-arousal-calm-silences). Applied like : at the tick the goal
+ /// takes over, and at construction for the Start goal. The sense reads the gain at the start of each tick, so a change reaches
+ /// one tick after the Actor sets it.
+ ///
+ public double SensoryGain { get; init; } = 1.0;
+
+ ///
+ /// The arousal this goal brings, in [0, 1]; null leaves arousal to the drive. Calm drops it so the stress bar drains
+ /// (lodur:ruling:stress-bar-shows-arousal-calm-silences). Reached over , then the drive owns arousal again.
+ ///
+ public double? EntryArousal { get; init; }
+
+ ///
+ /// How long after it takes over the goal's and are reached, finite and not negative, default 0 (at the
+ /// takeover tick): a linear ramp from their values at takeover, rounded to whole ticks once like the onset. The aftershock tail
+ /// of lodur:ruling:flinch-tail-after-stimulus. It does not ramp , which stays a snap. For the Start goal the targets apply at construction.
+ ///
+ public double EntrySeconds { get; init; }
+
+ ///
+ /// How long after it takes over the goal runs without will (rounded to whole ticks once, like the dwell), not negative, default 0 (voluntary from the first tick);
+ /// +infinity is involuntary throughout. While involuntary the behaviour writes at full weight and pays no Effort;
+ /// after it the goal is voluntary: sustained by like every other voluntary layer.
+ ///
+ public double InvoluntarySeconds { get; init; }
+
+ private Condition[] _when = Array.Empty();
+ private IReadOnlyList _whenView = Array.AsReadOnly(Array.Empty());
+
+ /// All must hold for the goal to be eligible; none means always eligible. Copied when set; read back as a read-only view.
+ public IReadOnlyList When
+ {
+ get => _whenView;
+ init
+ {
+ _when = new Condition[value.Count];
+ for (var c = 0; c < _when.Length; c++)
+ {
+ _when[c] = value[c];
+ }
+
+ _whenView = Array.AsReadOnly(_when);
+ }
+ }
+
+ /// The kind of thing this goal targets; null is an untargeted goal. Whether a target exists is decided in , not by Eligible.
+ public TargetFilter? Target { get; init; }
+
+ ///
+ /// A fact the goal wants to make true, about himself ( , never bit 63) or about the goal's target ( , which needs a
+ /// ); null is no want. A want pair whose want already holds is not offered; one that does not is planned to steps and scored
+ /// by the plan's length through , or tried direct at when no plan is found. A want goal's Priority
+ /// must not be negative. Only an Actor built with verbs selects a Brain that has wants.
+ ///
+ public Fact? Want { get; init; }
+
+ private Consideration[] _considerations = Array.Empty();
+ private IReadOnlyList _considerationsView = Array.AsReadOnly(Array.Empty());
+
+ /// Multiplied with Priority to score each (goal, percept) pair. Copied when set; read back as a read-only view.
+ public IReadOnlyList Considerations
+ {
+ get => _considerationsView;
+ init
+ {
+ _considerations = new Consideration[value.Count];
+ for (var c = 0; c < _considerations.Length; c++)
+ {
+ _considerations[c] = value[c];
+ }
+
+ _considerationsView = Array.AsReadOnly(_considerations);
+ }
+ }
+
+ /// Priority times every consideration but : the raw score, before the plan's length is known.
+ internal double Score(in DriveState drive, in Percept percept, float ox, float oy, float oz)
+ {
+ var score = Priority;
+ for (var c = 0; c < _considerations.Length; c++)
+ {
+ var k = _considerations[c];
+ double x;
+ switch (k.Input)
+ {
+ case ConsiderationInput.PlanSteps:
+ continue;
+ case ConsiderationInput.Drive:
+ x = DriveReads.Read(drive, k.Quantity);
+ break;
+ case ConsiderationInput.Distance:
+ {
+ double dx = percept.X - ox, dy = percept.Y - oy, dz = percept.Z - oz;
+ x = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+ break;
+ }
+ case ConsiderationInput.Salience:
+ x = percept.Salience;
+ break;
+ default:
+ x = percept.SecondsSinceSensed;
+ break;
+ }
+
+ score *= k.Response(x);
+ }
+
+ return score;
+ }
+
+ /// The product of the responses at plan length ; 1 with none.
+ internal double PlanFactor(int x)
+ {
+ var factor = 1.0;
+ for (var c = 0; c < _considerations.Length; c++)
+ {
+ if (_considerations[c].Input == ConsiderationInput.PlanSteps)
+ {
+ factor *= _considerations[c].Response(x);
+ }
+ }
+
+ return factor;
+ }
+
+ internal bool Eligible(in DriveState drive)
+ {
+ for (var c = 0; c < _when.Length; c++)
+ {
+ if (!_when[c].Holds(drive))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public PoseBehaviour Behaviour { get; init; } = new PoseBehaviour();
+ }
+
+ ///
+ /// Layer 4: the consumer's goals, selected by conditions over the drive state. Lodur has no flip rule of its
+ /// own; every rule is this data. Data only: the Actor commits the choice, after the deliberate latency.
+ ///
+ public sealed record Brain
+ {
+ private IReadOnlyList _goals = Array.Empty();
+
+ /// The goals, copied when set: later changes to the caller's list or arrays do not reach a Brain, and the getter is a read-only view.
+ public IReadOnlyList Goals
+ {
+ get => _goals;
+ init
+ {
+ var copy = new GoalSpec[value.Count];
+ for (var i = 0; i < copy.Length; i++)
+ {
+ copy[i] = value[i];
+ }
+
+ _goals = Array.AsReadOnly(copy);
+ }
+ }
+
+ /// The index of the goal a character begins in.
+ public int Start { get; init; }
+
+ /// How long a chosen switch takes to commit; a decision in flight commits even if its condition lapses.
+ public double DeliberateLatencySeconds { get; init; } = 0.1;
+
+ /// How much the current (goal, target) pair's score is multiplied by, finite and at least 1; 1 is no commitment.
+ public double TargetCommitment { get; init; } = 1.0;
+
+ /// The planner's depth, the intelligence stat's base: the most steps a want goal's plan may have, 0..8, default 0 (no plans; every want pair is tried direct).
+ public int PlanDepth { get; init; }
+
+ /// The factor on a pair's score when its goal's want has no plan within (or the think budget ran out): he goes at the target directly, in [0, 1], default 0.5 (a placeholder).
+ public double DirectDiscount { get; init; } = 0.5;
+
+ /// How long a direct try ( -1) of one (goal, target) pair may last before the Actor gives it up: it bars the pair's direct try, reports and decides again past the goal's dwell. Not NaN, not negative; +infinity never frustrates. Default 5 (a placeholder; ruling bds-unplannable-tries-direct).
+ public double FrustrationSeconds { get; init; } = 5.0;
+
+ /// How long a bar on a direct try lasts if its target is not forgotten first: the pair is tried direct again after it. Positive, not NaN; +infinity never lifts by time. Default 30 (a placeholder).
+ public double RetrySeconds { get; init; } = 30.0;
+
+ /// The most groundings one Select may regress across all its plans, at least 1, default 4096: one budget per decision, spent by deepening across the want pairs, short plans first (lodur:question:bds-think-budget-per-decision).
+ public int ThinkBudget { get; init; } = Planner.NodeBudget;
+
+ /// How close a thing must be to be in reach, in meters, finite and above 0, default 0.6 (an arm's length, 0.575 m, as a placeholder).
+ public double ReachMeters { get; init; } = 0.6;
+
+ /// True when any goal has a want: such a Brain is selected through an Actor's Deliberation, not the public Select.
+ internal bool HasWants
+ {
+ get
+ {
+ for (var i = 0; i < Goals.Count; i++)
+ {
+ if (Goals[i].Want is not null)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ }
+
+ ///
+ /// The pair wanted now. Each eligible untargeted goal is one pair (goal, 0) scored Priority times its Drive considerations; each eligible
+ /// targeted goal is one pair per percept slot with a non-zero Id and a Kind it accepts, scored Priority times every consideration. The pair
+ /// equal to is multiplied by . The highest score wins; ties go to the current pair,
+ /// then the lowest goal index, then the lowest slot. With no pair at all the goal in force stays and lets go of its target: (current.Goal, 0),
+ /// so a forgotten target is not held (the Actor commits it a latency later and the orient layers rest). A percept Id is only compared, never decoded.
+ /// Throws for a Brain with a want: the planner's gate needs an Actor's verbs, so the Actor selects it.
+ ///
+ public Choice Select(in DriveState drive, Perception perception, float observerX, float observerY, float observerZ, Choice current)
+ {
+ if (HasWants)
+ {
+ throw new InvalidOperationException("A Brain with a want is selected by its Actor, which holds the verbs the planner needs.");
+ }
+
+ return Select(drive, perception, observerX, observerY, observerZ, current, null);
+ }
+
+ ///
+ /// with the want gate. Pass 1 scores every pair raw (commitment applied) and offers
+ /// the untargeted-by-want pairs; a want pair whose want holds is not offered, the rest wait in the Deliberation. Pass 2 deepens across the waiting pairs: round k takes them by
+ /// bound (raw times the best factor any plan longer than k - 1 steps, or going direct, could earn), asks each for a plan of exactly k steps with what is left of ,
+ /// and offers raw times the plan-length factor for one found; a pair with none of k steps waits for round k + 1, and one with no plan within PlanDepth (or the budget gone) is offered
+ /// at raw times the factor at PlanDepth + 1 times , unless the Deliberation holds a bar on that pair's direct try (it is then not offered; it is offered when it plans). A round ends when no remaining bound can beat or tie-win the best, so short plans are found
+ /// first and one pair's dead end cannot starve the rest.
+ ///
+ internal Choice Select(in DriveState drive, Perception perception, float ox, float oy, float oz, Choice current, Deliberation? d)
+ {
+ var best = default(Pick);
+ var slots = perception.PerceptCount;
+ d?.Begin(perception, ox, oy, oz);
+ for (var i = 0; i < Goals.Count; i++)
+ {
+ var goal = Goals[i];
+ if (!goal.Eligible(drive))
+ {
+ continue;
+ }
+
+ if (goal.Target is null)
+ {
+ Consider(i, goal, -1, 0UL, goal.Score(drive, default, ox, oy, oz), current, d, ref best);
+ continue;
+ }
+
+ for (var s = 0; s < slots; s++)
+ {
+ var percept = perception.Percept(s);
+ if (percept.Id == 0UL || !goal.Target.Accepts(percept.Kind))
+ {
+ continue;
+ }
+
+ Consider(i, goal, s, percept.Id, goal.Score(drive, percept, ox, oy, oz), current, d, ref best);
+ }
+ }
+
+ if (d is not null)
+ {
+ for (var k = PlanDepth == 0 ? 0 : 1; ; k++)
+ {
+ while (d.TryPop(out var pair))
+ {
+ if (best.Found && pair.Bound < best.Score)
+ {
+ d.ClearRound();
+ break;
+ }
+
+ var goal = Goals[pair.Goal];
+ var length = d.PlanAt(pair.Goal, goal.Want!.Value, pair.Slot, k);
+ if (length == 0)
+ {
+ pair.Bound = pair.Raw * d.BoundFactor(pair.Goal, k);
+ d.Defer(pair);
+ continue;
+ }
+
+ if (length < 0 && d.Barred(pair.Goal, pair.Target))
+ {
+ continue; // a futile direct try is barred: neither offered nor deferred
+ }
+
+ var factor = length > 0 ? goal.PlanFactor(length) : goal.PlanFactor(PlanDepth + 1) * DirectDiscount;
+ if (Offer(pair.Goal, pair.Slot, pair.Target, pair.Raw * factor, pair.Current, ref best))
+ {
+ d.KeepBest(pair.Goal, length, goal.Want!.Value.Subject == FactSubject.Self);
+ }
+ }
+
+ if (!d.NextRound())
+ {
+ break;
+ }
+ }
+ }
+
+ return best.Found ? Pair(best.Goal, best.Target) : Pair(current.Goal, 0UL);
+ }
+
+ private static Choice Pair(int goal, ulong target) => new Choice(goal, target);
+
+ // One scored pair: offered now, or (a want pair) held back for the planner's gate. The commitment multiplies the raw score here, so pass 2 orders by the committed raw.
+ private void Consider(int goal, GoalSpec spec, int slot, ulong target, double raw, Choice current, Deliberation? d, ref Pick best)
+ {
+ var isCurrent = goal == current.Goal && target == current.Target;
+ if (isCurrent)
+ {
+ raw *= TargetCommitment;
+ }
+
+ if (spec.Want is not { } want)
+ {
+ if (Offer(goal, slot, target, raw, isCurrent, ref best))
+ {
+ d?.KeepBest(goal, 0, false);
+ }
+ }
+ else if (!d!.Holds(goal, want, slot))
+ {
+ d.Add(goal, slot, target, raw, isCurrent);
+ }
+ }
+
+ // Ties resolve by key (current, then lowest goal, then lowest slot), not by call order: pass 2 offers out of index order. True when the offer became the best, so its plan is kept.
+ private static bool Offer(int goal, int slot, ulong target, double score, bool isCurrent, ref Pick best)
+ {
+ if (!best.Found || score > best.Score
+ || (score == best.Score && (isCurrent != best.IsCurrent ? isCurrent : goal < best.Goal || (goal == best.Goal && slot < best.Slot))))
+ {
+ best = new Pick { Goal = goal, Slot = slot, Target = target, Score = score, IsCurrent = isCurrent, Found = true };
+ return true;
+ }
+
+ return false;
+ }
+
+ private struct Pick
+ {
+ public int Goal;
+ public int Slot;
+ public ulong Target;
+ public double Score;
+ public bool IsCurrent;
+ public bool Found;
+ }
+
+ internal void Validate()
+ {
+ if (Goals.Count == 0)
+ {
+ throw new ArgumentException("A brain needs at least one goal.");
+ }
+
+ if (Start < 0 || Start >= Goals.Count)
+ {
+ throw new ArgumentException("Start is not a goal index.");
+ }
+
+ if (!(DeliberateLatencySeconds >= 0.0 && double.IsFinite(DeliberateLatencySeconds)))
+ {
+ throw new ArgumentException("DeliberateLatencySeconds must be finite and not negative.");
+ }
+
+ if (!(double.IsFinite(TargetCommitment) && TargetCommitment >= 1.0))
+ {
+ throw new ArgumentException("TargetCommitment must be finite and at least 1.");
+ }
+
+ if (PlanDepth < 0 || PlanDepth > 8)
+ {
+ throw new ArgumentException("PlanDepth must be in 0..8.");
+ }
+
+ if (!(DirectDiscount >= 0.0 && DirectDiscount <= 1.0))
+ {
+ throw new ArgumentException("DirectDiscount must be in [0, 1].");
+ }
+
+ if (!(FrustrationSeconds >= 0.0))
+ {
+ throw new ArgumentException("FrustrationSeconds must not be NaN or negative.");
+ }
+
+ if (!(RetrySeconds > 0.0))
+ {
+ throw new ArgumentException("RetrySeconds must be positive (not NaN, zero or negative): a bar that lifts the next tick is no bar.");
+ }
+
+ if (ThinkBudget < 1)
+ {
+ throw new ArgumentException("ThinkBudget must be at least 1.");
+ }
+
+ if (!(double.IsFinite(ReachMeters) && ReachMeters > 0.0))
+ {
+ throw new ArgumentException("ReachMeters must be finite and above 0.");
+ }
+
+ var muscles = -1;
+ foreach (var goal in Goals)
+ {
+ if (goal.Target is { } filter && filter.Kinds.Count == 0)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a Target needs at least one kind.");
+ }
+
+ if ((goal.Target != null || goal.Considerations.Count > 0) && !(goal.Priority >= 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Target or considerations.");
+ }
+
+ if (goal.Want is { } want)
+ {
+ if (want.Subject != FactSubject.Self && want.Subject != FactSubject.This)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a Want is about himself or the target.");
+ }
+
+ if ((uint)want.Bit > 63u || (want.Subject == FactSubject.Self && want.Bit == 63))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a Want is on a bit in 0..63, and bit 63 is Lodur's reach, which the actor has none of.");
+ }
+
+ if (want.Subject == FactSubject.This && goal.Target is null)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a Want about the target needs a Target.");
+ }
+
+ if (!(goal.Priority >= 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Priority must not be negative on a goal with a Want.");
+ }
+ }
+
+ foreach (var k in goal.Considerations)
+ {
+ if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
+ || !(k.Y0 >= 0.0 && k.Y0 <= 1.0) || !(k.Y1 >= 0.0 && k.Y1 <= 1.0)
+ || !(double.IsFinite(k.Exponent) && k.Exponent > 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a consideration needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
+ }
+
+ if (k.Input == ConsiderationInput.PlanSteps)
+ {
+ if (goal.Want is null)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a PlanSteps consideration needs a goal with a Want.");
+ }
+ }
+ else if (k.Input != ConsiderationInput.Drive && goal.Target is null)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Distance, Salience and SecondsSinceSensed considerations need a targeted goal.");
+ }
+ }
+
+ if (!double.IsFinite(goal.Priority) || !(goal.Pull >= 0.0 && goal.Pull <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: priority must be finite and pull in [0, 1].");
+ }
+
+ if (!(goal.MinDwellSeconds >= 0.0 && double.IsFinite(goal.MinDwellSeconds)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: MinDwellSeconds must be finite (not infinite) and not negative.");
+ }
+
+ if (goal.EntryResolve is double entry && !(entry >= 0.0 && entry <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntryResolve must be in [0, 1].");
+ }
+
+ if (!(goal.SensoryGain >= 0.0 && goal.SensoryGain <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: SensoryGain must be in [0, 1].");
+ }
+
+ if (goal.EntryArousal is double entryArousal && !(entryArousal >= 0.0 && entryArousal <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntryArousal must be in [0, 1].");
+ }
+
+ if (!(goal.EntrySeconds >= 0.0 && double.IsFinite(goal.EntrySeconds)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: EntrySeconds must be finite and not negative.");
+ }
+
+ if (!(goal.Effort >= 0.0 && double.IsFinite(goal.Effort)))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: Effort must be finite and not negative.");
+ }
+
+ if (!(goal.InvoluntarySeconds >= 0.0))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: InvoluntarySeconds must not be negative or NaN (infinity is allowed).");
+ }
+
+ foreach (var c in goal.When)
+ {
+ if (!double.IsFinite(c.Threshold))
+ {
+ throw new ArgumentException($"Goal {goal.Id}: a condition threshold is not finite.");
+ }
+ }
+
+ goal.Behaviour.Validate(goal.Id);
+ if (muscles >= 0 && goal.Behaviour.MuscleCount != muscles)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: every behaviour needs the same muscle count.");
+ }
+
+ muscles = goal.Behaviour.MuscleCount;
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/Deliberation.cs b/src/Lodur.Core/Deliberation.cs
new file mode 100644
index 0000000..c6ad828
--- /dev/null
+++ b/src/Lodur.Core/Deliberation.cs
@@ -0,0 +1,459 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// A want pair held back for the planner's gate: its goal, percept slot (-1 for an untargeted goal), the percept's id, its raw score (commitment applied), the most it can still score (raw times the bound factor of the depth searched so far) and whether it is the current pair.
+ internal struct WantPair
+ {
+ public int Goal;
+ public int Slot;
+ public ulong Target;
+ public double Raw;
+ public double Bound;
+ public bool Current;
+ }
+
+ ///
+ /// What one Actor thinks with while its Brain selects: the planner, the want pairs waiting for the gate (a max-heap by bound, ties current, lowest goal, lowest slot),
+ /// the pairs deferred to the next round of deepening, the bound table, and the think budget spent so far in this Select. Pass 2 deepens across pairs (Korf's iterative
+ /// deepening, anytime): round k asks every live pair for a plan of exactly k steps, so short plans are found first and no pair starves the rest.
+ /// It also carries the plan of the decision: the plan of the pair best so far in this Select and the plan of the decision in force,
+ /// each made by the Select that chose (or re-chose) the pair and carried until the next one; Select never reads them. The best plan is also the plan of a pending decision: the Actor runs no Select
+ /// between a decision becoming pending and its commit, so nothing writes the best plan in that window (that rule is load-bearing here). Owned by one Actor; allocates only in its constructor. Not thread-safe.
+ ///
+ internal sealed class Deliberation
+ {
+ private const int Unplanned = int.MinValue;
+
+ private readonly Planner _planner;
+ private readonly Brain _brain;
+ private readonly PlanStep[] _plan;
+ private readonly WantPair[] _heap;
+ private readonly sbyte[] _selfHeld; // per goal this Select: -1 not asked, 0 the Self want does not hold, 1 it holds
+ private readonly int[] _selfLength; // per goal this Select: the Self want's plan length, -1 direct, Unplanned not asked
+ private Perception _perception;
+ private float _ox;
+ private float _oy;
+ private float _oz;
+ private int _count;
+ private int _spent;
+ private readonly int _depth;
+ private readonly double[] _bound; // per goal g and searched depth k in 0..PlanDepth: the most a pair with no plan of k or fewer steps can score, as a factor on raw
+ private readonly WantPair[] _next; // the pairs with no plan of this round's k steps, waiting for round k + 1
+ private int _nextCount;
+ private int _bestLength;
+ private int _inForceLength;
+ private readonly int[] _selfDepth; // per goal this Select: the depth a Self want has been searched to
+ private bool _gone; // this Select's budget is gone: every later pair goes direct
+ private readonly PlanStep[] _selfPlan; // per goal this Select: the plan found for its Self want, shared by its pairs
+ private readonly int _width; // the steps a plan buffer holds
+ private PlanStep[] _best; // the plan of the pair best so far in this Select, BestLength steps
+ private PlanStep[] _inForce; // the plan of the decision in force
+ private readonly ulong[] _barTarget; // per goal: the barred target's id (0 for a Self want's untargeted goal)
+ private readonly long[] _barUntil; // per goal: the tick the bar expires at; -1 is no bar
+
+ internal Deliberation(Brain brain, IReadOnlyList verbs, int capacity)
+ {
+ _brain = brain;
+ _planner = new Planner(verbs, capacity, brain.PlanDepth, brain.ReachMeters);
+ _plan = new PlanStep[Math.Max(1, brain.PlanDepth)];
+ _heap = new WantPair[brain.Goals.Count * capacity];
+ _selfHeld = new sbyte[brain.Goals.Count];
+ _selfLength = new int[brain.Goals.Count];
+ _perception = null!;
+ _depth = brain.PlanDepth;
+ _width = Math.Max(1, _depth);
+ _best = new PlanStep[_width];
+ _inForce = new PlanStep[_width];
+ _selfPlan = new PlanStep[brain.Goals.Count * _width];
+ _next = new WantPair[_heap.Length];
+ _selfDepth = new int[brain.Goals.Count];
+ _barTarget = new ulong[brain.Goals.Count];
+ _barUntil = new long[brain.Goals.Count];
+ Array.Fill(_barUntil, -1L);
+ _bound = new double[brain.Goals.Count * (_depth + 1)];
+ for (var g = 0; g < brain.Goals.Count; g++)
+ {
+ var direct = brain.Goals[g].PlanFactor(_depth + 1) * brain.DirectDiscount;
+ for (var k = 0; k <= _depth; k++)
+ {
+ var b = direct;
+ for (var x = k + 1; x <= _depth; x++)
+ {
+ b = Math.Max(b, brain.Goals[g].PlanFactor(x));
+ }
+
+ _bound[g * (_depth + 1) + k] = b;
+ }
+ }
+ }
+
+ /// The most a pair of with no plan of or fewer steps can score, as a factor on its raw score. No monotonicity of the plan-length factor is assumed.
+ internal double BoundFactor(int goal, int k) => _bound[goal * (_depth + 1) + k];
+
+ /// The actor's own facts this tick, supplied by the game (bit 63 never set).
+ internal ulong SelfFacts { get; set; }
+
+ /// The groundings the current Select has paid out of .
+ internal int Spent => _spent;
+
+ /// The plan of the decision in force, in execution order: step i for i below .
+ internal PlanStep Step(int i) => _inForce[i];
+
+ /// The length of the plan of the decision in force: n steps, -1 to go direct, 0 when its want holds, it has none, or its target left memory.
+ internal int InForceLength => _inForceLength;
+
+ /// Bars the direct try of the pair ( , ) until . One bar per goal: a new one replaces it.
+ internal void Bar(int goal, ulong target, long untilTick)
+ {
+ _barTarget[goal] = target;
+ _barUntil[goal] = untilTick;
+ }
+
+ /// Whether the direct try of the pair is barred: an equal bar, live ( runs each tick before the decision).
+ internal bool Barred(int goal, ulong target) => _barUntil[goal] >= 0 && _barTarget[goal] == target;
+
+ ///
+ /// Clears every bar whose time has come or whose target is no longer in memory. A changed fact does not lift a bar (ruling frustration-lifts-without-fact-changes):
+ /// a pair that becomes plannable is offered through it by Select.
+ ///
+ internal void Lift(Perception perception, long tick)
+ {
+ var ids = perception.PerceptIds;
+ for (var g = 0; g < _barUntil.Length; g++)
+ {
+ if (_barUntil[g] < 0)
+ {
+ continue;
+ }
+
+ var lift = tick >= _barUntil[g];
+ if (!lift && _barTarget[g] != 0UL)
+ {
+ lift = true;
+ for (var s = 0; s < ids.Length; s++)
+ {
+ if (ids[s] == _barTarget[g])
+ {
+ lift = false;
+ break;
+ }
+ }
+ }
+
+ if (lift)
+ {
+ _barUntil[g] = -1;
+ _barTarget[g] = 0UL;
+ }
+ }
+ }
+
+ /// Starts a Select: nothing waits, nothing is spent, nothing is known of the Self wants.
+ internal void Begin(Perception perception, float ox, float oy, float oz)
+ {
+ _perception = perception;
+ _ox = ox;
+ _oy = oy;
+ _oz = oz;
+ _count = 0;
+ _spent = 0;
+ _nextCount = 0;
+ _gone = false;
+ _bestLength = 0;
+ for (var g = 0; g < _selfHeld.Length; g++)
+ {
+ _selfHeld[g] = -1;
+ _selfLength[g] = Unplanned;
+ _selfDepth[g] = 0;
+ }
+ }
+
+ /// Whether the want already holds for the pair on (-1 for an untargeted goal): a depth-0 plan, which spends no budget. A Self want is asked once per goal.
+ internal bool Holds(int goal, Fact want, int slot)
+ {
+ if (want.Subject != FactSubject.Self)
+ {
+ return AskHolds(want, slot);
+ }
+
+ if (_selfHeld[goal] < 0)
+ {
+ _selfHeld[goal] = (sbyte)(AskHolds(want, 0) ? 1 : 0);
+ }
+
+ return _selfHeld[goal] == 1;
+ }
+
+ private bool AskHolds(Fact want, int slot) =>
+ _planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, slot, want, 0, _plan, 1) == 0;
+
+ ///
+ /// Round of the deepening for a want pair that does not hold: n = k when the pair has a plan of exactly k steps (none shorter was found in an earlier round),
+ /// 0 when it has none of k steps and k is below PlanDepth (defer to round k + 1), -1 to go at it direct (no plan within PlanDepth, PlanDepth is 0, or the budget is gone, and then
+ /// it stays gone for the rest of the Select). A Self want is searched once per goal and depth and shared by its pairs. Spends from the Select's one budget.
+ ///
+ internal int PlanAt(int goal, Fact want, int slot, int k)
+ {
+ if (_depth == 0)
+ {
+ return -1;
+ }
+
+ var self = want.Subject == FactSubject.Self;
+ if (self && _selfLength[goal] != Unplanned)
+ {
+ return _selfLength[goal]; // planned once for all its pairs, and shared at no cost even when the budget is gone
+ }
+
+ if (_gone)
+ {
+ return -1;
+ }
+
+ if (self && _selfDepth[goal] >= k)
+ {
+ return k == _depth ? -1 : 0;
+ }
+
+ var left = _brain.ThinkBudget - _spent;
+ if (left < 1)
+ {
+ _gone = true;
+ return -1;
+ }
+
+ var n = _planner.Plan(_perception, SelfFacts, _ox, _oy, _oz, self ? 0 : slot, want, k, _plan, left, k);
+ _spent = Math.Min(_brain.ThinkBudget, _spent + _planner.LastNodes);
+ int result;
+ if (n > 0)
+ {
+ result = n;
+ if (self)
+ {
+ Array.Copy(_plan, 0, _selfPlan, goal * _width, n);
+ }
+ }
+ else if (_planner.LastExhausted)
+ {
+ _gone = true;
+ result = -1;
+ }
+ else
+ {
+ result = k == _depth ? -1 : 0;
+ }
+
+ if (self)
+ {
+ _selfDepth[goal] = k;
+ if (result != 0)
+ {
+ _selfLength[goal] = result;
+ }
+ }
+
+ return result;
+ }
+
+ /// Holds a pair with no plan of this round's steps for the next round.
+ internal void Defer(in WantPair pair) => _next[_nextCount++] = pair;
+
+ /// Drops every pair still waiting in this round: none of them can beat the best found.
+ internal void ClearRound() => _count = 0;
+
+ /// Starts the next round with the deferred pairs; false when nothing was deferred.
+ internal bool NextRound()
+ {
+ if (_nextCount == 0)
+ {
+ return false;
+ }
+
+ _count = 0;
+ for (var i = 0; i < _nextCount; i++)
+ {
+ Push(_next[i]);
+ }
+
+ _nextCount = 0;
+ return true;
+ }
+
+ /// The pair just offered is the best so far in this Select: keep its plan ( steps, 0 for a pair without a want, -1 for a direct try).
+ internal void KeepBest(int goal, int length, bool self)
+ {
+ _bestLength = length;
+ if (length > 0)
+ {
+ Array.Copy(self ? _selfPlan : _plan, self ? goal * _width : 0, _best, 0, length);
+ }
+ }
+
+ /// The Select's best pair takes force, as the re-chosen pair in force or the pending decision at its commit: its plan is the plan in force.
+ internal void Refresh()
+ {
+ (_inForce, _best) = (_best, _inForce);
+ _inForceLength = _bestLength;
+ }
+
+ ///
+ /// The Select was refused (inside the goal's dwell) and the pair in force stays: its plan is made again with what is left of this Select's budget, to PlanDepth.
+ /// False when none is left or the search exhausts it; the plan is carried, and checked.
+ ///
+ internal bool ReplanInForce(Perception perception, float ox, float oy, float oz, Fact want, ulong target)
+ {
+ var left = _brain.ThinkBudget - _spent;
+ if (left < 1)
+ {
+ return false;
+ }
+
+ var slot = SlotOf(perception, want, target);
+ if (slot < 0)
+ {
+ _inForceLength = 0;
+ return true;
+ }
+
+ var n = _planner.Plan(perception, SelfFacts, ox, oy, oz, slot, want, _depth, _plan, left);
+ _spent = Math.Min(_brain.ThinkBudget, _spent + _planner.LastNodes);
+ if (_planner.LastExhausted)
+ {
+ return false; // a sliver of budget proves nothing: the plan in force is carried, and checked
+ }
+
+ if (n > 0)
+ {
+ Array.Copy(_plan, 0, _inForce, 0, n);
+ }
+
+ _inForceLength = n;
+ return true;
+ }
+
+ ///
+ /// A tick that wrote no plan: the plan in force is checked, never searched. It becomes 0 when the want holds now or its target left memory, and -1 (go direct) when one of its
+ /// steps' This or Tool left memory. Lodur has no step-execution signal, so a step done shows as a shorter plan at the next Select that re-chooses the pair.
+ ///
+ internal void CheckCarried(Perception perception, float ox, float oy, float oz, Fact want, ulong target)
+ {
+ if (_inForceLength == 0)
+ {
+ return;
+ }
+
+ var slot = SlotOf(perception, want, target);
+ if (slot < 0 || _planner.Plan(perception, SelfFacts, ox, oy, oz, slot, want, 0, _inForce, 1) == 0)
+ {
+ _inForceLength = 0;
+ return;
+ }
+
+ var ids = perception.PerceptIds;
+ for (var i = 0; i < _inForceLength; i++)
+ {
+ if (!Has(ids, _inForce[i].This) || (_inForce[i].Tool != 0UL && !Has(ids, _inForce[i].Tool)))
+ {
+ _inForceLength = -1;
+ return;
+ }
+ }
+ }
+
+ // The planner's target slot for a want: 0 for a Self want, else the slot holding the target's id, -1 when the target is 0 or not in memory.
+ private static int SlotOf(Perception perception, Fact want, ulong target)
+ {
+ if (want.Subject != FactSubject.This)
+ {
+ return 0;
+ }
+
+ var ids = perception.PerceptIds;
+ for (var s = 0; s < ids.Length; s++)
+ {
+ if (target != 0UL && ids[s] == target)
+ {
+ return s;
+ }
+ }
+
+ return -1;
+ }
+
+ private static bool Has(ReadOnlySpan ids, ulong id)
+ {
+ for (var s = 0; s < ids.Length; s++)
+ {
+ if (ids[s] == id)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ internal void Add(int goal, int slot, ulong target, double raw, bool current)
+ {
+ Push(new WantPair { Goal = goal, Slot = slot, Target = target, Raw = raw, Bound = raw * BoundFactor(goal, 0), Current = current });
+ }
+
+ private void Push(in WantPair pair)
+ {
+ var i = _count++;
+ _heap[i] = pair;
+ while (i > 0)
+ {
+ var parent = (i - 1) >> 1;
+ if (!Before(_heap[i], _heap[parent]))
+ {
+ break;
+ }
+
+ (_heap[i], _heap[parent]) = (_heap[parent], _heap[i]);
+ i = parent;
+ }
+ }
+
+ /// The waiting want pair with the highest bound (ties current, lowest goal, lowest slot).
+ internal bool TryPop(out WantPair pair)
+ {
+ if (_count == 0)
+ {
+ pair = default;
+ return false;
+ }
+
+ pair = _heap[0];
+ _heap[0] = _heap[--_count];
+ var i = 0;
+ while (true)
+ {
+ var l = 2 * i + 1;
+ if (l >= _count)
+ {
+ break;
+ }
+
+ var c = l + 1 < _count && Before(_heap[l + 1], _heap[l]) ? l + 1 : l;
+ if (!Before(_heap[c], _heap[i]))
+ {
+ break;
+ }
+
+ (_heap[i], _heap[c]) = (_heap[c], _heap[i]);
+ i = c;
+ }
+
+ return true;
+ }
+
+ private static bool Before(in WantPair a, in WantPair b) =>
+ a.Bound != b.Bound ? a.Bound > b.Bound
+ : a.Current != b.Current ? a.Current
+ : a.Goal != b.Goal ? a.Goal < b.Goal
+ : a.Slot < b.Slot;
+ }
+}
diff --git a/src/Lodur.Core/DriveState.cs b/src/Lodur.Core/DriveState.cs
new file mode 100644
index 0000000..ffd2671
--- /dev/null
+++ b/src/Lodur.Core/DriveState.cs
@@ -0,0 +1,149 @@
+using System;
+
+namespace Lodur
+{
+ /// The drive's tunables: how pain, strain and arousal accumulate, and how they drain the will.
+ public sealed record DriveParameters
+ {
+ public double PainRise { get; init; } = 1.0;
+ public double PainDecay { get; init; } = 0.05;
+ public double StrainRecover { get; init; } = 0.1;
+ public double ResolveDrainPain { get; init; } = 0.012;
+ public double ResolveDrainStrain { get; init; } = 0.05;
+ public double ResolveRecovery { get; init; } = 0.02;
+ public double ResolveRecoversBelowPain { get; init; } = 0.1;
+
+ /// Per-character multiplier on resolve drain (the consumer draws its trait spread).
+ public double DrainTrait { get; init; } = 1.0;
+
+ /// How fast arousal rises toward 1 under full sensory load.
+ public double ArousalRise { get; init; } = 0.5;
+
+ /// How fast arousal falls back once the load stops.
+ public double ArousalDecay { get; init; } = 0.1;
+
+ /// Resolve drained per second at full arousal, before the active goal's pull and the drain trait scale it.
+ public double ResolveDrainArousal { get; init; } = 0.1;
+
+ /// Resolve recovers only while arousal is below this, as well as pain being low.
+ public double ResolveRecoversBelowArousal { get; init; } = 0.1;
+
+ /// Once the will has broken it mends when resolve climbs back to this, in (0, 1]; it can then break again.
+ public double WillMendsAt { get; init; } = 0.25;
+
+ ///
+ /// How a voluntary layer's strength follows the will: the weight is Will^WillCurve, finite and above 0. Below 1 the layer
+ /// holds most of its strength until the will is nearly gone; above 1 it fades as soon as the will drops.
+ ///
+ public double WillCurve { get; init; } = 0.25;
+
+ /// Refuses a value the drive cannot run on, at construction rather than as a NaN several ticks in: every rate, trait and threshold is finite and not negative; WillMendsAt is in (0, 1]; WillCurve is above 0.
+ internal void Validate()
+ {
+ var rates = new[]
+ {
+ (PainRise, nameof(PainRise)), (PainDecay, nameof(PainDecay)), (StrainRecover, nameof(StrainRecover)),
+ (ResolveDrainPain, nameof(ResolveDrainPain)), (ResolveDrainStrain, nameof(ResolveDrainStrain)),
+ (ResolveRecovery, nameof(ResolveRecovery)), (ResolveRecoversBelowPain, nameof(ResolveRecoversBelowPain)),
+ (DrainTrait, nameof(DrainTrait)), (ArousalRise, nameof(ArousalRise)), (ArousalDecay, nameof(ArousalDecay)),
+ (ResolveDrainArousal, nameof(ResolveDrainArousal)), (ResolveRecoversBelowArousal, nameof(ResolveRecoversBelowArousal)),
+ };
+ foreach (var (value, name) in rates)
+ {
+ if (!(value >= 0.0 && double.IsFinite(value)))
+ {
+ throw new ArgumentException($"{name} must be finite and not negative.");
+ }
+ }
+
+ if (!(WillMendsAt > 0.0 && WillMendsAt <= 1.0))
+ {
+ throw new ArgumentException("WillMendsAt must be in (0, 1].");
+ }
+
+ if (!(WillCurve > 0.0 && double.IsFinite(WillCurve)))
+ {
+ throw new ArgumentException("WillCurve must be finite and above 0.");
+ }
+ }
+ }
+
+ ///
+ /// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the
+ /// reflex held down, arousal with sensory load; resolve drains under all three and recovers when pain and
+ /// arousal are both low. Resolve reaching zero breaks the will (counted in ); the broken will
+ /// mends when resolve climbs back to and can break again. Resolve keeps
+ /// evolving through a break. Only the owning steps it.
+ ///
+ public struct DriveState
+ {
+ public double Pain { get; private set; }
+ public double Strain { get; private set; }
+
+ /// Sensory load carried over time, 0..1; it rises under load and decays when quiet.
+ public double Arousal { get; internal set; }
+ public double Resolve { get; private set; }
+
+ /// True from a break until the will mends: broken now, not "has ever broken" (see ).
+ public bool WillBroken { get; private set; }
+
+ /// How many times the will has broken.
+ public int Breaks { get; private set; }
+
+ /// The fraction of resolve that attention lets through, 0..1. A slot, 1 until lodur-startle-attention fills it.
+ public double Attention { get; internal set; }
+
+ /// The ceiling on the will that wakefulness sets, 0..1; written each tick by the Actor from its (the only writer), 1 for an Actor with no physiology.
+ public double Consciousness { get; internal set; }
+
+ /// The will that is available to hold reflexes down and to power voluntary behaviour: resolve through attention, capped by consciousness.
+ public double Will => Math.Min(Resolve * Attention, Consciousness);
+
+ /// The gain on the sense channels in force, 0..1: the goal in force's as the Actor has reached it. Written only by the Actor.
+ public double SensoryGain { get; internal set; }
+
+ /// Air hunger, 0..1: written each tick by the Actor from its (the only writer), 0 for an Actor with no physiology. It raises arousal like sensory load does.
+ public double AirHunger { get; internal set; }
+
+ internal static DriveState Fresh => new DriveState { Resolve = 1.0, Attention = 1.0, Consciousness = 1.0, SensoryGain = 1.0 };
+
+ /// A goal's entry effect: sets resolve, then the mend check runs (a break the entry lifts past is mended). It is not a break and counts none.
+ internal void Enter(DriveParameters p, double resolve)
+ {
+ Resolve = resolve;
+ if (WillBroken && Resolve >= p.WillMendsAt)
+ {
+ WillBroken = false;
+ }
+ }
+
+ /// Steps one tick; returns true on the tick the will breaks (each break, not only the first). is the active goal's: it scales resolve drain by (1 - pull). is the active goal's resolve drained per second to sustain it (0 while it is involuntary); it joins the drain sum, so pull scales it too.
+ internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad, double load, double pull, double effort)
+ {
+ Arousal = Math.Min(Math.Max(Arousal + dt * (p.ArousalRise * Math.Max(load, AirHunger) * (1.0 - Arousal) - p.ArousalDecay * Arousal), 0.0), 1.0);
+ Pain = Math.Min(Math.Max(Pain + dt * (p.PainRise * afferent * (1.0 - Pain) - p.PainDecay * Pain), 0.0), 1.0);
+ Strain = Math.Max(0.0, Strain + dt * (strainLoad - p.StrainRecover * Strain));
+ var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain + p.ResolveDrainArousal * Arousal + effort) * (1.0 - pull) * p.DrainTrait;
+ var recovery = Pain < p.ResolveRecoversBelowPain && Arousal < p.ResolveRecoversBelowArousal ? p.ResolveRecovery * (1.0 - Resolve) : 0.0;
+ Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0);
+ if (WillBroken)
+ {
+ if (Resolve >= p.WillMendsAt)
+ {
+ WillBroken = false;
+ }
+
+ return false;
+ }
+
+ if (Resolve <= 0.0)
+ {
+ WillBroken = true;
+ Breaks++;
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/src/Lodur.Core/Ik.cs b/src/Lodur.Core/Ik.cs
new file mode 100644
index 0000000..420dd55
--- /dev/null
+++ b/src/Lodur.Core/Ik.cs
@@ -0,0 +1,893 @@
+using System;
+
+namespace Lodur
+{
+ /// A plain 3-vector for the solvers; a value type, so solving allocates nothing.
+ internal readonly struct IkVec
+ {
+ public readonly float X, Y, Z;
+
+ public IkVec(float x, float y, float z)
+ {
+ X = x; Y = y; Z = z;
+ }
+
+ public IkVec((float X, float Y, float Z) v)
+ {
+ X = v.X; Y = v.Y; Z = v.Z;
+ }
+
+ public static IkVec operator +(IkVec a, IkVec b) => new IkVec(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ public static IkVec operator -(IkVec a, IkVec b) => new IkVec(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
+ public static IkVec operator *(IkVec a, float s) => new IkVec(a.X * s, a.Y * s, a.Z * s);
+
+ public float Dot(IkVec b) => X * b.X + Y * b.Y + Z * b.Z;
+ public IkVec Cross(IkVec b) => new IkVec(Y * b.Z - Z * b.Y, Z * b.X - X * b.Z, X * b.Y - Y * b.X);
+ public float Length => MathF.Sqrt(Dot(this));
+
+ public IkVec Unit()
+ {
+ var l = Length;
+ return l > 0f ? this * (1f / l) : this;
+ }
+
+ public IkVec Rotated(in Quat q)
+ {
+ q.Rotate(X, Y, Z, out var x, out var y, out var z);
+ return new IkVec(x, y, z);
+ }
+ }
+
+ ///
+ /// Inverse kinematics as a producer of joint target rotations: a world point in, target rotations out, in the convention of the
+ /// body interface. It decides nothing about when to reach or how hard, and it reads the plan, never writes it.
+ ///
+ /// Convention: a joint's frame F is the shortest-arc rotation taking +z to the joint's axis (the plan's creation-pose axis). A target q
+ /// means the child's rotation relative to the parent, from the creation pose, is F q F^-1 in the parent's creation-pose frame. Twist is
+ /// about the frame's z, swing about its x and y. A spherical joint's Lower and Upper bound twist and Cone bounds swing; a hinge's Lower
+ /// and Upper bound its angle about frame z.
+ ///
+ ///
+ public static class Ik
+ {
+ /// The joint frame F of : the shortest arc from +z to the unit joint axis.
+ public static Quat JointFrame(in JointDef joint) => Arc(new IkVec(0f, 0f, 1f), new IkVec(joint.Axis).Unit());
+
+ /// The shortest-arc rotation taking unit vector a onto unit vector b.
+ internal static Quat Arc(IkVec a, IkVec b)
+ {
+ var dot = a.Dot(b);
+ if (dot < -1f + 1e-6f)
+ {
+ // Opposite: a half turn about any axis perpendicular to a.
+ var p = a.Cross(MathF.Abs(a.X) < 0.9f ? new IkVec(1f, 0f, 0f) : new IkVec(0f, 1f, 0f)).Unit();
+ return new Quat(p.X, p.Y, p.Z, 0f);
+ }
+
+ var c = a.Cross(b);
+ var w = 1f + dot;
+ var inv = 1f / MathF.Sqrt(c.Dot(c) + w * w);
+ return new Quat(c.X * inv, c.Y * inv, c.Z * inv, w * inv);
+ }
+
+ internal static Quat About(IkVec axis, float radians) => Quat.FromAxisAngle(axis.X, axis.Y, axis.Z, radians);
+
+ internal static float Clamp(float v, float lo, float hi) => v < lo ? lo : (v > hi ? hi : v);
+
+ /// The target in the parent part's creation-pose frame: where it sits if the parent were still at its creation pose.
+ internal static IkVec ToCreationFrame(in Quat parentRotation, in Quat parentRestInverse, IkVec parentCentre,
+ float px, float py, float pz, float tx, float ty, float tz)
+ {
+ var rel = parentRotation * parentRestInverse;
+ return parentCentre + new IkVec(tx - px, ty - py, tz - pz).Rotated(rel.Conjugate());
+ }
+ }
+
+ ///
+ /// A two-bone arm: shoulder (spherical), elbow (revolute) and wrist anchors of one side, found by label in the plan. Solves a world
+ /// point for the wrist anchor: the elbow flex is fixed by the distance, and the swivel about the shoulder-to-wrist line is the one that
+ /// leaves the shoulder target no twist, the shoulder's twist muscle being weak. When that swivel puts the swing past the cone, the swivel
+ /// is the one nearest it whose swing is inside the cone and whose twist is inside the twist limits (the joint-limit-feasible swivel range of
+ /// Tolani, Goswami and Badler 2000). When no swivel is feasible, the swivel is the one whose limit violation (swing past the cone plus
+ /// twist past its limits) is least, and its swing and twist clamp to the limits; as a goal leaves the feasible set that swivel is the
+ /// last feasible one, so the targets move continuously across the edge.
+ ///
+ /// That rule alone is the stateless rule, and mirrored options tie under it: where two swivels are equally good it must jump from one to
+ /// the other somewhere on the tie set. So a chain is one arm's solver across ticks and carries the arm's previous swivel (ruling
+ /// lodur:ruling:ik-swivel-temporal-coherence): each solve stays in the basin of the previous swivel and moves to the stateless choice only
+ /// when that is better by , never turning the swivel faster than . Better means less limit
+ /// violation, or, both swivels being feasible, less twist. The first solve after construction or is the stateless rule.
+ /// Identical goals can therefore give different targets depending on history; the same history gives the same targets.
+ ///
+ ///
+ /// The solved targets can still jump where the solution is discontinuous in the goal (the clamp's swing-twist split at a half-turn swing,
+ /// a basin change, a goal that leaps). So the targets the chain returns move toward the solved ones no faster than
+ /// : per solve the shoulder target turns, and the elbow target flexes, by at most MaxAngularRate times the
+ /// tick (ruling lodur:ruling:ik-output-slew-limit). While the goal holds still they converge on the solution. A goal that leaps is
+ /// followed at that rate, not at once. The first solve after construction or returns the solution itself.
+ ///
+ ///
+ public sealed class ArmChain
+ {
+ private readonly Quat _parentRestInverse, _frame, _frameInverse;
+ private readonly IkVec _parentCentre, _shoulderAnchor, _upper, _lower, _elbowAxis, _twistAxis;
+ private readonly float _flexSign, _flexLo, _flexHi, _cone, _twistLo, _twistHi, _coneSin2, _coneSinHalf, _coneCosHalf;
+ private readonly float _maxSwivelStep, _maxStep, _cosHalfMaxStep, _sinHalfMaxStep;
+
+ // The previous solve's shoulder target before clamping, whose swivel the next solve starts from; none after construction or Reset.
+ // The targets the previous solve returned, which the next one slews from, share the flag.
+ private Quat _previous, _shoulderOut;
+ private float _flexOut;
+ private bool _hasPrevious, _hasOutput;
+
+ private enum Hand : byte { Idle, Driving, Releasing }
+
+ // The hand-off and the hand path. The path is in the arm parent's creation frame; its time counts the ticks driven since it started.
+ private Hand _hand;
+ private double _weight;
+ private bool _newPath, _pathBlocked, _hasSegGoal;
+ private IkVec _pathStart, _pathVia, _segGoal, _aim;
+ private int _pathTicks;
+ private readonly float _dt;
+ private readonly IkVec[] _trunkCentre, _trunkHalf;
+ private readonly float _trunkFront, _forearmRadius;
+
+ ///
+ /// Radians of limit violation, or of twist when both swivels are feasible, by which the stateless choice must beat the held swivel's
+ /// basin before the arm leaves it. Placeholder: no measured pose cost sets it. It must sit far above the solver's resolution (about
+ /// 1e-5 rad), so noise cannot flip a tie, and well below the 1.0-1.57 rad between the mirrored basins Soul measured, so a clearly
+ /// better basin is taken.
+ ///
+ public const double BasinMargin = 0.05;
+
+ ///
+ /// The fastest the swivel turns, in radians per second. Placeholder: of the order of a deliberate, unhurried shoulder rotation, not a
+ /// measured one.
+ ///
+ public const float SwivelRate = 3f;
+
+ ///
+ /// The fastest the returned targets move, in radians per second: the shoulder target's turn and the elbow target's flex per solve are at
+ /// most this times the tick. Placeholder: near human peak arm angular speed, not measured for this body.
+ ///
+ public const float MaxAngularRate = 10f;
+
+ ///
+ /// Metres the via point sits ahead of the trunk's front. Placeholder: the probe (goal-ai-map fact 25) measured 0.15 to 0.3 m clearing the
+ /// seated far arm; no pose cost sets it.
+ ///
+ public const float ViaClearance = 0.2f;
+
+ /// Seconds of each of the path's two segments, wrist to via point and via point to goal. Placeholder: a deliberate reach, not measured (fact 25).
+ public const float PathSegmentSeconds = 0.3f;
+
+ // Swivel search: steps of Pi / SwivelSteps outward from the zero-twist swivel, then bisection to the feasible boundary. When none is
+ // feasible, the least-violating of LeastSteps steps round the circle, refined by golden section.
+ private const int SwivelSteps = 90;
+ private const int SwivelBisections = 16;
+ private const int LeastSteps = 36;
+ private const int LeastRefinements = 28;
+
+ // Among swivels that violate the limits equally (the arm along the twist axis, where the swivel only twists) the least twist wins.
+ // Small against the violation's slope of about one, so it barely moves the least-violating swivel.
+ private const double TwistPreference = 1e-5;
+
+ private ArmChain(BodyPlan plan, Side side, double tickSeconds)
+ {
+ if (!(double.IsFinite(tickSeconds) && tickSeconds > 0.0))
+ {
+ throw new ArgumentException($"the tick length {tickSeconds} s is not finite and positive.");
+ }
+
+ _dt = (float)tickSeconds;
+ _maxSwivelStep = (float)(SwivelRate * tickSeconds);
+ _maxStep = (float)(MaxAngularRate * tickSeconds);
+ _cosHalfMaxStep = MathF.Cos(0.5f * _maxStep);
+ _sinHalfMaxStep = MathF.Sin(0.5f * _maxStep);
+ var si = plan.JointIndex("Shoulder", side);
+ var ei = plan.JointIndex("Elbow", side);
+ var wi = plan.JointIndex("Wrist", side);
+ var s = plan.Joints[si];
+ var e = plan.Joints[ei];
+ var w = plan.Joints[wi];
+ if (s.Kind != JointKind.Spherical || e.Kind != JointKind.Revolute || w.Parent != e.Child || e.Parent != s.Child)
+ {
+ throw new ArgumentException($"the {side} arm is not a spherical shoulder, a revolute elbow and a wrist on the forearm.");
+ }
+
+ ShoulderJoint = si;
+ ElbowJoint = ei;
+ ParentPart = s.Parent;
+ var shoulder = new IkVec(s.Anchor);
+ var elbow = new IkVec(e.Anchor);
+ var wrist = new IkVec(w.Anchor);
+ _upper = elbow - shoulder;
+ _lower = wrist - elbow;
+ L1 = _upper.Length;
+ L2 = _lower.Length;
+ _elbowAxis = new IkVec(e.Axis).Unit();
+ _twistAxis = new IkVec(s.Axis).Unit();
+ // The closed form needs the creation pose straight and the hinge across both bones.
+ if (L1 < 1e-4f || L2 < 1e-4f || _upper.Cross(_lower).Length > 1e-3f * L1 * L2 || MathF.Abs(_elbowAxis.Dot(_lower)) > 1e-3f * L2)
+ {
+ throw new ArgumentException($"the {side} arm is not straight at its creation pose with the elbow hinge across it.");
+ }
+
+ // The hinge bends to one side of zero; a range straddling zero would make the flex ambiguous.
+ if (e.Lower < 0f && e.Upper <= 0f) _flexSign = -1f;
+ else if (e.Lower >= 0f && e.Upper > 0f) _flexSign = 1f;
+ else throw new ArgumentException($"the {side} elbow range [{e.Lower}, {e.Upper}] does not lie on one side of zero.");
+ _flexLo = e.Lower;
+ _flexHi = e.Upper;
+ _cone = s.Cone;
+ _twistLo = s.Lower;
+ _twistHi = s.Upper;
+ _coneSinHalf = MathF.Sin(0.5f * _cone);
+ _coneCosHalf = MathF.Cos(0.5f * _cone);
+ _coneSin2 = _coneSinHalf * _coneSinHalf;
+ _shoulderAnchor = shoulder;
+ _frame = Ik.JointFrame(s);
+ _frameInverse = _frame.Conjugate();
+ var parent = plan.Parts[ParentPart];
+ _parentCentre = new IkVec(parent.Position);
+ _parentRestInverse = parent.Rotation.Conjugate();
+ ShoulderAnchor = s.Anchor;
+ ElbowAnchor = e.Anchor;
+ WristAnchor = w.Anchor;
+ ForearmPart = e.Child;
+
+ // The trunk: the shoulder's parent part and its ancestors, each as its creation-pose axis-aligned bound.
+ var trunk = 0;
+ for (var part = s.Parent; part >= 0; part = plan.ParentOf(part)) trunk++;
+ _trunkCentre = new IkVec[trunk];
+ _trunkHalf = new IkVec[trunk];
+ _trunkFront = float.NegativeInfinity;
+ trunk = 0;
+ for (var part = s.Parent; part >= 0; part = plan.ParentOf(part))
+ {
+ var def = plan.Parts[part];
+ _trunkCentre[trunk] = new IkVec(def.Position);
+ _trunkHalf[trunk] = Half(def);
+ _trunkFront = MathF.Max(_trunkFront, def.Position.Z + _trunkHalf[trunk].Z);
+ trunk++;
+ }
+
+ var fore = plan.Parts[e.Child];
+ _forearmRadius = fore.Shape == PartShape.Box ? MathF.Min(fore.Size.X, MathF.Min(fore.Size.Y, fore.Size.Z)) : fore.Size.X;
+ _newPath = true;
+ }
+
+ // The half extents of a part's creation-pose axis-aligned bound.
+ private static IkVec Half(in PartDef part)
+ {
+ var q = part.Rotation;
+ var (sx, sy, sz) = part.Size;
+ q.Rotate(1f, 0f, 0f, out var xx, out var xy, out var xz);
+ q.Rotate(0f, 1f, 0f, out var yx, out var yy, out var yz);
+ q.Rotate(0f, 0f, 1f, out var zx, out var zy, out var zz);
+ switch (part.Shape)
+ {
+ case PartShape.Box:
+ return new IkVec(MathF.Abs(xx) * sx + MathF.Abs(yx) * sy + MathF.Abs(zx) * sz,
+ MathF.Abs(xy) * sx + MathF.Abs(yy) * sy + MathF.Abs(zy) * sz,
+ MathF.Abs(xz) * sx + MathF.Abs(yz) * sy + MathF.Abs(zz) * sz);
+ case PartShape.Capsule:
+ // Radius sx, half length sy along the part's y.
+ return new IkVec(MathF.Abs(yx) * sy + sx, MathF.Abs(yy) * sy + sx, MathF.Abs(yz) * sy + sx);
+ default:
+ return new IkVec(sx, sx, sx);
+ }
+ }
+
+ /// Finds the shoulder, elbow and wrist of by label; if the plan has no such arm.
+ /// One chain is one arm's solver across ticks of , which sets how far the swivel turns per solve.
+ public static ArmChain Of(BodyPlan plan, Side side, double tickSeconds) => new ArmChain(plan, side, tickSeconds);
+
+ ///
+ /// Forgets the previous swivel, the returned targets, the hand path and the hand-off: the next uses the stateless rule
+ /// and returns its solution unslewed, and the arm is idle, so passes the base through and engages
+ /// from it.
+ ///
+ public void Reset()
+ {
+ _hasPrevious = false;
+ _hasOutput = false;
+ _hand = Hand.Idle;
+ _newPath = true;
+ }
+
+ /// The next starts a new hand path from the measured wrist, keeping the swivel and the returned targets.
+ public void Restart() => _newPath = true;
+
+ /// The last solve's shoulder target before clamping, whose swivel the next solve holds (identity before any solve); tests read it.
+ internal Quat Held => _hasPrevious ? _previous : Quat.Identity;
+
+ /// The plan's joint ordinals, where the caller writes the two targets.
+ public int ShoulderJoint { get; }
+ public int ElbowJoint { get; }
+
+ /// The part the shoulder hangs from; Solve takes its world rotation and position.
+ public int ParentPart { get; }
+
+ /// The forearm part, which carries the wrist anchor; Drive takes the measured wrist from its pose.
+ public int ForearmPart { get; }
+
+ /// Creation-pose anchors. The effector is .
+ public (float X, float Y, float Z) ShoulderAnchor { get; }
+ public (float X, float Y, float Z) ElbowAnchor { get; }
+ public (float X, float Y, float Z) WristAnchor { get; }
+
+ /// Shoulder to elbow anchor, and elbow to wrist anchor, in metres.
+ public float L1 { get; }
+ public float L2 { get; }
+
+ ///
+ /// Targets that put the wrist anchor on the world point (tx, ty, tz), given the parent part's world rotation and position.
+ /// Returns false when the point was out of reach or a limit clamped; the targets are then the limits-clamped pose of the swivel that
+ /// violates the limits least, continuous with the reached targets at the edge of the feasible set, or, while the swivel turns between
+ /// basins, the clamped pose of the swivel on its way. The returned targets are slewed toward that solution at
+ /// ; the return value describes the solution. One call is one tick of the arm's history.
+ ///
+ public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat shoulder, out Quat elbow) =>
+ SolveCreation(Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz), out shoulder, out elbow);
+
+ // Solve for a wrist point already in the parent's creation frame.
+ private bool SolveCreation(IkVec target, out Quat shoulder, out Quat elbow)
+ {
+ var reached = true;
+ var v = target - _shoulderAnchor;
+ var d = v.Length;
+ var dMin = MathF.Abs(L1 - L2) + 1e-3f;
+ var dMax = L1 + L2 - 1e-3f;
+ var dc = Ik.Clamp(d, dMin, dMax);
+ if (dc != d) reached = false;
+ var vHat = d > 1e-6f ? v * (1f / d) : _upper.Unit();
+
+ var cosFlex = Ik.Clamp((dc * dc - L1 * L1 - L2 * L2) / (2f * L1 * L2), -1f, 1f);
+ var flexWant = _flexSign * MathF.Acos(cosFlex);
+ var flex = Ik.Clamp(flexWant, _flexLo, _flexHi);
+ if (flex != flexWant) reached = false;
+
+ // The hand offset at this flex, in the upper arm's creation frame, and the swing taking it onto the target direction.
+ var p = _upper + _lower.Rotated(Ik.About(_elbowAxis, flex));
+ var arc = Ik.Arc(p.Unit(), vHat);
+ var q = new IkVec(arc.X, arc.Y, arc.Z);
+ var num = -q.Dot(_twistAxis);
+ var den = arc.W * vHat.Dot(_twistAxis) + vHat.Cross(q).Dot(_twistAxis);
+ var zeroTwist = 2f * MathF.Atan2(num, den);
+ // The target is linear in the half-angle of the swivel: Local(phi) = cos(phi / 2) A + sin(phi / 2) B.
+ var a = _frameInverse * arc * _frame;
+ var b = _frameInverse * (new Quat(vHat.X, vHat.Y, vHat.Z, 0f) * arc) * _frame;
+ var phi = Stateless(a, b, zeroTwist, out var clamp);
+ if (_hasPrevious)
+ {
+ // The previous target's swivel on this goal's swivel circle: a and b are orthonormal, so the nearest point is a projection.
+ var held = 2f * MathF.Atan2(Dot(_previous, b), Dot(_previous, a));
+ var basin = BasinOptimum(a, b, zeroTwist, held);
+ var want = ClearlyBetter(a, b, phi, basin) ? phi : basin;
+ phi = held + Ik.Clamp(Wrap(want - held), -_maxSwivelStep, _maxSwivelStep);
+ clamp = !Feasible(Local(a, b, phi));
+ }
+
+ var local = Local(a, b, phi);
+ var slew = _hasOutput;
+ _previous = local;
+ _hasPrevious = true;
+ _hasOutput = true;
+ if (clamp)
+ {
+ // Infeasible: swing and twist clamped to the limits.
+ local = ClampToLimits(local);
+ reached = false;
+ }
+
+ if (slew)
+ {
+ _shoulderOut = Toward(_shoulderOut, local);
+ _flexOut += Ik.Clamp(flex - _flexOut, -_maxStep, _maxStep);
+ }
+ else
+ {
+ (_shoulderOut, _flexOut) = (local, flex);
+ }
+
+ shoulder = _shoulderOut;
+ elbow = Quat.FromAxisAngle(0f, 0f, 1f, _flexOut);
+ return reached;
+ }
+
+ ///
+ /// One tick the arm's layer drives: the targets to write for the wrist goal (tx, ty, tz) given the arm parent's world pose, the wrist
+ /// measured now (mx, my, mz) and the base shoulder and elbow targets, blended toward the solution by in [0, 1].
+ /// An arm that was idle starts slewing from the base targets; one that was releasing, from where its output was. The tick that engages the
+ /// arm, and every tick after , starts a hand path from the measured wrist. Returns whether the goal was reached,
+ /// as does for the point it was given.
+ ///
+ public bool Drive(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, float mx, float my, float mz,
+ in Quat baseShoulder, in Quat baseElbow, double weight, out Quat shoulder, out Quat elbow)
+ {
+ if (_hand != Hand.Driving)
+ {
+ if (_hand == Hand.Idle)
+ {
+ _shoulderOut = baseShoulder;
+ _flexOut = Flex(baseElbow);
+ _hasOutput = true;
+ }
+
+ _hand = Hand.Driving;
+ _newPath = true;
+ }
+
+ _weight = weight;
+ var goal = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz);
+ if (_newPath)
+ {
+ _newPath = false;
+ var wrist = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, mx, my, mz);
+ _pathStart = wrist;
+ _pathBlocked = Blocked(wrist, goal);
+ _pathVia = new IkVec(wrist.X, 0.5f * (wrist.Y + goal.Y), _trunkFront + ViaClearance);
+ _pathTicks = 0;
+ _hasSegGoal = false;
+ }
+
+ var aim = goal;
+ if (_pathBlocked && _pathTicks * _dt < 2f * PathSegmentSeconds)
+ {
+ var t = _pathTicks * _dt;
+ if (!_hasSegGoal && t >= PathSegmentSeconds)
+ {
+ _segGoal = goal;
+ _hasSegGoal = true;
+ }
+
+ aim = PathPoint(_pathStart, _pathVia, _segGoal, goal, t);
+ _pathTicks++;
+ }
+
+ _aim = aim;
+ var reached = SolveCreation(aim, out var s, out var e);
+ shoulder = Blend(baseShoulder, s, weight);
+ elbow = Blend(baseElbow, e, weight);
+ return reached;
+ }
+
+ ///
+ /// One tick the arm's layer does not drive: while the arm still holds a driven output, it slews to the base targets at
+ /// , written blended toward the base by the weight it was last driven at; when it has arrived, and for an arm
+ /// that never was driven, the written targets are the base ones, untouched.
+ ///
+ public void Release(in Quat baseShoulder, in Quat baseElbow, out Quat shoulder, out Quat elbow)
+ {
+ if (_hand == Hand.Idle)
+ {
+ shoulder = baseShoulder;
+ elbow = baseElbow;
+ return;
+ }
+
+ _hand = Hand.Releasing;
+ _shoulderOut = Toward(_shoulderOut, baseShoulder);
+ var flex = Flex(baseElbow);
+ var gap = flex - _flexOut;
+ _flexOut = MathF.Abs(gap) <= _maxStep ? flex : _flexOut + (gap > 0f ? _maxStep : -_maxStep);
+ if (_flexOut == flex && _shoulderOut.X == baseShoulder.X && _shoulderOut.Y == baseShoulder.Y && _shoulderOut.Z == baseShoulder.Z
+ && _shoulderOut.W == baseShoulder.W)
+ {
+ _hand = Hand.Idle;
+ shoulder = baseShoulder;
+ elbow = baseElbow;
+ return;
+ }
+
+ shoulder = Blend(baseShoulder, _shoulderOut, _weight);
+ elbow = Blend(baseElbow, Quat.FromAxisAngle(0f, 0f, 1f, _flexOut), _weight);
+ }
+
+ // The solution itself at weight 1, a blend toward it from the base below that.
+ private static Quat Blend(in Quat baseTarget, in Quat solution, double weight) =>
+ weight >= 1.0 ? solution : Quat.Nlerp(baseTarget, solution, (float)weight);
+
+ // The flex of an elbow target, a rotation about the hinge's frame z, on the shortest turn.
+ private static float Flex(in Quat elbow) => 2f * MathF.Atan2(elbow.W < 0f ? -elbow.Z : elbow.Z, MathF.Abs(elbow.W));
+
+ // Minimum jerk (Flash and Hogan 1985): 0 to 1 with zero velocity and acceleration at both ends.
+ internal static float MinimumJerk(float t)
+ {
+ t = Ik.Clamp(t, 0f, 1f);
+ return t * t * t * (10f - 15f * t + 6f * t * t);
+ }
+
+ ///
+ /// The hand path in the arm parent's creation frame at seconds: the start to the via point over
+ /// , then the goal plus the via point's offset from the goal as it was when the segment began, shrinking
+ /// to nothing, so a goal that moves is met at the end. is the goal at that moment.
+ ///
+ internal static (float X, float Y, float Z) PathPoint((float X, float Y, float Z) start, (float X, float Y, float Z) via,
+ (float X, float Y, float Z) segmentGoal, (float X, float Y, float Z) goal, float t)
+ {
+ var p = PathPoint(new IkVec(start), new IkVec(via), new IkVec(segmentGoal), new IkVec(goal), t);
+ return (p.X, p.Y, p.Z);
+ }
+
+ private static IkVec PathPoint(IkVec start, IkVec via, IkVec segmentGoal, IkVec goal, float t)
+ {
+ if (t < PathSegmentSeconds) return start + (via - start) * MinimumJerk(t / PathSegmentSeconds);
+ return goal + (via - segmentGoal) * (1f - MinimumJerk((t - PathSegmentSeconds) / PathSegmentSeconds));
+ }
+
+ /// Whether the last path start found the trunk in the way (tests read it).
+ internal bool PathBlocked => _pathBlocked;
+
+ /// The creation-frame point the last solved for: the path point, or the goal (tests read it).
+ internal (float X, float Y, float Z) Aim => (_aim.X, _aim.Y, _aim.Z);
+
+ // Whether the straight segment from the wrist to the goal passes within the forearm radius of a trunk bound.
+ private bool Blocked(IkVec wrist, IkVec goal)
+ {
+ for (var b = 0; b < _trunkCentre.Length; b++)
+ {
+ // The distance to a box is convex along a line, so a ternary search finds its least over the segment.
+ float lo = 0f, hi = 1f;
+ for (var i = 0; i < 40; i++)
+ {
+ var m1 = lo + (hi - lo) / 3f;
+ var m2 = hi - (hi - lo) / 3f;
+ if (BoxDistance(wrist + (goal - wrist) * m1, b) < BoxDistance(wrist + (goal - wrist) * m2, b)) hi = m2;
+ else lo = m1;
+ }
+
+ if (BoxDistance(wrist + (goal - wrist) * (0.5f * (lo + hi)), b) < _forearmRadius) return true;
+ }
+
+ return false;
+ }
+
+ private float BoxDistance(IkVec p, int box)
+ {
+ var d = p - _trunkCentre[box];
+ var h = _trunkHalf[box];
+ var x = MathF.Max(0f, MathF.Abs(d.X) - h.X);
+ var y = MathF.Max(0f, MathF.Abs(d.Y) - h.Y);
+ var z = MathF.Max(0f, MathF.Abs(d.Z) - h.Z);
+ return MathF.Sqrt(x * x + y * y + z * z);
+ }
+
+ // The rotation from current toward target, turned by at most the per-solve step: the target itself when it is within the step.
+ private Quat Toward(in Quat current, in Quat target)
+ {
+ var d = current.Conjugate() * target;
+ var s = d.W < 0f ? -1f : 1f;
+ var (x, y, z, w) = (s * d.X, s * d.Y, s * d.Z, s * d.W);
+ var sinHalf = MathF.Sqrt(x * x + y * y + z * z);
+ if (2f * MathF.Atan2(sinHalf, w) <= _maxStep) return target;
+ var k = _sinHalfMaxStep / sinHalf;
+ // Renormalised, so a goal outrunning the rate for many ticks does not drift the target off the unit sphere.
+ var r = current * new Quat(x * k, y * k, z * k, _cosHalfMaxStep);
+ var n = 1f / MathF.Sqrt(r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W);
+ return new Quat(r.X * n, r.Y * n, r.Z * n, r.W * n);
+ }
+
+ // The stateless rule: zero twist inside the cone, else the nearest feasible swivel, else the least-violating one (clamp set).
+ private float Stateless(in Quat a, in Quat b, float zeroTwist, out bool clamp)
+ {
+ clamp = false;
+ if (InsideCone(Local(a, b, zeroTwist))) return zeroTwist;
+ if (SomeSwivelInsideCone(a, b) && NearestFeasible(a, b, zeroTwist, out var feasible)) return feasible;
+ clamp = true;
+ return LeastViolating(a, b, zeroTwist);
+ }
+
+ // The best swivel of the held swivel's basin. When some swivel is feasible: from the held swivel, or the feasible one nearest it,
+ // toward zero twist while feasible. When none is: the least violation downhill from the held swivel.
+ private float BasinOptimum(in Quat a, in Quat b, float zeroTwist, float held)
+ {
+ if (SomeSwivelInsideCone(a, b))
+ {
+ if (Feasible(Local(a, b, held))) return TowardZeroTwist(a, b, zeroTwist, held);
+ if (NearestFeasible(a, b, held, out var start)) return TowardZeroTwist(a, b, zeroTwist, start);
+ }
+
+ return LocalLeastViolating(a, b, held);
+ }
+
+ // From the feasible swivel start toward the zero-twist swivel, the way twist shrinks: the zero-twist swivel if every step there is
+ // feasible, else the feasible boundary on the way.
+ private float TowardZeroTwist(in Quat a, in Quat b, float zeroTwist, float start)
+ {
+ var d = Wrap(start - zeroTwist);
+ if (d == 0f) return zeroTwist;
+ var dir = d > 0f ? -1f : 1f;
+ var dist = MathF.Abs(d);
+ const float step = MathF.PI / SwivelSteps;
+ var inside = start;
+ for (var k = 1; k <= SwivelSteps; k++)
+ {
+ var t = MathF.Min(k * step, dist);
+ var phi = start + dir * t;
+ if (!Feasible(Local(a, b, phi))) return Boundary(a, b, inside, phi);
+ if (t >= dist) return zeroTwist;
+ inside = phi;
+ }
+
+ return inside;
+ }
+
+ // Whether swivel x beats swivel y by the margin: less violation, or, both feasible, less twist.
+ private bool ClearlyBetter(in Quat a, in Quat b, float x, float y)
+ {
+ if (Violation(a, b, x) < Violation(a, b, y) - BasinMargin) return true;
+ var lx = Local(a, b, x);
+ var ly = Local(a, b, y);
+ return Feasible(lx) && Feasible(ly) && MathF.Abs(Twist(lx)) < MathF.Abs(Twist(ly)) - (float)BasinMargin;
+ }
+
+ private static float Twist(in Quat local) => 2f * MathF.Atan2(local.Z, local.W);
+
+ private static float Dot(in Quat p, in Quat q) => p.X * q.X + p.Y * q.Y + p.Z * q.Z + p.W * q.W;
+
+ // An angle difference into [-pi, pi]: the swivel's period is a full turn.
+ private static float Wrap(float x) => x - 2f * MathF.PI * MathF.Round(x / (2f * MathF.PI));
+
+ // The shoulder target in the joint frame for the swivel phi, with w >= 0.
+ private static Quat Local(in Quat a, in Quat b, float phi)
+ {
+ var c = MathF.Cos(0.5f * phi);
+ var s = MathF.Sin(0.5f * phi);
+ var local = new Quat(c * a.X + s * b.X, c * a.Y + s * b.Y, c * a.Z + s * b.Z, c * a.W + s * b.W);
+ return local.W < 0f ? new Quat(-local.X, -local.Y, -local.Z, -local.W) : local;
+ }
+
+ // Swing is the angle between the frame z and its image: inside the cone when sin^2(swing / 2) = x^2 + y^2 <= sin^2(cone / 2).
+ private bool InsideCone(in Quat local) => local.X * local.X + local.Y * local.Y <= _coneSin2;
+
+ // x^2 + y^2 is a quadratic form in (cos(phi / 2), sin(phi / 2)); its least value over the swivel is the form's smaller eigenvalue.
+ private bool SomeSwivelInsideCone(in Quat a, in Quat b)
+ {
+ var maa = a.X * a.X + a.Y * a.Y;
+ var mbb = b.X * b.X + b.Y * b.Y;
+ var mab = a.X * b.X + a.Y * b.Y;
+ var half = 0.5f * (maa - mbb);
+ return 0.5f * (maa + mbb) - MathF.Sqrt(half * half + mab * mab) <= _coneSin2;
+ }
+
+ private bool Feasible(in Quat local)
+ {
+ if (!InsideCone(local)) return false;
+ var twist = Twist(local);
+ return twist >= _twistLo && twist <= _twistHi;
+ }
+
+ // Bisection between a feasible and an infeasible swivel to the boundary; the feasible end.
+ private float Boundary(in Quat a, in Quat b, float inside, float outside)
+ {
+ for (var i = 0; i < SwivelBisections; i++)
+ {
+ var mid = 0.5f * (inside + outside);
+ if (Feasible(Local(a, b, mid))) inside = mid;
+ else outside = mid;
+ }
+
+ return inside;
+ }
+
+ // The feasible swivel nearest phi0: step outward both ways, and at the first step that lands inside, bisect back to the boundary;
+ // of the two sides, the one with the smaller twist. False when no swivel is feasible.
+ private bool NearestFeasible(in Quat a, in Quat b, float phi0, out float swivel)
+ {
+ swivel = 0f;
+ const float step = MathF.PI / SwivelSteps;
+ for (var k = 1; k <= SwivelSteps; k++)
+ {
+ var found = false;
+ var bestTwist = float.MaxValue;
+ for (var sign = -1; sign <= 1; sign += 2)
+ {
+ var phi = phi0 + sign * k * step;
+ if (!Feasible(Local(a, b, phi))) continue;
+ var inside = Boundary(a, b, phi, phi0 + sign * (k - 1) * step);
+ var twist = MathF.Abs(Twist(Local(a, b, inside)));
+ if (twist < bestTwist)
+ {
+ bestTwist = twist;
+ swivel = inside;
+ found = true;
+ }
+ }
+
+ if (found) return true;
+ }
+
+ return false;
+ }
+
+ // Radians past the limits at the swivel phi, swing past the cone plus twist past its range, with the small twist preference. In
+ // double: the least point of a smooth minimum is found only to the square root of the arithmetic's precision.
+ private double Violation(in Quat a, in Quat b, double phi)
+ {
+ var c = Math.Cos(0.5 * phi);
+ var s = Math.Sin(0.5 * phi);
+ var x = c * a.X + s * b.X;
+ var y = c * a.Y + s * b.Y;
+ var z = c * a.Z + s * b.Z;
+ var w = c * a.W + s * b.W;
+ if (w < 0.0)
+ {
+ z = -z;
+ w = -w;
+ }
+
+ var swing = 2.0 * Math.Atan2(Math.Sqrt(x * x + y * y), Math.Sqrt(z * z + w * w));
+ var twist = 2.0 * Math.Atan2(z, w);
+ var over = twist < _twistLo ? _twistLo - twist : (twist > _twistHi ? twist - _twistHi : 0.0);
+ return Math.Max(0.0, swing - _cone) + over + TwistPreference * Math.Abs(twist);
+ }
+
+ // The least-violating swivel: the least of LeastSteps steps round the circle from phi0, refined by golden section within a step
+ // either side.
+ private float LeastViolating(in Quat a, in Quat b, float phi0)
+ {
+ const double step = 2.0 * Math.PI / LeastSteps;
+ var best = (double)phi0;
+ var least = Violation(a, b, best);
+ for (var k = 1; k < LeastSteps; k++)
+ {
+ var phi = phi0 + k * step;
+ var v = Violation(a, b, phi);
+ if (v < least)
+ {
+ least = v;
+ best = phi;
+ }
+ }
+
+ return Golden(a, b, best - step, best + step);
+ }
+
+ // The least-violating swivel of the held swivel's basin: downhill in steps of a LeastSteps-th of the circle while the violation
+ // falls, then golden section within a step either side.
+ private float LocalLeastViolating(in Quat a, in Quat b, float held)
+ {
+ const double step = 2.0 * Math.PI / LeastSteps;
+ var best = (double)held;
+ var least = Violation(a, b, best);
+ var up = Violation(a, b, best + step);
+ var down = Violation(a, b, best - step);
+ if (up < least || down < least)
+ {
+ var dir = up < down ? 1.0 : -1.0;
+ for (var k = 0; k < LeastSteps; k++)
+ {
+ var next = best + dir * step;
+ var v = Violation(a, b, next);
+ if (v >= least) break;
+ best = next;
+ least = v;
+ }
+ }
+
+ return Golden(a, b, best - step, best + step);
+ }
+
+ // Golden-section search for the least violation on [lo, hi].
+ private float Golden(in Quat a, in Quat b, double lo, double hi)
+ {
+ const double g = 0.6180339887498949;
+ var p = hi - g * (hi - lo);
+ var q = lo + g * (hi - lo);
+ var fp = Violation(a, b, p);
+ var fq = Violation(a, b, q);
+ for (var i = 0; i < LeastRefinements; i++)
+ {
+ if (fp <= fq)
+ {
+ hi = q;
+ q = p;
+ fq = fp;
+ p = hi - g * (hi - lo);
+ fp = Violation(a, b, p);
+ }
+ else
+ {
+ lo = p;
+ p = q;
+ fp = fq;
+ q = lo + g * (hi - lo);
+ fq = Violation(a, b, q);
+ }
+ }
+
+ return (float)(fp <= fq ? p : q);
+ }
+
+ // Twist clamped to its range and swing to the cone, the swing direction kept. The target is swing * twist, the twist about the frame
+ // z and the swing about an axis in its xy plane.
+ private Quat ClampToLimits(in Quat local)
+ {
+ // At a half-turn swing the twist is undefined: read it as none.
+ var tl = MathF.Sqrt(local.Z * local.Z + local.W * local.W);
+ var tz = tl > 1e-6f ? local.Z / tl : 0f;
+ var tw = tl > 1e-6f ? local.W / tl : 1f;
+ var sx = tw * local.X - tz * local.Y;
+ var sy = tz * local.X + tw * local.Y;
+ var sw = tl;
+ var s2 = sx * sx + sy * sy;
+ if (s2 > _coneSin2)
+ {
+ var k = _coneSinHalf / MathF.Sqrt(s2);
+ sx *= k;
+ sy *= k;
+ sw = _coneCosHalf;
+ }
+
+ var half = 0.5f * Ik.Clamp(2f * MathF.Atan2(tz, tw), _twistLo, _twistHi);
+ tz = MathF.Sin(half);
+ tw = MathF.Cos(half);
+ return new Quat(tw * sx + tz * sy, tw * sy - tz * sx, sw * tz, sw * tw);
+ }
+ }
+
+ ///
+ /// A head that looks: one spherical joint (the neck by default) turned so the child part's creation-pose forward, +z, points at a world
+ /// point. Yaw about the joint axis is the joint's twist and is clamped to [Lower, Upper]; pitch about the creation-pose left axis is swing and
+ /// is clamped to Cone.
+ ///
+ public sealed class LookChain
+ {
+ private readonly Quat _parentRestInverse, _frame, _frameInverse;
+ private readonly IkVec _parentCentre, _childCentre, _up, _forward, _left;
+ private readonly float _lower, _upper, _cone;
+
+ private LookChain(BodyPlan plan, string joint)
+ {
+ var ji = plan.JointIndex(joint);
+ var j = plan.Joints[ji];
+ if (j.Kind != JointKind.Spherical) throw new ArgumentException($"joint '{joint}' is not spherical.");
+ Joint = ji;
+ ParentPart = j.Parent;
+ ChildPart = j.Child;
+ _up = new IkVec(j.Axis).Unit();
+ var z = new IkVec(0f, 0f, 1f);
+ var forward = z - _up * z.Dot(_up);
+ if (forward.Length < 1e-3f) throw new ArgumentException($"joint '{joint}' has an axis along forward, so it has no yaw.");
+ _forward = forward.Unit();
+ _left = _up.Cross(_forward);
+ _lower = j.Lower;
+ _upper = j.Upper;
+ _cone = j.Cone;
+ _frame = Ik.JointFrame(j);
+ _frameInverse = _frame.Conjugate();
+ var parent = plan.Parts[j.Parent];
+ _parentCentre = new IkVec(parent.Position);
+ _parentRestInverse = parent.Rotation.Conjugate();
+ _childCentre = new IkVec(plan.Parts[j.Child].Position);
+ }
+
+ public static LookChain Of(BodyPlan plan, string joint = "Neck") => new LookChain(plan, joint);
+
+ /// The plan's joint ordinal, where the caller writes the target.
+ public int Joint { get; }
+ public int ParentPart { get; }
+ public int ChildPart { get; }
+
+ ///
+ /// The target that points the child part at the world point: the direction runs from the child's creation-pose centre to the point,
+ /// in the parent's frame. Returns false when yaw or pitch was clamped.
+ ///
+ public bool Solve(in Quat parentRotation, float px, float py, float pz, float tx, float ty, float tz, out Quat neck)
+ {
+ var reached = true;
+ var dir = Ik.ToCreationFrame(parentRotation, _parentRestInverse, _parentCentre, px, py, pz, tx, ty, tz) - _childCentre;
+ var len = dir.Length;
+ var d = len > 1e-6f ? dir * (1f / len) : _forward;
+ var yawWant = MathF.Atan2(d.Dot(_left), d.Dot(_forward));
+ var pitchWant = -MathF.Asin(Ik.Clamp(d.Dot(_up), -1f, 1f));
+ var yaw = Ik.Clamp(yawWant, _lower, _upper);
+ var pitch = Ik.Clamp(pitchWant, -_cone, _cone);
+ if (yaw != yawWant || pitch != pitchWant) reached = false;
+ neck = _frameInverse * (Ik.About(_up, yaw) * Ik.About(_left, pitch)) * _frame;
+ return reached;
+ }
+ }
+}
diff --git a/src/Lodur.Core/IsExternalInit.cs b/src/Lodur.Core/IsExternalInit.cs
new file mode 100644
index 0000000..a925713
--- /dev/null
+++ b/src/Lodur.Core/IsExternalInit.cs
@@ -0,0 +1,7 @@
+// Lets C# 9 records use init accessors on netstandard2.1, which does not ship this marker type.
+namespace System.Runtime.CompilerServices
+{
+ internal static class IsExternalInit
+ {
+ }
+}
diff --git a/src/Lodur.Core/Lodur.Core.csproj b/src/Lodur.Core/Lodur.Core.csproj
index 9588aab..bfe4eb4 100644
--- a/src/Lodur.Core/Lodur.Core.csproj
+++ b/src/Lodur.Core/Lodur.Core.csproj
@@ -1,10 +1,15 @@
-
+
netstandard2.1
12.0
Lodur
+
+
+
+
+
diff --git a/src/Lodur.Core/Orient.cs b/src/Lodur.Core/Orient.cs
new file mode 100644
index 0000000..e48d7f4
--- /dev/null
+++ b/src/Lodur.Core/Orient.cs
@@ -0,0 +1,405 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// A part's world rotation and centre, as the caller reads them off the body each tick (one per plan part).
+ public readonly record struct PartPose(Quat Rotation, float X, float Y, float Z);
+
+ /// What an arm layer does with the wrists.
+ public enum ArmMode
+ {
+ /// The wrist goes to the target.
+ Reach,
+ /// The wrists go between the head and the target, a hand's breadth either side of the line.
+ WardOff,
+ /// The wrists go to a fixed point in the arm parent's frame; the target is ignored.
+ Present,
+ }
+
+ /// Which arm or arms a layer drives.
+ public enum ArmSide
+ {
+ Left,
+ Right,
+ Both,
+ /// The arm whose shoulder was nearer the target when the (goal, target) pair committed; held until the next commit.
+ Nearer,
+ }
+
+ /// Turns the head toward the committed target: the neck's joint target is blended toward the look solution by . Joint targets only, never strength.
+ public sealed record LookLayer
+ {
+ /// The blend from the base neck pose to the look solution, in [0, 1].
+ public double Weight { get; init; } = 1.0;
+
+ internal void Validate(string goal)
+ {
+ if (!(double.IsFinite(Weight) && Weight >= 0.0 && Weight <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal}: a Look layer's Weight must be finite and in [0, 1].");
+ }
+ }
+ }
+
+ /// Drives the shoulder and elbow of one or both arms from the arm solver: the base pose is blended toward the solution by . Joint targets only, never strength.
+ public sealed record ArmLayer
+ {
+ public ArmMode Mode { get; init; }
+
+ public ArmSide Side { get; init; }
+
+ /// The blend from the base shoulder and elbow poses to the solution, in [0, 1].
+ public double Weight { get; init; } = 1.0;
+
+ /// WardOff: metres from the head centre toward the target, where the wrists meet the line. Positive.
+ public float Distance { get; init; }
+
+ /// WardOff: metres each wrist sits either side of that line, across the torso (the left wrist toward the actor's left). Not negative.
+ public float Spread { get; init; }
+
+ /// Present: the wrists' goal in the arm parent's creation frame, given for the right arm; the left arm takes it mirrored in x.
+ public (float X, float Y, float Z) Point { get; init; }
+
+ internal void Validate(string goal)
+ {
+ if (!(double.IsFinite(Weight) && Weight >= 0.0 && Weight <= 1.0))
+ {
+ throw new ArgumentException($"Goal {goal}: an Arms layer's Weight must be finite and in [0, 1].");
+ }
+
+ if (Mode == ArmMode.WardOff && !(float.IsFinite(Distance) && Distance > 0f && float.IsFinite(Spread) && Spread >= 0f))
+ {
+ throw new ArgumentException($"Goal {goal}: a WardOff layer needs a finite Distance above 0 and a finite Spread of at least 0.");
+ }
+
+ if (Mode == ArmMode.Present)
+ {
+ if (Side == ArmSide.Nearer)
+ {
+ throw new ArgumentException($"Goal {goal}: a Present layer ignores the target, so it cannot pick the Nearer arm.");
+ }
+
+ if (!(float.IsFinite(Point.X) && float.IsFinite(Point.Y) && float.IsFinite(Point.Z)))
+ {
+ throw new ArgumentException($"Goal {goal}: a Present layer's Point must be finite.");
+ }
+ }
+
+ if (!Enum.IsDefined(typeof(ArmMode), Mode) || !Enum.IsDefined(typeof(ArmSide), Side))
+ {
+ throw new ArgumentException($"Goal {goal}: an Arms layer has a Mode or Side that is not defined.");
+ }
+ }
+ }
+
+ ///
+ /// Shrinks from a threat: the base pose is blended toward or by the target's bearing and
+ /// (a Distance consideration, head centre to target, whose response is the blend depth). A frontal threat
+ /// blends half of each. Joint targets only, never strength.
+ ///
+ public sealed record RecoilLayer
+ {
+ private Quat[] _left = Array.Empty();
+ private Quat[] _right = Array.Empty();
+ private IReadOnlyList _leftView = Array.AsReadOnly(Array.Empty());
+ private IReadOnlyList _rightView = Array.AsReadOnly(Array.Empty());
+
+ /// The pose that shrinks from a threat on the actor's left, one rotation per muscle. Copied when set; read back as a read-only view.
+ public IReadOnlyList AwayLeft
+ {
+ get => _leftView;
+ init
+ {
+ _left = Copy(value);
+ _leftView = Array.AsReadOnly(_left);
+ }
+ }
+
+ /// The pose that shrinks from a threat on the actor's right. Copied when set; read back as a read-only view.
+ public IReadOnlyList AwayRight
+ {
+ get => _rightView;
+ init
+ {
+ _right = Copy(value);
+ _rightView = Array.AsReadOnly(_right);
+ }
+ }
+
+ /// Input Distance (the head centre to the target); the response is the blend depth, 0 meaning the base pose.
+ public Consideration Proximity { get; init; }
+
+ internal Quat[] Left => _left;
+
+ internal Quat[] Right => _right;
+
+ private static Quat[] Copy(IReadOnlyList source)
+ {
+ var copy = new Quat[source.Count];
+ for (var m = 0; m < copy.Length; m++)
+ {
+ copy[m] = source[m];
+ }
+
+ return copy;
+ }
+
+ internal void Validate(string goal, int muscles)
+ {
+ if (_left.Length != muscles || _right.Length != muscles)
+ {
+ throw new ArgumentException($"Goal {goal}: a Recoil layer needs AwayLeft and AwayRight poses of one rotation per muscle.");
+ }
+
+ var k = Proximity;
+ if (k.Input != ConsiderationInput.Distance)
+ {
+ throw new ArgumentException($"Goal {goal}: a Recoil layer's Proximity must read Distance.");
+ }
+
+ if (!double.IsFinite(k.X0) || !double.IsFinite(k.X1) || k.X1 == k.X0
+ || !(k.Y0 >= 0.0 && k.Y0 <= 1.0) || !(k.Y1 >= 0.0 && k.Y1 <= 1.0)
+ || !(double.IsFinite(k.Exponent) && k.Exponent > 0.0))
+ {
+ throw new ArgumentException($"Goal {goal}: a Recoil layer's Proximity needs finite X0 != X1, Y0 and Y1 in [0, 1], and Exponent > 0.");
+ }
+ }
+ }
+
+ /// One tick's inputs to the layers: the rig, the caller's part poses, the committed target (Id 0: none) and the arm the Nearer mode holds.
+ internal readonly ref struct OrientInput
+ {
+ public readonly OrientRig? Rig;
+ public readonly ReadOnlySpan Parts;
+ public readonly Percept Target;
+ public readonly Side Arm;
+
+ public OrientInput(OrientRig rig, ReadOnlySpan parts, Percept target, Side arm)
+ {
+ Rig = rig;
+ Parts = parts;
+ Target = target;
+ Arm = arm;
+ }
+ }
+
+ ///
+ /// The solvers an Actor's brain needs, resolved once from the body plan: the look chain when any goal looks, wards off or recoils (they read
+ /// the head), an arm chain for each side an Arms layer can use. A chain the plan cannot give refuses at construction, naming the goal, so a
+ /// plan the closed form cannot solve fails at spawn and never mid-tick. The arm chains are the Actor's arms across ticks: each holds its
+ /// arm's swivel, hand path and written targets from tick to tick, and the rig holds nothing else. The arms are composed on every tick of an
+ /// Actor with a rig, so an arm its layer does not drive eases back to the base pose ( ); solving allocates nothing.
+ ///
+ internal sealed class OrientRig
+ {
+ private readonly BodyPlan _plan;
+ private readonly LookChain? _look;
+ private readonly ArmChain? _left;
+ private readonly ArmChain? _right;
+
+ public OrientRig(BodyPlan plan, Brain brain, double tickSeconds)
+ {
+ _plan = plan;
+ foreach (var goal in brain.Goals)
+ {
+ var b = goal.Behaviour;
+ if (!b.HasLayers)
+ {
+ continue;
+ }
+
+ if (_look == null && (b.Look != null || b.Recoil != null || b.Arms?.Mode == ArmMode.WardOff))
+ {
+ try
+ {
+ _look = LookChain.Of(plan);
+ }
+ catch (ArgumentException e)
+ {
+ throw new ArgumentException($"Goal {goal.Id}: the body has no head that can look: {e.Message}", e);
+ }
+ }
+
+ if (b.Arms is { } arms)
+ {
+ if (_left == null && arms.Side != ArmSide.Right)
+ {
+ _left = Arm(plan, goal.Id, Side.Left, tickSeconds);
+ }
+
+ if (_right == null && arms.Side != ArmSide.Left)
+ {
+ _right = Arm(plan, goal.Id, Side.Right, tickSeconds);
+ }
+ }
+ }
+ }
+
+ private static ArmChain Arm(BodyPlan plan, string goal, Side side, double tickSeconds)
+ {
+ try
+ {
+ return ArmChain.Of(plan, side, tickSeconds);
+ }
+ catch (ArgumentException e)
+ {
+ throw new ArgumentException($"Goal {goal}: the {side} arm cannot take an Arms layer: {e.Message}", e);
+ }
+ }
+
+ /// Forgets both arms' held swivels, paths and written targets: each arm is idle, and engages from the base pose.
+ public void ResetArms()
+ {
+ _left?.Reset();
+ _right?.Reset();
+ }
+
+ /// The Actor committed a (goal, target) pair: each arm starts a new hand path when next driven.
+ public void Commit()
+ {
+ _left?.Restart();
+ _right?.Restart();
+ }
+
+ /// The arm whose shoulder is nearer the target; ties go to the right.
+ public Side NearerArm(ReadOnlySpan parts, in Percept target)
+ {
+ if (_left == null || _right == null)
+ {
+ return Side.Right;
+ }
+
+ var l = ShoulderDistance(_left, parts, target);
+ var r = ShoulderDistance(_right, parts, target);
+ return l < r ? Side.Left : Side.Right;
+ }
+
+ private float ShoulderDistance(ArmChain arm, ReadOnlySpan parts, in Percept target)
+ {
+ var s = World(arm.ParentPart, parts, new IkVec(arm.ShoulderAnchor));
+ return (new IkVec(target.X, target.Y, target.Z) - s).Length;
+ }
+
+ /// A point given in a part's creation frame, where it is now: the part's centre plus its rotation from creation applied to the offset.
+ private IkVec World(int part, ReadOnlySpan parts, IkVec creationPoint)
+ {
+ var def = _plan.Parts[part];
+ var pose = parts[part];
+ var rel = pose.Rotation * def.Rotation.Conjugate();
+ return new IkVec(pose.X, pose.Y, pose.Z) + (creationPoint - new IkVec(def.Position)).Rotated(rel);
+ }
+
+ ///
+ /// Composes the layers onto the base pose already in : recoil, then look, then the arms. An arm the behaviour
+ /// does not drive this tick is released, which passes the base pose through once it has eased back. The part poses are read only for what is
+ /// driven.
+ ///
+ public void Compose(PoseBehaviour b, in OrientInput input, Span targets)
+ {
+ var parts = input.Parts;
+ var hasTarget = input.Target.Id != 0UL;
+ var goal = new IkVec(input.Target.X, input.Target.Y, input.Target.Z);
+
+ // The head centre, the torso's left axis and the unit direction to the target: read only when a layer needs the target.
+ var head = default(IkVec);
+ var left = default(IkVec);
+ var toward = default(IkVec);
+ var distance = 0f;
+ if (hasTarget && _look != null && b.HasLayers)
+ {
+ var h = parts[_look.ChildPart];
+ head = new IkVec(h.X, h.Y, h.Z);
+ var torso = _look.ParentPart;
+ left = new IkVec(1f, 0f, 0f).Rotated(parts[torso].Rotation * _plan.Parts[torso].Rotation.Conjugate());
+ var v = goal - head;
+ distance = v.Length;
+ toward = distance > 1e-6f ? v * (1f / distance) : new IkVec(0f, 0f, 1f);
+ }
+
+ if (hasTarget && b.Recoil is { } recoil && _look != null)
+ {
+ var s = Ik.Clamp(toward.Dot(left), -1f, 1f);
+ var depth = (float)recoil.Proximity.Response(distance);
+ var wl = depth * (1f + s) * 0.5f;
+ var wr = depth * (1f - s) * 0.5f;
+ var awayL = recoil.Left;
+ var awayR = recoil.Right;
+ for (var m = 0; m < targets.Length; m++)
+ {
+ targets[m] = Quat.Nlerp(Quat.Nlerp(targets[m], awayL[m], wl), awayR[m], wr);
+ }
+ }
+
+ if (hasTarget && b.Look is { } look && _look != null)
+ {
+ var t = parts[_look.ParentPart];
+ _look.Solve(t.Rotation, t.X, t.Y, t.Z, goal.X, goal.Y, goal.Z, out var neck);
+ targets[_look.Joint] = Toward(targets[_look.Joint], neck, look.Weight);
+ }
+
+ var driveLeft = false;
+ var driveRight = false;
+ if (b.Arms is { } arms && (hasTarget || arms.Mode == ArmMode.Present))
+ {
+ driveLeft = _left != null && (arms.Side == ArmSide.Left || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm == Side.Left));
+ driveRight = _right != null && (arms.Side == ArmSide.Right || arms.Side == ArmSide.Both || (arms.Side == ArmSide.Nearer && input.Arm != Side.Left));
+ if (driveLeft)
+ {
+ Drive(_left!, 1f, arms, parts, goal, head, toward, left, targets);
+ }
+
+ if (driveRight)
+ {
+ Drive(_right!, -1f, arms, parts, goal, head, toward, left, targets);
+ }
+ }
+
+ if (!driveLeft && _left != null)
+ {
+ Release(_left, targets);
+ }
+
+ if (!driveRight && _right != null)
+ {
+ Release(_right, targets);
+ }
+ }
+
+ private static void Release(ArmChain arm, Span targets)
+ {
+ arm.Release(targets[arm.ShoulderJoint], targets[arm.ElbowJoint], out var shoulder, out var elbow);
+ targets[arm.ShoulderJoint] = shoulder;
+ targets[arm.ElbowJoint] = elbow;
+ }
+
+ // The solution itself at weight 1, a blend toward it below that.
+ private static Quat Toward(in Quat from, in Quat solution, double weight) => weight >= 1.0 ? solution : Quat.Nlerp(from, solution, (float)weight);
+
+ // across: +1 for the left arm (its wrist sits toward the torso's left), -1 for the right.
+ private void Drive(ArmChain arm, float across, ArmLayer arms, ReadOnlySpan parts, IkVec target, IkVec head, IkVec toward, IkVec left, Span targets)
+ {
+ IkVec wrist;
+ switch (arms.Mode)
+ {
+ case ArmMode.Reach:
+ wrist = target;
+ break;
+ case ArmMode.WardOff:
+ wrist = head + toward * arms.Distance + left * (across * arms.Spread);
+ break;
+ default:
+ // Given for the right arm, whose side is -x (forward is +z, left is +x); the left arm mirrors it.
+ wrist = World(arm.ParentPart, parts, new IkVec(across * -arms.Point.X, arms.Point.Y, arms.Point.Z));
+ break;
+ }
+
+ var p = parts[arm.ParentPart];
+ var hand = World(arm.ForearmPart, parts, new IkVec(arm.WristAnchor));
+ arm.Drive(p.Rotation, p.X, p.Y, p.Z, wrist.X, wrist.Y, wrist.Z, hand.X, hand.Y, hand.Z, targets[arm.ShoulderJoint], targets[arm.ElbowJoint], arms.Weight,
+ out var shoulder, out var elbow);
+ targets[arm.ShoulderJoint] = shoulder;
+ targets[arm.ElbowJoint] = elbow;
+ }
+ }
+}
diff --git a/src/Lodur.Core/PdMuscle.cs b/src/Lodur.Core/PdMuscle.cs
index 05c0cb1..525e6b3 100644
--- a/src/Lodur.Core/PdMuscle.cs
+++ b/src/Lodur.Core/PdMuscle.cs
@@ -30,6 +30,18 @@ namespace Lodur
return new Quat(x * s, y * s, z * s, MathF.Cos(half));
}
+ /// Normalised linear blend from (t = 0) to (t = 1), the shorter way round.
+ public static Quat Nlerp(in Quat a, in Quat b, float t)
+ {
+ var s = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f;
+ var x = a.X + t * (s * b.X - a.X);
+ var y = a.Y + t * (s * b.Y - a.Y);
+ var z = a.Z + t * (s * b.Z - a.Z);
+ var w = a.W + t * (s * b.W - a.W);
+ var inv = 1f / MathF.Sqrt(x * x + y * y + z * z + w * w);
+ return new Quat(x * inv, y * inv, z * inv, w * inv);
+ }
+
/// Rotates the vector v by this quaternion.
public void Rotate(float vx, float vy, float vz, out float rx, out float ry, out float rz)
{
@@ -53,10 +65,17 @@ namespace Lodur
{
public readonly float SwingStiffness, SwingDamping, TwistStiffness, TwistDamping;
- public MuscleGains(float swingStiffness, float swingDamping, float twistStiffness, float twistDamping)
+ ///
+ /// The fraction of damping kept whatever the strength, in [0, 1] (tissue viscosity): a limp joint with Passive 1
+ /// still resists being swung, with no stiffness. Default 0, where limp is exactly zero torque.
+ ///
+ public readonly float Passive;
+
+ public MuscleGains(float swingStiffness, float swingDamping, float twistStiffness, float twistDamping, float passive = 0f)
{
SwingStiffness = swingStiffness; SwingDamping = swingDamping;
TwistStiffness = twistStiffness; TwistDamping = twistDamping;
+ Passive = passive > 0f ? (passive < 1f ? passive : 1f) : 0f;
}
}
@@ -71,14 +90,18 @@ namespace Lodur
/// Torque on the child, in the parent joint frame, that turns (child frame
/// relative to parent frame) toward and damps
/// (child minus parent, in the parent frame). Strength scales every gain together, so the
- /// damping ratio does not change with it; strength 0 is a limp joint and returns exactly zero.
+ /// damping ratio does not change with it. Damping is scaled by the larger of the strength and
+ /// , stiffness by the strength alone: strength 0 is a limp joint, exactly zero torque
+ /// when Passive is 0 and pure damping when it is not.
/// The rotation error takes the shorter way round.
///
public static void Torque(
in Quat rotation, float wx, float wy, float wz, in Quat target, in MuscleGains gains, float strength,
out float tx, out float ty, out float tz)
{
- if (strength <= 0f)
+ var stiff = strength > 0f ? strength : 0f; // negative or NaN strength is limp
+ var damp = stiff > gains.Passive ? stiff : gains.Passive;
+ if (damp <= 0f)
{
tx = ty = tz = 0f;
return;
@@ -94,9 +117,18 @@ namespace Lodur
var sin = MathF.Sqrt(e.X * e.X + e.Y * e.Y + e.Z * e.Z);
// Rotation vector of the error: angle * axis, with the small-angle limit of 2 * vector part.
var scale = sin < 1e-6f ? 2f : 2f * MathF.Atan2(sin, e.W) / sin;
- tx = strength * (gains.SwingStiffness * scale * e.X - gains.SwingDamping * wx);
- ty = strength * (gains.SwingStiffness * scale * e.Y - gains.SwingDamping * wy);
- tz = strength * (gains.TwistStiffness * scale * e.Z - gains.TwistDamping * wz);
+ if (damp == stiff)
+ {
+ // The whole law at one strength, in the form every pinned replay was recorded with.
+ tx = stiff * (gains.SwingStiffness * scale * e.X - gains.SwingDamping * wx);
+ ty = stiff * (gains.SwingStiffness * scale * e.Y - gains.SwingDamping * wy);
+ tz = stiff * (gains.TwistStiffness * scale * e.Z - gains.TwistDamping * wz);
+ return;
+ }
+
+ tx = stiff * gains.SwingStiffness * scale * e.X - damp * gains.SwingDamping * wx;
+ ty = stiff * gains.SwingStiffness * scale * e.Y - damp * gains.SwingDamping * wy;
+ tz = stiff * gains.TwistStiffness * scale * e.Z - damp * gains.TwistDamping * wz;
}
}
}
diff --git a/src/Lodur.Core/Perception.cs b/src/Lodur.Core/Perception.cs
new file mode 100644
index 0000000..1ca9351
--- /dev/null
+++ b/src/Lodur.Core/Perception.cs
@@ -0,0 +1,533 @@
+using System;
+
+namespace Lodur
+{
+ ///
+ /// A game stimulus: an axis-aligned box volume with an intensity the game writes every tick. Lodur reads
+ /// it and decides containment and transduction; the box is never a physics body.
+ ///
+ public struct BoxStimulus
+ {
+ public float CenterX, CenterY, CenterZ;
+ public float HalfX, HalfY, HalfZ;
+
+ /// Noxious intensity inside the box, written by the game each tick (0..1 in the slice's scale).
+ public double Intensity;
+
+ public BoxStimulus(float centerX, float centerY, float centerZ, float halfX, float halfY, float halfZ, double intensity = 0.0)
+ {
+ CenterX = centerX; CenterY = centerY; CenterZ = centerZ;
+ HalfX = halfX; HalfY = halfY; HalfZ = halfZ;
+ Intensity = intensity;
+ }
+
+ /// True when the point is inside the box or on one of its faces.
+ public bool Contains(float x, float y, float z) =>
+ MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ;
+ }
+
+ /// The sensory channels a point emitter can speak on. Each has its own stimulus, sensitisation and nerve.
+ public enum Channel
+ {
+ Audio = 0,
+ Visual = 1,
+ Interrupt = 2,
+ }
+
+ ///
+ /// A game stimulus at a point: sound, flicker, a notification. The game writes its position and intensity every
+ /// tick; Lodur decides what reaches the sense region. What arrives is the intensity falling off linearly to zero
+ /// at the radius. With an it is also a thing the puppet can come to know, remembered as a percept.
+ ///
+ public struct Emitter
+ {
+ public Channel Channel;
+ public float X, Y, Z;
+ public float Radius;
+ public double Intensity;
+
+ /// The game's stable id for the thing this emitter belongs to. 0 is anonymous: it loads the nerve and is never a percept. The top bit is reserved ( ); refuses it.
+ public ulong Id;
+
+ /// The game's tag for the thing (what kind it is). Lodur carries it and never interprets it; emitters sharing an id must share a kind.
+ public uint Kind;
+
+ /// The thing's facts as the game sees them, bit i is fact i. The game owns every bit but (63), which refuses; emitters sharing an id must share facts.
+ public ulong Facts;
+
+ public Emitter(Channel channel, float x, float y, float z, float radius, double intensity = 0.0, ulong id = 0, uint kind = 0, ulong facts = 0)
+ {
+ Channel = channel;
+ X = x; Y = y; Z = z;
+ Radius = radius;
+ Intensity = intensity;
+ Id = id;
+ Kind = kind;
+ Facts = facts;
+ }
+
+ /// Intensity * max(0, 1 - distance / Radius) at the point; zero at and beyond the radius.
+ public double Received(float x, float y, float z)
+ {
+ double dx = x - X, dy = y - Y, dz = z - Z;
+ var distance = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+ return Radius > 0f && distance < Radius ? Intensity * (1.0 - distance / Radius) : 0.0;
+ }
+ }
+
+ /// The nerve's tunables, the transduction of any channel, noxious or sensory: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain.
+ public sealed record NerveParameters
+ {
+ public double Threshold { get; init; } = 0.1;
+ public double SensitisationGrowth { get; init; } = 0.04;
+ public double SensitisationRecovery { get; init; } = 0.02;
+ public double SensitisationCap { get; init; } = 2.0;
+ public double ConductionDelaySeconds { get; init; } = 0.06;
+
+ /// Per-character gain (the consumer draws its trait spread).
+ public double Gain { get; init; } = 1.0;
+ }
+
+ /// The percept memory's tunables.
+ public sealed record PerceptParameters
+ {
+ /// How many things can be remembered at once, 1..256.
+ public int Capacity { get; init; } = 16;
+
+ /// How long a thing stays remembered after it was last sensed; finite and not negative.
+ public double MemorySeconds { get; init; } = 5.0;
+
+ public void Validate()
+ {
+ if (Capacity < 1 || Capacity > 256)
+ {
+ throw new ArgumentException("The percept capacity must be in 1..256.", nameof(Capacity));
+ }
+
+ if (!(MemorySeconds >= 0.0 && MemorySeconds < double.PositiveInfinity))
+ {
+ throw new ArgumentException("The percept memory time must be finite and not negative.", nameof(MemorySeconds));
+ }
+ }
+ }
+
+ /// One remembered thing. Id 0 is a free slot. Nothing here says whether the thing is real.
+ public readonly struct Percept
+ {
+ public ulong Id { get; }
+ public uint Kind { get; }
+
+ /// The thing's facts as last sensed; a thing changed out of sight keeps its old facts.
+ public ulong Facts { get; }
+
+ /// Where the emitter that reached the puppet hardest was, the last tick the thing was sensed.
+ public float X { get; }
+ public float Y { get; }
+ public float Z { get; }
+
+ /// The largest intensity received among the thing's emitters times the sensory gain; 0 on a tick it is not sensed.
+ public double Salience { get; }
+
+ /// 0 on a tick the thing is sensed.
+ public double SecondsSinceSensed { get; }
+
+ public Percept(ulong id, uint kind, float x, float y, float z, double salience, double secondsSinceSensed, ulong facts = 0)
+ {
+ Id = id; Kind = kind; Facts = facts; X = x; Y = y; Z = z; Salience = salience; SecondsSinceSensed = secondsSinceSensed;
+ }
+ }
+
+ ///
+ /// Layer 1 for one character, a fixed number of body regions. Each tick it takes one point per region and the
+ /// game's stimulus sources and produces, per region, the stimulus there and the afferent signal after
+ /// threshold, sensitisation and conduction delay. With a sensory nerve it also senses point emitters at one
+ /// region on three channels and combines the channels into one load and remembers the identified things it senses in a bounded slot table. Everything is allocated in the constructor.
+ ///
+ public sealed class Perception
+ {
+ private readonly NerveParameters _p;
+ private readonly double _dt;
+ private readonly int _regions;
+ private readonly int _slots;
+ private readonly double[] _ring; // afferent signal in flight along the nerve, region-major
+ private readonly double[] _sens;
+ private readonly double[] _stimulus;
+ private readonly double[] _afferent;
+ private readonly NerveParameters? _senses;
+ private readonly int _senseRegion;
+ private readonly int _senseSlots;
+ private readonly double[] _senseRing; // afferent in flight per channel, channel-major
+ private readonly double[] _senseSens = new double[ChannelCount];
+ private readonly double[] _senseStimulus = new double[ChannelCount];
+ private readonly double[] _senseAfferent = new double[ChannelCount];
+ private readonly double _memorySeconds;
+ private readonly ulong[] _pId; // percept slots; id 0 is free
+ private readonly uint[] _pKind;
+ private readonly ulong[] _pFacts;
+ private readonly float[] _pX, _pY, _pZ;
+ private readonly double[] _pSalience;
+ private readonly double[] _pSince;
+ private readonly bool[] _pSensed; // sensed this tick
+ private long _tick;
+
+ private const int ChannelCount = 3;
+
+ /// The top bit of an emitter id, reserved to Lodur's phantoms; refuses a caller emitter that sets it.
+ public const ulong PhantomIdBit = 1UL << 63;
+
+ /// The top fact bit, Lodur's own: whether the thing is within reach. The planner is its only writer, deriving it per call from distance; refuses an emitter that sets it.
+ public const ulong InReachFact = 1UL << 63;
+
+ /// The nerve of the sensory channels; null for a body with no senses (the load stays zero).
+ /// The region whose point the emitters are sensed at.
+ public Perception(NerveParameters parameters, double tickSeconds, int regionCount, NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null)
+ {
+ _p = parameters;
+ _dt = tickSeconds;
+ _regions = regionCount;
+ var delayTicks = (int)Math.Round(parameters.ConductionDelaySeconds / tickSeconds);
+ _slots = Math.Max(1, delayTicks);
+ _ring = new double[regionCount * _slots];
+ _sens = new double[regionCount];
+ Array.Fill(_sens, 1.0);
+ _stimulus = new double[regionCount];
+ _afferent = new double[regionCount];
+ _senses = senses;
+ _senseRegion = senseRegion;
+ if (senses != null)
+ {
+ if ((uint)senseRegion >= (uint)regionCount)
+ {
+ throw new ArgumentOutOfRangeException(nameof(senseRegion), $"The sense region must be one of {regionCount} regions.");
+ }
+
+ _senseSlots = Math.Max(1, (int)Math.Round(senses.ConductionDelaySeconds / tickSeconds));
+ _senseRing = new double[ChannelCount * _senseSlots];
+ Array.Fill(_senseSens, 1.0);
+ var pp = percepts ?? new PerceptParameters();
+ pp.Validate();
+ _memorySeconds = pp.MemorySeconds;
+ _pId = new ulong[pp.Capacity];
+ _pKind = new uint[pp.Capacity];
+ _pFacts = new ulong[pp.Capacity];
+ _pX = new float[pp.Capacity];
+ _pY = new float[pp.Capacity];
+ _pZ = new float[pp.Capacity];
+ _pSalience = new double[pp.Capacity];
+ _pSince = new double[pp.Capacity];
+ _pSensed = new bool[pp.Capacity];
+ }
+ else
+ {
+ _senseRing = Array.Empty();
+ _pId = Array.Empty();
+ _pKind = Array.Empty();
+ _pFacts = Array.Empty();
+ _pX = _pY = _pZ = Array.Empty();
+ _pSalience = _pSince = Array.Empty();
+ _pSensed = Array.Empty();
+ }
+ }
+
+ public int RegionCount => _regions;
+
+ /// The stimulus at the region's point this tick: the largest intensity among the boxes containing it.
+ public double Stimulus(int region) => _stimulus[region];
+
+ /// The afferent signal arriving this tick: what the nerve took in a conduction delay ago.
+ public double Afferent(int region) => _afferent[region];
+
+ /// The sensory signals combined: 1 - the product over channels of (1 - afferent, capped at 1), the afferents being the gated ones (see ). Zero with no senses or no emitters.
+ public double Load { get; private set; }
+
+ /// The largest intensity of the channel's emitters at the sense region's point this tick.
+ public double ChannelStimulus(Channel channel) => _senseStimulus[(int)channel];
+
+ ///
+ /// The channel's afferent arriving this tick, after threshold, sensitisation and conduction delay, times the sensory gain
+ /// was given (lodur:ruling:stress-bar-shows-arousal-calm-silences). stays the world's.
+ ///
+ public double ChannelAfferent(Channel channel) => _senseAfferent[(int)channel];
+
+ /// The region whose point the senses are sensed at.
+ public int SenseRegion => _senseRegion;
+
+ /// The number of percept slots: the capacity, or 0 with no senses. A slot is free when its percept's id is 0.
+ public int PerceptCount => _pId.Length;
+
+ /// The percept in the slot. A thing keeps its slot while it is remembered; a free slot reads as Id 0.
+ public Percept Percept(int slot) =>
+ new Percept(_pId[slot], _pKind[slot], _pX[slot], _pY[slot], _pZ[slot], _pSalience[slot], _pSince[slot], _pFacts[slot]);
+
+ // The planner reads every slot each call; a Percept per slot would copy fields it never looks at.
+ internal ReadOnlySpan PerceptIds => _pId;
+ internal ReadOnlySpan PerceptKinds => _pKind;
+ internal ReadOnlySpan PerceptFacts => _pFacts;
+ internal ReadOnlySpan PerceptX => _pX;
+ internal ReadOnlySpan PerceptY => _pY;
+ internal ReadOnlySpan PerceptZ => _pZ;
+
+ ///
+ /// Senses once per physics step. The spans are the caller's, one point per region. The sensory gain (default 1, the identity) multiplies the sense
+ /// channels' afferents as they leave the conduction delay, so a change of gain reaches on the next call it is passed to; the nociceptive region
+ /// afferents are never gated. A gain outside [0, 1] (NaN and infinity included) is refused,
+ /// as is an emitter that sets or and two emitters of one id with different kinds or facts.
+ ///
+ public void Sense(ReadOnlySpan x, ReadOnlySpan y, ReadOnlySpan z, ReadOnlySpan sources,
+ ReadOnlySpan emitters = default, double sensoryGain = 1.0)
+ {
+ if (x.Length != _regions || y.Length != _regions || z.Length != _regions)
+ {
+ throw new ArgumentException($"x, y and z need {_regions} entries, one per region.");
+ }
+
+ if (!(sensoryGain >= 0.0 && sensoryGain <= 1.0))
+ {
+ throw new ArgumentException("The sensory gain must be in [0, 1].", nameof(sensoryGain));
+ }
+
+ if (_senses != null)
+ {
+ // Refused before any state steps, so a bad emitter leaves the tick unrun.
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ if ((uint)emitters[i].Channel >= ChannelCount)
+ {
+ throw new ArgumentException($"Emitter {i} has channel {(int)emitters[i].Channel}; the channels are Audio, Visual and Interrupt.", nameof(emitters));
+ }
+
+ var id = emitters[i].Id;
+ if ((id & PhantomIdBit) != 0)
+ {
+ throw new ArgumentException($"Emitter {i} sets the phantom id bit, which is reserved to Lodur.", nameof(emitters));
+ }
+
+ if ((emitters[i].Facts & InReachFact) != 0)
+ {
+ throw new ArgumentException($"Emitter {i} sets the in-reach fact bit, which is reserved to Lodur.", nameof(emitters));
+ }
+
+ if (id != 0)
+ {
+ for (var j = 0; j < i; j++)
+ {
+ if (emitters[j].Id == id && emitters[j].Kind != emitters[i].Kind)
+ {
+ throw new ArgumentException($"Emitters {j} and {i} share id {id} with different kinds.", nameof(emitters));
+ }
+
+ if (emitters[j].Id == id && emitters[j].Facts != emitters[i].Facts)
+ {
+ throw new ArgumentException($"Emitters {j} and {i} share id {id} with different facts.", nameof(emitters));
+ }
+ }
+ }
+ }
+ }
+
+ var slot = (int)(_tick % _slots);
+ for (var r = 0; r < _regions; r++)
+ {
+ var stimulus = 0.0;
+ for (var i = 0; i < sources.Length; i++)
+ {
+ if (sources[i].Intensity > stimulus && sources[i].Contains(x[r], y[r], z[r]))
+ {
+ stimulus = sources[i].Intensity;
+ }
+ }
+
+ // Nociceptor: threshold, then sensitisation, then conduction delay.
+ var above = Math.Max(0.0, stimulus - _p.Threshold);
+ var sens = _sens[r] + _dt * (_p.SensitisationGrowth * above - _p.SensitisationRecovery * (_sens[r] - 1.0));
+ sens = Math.Min(Math.Max(sens, 1.0), _p.SensitisationCap);
+ _sens[r] = sens;
+ var ring = r * _slots + slot;
+ _afferent[r] = _ring[ring]; // written one conduction delay ago
+ _ring[ring] = above * sens * _p.Gain;
+ _stimulus[r] = stimulus;
+ }
+
+ if (_senses != null)
+ {
+ SenseEmitters(x[_senseRegion], y[_senseRegion], z[_senseRegion], emitters, sensoryGain);
+ }
+
+ _tick++;
+ }
+
+ private void SenseEmitters(float x, float y, float z, ReadOnlySpan emitters, double gain)
+ {
+ var senses = _senses!;
+ var slot = (int)(_tick % _senseSlots);
+ Array.Clear(_senseStimulus, 0, ChannelCount);
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ var c = (int)emitters[i].Channel;
+ var received = emitters[i].Received(x, y, z);
+ if (received > _senseStimulus[c])
+ {
+ _senseStimulus[c] = received;
+ }
+ }
+
+ var quiet = 1.0;
+ for (var c = 0; c < ChannelCount; c++)
+ {
+ var above = Math.Max(0.0, _senseStimulus[c] - senses.Threshold);
+ var sens = _senseSens[c] + _dt * (senses.SensitisationGrowth * above - senses.SensitisationRecovery * (_senseSens[c] - 1.0));
+ sens = Math.Min(Math.Max(sens, 1.0), senses.SensitisationCap);
+ _senseSens[c] = sens;
+ var ring = c * _senseSlots + slot;
+ // Written one conduction delay ago; the gate sits after the ring, so sensitisation still follows the world.
+ _senseAfferent[c] = _senseRing[ring] * gain;
+ _senseRing[ring] = above * sens * senses.Gain;
+ quiet *= 1.0 - Math.Min(1.0, _senseAfferent[c]);
+ }
+
+ Load = 1.0 - quiet;
+ SensePercepts(x, y, z, emitters, gain);
+ }
+
+ // A thing is sensed when it has an id, the gain is above zero and the sense point is strictly inside the emitter's radius.
+ private void SensePercepts(float x, float y, float z, ReadOnlySpan emitters, double gain)
+ {
+ for (var s = 0; s < _pId.Length; s++)
+ {
+ if (_pId[s] == 0)
+ {
+ continue;
+ }
+
+ _pSensed[s] = false;
+ _pSalience[s] = 0.0;
+ _pSince[s] += _dt;
+ }
+
+ if (gain > 0.0)
+ {
+ // Things already remembered first, so a newcomer can never evict one that is sensed this tick.
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ var slot = Reaches(emitters[i], x, y, z) ? SlotOf(emitters[i].Id) : -1;
+ if (slot >= 0)
+ {
+ Touch(slot, emitters[i], x, y, z, gain);
+ }
+ }
+ }
+
+ for (var s = 0; s < _pId.Length; s++)
+ {
+ if (_pId[s] != 0 && !_pSensed[s] && _pSince[s] > _memorySeconds)
+ {
+ _pId[s] = 0;
+ _pKind[s] = 0;
+ _pFacts[s] = 0;
+ _pX[s] = 0f; _pY[s] = 0f; _pZ[s] = 0f;
+ _pSalience[s] = 0.0;
+ _pSince[s] = 0.0;
+ }
+ }
+
+ if (gain > 0.0)
+ {
+ for (var i = 0; i < emitters.Length; i++)
+ {
+ if (!Reaches(emitters[i], x, y, z))
+ {
+ continue;
+ }
+
+ var slot = SlotOf(emitters[i].Id);
+ if (slot < 0)
+ {
+ slot = Admit(emitters[i].Id, emitters[i].Kind);
+ }
+
+ if (slot >= 0)
+ {
+ Touch(slot, emitters[i], x, y, z, gain);
+ }
+ }
+ }
+ }
+
+ private static bool Reaches(in Emitter e, float x, float y, float z)
+ {
+ if (e.Id == 0 || !(e.Radius > 0f))
+ {
+ return false;
+ }
+
+ double dx = x - e.X, dy = y - e.Y, dz = z - e.Z;
+ return Math.Sqrt(dx * dx + dy * dy + dz * dz) < e.Radius;
+ }
+
+ private int SlotOf(ulong id)
+ {
+ for (var s = 0; s < _pId.Length; s++)
+ {
+ if (_pId[s] == id)
+ {
+ return s;
+ }
+ }
+
+ return -1;
+ }
+
+ // The lowest free slot, else the unsensed slot longest unsensed (ties lowest slot); -1 when every slot was sensed this tick.
+ private int Admit(ulong id, uint kind)
+ {
+ var slot = -1;
+ for (var s = 0; s < _pId.Length; s++)
+ {
+ if (_pId[s] == 0)
+ {
+ slot = s;
+ break;
+ }
+ }
+
+ if (slot < 0)
+ {
+ for (var s = 0; s < _pId.Length; s++)
+ {
+ if (!_pSensed[s] && (slot < 0 || _pSince[s] > _pSince[slot]))
+ {
+ slot = s;
+ }
+ }
+ }
+
+ if (slot >= 0)
+ {
+ _pId[slot] = id;
+ _pKind[slot] = kind;
+ _pFacts[slot] = 0;
+ _pSensed[slot] = false;
+ _pSalience[slot] = 0.0;
+ _pSince[slot] = 0.0;
+ }
+
+ return slot;
+ }
+
+ // The first emitter of the tick fills the slot; a later one replaces it only by reaching him strictly harder.
+ private void Touch(int slot, in Emitter e, float x, float y, float z, double gain)
+ {
+ var salience = e.Received(x, y, z) * gain;
+ if (!_pSensed[slot] || salience > _pSalience[slot])
+ {
+ _pX[slot] = e.X; _pY[slot] = e.Y; _pZ[slot] = e.Z;
+ _pSalience[slot] = salience;
+ }
+
+ _pKind[slot] = e.Kind;
+ _pFacts[slot] = e.Facts;
+ _pSensed[slot] = true;
+ _pSince[slot] = 0.0;
+ }
+ }
+}
diff --git a/src/Lodur.Core/Physiology.cs b/src/Lodur.Core/Physiology.cs
new file mode 100644
index 0000000..d196d20
--- /dev/null
+++ b/src/Lodur.Core/Physiology.cs
@@ -0,0 +1,543 @@
+using System;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace Lodur
+{
+ /// Why a body died; the first rule that held at the end of the step that killed it (ruling bds-death).
+ public enum DeathCause { None, VitalTissue, BloodLoss, Consciousness }
+
+ ///
+ /// The liquid at a body's airway openings this step, as the caller measures it: the live liquid and the pooled liquid, each a non-negative amount
+ /// summed over the openings, and Drop in m, at least 0: how far the lowest opening's rim lies below the deepest point liquid pools at inside the airway, 0 when none lies below.
+ /// The default is nothing at the airway.
+ ///
+ public readonly record struct AirwaySample(double Live, double Pooled, double Drop)
+ {
+ /// One entry per opening: Live and Pooled summed, Drop the largest of the openings' signed drops, floored at 0 (0 with no opening).
+ public static AirwaySample Of(ReadOnlySpan live, ReadOnlySpan pooled, ReadOnlySpan drop)
+ {
+ double l = 0.0, p = 0.0, f = 0.0;
+ for (var i = 0; i < live.Length; i++) l += live[i];
+ for (var i = 0; i < pooled.Length; i++) p += pooled[i];
+ for (var i = 0; i < drop.Length; i++) f = Math.Max(f, drop[i]);
+ return new AirwaySample(l, p, f);
+ }
+ }
+
+ ///
+ /// What the stepping Actor reports each step. Arousal is the sensory load carried over time and Effort the mean strength the muscles actually applied last tick,
+ /// after each joint's motor ceiling (the Actor reports it so, not what the behaviour asked), each in [0, 1]. BreathHeld is whether the breath is held this step
+ /// (decided by the Actor on the tick before); Airway is what the caller finds at the airway. The default is rest, breathing freely, nothing at the airway.
+ ///
+ public readonly record struct PhysiologyInput(double Arousal, double Effort, bool BreathHeld = false, AirwaySample Airway = default);
+
+ ///
+ /// The body's physiology: tissue integrity, bound afflictions, blood and its oxygen, the capacities they fold into, the motor ceiling and death.
+ /// Harm enters only through ; time through . Integrity is derived from the severities of the
+ /// Injures afflictions bound to a tissue (part HP is never stored), and capacities, bleed and the motor ceiling are recomputed each step;
+ /// nobody writes them. A bleed leaves the circulation once, through the part's surface ( ) or into the airway ( ), split by each tissue's ; the gases are integrated by Step and nobody writes those either. Content owns every label and number ( ). Everything is allocated in the constructor.
+ ///
+ public sealed class Physiology
+ {
+ private readonly BodyPlan _body;
+ private readonly double _slowScale;
+ private readonly double _nominal;
+ private readonly double _lethalLoss;
+ private readonly double _regen;
+ private readonly AfflictionDef[] _defs;
+ private readonly Effect[] _organism;
+ private readonly int[] _partStart; // first tissue of each part in the flattened tissues; one past the last at [parts]
+ private readonly TissueDef[] _tissues;
+ private readonly double[] _injury;
+ private readonly double[] _integrity;
+ private readonly double[] _capacityWeight; // per capacity, indexed by EffectTarget (Consciousness, BloodPumping, Breathing)
+ private readonly RespirationDef _respiration;
+ private readonly AirwayDef _airway;
+ private readonly double[] _drivers; // the organism's driver values as the step began, indexed by EffectDriver
+ private readonly double[] _motorWeight; // per part
+ private readonly int[] _slotDef; // -1: free
+ private readonly int[] _slotPart;
+ private readonly int[] _slotTissue; // flattened
+ private readonly double[] _slotSeverity;
+ private readonly double[] _slotAge;
+ private readonly double[] _bleed; // per part, m^3/s, through the surface
+ private readonly double _bloodGain;
+ private double _airwayBleed; // m^3/s into the airway
+ private readonly double[] _motor; // per joint
+ private double _volume;
+ private double _consciousness;
+ private double _pumping = 1.0;
+ private double _breathing = 1.0;
+ private double _bloodOxygen = 1.0;
+ private double _brainOxygen = 1.0;
+ private double _airwayLiquid;
+ private double _occlusion;
+ private double _carbonDioxide;
+ private double _urge;
+ private double _coughed;
+ private double _drained;
+ private double _drawnLive;
+ private double _drawnPooled;
+ private bool _atAirway;
+ private long _steps;
+ private bool _bound;
+
+ /// The world's liquid volume per m^3 of blood, owned by the caller: blood bled into the airway enters it at this multiple of its real volume. Finite and above 0.
+ public Physiology(BodyPlan body, PhysiologyPlan plan, double slowScale, double bloodGain = 1.0)
+ {
+ if (!(slowScale > 0.0 && !double.IsInfinity(slowScale))) throw new ArgumentException("the slow scale must be finite and above 0.");
+ if (!(bloodGain > 0.0 && !double.IsInfinity(bloodGain))) throw new ArgumentException("the blood gain must be finite and above 0.");
+ _bloodGain = bloodGain;
+ _body = body;
+ _slowScale = slowScale;
+ _nominal = plan.Blood.NominalVolume;
+ _lethalLoss = plan.Blood.LethalLossFraction;
+ _regen = plan.Blood.RegenPerSecond;
+ _respiration = plan.Respiration;
+ _airway = plan.Airway;
+ _volume = _nominal;
+ _capacityWeight = new double[CapacityCount];
+ _drivers = new double[Enum.GetValues(typeof(EffectDriver)).Length];
+
+ _defs = new AfflictionDef[plan.Afflictions.Count];
+ for (var i = 0; i < _defs.Length; i++) _defs[i] = plan.Afflictions[i];
+ _organism = new Effect[plan.OrganismEffects.Count];
+ for (var i = 0; i < _organism.Length; i++) _organism[i] = plan.OrganismEffects[i];
+
+ var parts = body.Parts.Count;
+ var stackOf = plan.Resolve(body);
+
+ _partStart = new int[parts + 1];
+ var total = 0;
+ for (var p = 0; p < parts; p++)
+ {
+ _partStart[p] = total;
+ total += plan.Parts[stackOf[p]].Tissues.Count;
+ }
+
+ _partStart[parts] = total;
+ _tissues = new TissueDef[total];
+ _injury = new double[total];
+ _integrity = new double[total];
+ _motorWeight = new double[parts];
+ for (var p = 0; p < parts; p++)
+ {
+ var stack = plan.Parts[stackOf[p]].Tissues;
+ for (var l = 0; l < stack.Count; l++)
+ {
+ var t = stack[l];
+ _tissues[_partStart[p] + l] = t;
+ _integrity[_partStart[p] + l] = 1.0;
+ _capacityWeight[(int)EffectTarget.Consciousness] += t.Consciousness;
+ _capacityWeight[(int)EffectTarget.BloodPumping] += t.BloodPumping;
+ _capacityWeight[(int)EffectTarget.Breathing] += t.Breathing;
+ _motorWeight[p] += t.Motor;
+ }
+ }
+
+ if (!(_capacityWeight[(int)EffectTarget.Consciousness] > 0.0)) throw new ArgumentException("no tissue carries consciousness.");
+ _motor = new double[body.Joints.Count];
+ for (var j = 0; j < _motor.Length; j++)
+ {
+ if (!(_motorWeight[body.Joints[j].Child] > 0.0))
+ {
+ throw new ArgumentException($"the part below joint '{body.Joints[j].Label}' {body.Joints[j].Side} has no motor tissue.");
+ }
+
+ _motor[j] = 1.0;
+ }
+
+ _consciousness = 1.0;
+ _bleed = new double[parts];
+ var slots = plan.AfflictionSlots;
+ _slotDef = new int[slots];
+ _slotPart = new int[slots];
+ _slotTissue = new int[slots];
+ _slotSeverity = new double[slots];
+ _slotAge = new double[slots];
+ for (var s = 0; s < slots; s++) _slotDef[s] = -1;
+ }
+
+ public int JointCount => _motor.Length;
+
+ /// Blood volume in m^3; starts at the nominal volume.
+ public double BloodVolume => _volume;
+
+ /// The fraction of the lethal loss lost so far: 0 at nominal volume, 1 where the blood kills. Derived from the volume.
+ public double BloodLoss => (1.0 - _volume / _nominal) / _lethalLoss;
+
+ public bool Dead { get; private set; }
+ public DeathCause Cause { get; private set; }
+
+ /// The ordinal (from 0) of the that killed, -1 while alive.
+ public long DiedAtStep { get; private set; } = -1;
+
+ /// Afflictions refused because the table lacked room; a span call refused counts once.
+ public int Refused { get; private set; }
+
+ /// Wakefulness, 0..1; 0 once dead.
+ public double Consciousness => Dead ? 0.0 : _consciousness;
+
+ /// The heart's capacity to drive what bleeds, 0..1; 0 once dead.
+ public double BloodPumping => Dead ? 0.0 : _pumping;
+
+ /// The lungs' capacity to ventilate, 0..1; 0 once dead. An empty Breathing weight reads 1, as BloodPumping does.
+ public double Breathing => Dead ? 0.0 : _breathing;
+
+ /// The blood's oxygen store, 0..1, starting full; integrated by .
+ public double BloodOxygen => _bloodOxygen;
+
+ /// The brain's oxygen, 0..1, starting full: it relaxes toward what the pumping delivers from the blood store. Content turns it into consciousness.
+ public double BrainOxygen => _brainOxygen;
+
+ /// The liquid in the airway in m^3, 0 to the airway's capacity; integrated by .
+ public double AirwayLiquid => _airwayLiquid;
+
+ /// The fraction of the airway the liquid fills, 0..1; it takes that share of the ventilation. Derived from the liquid each step.
+ public double Occlusion => _occlusion;
+
+ /// Carbon dioxide, 0 at rest and about 1 at the break point; it rises with the load that uses oxygen and is blown off by ventilation.
+ public double CarbonDioxide => _carbonDioxide;
+
+ /// Air hunger, 0..1: the larger of the carbon dioxide urge and the ventilation deficit urge as the last step computed them; 0 once dead. The Actor carries it to the drive.
+ public double BreathUrge => Dead ? 0.0 : _urge;
+
+ /// True when the liquid at the airway the last step was sampled was at least the airway's HoldAt: the Actor holds the breath while it is.
+ public bool LiquidAtAirway => _atAirway;
+
+ /// The liquid in world m^3 the last step coughed out of the airway.
+ public double Coughed => _coughed;
+
+ /// The liquid in world m^3 the last step drained out of the airway (by gravity through the mouth), including what a full airway spilled.
+ public double Drained => _drained;
+
+ /// The liquid in world m^3 the last step drew into the airway from the live liquid at the openings, after the room-left clip; 0 for a held breath, and after a Step on a dead physiology.
+ public double DrawnLive => _drawnLive;
+
+ /// The liquid in world m^3 the last step drew into the airway from the pooled liquid at the openings, after the room-left clip; 0 for a held breath, and after a Step on a dead physiology.
+ public double DrawnPooled => _drawnPooled;
+
+ /// The tissue's remaining fraction, 0..1, as of the last step.
+ public double Integrity(int part, int layer) => _integrity[Flat(part, layer)];
+
+ /// The blood lost through the part's surface in real m^3/s over the last Step that ran, the dying step included; 0 after a Step on a dead physiology.
+ public double Bleed(int part) => _bleed[part];
+
+ /// The blood bled into the airway in real m^3/s over the last Step that ran (same lifetime as ); it enters the airway at the blood gain.
+ public double AirwayBleed => _airwayBleed;
+
+ /// The ceiling on a joint's muscle strength, 0..1: its capacity times consciousness; 0 once dead.
+ public double MotorCeiling(int joint) => Dead ? 0.0 : _motor[joint];
+
+ /// The layer of the part's stack with this label (the layer index and take).
+ public int TissueIndex(int part, string label)
+ {
+ for (var i = _partStart[part]; i < _partStart[part + 1]; i++)
+ {
+ if (_tissues[i].Label == label) return i - _partStart[part];
+ }
+
+ throw new ArgumentException($"part {part} has no tissue labelled '{label}'.");
+ }
+
+ internal int SlotCount => _slotDef.Length;
+ internal int SlotDef(int slot) => _slotDef[slot];
+ internal double SlotSeverity(int slot) => _slotSeverity[slot];
+ internal double SlotAge(int slot) => _slotAge[slot];
+
+ /// Set by the Actor that steps this physiology; one Actor steps one physiology until lodur-grafting moves stepping to the organism.
+ internal bool TryBind()
+ {
+ if (_bound) return false;
+ _bound = true;
+ return true;
+ }
+
+ private int Flat(int part, int layer)
+ {
+ if ((uint)part >= (uint)_bleed.Length) throw new ArgumentException("not a part.");
+ var i = _partStart[part] + layer;
+ if (layer < 0 || i >= _partStart[part + 1]) throw new ArgumentException("not a layer of the part.");
+ return i;
+ }
+
+ ///
+ /// Binds a new instance of the affliction to a tissue, never merged with another. Returns false, counting a refusal and
+ /// overwriting nothing, when the table is full. Allowed while dead: it records the wound and nothing steps.
+ ///
+ public bool Afflict(int affliction, int part, int layer, double severity) =>
+ Afflict(affliction, part, MemoryMarshal.CreateReadOnlySpan(ref layer, 1), severity);
+
+ ///
+ /// A wound of several layers of one part, all or none: binds one new instance of the affliction per layer, in span order into
+ /// the lowest free slots, and returns true; with fewer free slots than layers it writes nothing, counts one refusal and returns
+ /// false. The affliction, severity and every layer are validated before anything is written; an empty span or a layer named
+ /// twice throws. Allowed while dead, as the single-layer call.
+ ///
+ public bool Afflict(int affliction, int part, ReadOnlySpan layers, double severity)
+ {
+ if ((uint)affliction >= (uint)_defs.Length) throw new ArgumentException("not an affliction.");
+ if (layers.Length == 0) throw new ArgumentException("a wound needs at least one layer.");
+ if (!(severity > 0.0 && !double.IsInfinity(severity))) throw new ArgumentException("severity must be finite and above 0.");
+ for (var i = 0; i < layers.Length; i++)
+ {
+ Flat(part, layers[i]);
+ for (var j = 0; j < i; j++)
+ if (layers[j] == layers[i]) throw new ArgumentException("a layer is named twice.");
+ }
+
+ var free = 0;
+ for (var s = 0; s < _slotDef.Length; s++)
+ if (_slotDef[s] < 0) free++;
+ if (free < layers.Length)
+ {
+ Refused++;
+ return false;
+ }
+
+ var slot = 0;
+ for (var i = 0; i < layers.Length; i++)
+ {
+ while (_slotDef[slot] >= 0) slot++;
+ _slotDef[slot] = affliction;
+ _slotPart[slot] = part;
+ _slotTissue[slot] = Flat(part, layers[i]);
+ _slotSeverity[slot] = severity;
+ _slotAge[slot] = 0.0;
+ }
+
+ return true;
+ }
+
+ ///
+ /// Advances by dt seconds of the caller's clock: afflictions age and change severity (healed ones free their slot), integrity,
+ /// capacities, bleeding and regrowth follow, then the airway and the gases on the Acute clock, the motor ceilings, and death is judged once. Bleeding is computed before the airway.
+ /// A dead physiology does not change, except that its flows (Bleed, AirwayBleed, Coughed, Drained, DrawnLive, DrawnPooled) read 0 after a Step on it. A non-finite input, or one outside [0, 1], is refused before anything changes.
+ ///
+ public void Step(double dt, in PhysiologyInput input = default)
+ {
+ if (!(input.Arousal >= 0.0 && input.Arousal <= 1.0 && input.Effort >= 0.0 && input.Effort <= 1.0))
+ {
+ throw new ArgumentException("the input's arousal and effort must be finite and in [0, 1].");
+ }
+
+ var air = input.Airway;
+ if (!(air.Live >= 0.0 && air.Live < double.PositiveInfinity && air.Pooled >= 0.0 && air.Pooled < double.PositiveInfinity && air.Drop >= 0.0 && air.Drop < double.PositiveInfinity))
+ {
+ throw new ArgumentException("the airway sample's liquid must be finite and not negative and its drop finite and not negative.");
+ }
+
+ if (Dead)
+ {
+ Array.Clear(_bleed, 0, _bleed.Length);
+ _airwayBleed = 0.0;
+ _coughed = 0.0;
+ _drained = 0.0;
+ _drawnLive = 0.0;
+ _drawnPooled = 0.0;
+ return;
+ }
+
+ var slowDt = dt * _slowScale;
+
+ // 1. Each live affliction on its own clock.
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] < 0) continue;
+ var def = _defs[_slotDef[s]];
+ var c = def.Clock == PhysiologyClock.Acute ? dt : slowDt;
+ _slotAge[s] += c;
+ _slotSeverity[s] += def.SeverityRate * c;
+ if (_slotSeverity[s] <= 0.0) _slotDef[s] = -1;
+ }
+
+ // 2. Integrity from the severities of the Injures afflictions.
+ Array.Clear(_injury, 0, _injury.Length);
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] >= 0 && _defs[_slotDef[s]].Injures) _injury[_slotTissue[s]] += _slotSeverity[s];
+ }
+
+ for (var i = 0; i < _integrity.Length; i++) _integrity[i] = Clamp01(1.0 - _injury[i] / _tissues[i].Hp);
+
+ // 3. Capacities: the weighted mean integrity, then every effect's offsets, then its factors. The blood loss and brain oxygen they read are the values the step began with.
+ _drivers[(int)EffectDriver.BloodLoss] = BloodLoss;
+ _drivers[(int)EffectDriver.BrainOxygen] = _brainOxygen;
+ _consciousness = Capacity(EffectTarget.Consciousness);
+ _pumping = Capacity(EffectTarget.BloodPumping);
+ _breathing = Capacity(EffectTarget.Breathing);
+
+ // 4. Bleeding: each affliction's bleed effects, through its tissue's vascularity and the pumping; the tissue's airway share enters the airway, the rest leaves through the part's surface.
+ Array.Clear(_bleed, 0, _bleed.Length);
+ var totalBleed = 0.0;
+ var internalBleed = 0.0;
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] < 0) continue;
+ double offset = 0.0, factor = 1.0;
+ Fold(_defs[_slotDef[s]].Effects, EffectTarget.Bleed, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
+ var tissue = _tissues[_slotTissue[s]];
+ var rate = Math.Max(0.0, offset * factor) * tissue.Vascularity * _pumping;
+ _bleed[_slotPart[s]] += rate * (1.0 - tissue.AirwayShare);
+ internalBleed += rate * tissue.AirwayShare;
+ totalBleed += rate;
+ }
+
+ _airwayBleed = internalBleed;
+ _volume -= totalBleed * dt;
+
+ // 4b. The airway, a quantity (not particles): liquid at the openings is drawn in by a free breath, never by a held one, and only into the room left; blood bled into it enters at the
+ // blood gain whether or not the breath is held; a cough clears it by this step's consciousness, and it drains by gravity through the mouth. What a full airway cannot hold of the bled blood
+ // spills through the mouth. What a step removes is reported as Coughed and Drained, and what a breath drew as DrawnLive and DrawnPooled; occlusion takes its share of the ventilation below.
+ var held = input.BreathHeld;
+ var aw = _airway;
+ var at = aw.LiveWeight * air.Live + aw.PooledWeight * air.Pooled;
+ _atAirway = at > 0.0 && at >= aw.HoldAt;
+ var inflow = held ? 0.0 : aw.DrawPerSecond * _breathing * at;
+ var cough = aw.CoughPerSecond * Effect.EvalCurve(aw.CoughByConsciousness, _consciousness);
+ var drain = aw.DrainPerSecond * Clamp01(air.Drop / aw.DrainDrop);
+ var total = cough + drain;
+ var bled = dt * _bloodGain * _airwayBleed;
+ var drawRaw = dt * inflow;
+ var avail = _airwayLiquid + bled + drawRaw;
+ var want = dt * total * _airwayLiquid;
+ var removed = want < avail ? want : avail;
+ var after = avail - removed;
+ // Only bled blood overflows: a breath draws into the room left, so the spill is what the airway held plus what bled in, less what left, above capacity (after - capacity - drawRaw, ordered so a full airway with no bleed spills exactly 0).
+ var spill = Math.Max(0.0, _airwayLiquid + bled - removed - aw.Capacity);
+ // Coughed is capped at removed: for a cough that is not a power of two removed x cough / total can exceed removed by an ulp, and Drained (removed - Coughed + spill) would read a negative, which no consumer can take.
+ _coughed = total > 0.0 ? Math.Min(removed, removed * cough / total) : 0.0;
+ _drained = removed - _coughed + spill;
+ // What the breath really drew: the draw clipped to the room left after what the airway held, bled in and lost (a full airway with nothing removed leaves exactly 0), split by the sample's weighted shares.
+ var drawn = Math.Max(0.0, Math.Min(drawRaw, aw.Capacity - (_airwayLiquid + bled - removed)));
+ _drawnLive = at > 0.0 ? drawn * (aw.LiveWeight * air.Live / at) : 0.0;
+ _drawnPooled = at > 0.0 ? drawn * (aw.PooledWeight * air.Pooled / at) : 0.0;
+ _airwayLiquid = Math.Min(aw.Capacity, after);
+ _occlusion = Clamp01(_airwayLiquid / aw.Capacity);
+
+ // 5. Regrowth, on the slow clock, only while nothing bleeds.
+ if (totalBleed == 0.0)
+ {
+ _volume = Math.Min(_nominal, _volume + _regen * _nominal * slowDt);
+ }
+
+ // 6. The gases, on the Acute clock (ruling bds-asphyxia-real-time): the blood store refills by ventilation and is used by exertion;
+ // the brain relaxes toward what the pumping delivers. Placeholder constants live in content (RespirationDef).
+ var r = _respiration;
+ var load = 1.0 + r.ArousalUse * input.Arousal + r.EffortUse * input.Effort;
+ var use = r.BasalUsePerSecond * load;
+ var ventilation = held ? 0.0 : _breathing * (1.0 - _occlusion);
+ _bloodOxygen = Clamp01(_bloodOxygen + dt * (r.UptakePerSecond * ventilation * (1.0 - _bloodOxygen) - use));
+ _carbonDioxide = Math.Max(0.0, _carbonDioxide + dt * (r.CarbonDioxideRise * load - r.CarbonDioxideClear * ventilation * _carbonDioxide));
+ // Air hunger: carbon dioxide, or a breath tried and not got (neuroventilatory dissociation, felt at once); a held breath is not tried, so its urge is carbon dioxide alone.
+ var deficit = held ? 0.0 : 1.0 - _breathing * (1.0 - _occlusion);
+ _urge = Math.Max(Effect.EvalCurve(r.UrgeByCarbonDioxide, _carbonDioxide), Effect.EvalCurve(r.UrgeByVentilationDeficit, deficit));
+ _brainOxygen = Clamp01(_brainOxygen + (_pumping * _bloodOxygen - _brainOxygen) * (1.0 - Math.Exp(-dt / r.BrainSeconds)));
+
+ // 7. Motor ceilings: the child part's motor-weighted integrity, folded with its live afflictions' motor effects, times consciousness.
+ for (var j = 0; j < _motor.Length; j++)
+ {
+ var part = _body.Joints[j].Child;
+ var mean = 0.0;
+ for (var i = _partStart[part]; i < _partStart[part + 1]; i++)
+ {
+ var w = _tissues[i].Motor;
+ if (w > 0.0) mean += w * _integrity[i];
+ }
+
+ double offset = 0.0, factor = 1.0;
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] >= 0 && _slotPart[s] == part)
+ {
+ Fold(_defs[_slotDef[s]].Effects, EffectTarget.Motor, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
+ }
+ }
+
+ _motor[j] = Clamp01((mean / _motorWeight[part] + offset) * factor) * _consciousness;
+ }
+
+ // 8. Death, once, for every cause; the first rule that holds names it.
+ var cause = DeathCause.None;
+ for (var i = 0; i < _tissues.Length && cause == DeathCause.None; i++)
+ {
+ if (_tissues[i].Vital && _integrity[i] <= 0.0) cause = DeathCause.VitalTissue;
+ }
+
+ if (cause == DeathCause.None && BloodLoss >= 1.0) cause = DeathCause.BloodLoss;
+ if (cause == DeathCause.None && _consciousness <= 0.0) cause = DeathCause.Consciousness;
+ if (cause != DeathCause.None)
+ {
+ Dead = true;
+ Cause = cause;
+ DiedAtStep = _steps;
+ }
+
+ _steps++;
+ }
+
+ private const int CapacityCount = 3;
+
+ private static double Weight(in TissueDef t, EffectTarget target) => target switch
+ {
+ EffectTarget.Consciousness => t.Consciousness,
+ EffectTarget.BloodPumping => t.BloodPumping,
+ _ => t.Breathing,
+ };
+
+ private double Capacity(EffectTarget target)
+ {
+ var weightSum = _capacityWeight[(int)target];
+ var mean = 1.0;
+ if (weightSum > 0.0)
+ {
+ var acc = 0.0;
+ for (var i = 0; i < _tissues.Length; i++)
+ {
+ var w = Weight(_tissues[i], target);
+ if (w > 0.0) acc += w * _integrity[i];
+ }
+
+ mean = acc / weightSum;
+ }
+
+ double offset = 0.0, factor = 1.0;
+ for (var i = 0; i < _organism.Length; i++)
+ {
+ Fold(_organism[i], target, 0.0, 0.0, ref offset, ref factor);
+ }
+
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] >= 0) Fold(_defs[_slotDef[s]].Effects, target, _slotSeverity[s], _slotAge[s], ref offset, ref factor);
+ }
+
+ return Clamp01((mean + offset) * factor);
+ }
+
+ private void Fold(IReadOnlyList effects, EffectTarget target, double severity, double age, ref double offset, ref double factor)
+ {
+ for (var i = 0; i < effects.Count; i++)
+ {
+ Fold(effects[i], target, severity, age, ref offset, ref factor);
+ }
+ }
+
+ private void Fold(Effect e, EffectTarget target, double severity, double age, ref double offset, ref double factor)
+ {
+ if (e.Target != target) return;
+ var x = e.Driver switch
+ {
+ EffectDriver.Severity => severity,
+ EffectDriver.Age => age,
+ _ => _drivers[(int)e.Driver],
+ };
+ var v = e.Eval(x);
+ if (e.Op == EffectOp.Offset) offset += v;
+ else factor *= v;
+ }
+
+ private static double Clamp01(double x) => x < 0.0 ? 0.0 : x > 1.0 ? 1.0 : x;
+ }
+}
diff --git a/src/Lodur.Core/PhysiologyPlan.cs b/src/Lodur.Core/PhysiologyPlan.cs
new file mode 100644
index 0000000..9fd23d2
--- /dev/null
+++ b/src/Lodur.Core/PhysiologyPlan.cs
@@ -0,0 +1,398 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// The clock a process runs on: Acute on the caller's seconds, Slow on those times the session's slow scale (ruling bds-physiology-clock).
+ public enum PhysiologyClock { Acute, Slow }
+
+ ///
+ /// What an effect shapes. One mechanism reads each: capacities (Consciousness, BloodPumping, Breathing, the last read by gas exchange as
+ /// ventilation), an affliction's bleed rate, a part's motor ceiling. The three capacities come first and their order is the capacity index.
+ ///
+ public enum EffectTarget { Consciousness, BloodPumping, Breathing, Bleed, Motor }
+
+ /// How an effect's value joins its target: summed into the offsets, or multiplied into the factors.
+ public enum EffectOp { Offset, Factor }
+
+ ///
+ /// What an effect's curve is read at: its affliction's severity or age (in its clock's seconds), or an organism value as the step began:
+ /// the blood loss or the brain oxygen. Severity and Age belong to an affliction alone; BloodLoss and BrainOxygen index the organism's driver array.
+ ///
+ public enum EffectDriver { Severity, Age, BloodLoss, BrainOxygen }
+
+ ///
+ /// The material of a layer simulated as a particle sheet. is the particle spacing in m. The compliances are
+ /// XPBD compliances in m/N: along the sheet's edges (also its joint stitches) and to the bone. is
+ /// ultimate stress in Pa; the sheet builder derives an edge's break force as TensileStrength x Thickness x Spacing.
+ ///
+ public readonly record struct SheetDef(double Spacing, double EdgeCompliance, double AttachCompliance, double TensileStrength);
+
+ /// A sphere in the part's frame (origin at the part's Position, axes by its Rotation) that a sited core occupies: in m about .
+ public readonly record struct TissueSite((float X, float Y, float Z) Centre, float Radius);
+
+ ///
+ /// One tissue layer of a part. , and are
+ /// function weights, a closed set with one reader each ( is the lungs' share of ventilation): a capacity is the weighted mean integrity of the tissues that carry its weight.
+ /// A Vital tissue at integrity 0 kills. A stack is shells ( above 0, in m) outside-in, then cores (Thickness 0:
+ /// bone, organs, a muscle with no sheet); a core with a occupies that sphere of the part, one with none fills what the shells leave of the part's shape. Stack order is depth order: a sited tissue may sit among the shells (a vessel between fat and a muscle sheet), at the depth the shells listed before it give; an unsited core fills past all the shells and may not precede one. is the
+ /// material of a shell simulated as a particle sheet; null means it is not.
+ ///
+ public readonly record struct TissueDef(
+ string Label, double Hp, double Vascularity, bool Vital = false, double Consciousness = 0.0, double BloodPumping = 0.0, double Motor = 0.0, double Breathing = 0.0)
+ {
+ public double Thickness { get; init; }
+ public SheetDef? Sheet { get; init; }
+
+ /// Where a core sits in the part's frame; null fills the part past its shells. A shell takes none. A sited tissue's depth is the summed thickness of the shells listed before it.
+ public TissueSite? Site { get; init; }
+
+ /// The fraction, 0..1, of a wound's bleed in this tissue that enters the airway instead of leaving through the part's surface (the larynx, trachea and lungs' mucosa); 0 for every other tissue.
+ public double AirwayShare { get; init; }
+ }
+
+ /// The one tissue stack of a part, outside-in, owned by and joined to a only through .
+ public readonly record struct PartTissuesDef(string PartLabel, Side Side, IReadOnlyList Tissues)
+ {
+ ///
+ /// The layers a wound of (m, finite and above 0) at (the part's frame) reaches, written into as stack indices in stack order; returns the count.
+ /// Stack order is depth order: with B the summed Thickness of the shells listed before a tissue, a shell is reached iff depth exceeds B, and a core iff depth exceeds B and (it has no Site, or depth exceeds the distance from point to the Site's centre less its radius).
+ /// The validator refuses a shell after an unsited core, so an unsited core's B is every shell's total. Strict: a depth equal to a boundary does not reach past it. Allocates nothing.
+ ///
+ public int Reach((float X, float Y, float Z) point, double depth, Span layers)
+ {
+ if (!(double.IsFinite(depth) && depth > 0.0)) throw new ArgumentException("depth is not finite and above 0.");
+ if (!(float.IsFinite(point.X) && float.IsFinite(point.Y) && float.IsFinite(point.Z))) throw new ArgumentException("the point is not finite.");
+ if (layers.Length < Tissues.Count) throw new ArgumentException("layers is shorter than the stack.");
+ var n = 0;
+ var before = 0.0;
+ for (var i = 0; i < Tissues.Count; i++)
+ {
+ var t = Tissues[i];
+ if (t.Thickness > 0.0)
+ {
+ if (depth > before) layers[n++] = i;
+ before += t.Thickness;
+ }
+ else
+ {
+ if (!(depth > before)) continue;
+ if (t.Site is not TissueSite site) layers[n++] = i;
+ else
+ {
+ double dx = point.X - site.Centre.X, dy = point.Y - site.Centre.Y, dz = point.Z - site.Centre.Z;
+ if (depth > Math.Sqrt(dx * dx + dy * dy + dz * dz) - site.Radius) layers[n++] = i;
+ }
+ }
+ }
+
+ return n;
+ }
+ }
+
+ /// The blood: nominal volume in m^3, the lost fraction that kills, and the regrowth per slow second as a fraction of nominal.
+ public readonly record struct BloodDef(double NominalVolume, double LethalLossFraction, double RegenPerSecond);
+
+ ///
+ /// The gases, all on the Acute clock (ruling bds-asphyxia-real-time): the blood oxygen store S refills at
+ /// x ventilation x (1 - S) per second and is used at x
+ /// (1 + x arousal + x effort); the brain oxygen relaxes toward BloodPumping x S
+ /// with time constant . Both stores run 0..1. Carbon dioxide C (0 at rest, about 1 at the break point) rises at
+ /// x (1 + ArousalUse x arousal + EffortUse x effort) per second, the load that uses oxygen, and is blown off at
+ /// x ventilation x C. Air hunger is the larger of two curves: read at C and
+ /// read at the deficit, 1 - Breathing x (1 - occlusion), a breath tried and not got (zero while the breath is held).
+ ///
+ public readonly record struct RespirationDef(
+ double UptakePerSecond, double BasalUsePerSecond, double ArousalUse, double EffortUse, double BrainSeconds,
+ double CarbonDioxideRise, double CarbonDioxideClear,
+ IReadOnlyList<(double X, double Y)> UrgeByCarbonDioxide, IReadOnlyList<(double X, double Y)> UrgeByVentilationDeficit);
+
+ ///
+ /// The airway as a quantity, not as particles: it holds m^3 of liquid at most. Liquid at the airway is
+ /// x the live liquid plus x the pooled; at or more it is "at the airway"
+ /// and the Actor holds the breath. A free breath draws x Breathing x (liquid at the airway) per second into it; a cough
+ /// removes x (consciousness) x contents per second; and it drains at
+ /// x clamp01(drop / ) x contents, drop being how far (m) the lowest opening's rim lies below the deepest airway sump along
+ /// gravity: m of drop drains at the full rate. The airway holds liquid in the world's units (what the openings sample); blood bled into it
+ /// ( ) enters at the physiology's blood gain; a breath draws only into the room left, and what bleeds into a full airway spills through the mouth and is reported as drained.
+ ///
+ public readonly record struct AirwayDef(
+ double Capacity, double DrawPerSecond, double LiveWeight, double PooledWeight, double HoldAt, double CoughPerSecond,
+ IReadOnlyList<(double X, double Y)> CoughByConsciousness, double DrainPerSecond, double DrainDrop);
+
+ ///
+ /// A piecewise-linear curve in its driver, clamped at the ends. An equal-x pair is a step: at that x the later value holds
+ /// (a stage begins at its threshold). Effects only shape values a mechanism reads; they never write state.
+ ///
+ public readonly record struct Effect(EffectTarget Target, EffectOp Op, EffectDriver Driver, IReadOnlyList<(double X, double Y)> Curve)
+ {
+ public double Eval(double x) => EvalCurve(Curve, x);
+
+ /// The evaluation every curve of the plan shares: clamped at the ends, an equal-x pair a step.
+ internal static double EvalCurve(IReadOnlyList<(double X, double Y)> c, double x)
+ {
+ if (x < c[0].X)
+ {
+ return c[0].Y;
+ }
+
+ for (var i = 1; i < c.Count; i++)
+ {
+ if (x < c[i].X)
+ {
+ var a = c[i - 1];
+ var b = c[i];
+ return a.Y + (b.Y - a.Y) * ((x - a.X) / (b.X - a.X));
+ }
+ }
+
+ return c[c.Count - 1].Y;
+ }
+ }
+
+ ///
+ /// A kind of harm or condition. is per second of its clock (negative heals); an Injures
+ /// affliction's severity is HP lost from its tissue; a live affliction's effects apply while it lives.
+ ///
+ public readonly record struct AfflictionDef(string Label, PhysiologyClock Clock, double SeverityRate, bool Injures, IReadOnlyList Effects);
+
+ ///
+ /// Physiology as content: tissue stacks per body part, the afflictions that can be bound, the organism-wide effects of the organism's blood
+ /// loss and brain oxygen, the blood, the respiration and the size of the affliction table. Validated at construction; resolved against a by , the one (label, side) join, which and the sheet builder both call.
+ ///
+ public sealed class PhysiologyPlan
+ {
+ private readonly Dictionary _afflictionIndex = new Dictionary();
+
+ public PhysiologyPlan(
+ IReadOnlyList parts, IReadOnlyList afflictions, IReadOnlyList organismEffects,
+ BloodDef blood, RespirationDef respiration, AirwayDef airway, int afflictionSlots)
+ {
+ var ownedParts = new List(parts.Count);
+ foreach (var p in parts)
+ {
+ ownedParts.Add(p with { Tissues = new List(p.Tissues).AsReadOnly() });
+ }
+
+ var ownedAfflictions = new List(afflictions.Count);
+ foreach (var a in afflictions)
+ {
+ ownedAfflictions.Add(a with { Effects = Own(a.Effects) });
+ }
+
+ Parts = ownedParts.AsReadOnly();
+ Afflictions = ownedAfflictions.AsReadOnly();
+ OrganismEffects = Own(organismEffects);
+ Blood = blood;
+ Respiration = respiration with { UrgeByCarbonDioxide = OwnCurve(respiration.UrgeByCarbonDioxide), UrgeByVentilationDeficit = OwnCurve(respiration.UrgeByVentilationDeficit) };
+ Airway = airway with { CoughByConsciousness = OwnCurve(airway.CoughByConsciousness) };
+ AfflictionSlots = afflictionSlots;
+ Validate();
+ }
+
+ public IReadOnlyList Parts { get; }
+ public IReadOnlyList Afflictions { get; }
+ public IReadOnlyList OrganismEffects { get; }
+ public BloodDef Blood { get; }
+ public RespirationDef Respiration { get; }
+ public AirwayDef Airway { get; }
+ public int AfflictionSlots { get; }
+
+ public int AfflictionIndex(string label) =>
+ _afflictionIndex.TryGetValue(label, out var i) ? i : throw new ArgumentException($"no affliction labelled '{label}'.");
+
+ ///
+ /// The one (label, side) join of stacks to a body: element p is the index in of body part p's stack. Refuses a
+ /// stack naming no part, a part with two stacks, a part with no stack, and shells that do not fit (a stack's summed Thickness must be
+ /// below the part's inscribed half extent, compared at the shape's float precision), and a sited core whose site centre is not strictly inside its part's shape. Physiology and the sheet builder call it; it allocates, at construction only.
+ ///
+ public int[] Resolve(BodyPlan body)
+ {
+ var parts = body.Parts.Count;
+ var stackOf = new int[parts];
+ for (var p = 0; p < parts; p++) stackOf[p] = -1;
+ for (var s = 0; s < Parts.Count; s++)
+ {
+ var def = Parts[s];
+ var part = -1;
+ for (var p = 0; p < parts; p++)
+ {
+ if (body.Parts[p].Label == def.PartLabel && body.Parts[p].Side == def.Side) part = p;
+ }
+
+ if (part < 0) throw new ArgumentException($"a tissue stack names no body part: '{def.PartLabel}' {def.Side}.");
+ if (stackOf[part] >= 0) throw new ArgumentException($"body part '{def.PartLabel}' {def.Side} has two tissue stacks.");
+ stackOf[part] = s;
+ }
+
+ for (var p = 0; p < parts; p++)
+ {
+ var d = body.Parts[p];
+ if (stackOf[p] < 0) throw new ArgumentException($"body part '{d.Label}' {d.Side} has no tissue stack.");
+ var shells = 0.0;
+ foreach (var t in Parts[stackOf[p]].Tissues) shells += t.Thickness;
+ var half = d.Shape == PartShape.Box ? Math.Min(d.Size.X, Math.Min(d.Size.Y, d.Size.Z)) : d.Size.X;
+ if (!((float)shells < half)) throw new ArgumentException($"body part '{d.Label}' {d.Side}: the shells ({shells} m) do not fit inside its inscribed half extent ({half} m).");
+ foreach (var t in Parts[stackOf[p]].Tissues)
+ {
+ if (t.Site is TissueSite site && !Inside(d, site.Centre)) throw new ArgumentException($"body part '{d.Label}' {d.Side}: the site of tissue '{t.Label}' is not inside the part's shape.");
+ }
+ }
+
+ return stackOf;
+ }
+
+ private static bool Inside(PartDef d, (float X, float Y, float Z) c)
+ {
+ double x = c.X, y = c.Y, z = c.Z;
+ switch (d.Shape)
+ {
+ case PartShape.Box: return Math.Abs(x) < d.Size.X && Math.Abs(y) < d.Size.Y && Math.Abs(z) < d.Size.Z;
+ case PartShape.Capsule:
+ double along = Math.Max(-d.Size.Y, Math.Min(d.Size.Y, y));
+ return Math.Sqrt(x * x + (y - along) * (y - along) + z * z) < d.Size.X;
+ default: return Math.Sqrt(x * x + y * y + z * z) < d.Size.X;
+ }
+ }
+
+ private static IReadOnlyList<(double X, double Y)> OwnCurve(IReadOnlyList<(double X, double Y)>? curve) =>
+ curve == null ? null! : new List<(double X, double Y)>(curve).AsReadOnly();
+
+ private static IReadOnlyList Own(IReadOnlyList effects)
+ {
+ var list = new List(effects.Count);
+ foreach (var e in effects)
+ {
+ list.Add(e with { Curve = new List<(double X, double Y)>(e.Curve).AsReadOnly() });
+ }
+
+ return list.AsReadOnly();
+ }
+
+ private static bool IsFinite(double d) => !double.IsNaN(d) && !double.IsInfinity(d);
+
+ private void Validate()
+ {
+ foreach (var p in Parts)
+ {
+ var seen = new HashSet();
+ var core = false;
+ foreach (var t in p.Tissues)
+ {
+ var where = $"tissue '{t.Label}' of part '{p.PartLabel}' {p.Side}";
+ if (string.IsNullOrEmpty(t.Label)) throw new ArgumentException($"a tissue of part '{p.PartLabel}' {p.Side} has an empty label.");
+ if (!seen.Add(t.Label)) throw new ArgumentException($"{where}: the label is not unique within the part.");
+ if (!(IsFinite(t.Hp) && t.Hp > 0.0)) throw new ArgumentException($"{where}: Hp is not finite and above 0.");
+ if (!(IsFinite(t.Vascularity) && t.Vascularity >= 0.0)) throw new ArgumentException($"{where}: vascularity is not finite and at least 0.");
+ if (!(IsFinite(t.AirwayShare) && t.AirwayShare >= 0.0 && t.AirwayShare <= 1.0)) throw new ArgumentException($"{where}: the airway share is not finite and in [0, 1].");
+ if (!(IsFinite(t.Consciousness) && t.Consciousness >= 0.0 && IsFinite(t.BloodPumping) && t.BloodPumping >= 0.0 && IsFinite(t.Motor) && t.Motor >= 0.0 && IsFinite(t.Breathing) && t.Breathing >= 0.0))
+ {
+ throw new ArgumentException($"{where}: a function weight is not finite and at least 0.");
+ }
+
+ if (!(IsFinite(t.Thickness) && t.Thickness >= 0.0)) throw new ArgumentException($"{where}: thickness is not finite and at least 0.");
+ if (t.Site is TissueSite site)
+ {
+ if (t.Thickness > 0.0) throw new ArgumentException($"{where}: a shell takes no site.");
+ if (!(float.IsFinite(site.Centre.X) && float.IsFinite(site.Centre.Y) && float.IsFinite(site.Centre.Z))) throw new ArgumentException($"{where}: the site centre is not finite.");
+ if (!(float.IsFinite(site.Radius) && site.Radius > 0f)) throw new ArgumentException($"{where}: the site radius is not finite and above 0.");
+ }
+
+ if (t.Thickness == 0.0 && t.Site is null) core = true;
+ else if (t.Thickness > 0.0 && core) throw new ArgumentException($"{where}: a shell follows a core.");
+ if (t.Sheet is SheetDef sh)
+ {
+ if (!(t.Thickness > 0.0)) throw new ArgumentException($"{where}: a sheet needs a thickness above 0.");
+ if (!(IsFinite(sh.Spacing) && sh.Spacing > 0.0)) throw new ArgumentException($"{where}: sheet spacing is not finite and above 0.");
+ if (!(IsFinite(sh.EdgeCompliance) && sh.EdgeCompliance >= 0.0 && IsFinite(sh.AttachCompliance) && sh.AttachCompliance >= 0.0))
+ {
+ throw new ArgumentException($"{where}: a sheet compliance is not finite and at least 0.");
+ }
+
+ if (!(IsFinite(sh.TensileStrength) && sh.TensileStrength > 0.0)) throw new ArgumentException($"{where}: sheet tensile strength is not finite and above 0.");
+ }
+ }
+ }
+
+ var labels = new HashSet();
+ for (var i = 0; i < Afflictions.Count; i++)
+ {
+ var a = Afflictions[i];
+ if (string.IsNullOrEmpty(a.Label)) throw new ArgumentException("an affliction has an empty label.");
+ if (!labels.Add(a.Label)) throw new ArgumentException($"affliction '{a.Label}': the label is not unique.");
+ _afflictionIndex.Add(a.Label, i);
+ if (!Enum.IsDefined(typeof(PhysiologyClock), a.Clock)) throw new ArgumentException($"affliction '{a.Label}': the clock is not defined.");
+ if (!IsFinite(a.SeverityRate)) throw new ArgumentException($"affliction '{a.Label}': the severity rate is not finite.");
+ foreach (var e in a.Effects)
+ {
+ ValidateEffect(e, $"affliction '{a.Label}'");
+ }
+ }
+
+ foreach (var e in OrganismEffects)
+ {
+ ValidateEffect(e, "an organism effect");
+ if (e.Target != EffectTarget.Consciousness && e.Target != EffectTarget.BloodPumping && e.Target != EffectTarget.Breathing)
+ {
+ throw new ArgumentException("an organism effect targets only a capacity: Consciousness, BloodPumping or Breathing.");
+ }
+
+ if (e.Driver == EffectDriver.Severity || e.Driver == EffectDriver.Age)
+ {
+ throw new ArgumentException("an organism effect is not driven by Severity or Age: those belong to an affliction.");
+ }
+ }
+
+ if (!(IsFinite(Blood.NominalVolume) && Blood.NominalVolume > 0.0)) throw new ArgumentException("blood: the nominal volume is not finite and above 0.");
+ if (!(Blood.LethalLossFraction > 0.0 && Blood.LethalLossFraction <= 1.0)) throw new ArgumentException("blood: the lethal loss fraction is not in (0, 1].");
+ if (!(IsFinite(Blood.RegenPerSecond) && Blood.RegenPerSecond >= 0.0)) throw new ArgumentException("blood: the regrowth is not finite and at least 0.");
+ var r = Respiration;
+ if (!(IsFinite(r.UptakePerSecond) && r.UptakePerSecond >= 0.0 && IsFinite(r.BasalUsePerSecond) && r.BasalUsePerSecond >= 0.0
+ && IsFinite(r.ArousalUse) && r.ArousalUse >= 0.0 && IsFinite(r.EffortUse) && r.EffortUse >= 0.0))
+ {
+ throw new ArgumentException("respiration: a rate is not finite and at least 0.");
+ }
+
+ if (!(IsFinite(r.BrainSeconds) && r.BrainSeconds > 0.0)) throw new ArgumentException("respiration: BrainSeconds is not finite and above 0.");
+ if (!(IsFinite(r.CarbonDioxideRise) && r.CarbonDioxideRise >= 0.0 && IsFinite(r.CarbonDioxideClear) && r.CarbonDioxideClear >= 0.0))
+ {
+ throw new ArgumentException("respiration: a carbon dioxide rate is not finite and at least 0.");
+ }
+
+ ValidateCurve(r.UrgeByCarbonDioxide, "respiration: the carbon dioxide urge curve");
+ ValidateCurve(r.UrgeByVentilationDeficit, "respiration: the ventilation deficit urge curve");
+ var w = Airway;
+ if (!(IsFinite(w.Capacity) && w.Capacity > 0.0)) throw new ArgumentException("airway: the capacity is not finite and above 0.");
+ if (!(IsFinite(w.DrawPerSecond) && w.DrawPerSecond >= 0.0 && IsFinite(w.LiveWeight) && w.LiveWeight >= 0.0 && IsFinite(w.PooledWeight) && w.PooledWeight >= 0.0
+ && IsFinite(w.HoldAt) && w.HoldAt >= 0.0 && IsFinite(w.CoughPerSecond) && w.CoughPerSecond >= 0.0 && IsFinite(w.DrainPerSecond) && w.DrainPerSecond >= 0.0))
+ {
+ throw new ArgumentException("airway: a number is not finite and at least 0.");
+ }
+
+ if (!(w.DrainDrop > 0.0 && w.DrainDrop < double.PositiveInfinity)) throw new ArgumentException("airway: DrainDrop is not finite and above 0.");
+ ValidateCurve(w.CoughByConsciousness, "airway: the cough curve");
+ if (AfflictionSlots < 1) throw new ArgumentException("the affliction table needs at least one slot.");
+ }
+
+ private static void ValidateEffect(Effect e, string where)
+ {
+ if (!Enum.IsDefined(typeof(EffectTarget), e.Target) || !Enum.IsDefined(typeof(EffectOp), e.Op) || !Enum.IsDefined(typeof(EffectDriver), e.Driver))
+ {
+ throw new ArgumentException($"{where}: an effect has an undefined target, op or driver.");
+ }
+
+ ValidateCurve(e.Curve, $"{where}: an effect curve");
+ }
+
+ private static void ValidateCurve(IReadOnlyList<(double X, double Y)> curve, string where)
+ {
+ if (curve == null || curve.Count == 0) throw new ArgumentException($"{where} is empty.");
+ for (var i = 0; i < curve.Count; i++)
+ {
+ var (x, y) = curve[i];
+ if (!IsFinite(x) || !IsFinite(y)) throw new ArgumentException($"{where} has a non-finite point.");
+ if (i > 0 && x < curve[i - 1].X) throw new ArgumentException($"{where}'s x decreases.");
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/PhysiologyPlans.cs b/src/Lodur.Core/PhysiologyPlans.cs
new file mode 100644
index 0000000..e4d8db0
--- /dev/null
+++ b/src/Lodur.Core/PhysiologyPlans.cs
@@ -0,0 +1,122 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// Physiology content in code, until it lives in a store; the only place tissue, organ and affliction labels are spelled.
+ public static class PhysiologyPlans
+ {
+ private const double Day = 86400.0;
+
+ // Vascularity is the blood a wound in the tissue loses relative to muscle (play-tuned placeholders): skin and bone are thin, organs rich.
+ private const double SkinV = 0.2, MuscleV = 1.0, BoneV = 0.3, BrainV = 1.0, HeartV = 4.0, LungV = 2.0, LiverV = 3.0, KidneyV = 2.0, GutV = 1.0;
+
+ // Airway tissues: mucosa as perfused as muscle (placeholders). AirwayShare is the fraction of a wound's bleed that enters the airway: all of the larynx's and trachea's, half a lung's (half coughed up, half stays in the chest).
+ private const double LarynxV = 0.7, TracheaV = 1.0, MucosaShare = 1.0, LungShare = 0.5;
+
+ // Major vessels: a sited tissue placed among the shells at its depth (ruling bds-bleed-by-vessels), so a knife at the side of the neck or the inner thigh reaches one and the front of the throat does not.
+ // VesselV is play-tuned (probe: at the BDS knife's severity 20 and blood gain 10 either dies of blood loss at about 30 s; 3.0 gave 33.9 s, 4.0 gave 26.5 s). A vessel is no airway tissue (AirwayShare 0).
+ // LarynxV 1.0 -> 0.7: at 1.0 the front of the throat bled him out before it drowned him (grid in the cut report); 0.7 with the cough at 0.3 drowns him first (ruling bds-drown-in-own-blood-first).
+ private const double VesselV = 3.5;
+
+ // Fat is thickness in the stack, not particles; its vascularity is a placeholder.
+ private const double FatV = 0.1;
+
+ // Shell thickness in m. Skin: mean dermis thickness of excised back skin (research tissue-tensile-strength.ts-skin-annaidh-2012). Fat and muscle sheet: (placeholder).
+ private const double SkinT = 0.00256, FatT = 0.005, MuscleSheetT = 0.015;
+
+ // Sheet material: spacing m, edge and attach compliance m/N, tensile strength Pa. Skin strength is the same study's ultimate stress (21.6 MPa);
+ // spacing and compliances are (placeholder) values the fella.c and sieve.c probes ran with (flesh-map P1, P2, P6). Muscle strength is (placeholder): no human failure value.
+ private static readonly SheetDef SkinSheet = new SheetDef(0.10, 2e-4, 1e-3, 21.6e6);
+ private static readonly SheetDef MuscleSheetMaterial = new SheetDef(0.14, 1e-4, 1e-4, 0.5e6);
+
+ private static TissueDef Skin(double hp) => new TissueDef("Skin", hp, SkinV) { Thickness = SkinT, Sheet = SkinSheet };
+ private static TissueDef Fat(double hp) => new TissueDef("Fat", hp, FatV) { Thickness = FatT };
+ private static TissueDef Muscle(double hp) => new TissueDef("Muscle", hp, MuscleV, Motor: 1.0);
+ private static TissueDef MuscleSheet(double hp) => Muscle(hp) with { Thickness = MuscleSheetT, Sheet = MuscleSheetMaterial };
+ private static TissueDef Bone(string label, double hp) => new TissueDef(label, hp, BoneV);
+
+ private static Effect Curve(EffectTarget target, EffectOp op, EffectDriver driver, params (double X, double Y)[] curve) => new Effect(target, op, driver, curve);
+
+ ///
+ /// The 19-part humanoid of : tissue stacks outside-in with RimWorld's human part HP (fat and bone are stack thickness and core, not particles), the
+ /// blood, the stages of blood loss, the hypoxia curve and the respiration, and the Cut and Bruise afflictions. Numbers not cited are play-tuned placeholders; the respiration constants (uptake, basal and exertion use, brain lag) are literature-shaped placeholders.
+ ///
+ public static PhysiologyPlan Humanoid()
+ {
+ var parts = new List();
+ void Stack(string part, Side side, params TissueDef[] tissues) => parts.Add(new PartTissuesDef(part, side, tissues));
+
+ Stack("Pelvis", Side.Center, Skin(10), Fat(10), MuscleSheet(30), Bone("Pelvis", 25), new TissueDef("Gut", 20, GutV));
+ Stack("Torso", Side.Center,
+ Skin(10), Fat(10), MuscleSheet(40), Bone("Ribcage", 25),
+ // Organ sites (placeholders in the part's frame, left is +x, probed against PartTissuesDef.Reach); the ribcage stays unsited and fills the torso.
+ new TissueDef("Heart", 15, HeartV, BloodPumping: 1.0) { Site = new TissueSite((0.02f, 0.05f, 0.03f), 0.05f) },
+ new TissueDef("LungLeft", 15, LungV, Breathing: 1.0) { AirwayShare = LungShare, Site = new TissueSite((0.08f, 0.07f, 0f), 0.06f) },
+ new TissueDef("LungRight", 15, LungV, Breathing: 1.0) { AirwayShare = LungShare, Site = new TissueSite((-0.08f, 0.07f, 0f), 0.06f) },
+ new TissueDef("Liver", 20, LiverV) { Site = new TissueSite((-0.06f, -0.1f, 0.01f), 0.06f) },
+ new TissueDef("KidneyLeft", 15, KidneyV) { Site = new TissueSite((0.06f, -0.15f, -0.05f), 0.03f) },
+ new TissueDef("KidneyRight", 15, KidneyV) { Site = new TissueSite((-0.06f, -0.15f, -0.05f), 0.03f) },
+ new TissueDef("Trachea", 10, TracheaV) { AirwayShare = MucosaShare, Site = new TissueSite((0f, 0.2f, 0.06f), 0.015f) });
+ // The neck's muscle carries the Neck joint's motor weight: the head has to be a joint child with a muscle (spec discrepancy, report deviation).
+ // Head sites are placeholders in the part's frame (+z face, -y chin), probed against PartTissuesDef.Reach: the neck muscle low at the chin, skull and brain about the crown, the larynx at the throat.
+ // The carotids lie at the side of the neck, 0.055 m either side of the midline (placeholders), after the fat and before the muscle: a depth-2 cm wound at the side reaches one, the front of the throat does not.
+ Stack("Head", Side.Center, Skin(5), Fat(5),
+ new TissueDef("CarotidLeft", 10, VesselV) { Site = new TissueSite((0.055f, -0.07f, 0.01f), 0.012f) },
+ new TissueDef("CarotidRight", 10, VesselV) { Site = new TissueSite((-0.055f, -0.07f, 0.01f), 0.012f) },
+ Muscle(25) with { Site = new TissueSite((0f, -0.085f, -0.01f), 0.06f) }, Bone("Skull", 25) with { Site = new TissueSite((0f, 0.02f, -0.005f), 0.09f) },
+ new TissueDef("Brain", 10, BrainV, Vital: true, Consciousness: 1.0) { Site = new TissueSite((0f, 0.02f, -0.005f), 0.07f) },
+ new TissueDef("Larynx", 10, LarynxV) { AirwayShare = MucosaShare, Site = new TissueSite((0f, -0.075f, 0.06f), 0.015f) });
+ foreach (var side in new[] { Side.Left, Side.Right })
+ {
+ Stack("UpperArm", side, Skin(8), Fat(8), MuscleSheet(30), Bone("Humerus", 25));
+ Stack("LowerArm", side, Skin(8), Fat(8), MuscleSheet(25), Bone("Radius", 20));
+ // The femoral vessel runs at the inner thigh (sx +1 Left, -1 Right: the inner side is toward the midline), between the fat and the muscle sheet (placeholder site in the part's frame).
+ var sx = side == Side.Left ? 1f : -1f;
+ Stack("Thigh", side, Skin(10), Fat(10), new TissueDef("Femoral", 10, VesselV) { Site = new TissueSite((-sx * 0.032f, 0.12f, 0.032f), 0.012f) }, MuscleSheet(30), Bone("Femur", 25));
+ Stack("Shin", side, Skin(8), Fat(8), MuscleSheet(25), Bone("Tibia", 25));
+ Stack("Foot", side, Skin(5), Muscle(20), Bone("Bones", 25));
+ Stack("Palm", side, Skin(5), Muscle(20), Bone("Metacarpals", 15));
+ Stack("Thumb", side, Skin(3), Muscle(8), Bone("Bone", 8));
+ Stack("Fingers", side, Skin(3), Muscle(8), Bone("Bone", 8));
+ }
+
+ // RimWorld's blood-loss stages (research rw-blood-bleeding) as step offsets on consciousness, by fraction of the lethal loss.
+ var bloodLoss = Curve(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss,
+ (0.0, 0.0), (0.15, 0.0), (0.15, -0.1), (0.30, -0.1), (0.30, -0.2), (0.45, -0.2), (0.45, -0.4), (0.60, -0.4), (0.60, -0.9), (1.0, -0.9));
+
+ // Brain oxygen to consciousness: flat 1 above 0.70 so a healthy body reads exactly 1, falling to 0 at 0.10. A stopped heart or a smothering
+ // reaches it through the stores. (placeholder, fitted to ~75 s unconscious while struggling and death at 134-360 s, PMC8928428 and Szpilman NEJM 2012;
+ // 6-10 s after cerebral circulation stops, Rossen, Kabat and Anderson 1943; rulings bds-asphyxia-real-time, bds-heart-stop-stagger)
+ var hypoxia = Curve(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, (0.10, 0.0), (0.35, 0.1), (0.70, 1.0));
+
+ var afflictions = new[]
+ {
+ // Acute: a wound (Cut, Bruise) bleeds, clots and heals in real seconds whatever the slow scale (ruling bds-physiology-clock); Slow is for toxins, radiation and osmosis only. 1 mL/s per HP of severity
+ // (play-tuned), clotting with age (play-tuned); heals 10 HP per day of real seconds (RimWorld's rate).
+ new AfflictionDef("Cut", PhysiologyClock.Acute, -10.0 / Day, true, new[]
+ {
+ Curve(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, (0.0, 0.0), (100.0, 1e-4)),
+ Curve(EffectTarget.Bleed, EffectOp.Factor, EffectDriver.Age, (0.0, 1.0), (60.0, 0.5), (300.0, 0.1)),
+ }),
+ new AfflictionDef("Bruise", PhysiologyClock.Acute, -20.0 / Day, true, Array.Empty()),
+ };
+
+ // ATLS class IV past 40% loss (research df-and-atls) puts the lethal fraction at 0.5 (play-tuned); regrowth is RimWorld's 0.333 per slow day.
+ return new PhysiologyPlan(parts, afflictions, new[] { bloodLoss, hypoxia }, new BloodDef(0.005, 0.5, 0.333 / Day),
+ new RespirationDef(
+ 1.0, 0.002, 0.5, 4.0, 9.5,
+ // CO2 (placeholders, the readings are the real Actor smothered: struggle takes over at 0.1 s, out 81.6 s, dead 154.3 s; calm breath-hold gasps at 60.1 s). Rise 1/300 per second of
+ // basal load: carbon dioxide reaches its urge threshold in tens of seconds of exertion with no ventilation (breath-hold breaking point, PMC8511405; Frontiers Physiol 2021, 10.3389/fphys.2021.731633).
+ // Clear 0.5 per ventilated second keeps a healthy body at 0.01-0.07, below the curves' floor of 0.5.
+ 1.0 / 300.0, 0.5,
+ // Urge by CO2 (placeholder): nothing up to 0.5, full at 1.3. Urge by ventilation deficit (placeholder): nothing up to a deficit of 0.5 (a lung lost), 0.6 at no breath at all;
+ // a breath tried and not got is felt at once (Banzett, Lansing and Schwartzstein, Air hunger, Respir Physiol Neurobiol 2008).
+ new[] { (0.5, 0.0), (1.3, 1.0) }, new[] { (0.5, 0.0), (1.0, 0.6) }),
+ // The airway (placeholders). Capacity 150 mL is 2 mL/kg at 75 kg (an upper-airway and bronchial volume, the lung's own is far larger: the airway fills before the lung); it holds the breath from 15.6 mL
+ // of liquid at the openings (a mouthful, a tenth of the capacity). A free breath draws the liquid at the airway in at 1 per second, an awake cough clears 0.3 per second of what is there (a continuous airway bleed at the knife's severity must beat the cough, or the front of the throat bleeds him out instead of drowning him) and fails below 0.3
+ // consciousness, and the airway drains at 0.1 per second once the lowest rim of an opening lies 5 cm below the deepest sump (a true side pose, drop 0.025 m the mouth's half-width, halves it; side-lying falls measure a median 0.043 m, upright -0.047 m, so he drains nothing standing). Liquid and pooled liquid count alike.
+ new AirwayDef(150e-6, 1.0, 1.0, 1.0, 15.6e-6, 0.3, new[] { (0.3, 0.0), (0.6, 1.0) }, 0.1, 0.05), 64);
+ }
+ }
+}
diff --git a/src/Lodur.Core/Planner.cs b/src/Lodur.Core/Planner.cs
new file mode 100644
index 0000000..d33eb3d
--- /dev/null
+++ b/src/Lodur.Core/Planner.cs
@@ -0,0 +1,629 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// Whom a fact is about, in a verb: the actor, the verb's target, or the verb's second thing.
+ public enum FactSubject
+ {
+ Self,
+ This,
+ Tool,
+ }
+
+ /// One literal: bit (0..63) of the subject's facts is . Lodur never interprets a bit except .
+ public readonly record struct Fact(FactSubject Subject, int Bit, bool Value);
+
+ ///
+ /// A thing the game lets the puppet do, as the planner sees it: what must hold before and what holds after.
+ /// Content, authored by the consumer; the planner never reads .
+ ///
+ public sealed record Verb
+ {
+ private IReadOnlyList _needsView = Array.AsReadOnly(Array.Empty());
+ private IReadOnlyList _givesView = Array.AsReadOnly(Array.Empty());
+
+ /// The consumer's name for the verb; never read.
+ public string Id { get; init; } = "";
+
+ /// The kinds the verb's target may be; null accepts any kind.
+ public TargetFilter? This { get; init; }
+
+ /// The kinds the verb's second thing may be; null means the verb takes no second thing.
+ public TargetFilter? Tool { get; init; }
+
+ /// What must hold before the verb. Copied when set; read back as a read-only view.
+ public IReadOnlyList Needs
+ {
+ get => _needsView;
+ init => _needsView = Array.AsReadOnly(Planner.Copy(value));
+ }
+
+ /// What holds after the verb. Copied when set; read back as a read-only view.
+ public IReadOnlyList Gives
+ {
+ get => _givesView;
+ init => _givesView = Array.AsReadOnly(Planner.Copy(value));
+ }
+ }
+
+ /// One step of a plan: the verb's index in the planner's list and the percept ids it is grounded on (Tool 0: none). Ids, not slots, because slots are reused.
+ public readonly record struct PlanStep(int Verb, ulong This, ulong Tool);
+
+ ///
+ /// A bounded regressive planner over the percepts' facts. Given a want it finds the shallowest sequence of at most
+ /// depth verbs that would make it hold, working back from the want through what each verb gives and needs.
+ /// It reads percepts and keeps nothing: the plan is the caller's, derived per call. Everything it allocates is allocated here.
+ /// Not thread-safe: the search works in the planner's own buffers.
+ ///
+ public sealed class Planner
+ {
+ private const int MaxNeeds = 8;
+
+ ///
+ /// The default budget of a call: the most groundings it may regress, counted across all its depths. A counter, not a clock, so the cut-off is the same on every machine.
+ /// A call that spends its budget returns -1 and sets .
+ ///
+ public const int NodeBudget = 4096;
+
+ private readonly Verb[] _verbs;
+ private readonly Fact[][] _needs;
+ private readonly Fact[][] _gives;
+ private readonly uint[]?[] _thisKinds; // the kinds a verb's target may be; null accepts any
+ private readonly uint[]?[] _toolKinds; // the kinds a verb's second thing may be; null when it takes none
+ private readonly ulong[] _givenBits; // per verb, bit i set when one of its gives is on bit i of any subject
+ private readonly bool[] _moves; // per verb, a This give of bit 63 true: the step brings its This into reach
+ private readonly float[] _px; // the slots' remembered positions, copied per call
+ private readonly float[] _py;
+ private readonly float[] _pz;
+ private readonly int _words;
+ private readonly int _capacity;
+ private readonly double _reach;
+ private readonly int _stride;
+ private readonly ulong[] _facts; // thing 0 is self, thing 1 + s is percept slot s
+ private readonly ulong[] _slotId;
+ private readonly uint[] _slotKind;
+ private readonly int[] _set; // the needed literals with r steps left, at r * _stride
+ private readonly int[] _setCount;
+ private readonly int[] _stepVerb; // the step chosen with r steps left, at r - 1
+ private readonly int[] _stepThis;
+ private readonly int[] _stepTool;
+ private readonly ulong[] _meetsThis; // per level, the slots whose literal a This give of the verb in hand meets, _words per level
+ private readonly ulong[] _meetsTool;
+ private int _nodes;
+ private int _budget;
+ private bool _exhausted;
+
+ public Planner(IReadOnlyList verbs, int capacity, int maxDepth, double reachMeters)
+ {
+ if (verbs is null)
+ {
+ throw new ArgumentNullException(nameof(verbs));
+ }
+
+ if (maxDepth < 0 || maxDepth > 8)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxDepth), "The planner's depth must be in 0..8.");
+ }
+
+ if (!(reachMeters > 0.0 && reachMeters < double.PositiveInfinity))
+ {
+ throw new ArgumentException("The reach must be finite and above zero.", nameof(reachMeters));
+ }
+
+ if (capacity < 1 || capacity > 256)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), "The planner's capacity must be in 1..256.");
+ }
+
+ _verbs = new Verb[verbs.Count];
+ _needs = new Fact[verbs.Count][];
+ _gives = new Fact[verbs.Count][];
+ _thisKinds = new uint[verbs.Count][];
+ _toolKinds = new uint[verbs.Count][];
+ _givenBits = new ulong[verbs.Count];
+ _moves = new bool[verbs.Count];
+ for (var v = 0; v < _verbs.Length; v++)
+ {
+ var verb = verbs[v] ?? throw new ArgumentException($"Verb {v} is null.", nameof(verbs));
+ Validate(v, verb);
+ _verbs[v] = verb;
+ _needs[v] = Copy(verb.Needs);
+ _gives[v] = Copy(verb.Gives);
+ _thisKinds[v] = Kinds(verb.This);
+ _toolKinds[v] = Kinds(verb.Tool);
+ foreach (var g in _gives[v])
+ {
+ _givenBits[v] |= 1UL << g.Bit;
+ _moves[v] |= g.Subject == FactSubject.This && g.Bit == 63 && g.Value;
+ }
+ }
+
+ MaxDepth = maxDepth;
+ _capacity = capacity;
+ _reach = reachMeters;
+ _stride = 1 + maxDepth * MaxNeeds;
+ _facts = new ulong[capacity + 1];
+ _slotId = new ulong[capacity];
+ _slotKind = new uint[capacity];
+ _px = new float[capacity];
+ _py = new float[capacity];
+ _pz = new float[capacity];
+ _set = new int[(maxDepth + 1) * _stride];
+ _setCount = new int[maxDepth + 1];
+ _stepVerb = new int[Math.Max(1, maxDepth)];
+ _stepThis = new int[Math.Max(1, maxDepth)];
+ _stepTool = new int[Math.Max(1, maxDepth)];
+ _words = (capacity + 63) >> 6;
+ _meetsThis = new ulong[(maxDepth + 1) * _words];
+ _meetsTool = new ulong[(maxDepth + 1) * _words];
+ }
+
+ /// The deepest plan this planner can be asked for.
+ public int MaxDepth { get; }
+
+ /// The groundings the last call regressed; above the call budget means it ran out and returned -1.
+ public int LastNodes => _nodes;
+
+ /// True when the last call returned -1 because it spent its budget, not because no plan within the depth exists.
+ public bool LastExhausted => _exhausted;
+
+ ///
+ /// 0 when the want already holds, else the length of the shallowest plan of at most steps, written into
+ /// in execution order, else -1. The want is about self or about the percept in .
+ /// A thing's facts are those it was last sensed with, bit 63 replaced by whether it is within reach of the point.
+ /// A step that gives its This reach (bit 63 true) is a move: after it, another thing is in reach exactly when it is within reach of that This.
+ /// is the most groundings the call may regress, at least 1; a call that spends it returns -1 and sets .
+ /// (1..max(depth, 1)) is where the deepening starts: a call with depth k and fromDepth k searches for a plan of exactly k steps and returns none shallower
+ /// (0 still means the want holds).
+ ///
+ public int Plan(Perception perception, ulong selfFacts, float ox, float oy, float oz, int targetSlot, Fact want, int depth, Span plan, int budget = NodeBudget, int fromDepth = 1)
+ {
+ Check(perception, targetSlot, want, depth, plan.Length, budget, fromDepth);
+ _nodes = 0;
+ _budget = budget;
+ _exhausted = false;
+
+ _facts[0] = selfFacts & ~Perception.InReachFact;
+ var ids = perception.PerceptIds;
+ var kinds = perception.PerceptKinds;
+ var facts = perception.PerceptFacts;
+ var xs = perception.PerceptX;
+ var ys = perception.PerceptY;
+ var zs = perception.PerceptZ;
+ var reachSquared = _reach * _reach;
+ ids.CopyTo(_slotId);
+ kinds.CopyTo(_slotKind);
+ xs.CopyTo(_px);
+ ys.CopyTo(_py);
+ zs.CopyTo(_pz);
+ for (var s = 0; s < _capacity; s++)
+ {
+ double dx = xs[s] - ox, dy = ys[s] - oy, dz = zs[s] - oz;
+ _facts[s + 1] = (facts[s] & ~Perception.InReachFact) | (dx * dx + dy * dy + dz * dz <= reachSquared ? Perception.InReachFact : 0UL);
+ }
+
+ var wantLit = Lit(want.Subject == FactSubject.Self ? 0 : targetSlot + 1, want.Bit, want.Value);
+ if (Holds(wantLit))
+ {
+ return 0;
+ }
+
+ for (var d = fromDepth; d <= depth; d++)
+ {
+ _set[d * _stride] = wantLit;
+ _setCount[d] = 1;
+ if (Search(d))
+ {
+ for (var i = 0; i < d; i++)
+ {
+ plan[i] = Step(_stepVerb[i], _slotId[_stepThis[i]], _stepTool[i] < 0 ? 0UL : _slotId[_stepTool[i]]);
+ }
+
+ return d;
+ }
+
+ if (_nodes > _budget)
+ {
+ break;
+ }
+ }
+
+ _exhausted = _nodes > _budget;
+ return -1;
+ }
+
+ // Can the set at r be reached in exactly r steps from the state? The last step is chosen here, in ascending (verb, This slot, Tool slot).
+ private bool Search(int r)
+ {
+ var cur = r * _stride;
+ var n = _setCount[r];
+ if (r == 0)
+ {
+ for (var i = 0; i < n; i++)
+ {
+ if (!Holds(_set[i]))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ var open = 0UL;
+ for (var i = 0; i < n; i++)
+ {
+ open |= 1UL << ((_set[cur + i] >> 1) & 63);
+ }
+
+ for (var v = 0; v < _verbs.Length; v++)
+ {
+ // Relevance, before any grounding: a step is only worth taking if it gives a literal still open.
+ if ((_givenBits[v] & open) == 0UL || !Meets(v, r, cur, n, out var meetsSelf))
+ {
+ continue;
+ }
+
+ var thisKinds = _thisKinds[v];
+ var toolKinds = _toolKinds[v];
+ var m = r * _words;
+ for (var a = 0; a < _capacity; a++)
+ {
+ if (_slotId[a] == 0 || (thisKinds is not null && !Has(thisKinds, _slotKind[a])))
+ {
+ continue;
+ }
+
+ var meetsA = meetsSelf || ((_meetsThis[m + (a >> 6)] >> (a & 63)) & 1UL) != 0UL;
+ if (toolKinds is null)
+ {
+ if (meetsA && Try(r, v, a, -1, cur, n))
+ {
+ return true;
+ }
+
+ if (_nodes > _budget)
+ {
+ return false;
+ }
+
+ continue;
+ }
+
+ for (var b = 0; b < _capacity; b++)
+ {
+ if (b == a || _slotId[b] == 0 || !Has(toolKinds, _slotKind[b]) || !(meetsA || ((_meetsTool[m + (b >> 6)] >> (b & 63)) & 1UL) != 0UL))
+ {
+ continue;
+ }
+
+ if (Try(r, v, a, b, cur, n))
+ {
+ return true;
+ }
+
+ if (_nodes > _budget)
+ {
+ return false;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ // Takes the step v on (a, b) as the last of r: regress through it and search the rest.
+ private bool Try(int r, int v, int a, int b, int cur, int n)
+ {
+ _nodes++;
+ if (_nodes > _budget || !Regress(v, a, b, cur, n, (r - 1) * _stride, out var count))
+ {
+ return false;
+ }
+
+ _setCount[r - 1] = count;
+ _stepVerb[r - 1] = v;
+ _stepThis[r - 1] = a;
+ _stepTool[r - 1] = b;
+ return Search(r - 1);
+ }
+
+ // Which groundings of the verb give a literal the set at r still needs: a Self give meets one whatever the grounding (meetsSelf),
+ // a This give meets the one on the slot it is grounded on, a Tool give likewise; those slots are left in the level's masks.
+ // False when no grounding of the verb meets anything.
+ private bool Meets(int v, int r, int cur, int n, out bool meetsSelf)
+ {
+ meetsSelf = false;
+ var m = r * _words;
+ for (var w = 0; w < _words; w++)
+ {
+ _meetsThis[m + w] = 0UL;
+ _meetsTool[m + w] = 0UL;
+ }
+
+ var any = false;
+ var gives = _gives[v];
+ for (var g = 0; g < gives.Length; g++)
+ {
+ var gf = gives[g];
+ for (var i = 0; i < n; i++)
+ {
+ var l = _set[cur + i];
+ if (_moves[v] && gf.Subject == FactSubject.This && gf.Bit == 63 && gf.Value && ((l >> 1) & 63) == 63 && (l >> 7) > 0)
+ {
+ // A move: the literal on slot o holds after it for every This slot a with o near a exactly as the literal says (a == o is near).
+ var o = (l >> 7) - 1;
+ for (var a = 0; a < _capacity; a++)
+ {
+ if (_slotId[a] != 0 && Near(o, a) == ((l & 1) != 0))
+ {
+ _meetsThis[m + (a >> 6)] |= 1UL << (a & 63);
+ any = true;
+ }
+ }
+
+ continue;
+ }
+
+ if (((l >> 1) & 63) != gf.Bit || (l & 1) != (gf.Value ? 1 : 0))
+ {
+ continue;
+ }
+
+ var thing = l >> 7;
+ if (gf.Subject == FactSubject.Self)
+ {
+ if (thing == 0)
+ {
+ meetsSelf = true;
+ any = true;
+ }
+ }
+ else if (thing > 0)
+ {
+ var mask = gf.Subject == FactSubject.This ? _meetsThis : _meetsTool;
+ mask[m + ((thing - 1) >> 6)] |= 1UL << ((thing - 1) & 63);
+ any = true;
+ }
+ }
+ }
+
+ return any;
+ }
+
+ private static bool Has(uint[] kinds, uint kind)
+ {
+ for (var i = 0; i < kinds.Length; i++)
+ {
+ if (kinds[i] == kind)
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static uint[]? Kinds(TargetFilter? filter)
+ {
+ if (filter is null)
+ {
+ return null;
+ }
+
+ var kinds = new uint[filter.Kinds.Count];
+ for (var i = 0; i < kinds.Length; i++)
+ {
+ kinds[i] = filter.Kinds[i];
+ }
+
+ return kinds;
+ }
+
+ // The set before the step: what the step gives that is needed is met, what it needs is added. False when the
+ // step undoes something needed or leaves a literal and its negation. That it meets something is Search's relevance check.
+ private bool Regress(int v, int a, int b, int cur, int n, int next, out int count)
+ {
+ count = 0;
+ var gives = _gives[v];
+ for (var g = 0; g < gives.Length; g++)
+ {
+ var lit = Ground(gives[g], a, b);
+ for (var i = 0; i < n; i++)
+ {
+ var l = _set[cur + i];
+ if ((l >> 1) != (lit >> 1))
+ {
+ continue;
+ }
+
+ if (l != lit)
+ {
+ return false;
+ }
+ }
+ }
+
+ for (var i = 0; i < n; i++)
+ {
+ var l = _set[cur + i];
+ var given = false;
+ for (var g = 0; g < gives.Length && !given; g++)
+ {
+ given = Ground(gives[g], a, b) == l;
+ }
+
+ if (!given && _moves[v] && ((l >> 1) & 63) == 63 && (l >> 7) > 0 && (l >> 7) - 1 != a)
+ {
+ // After a move to a, every other thing is in reach exactly when it is near a: that literal is met or the step is refused.
+ if (Near((l >> 7) - 1, a) != ((l & 1) != 0))
+ {
+ return false;
+ }
+
+ given = true;
+ }
+
+ if (!given)
+ {
+ _set[next + count++] = l;
+ }
+ }
+
+ var needs = _needs[v];
+ for (var k = 0; k < needs.Length; k++)
+ {
+ var lit = Ground(needs[k], a, b);
+ var present = false;
+ for (var i = 0; i < count; i++)
+ {
+ var l = _set[next + i];
+ if (l == lit)
+ {
+ present = true;
+ }
+ else if (l == (lit ^ 1))
+ {
+ return false;
+ }
+ }
+
+ if (!present)
+ {
+ _set[next + count++] = lit;
+ }
+ }
+
+ return true;
+ }
+
+ // The one reach test: squared distance of remembered positions against reach squared. The start state applies it to the observer point.
+ private bool Near(int o, int a)
+ {
+ double dx = _px[o] - _px[a], dy = _py[o] - _py[a], dz = _pz[o] - _pz[a];
+ return dx * dx + dy * dy + dz * dz <= _reach * _reach;
+ }
+
+ private bool Holds(int lit) => (int)((_facts[lit >> 7] >> ((lit >> 1) & 63)) & 1UL) == (lit & 1);
+
+ private static int Lit(int thing, int bit, bool value) => (thing << 7) | (bit << 1) | (value ? 1 : 0);
+
+ private static int Ground(Fact f, int thisSlot, int toolSlot) =>
+ Lit(f.Subject == FactSubject.Self ? 0 : (f.Subject == FactSubject.This ? thisSlot : toolSlot) + 1, f.Bit, f.Value);
+
+ private static PlanStep Step(int verb, ulong thisId, ulong toolId) => new PlanStep(verb, thisId, toolId);
+
+ private void Check(Perception perception, int targetSlot, Fact want, int depth, int planLength, int budget, int fromDepth)
+ {
+ if (budget < 1)
+ {
+ throw new ArgumentOutOfRangeException(nameof(budget), "The budget must be at least 1.");
+ }
+
+ if (perception is null)
+ {
+ throw new ArgumentNullException(nameof(perception));
+ }
+
+ if (perception.PerceptCount != _capacity)
+ {
+ throw new ArgumentException($"The planner holds {_capacity} percept slots; the perception has {perception.PerceptCount}.", nameof(perception));
+ }
+
+ if (depth < 0 || depth > MaxDepth)
+ {
+ throw new ArgumentOutOfRangeException(nameof(depth), $"The depth must be in 0..{MaxDepth}.");
+ }
+
+ if (fromDepth < 1 || fromDepth > Math.Max(depth, 1))
+ {
+ throw new ArgumentOutOfRangeException(nameof(fromDepth), "The first depth must be in 1..max(depth, 1).");
+ }
+
+ if (planLength < depth)
+ {
+ throw new ArgumentException("The plan span is shorter than the depth.", "plan");
+ }
+
+ if (want.Subject == FactSubject.Tool || (uint)want.Subject > 2u || (uint)want.Bit > 63u)
+ {
+ throw new ArgumentException("The want is about self or the target, on a bit in 0..63.", nameof(want));
+ }
+
+ if (want.Subject == FactSubject.Self && want.Bit == 63)
+ {
+ throw new ArgumentException("Bit 63 is Lodur's reach; self has none.", nameof(want));
+ }
+
+ if (want.Subject == FactSubject.This && ((uint)targetSlot >= (uint)_capacity || perception.Percept(targetSlot).Id == 0))
+ {
+ throw new ArgumentException("A want on the target needs an occupied target slot.", nameof(targetSlot));
+ }
+ }
+
+ internal static Fact[] Copy(IReadOnlyList facts)
+ {
+ var copy = new Fact[facts.Count];
+ for (var i = 0; i < copy.Length; i++)
+ {
+ copy[i] = facts[i];
+ }
+
+ return copy;
+ }
+
+ private static void Validate(int index, Verb verb)
+ {
+ var name = $"Verb {index} ({verb.Id})";
+ if ((verb.This is not null && verb.This.Kinds.Count == 0) || (verb.Tool is not null && verb.Tool.Kinds.Count == 0))
+ {
+ throw new ArgumentException($"{name} has a filter with no kinds.");
+ }
+
+ if (verb.Gives.Count == 0)
+ {
+ throw new ArgumentException($"{name} gives nothing.");
+ }
+
+ if (verb.Needs.Count > MaxNeeds || verb.Gives.Count > MaxNeeds)
+ {
+ throw new ArgumentException($"{name} has more than {MaxNeeds} needs or gives.");
+ }
+
+ ValidateFacts(name, verb, verb.Needs);
+ ValidateFacts(name, verb, verb.Gives);
+ }
+
+ private static void ValidateFacts(string name, Verb verb, IReadOnlyList facts)
+ {
+ for (var i = 0; i < facts.Count; i++)
+ {
+ var f = facts[i];
+ if ((uint)f.Bit > 63u || (uint)f.Subject > 2u)
+ {
+ throw new ArgumentException($"{name} has a fact on bit {f.Bit} of subject {f.Subject}; bits are 0..63.");
+ }
+
+ if (f.Subject == FactSubject.Tool && verb.Tool is null)
+ {
+ throw new ArgumentException($"{name} has a Tool fact but takes no second thing.");
+ }
+
+ if (f.Subject == FactSubject.Self && f.Bit == 63)
+ {
+ throw new ArgumentException($"{name} has a Self fact on bit 63, which is Lodur's reach.");
+ }
+
+ for (var j = 0; j < i; j++)
+ {
+ if (facts[j].Subject == f.Subject && facts[j].Bit == f.Bit && facts[j].Value != f.Value)
+ {
+ throw new ArgumentException($"{name} lists {f.Subject} bit {f.Bit} both ways.");
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/PoseBehaviour.cs b/src/Lodur.Core/PoseBehaviour.cs
new file mode 100644
index 0000000..76c6671
--- /dev/null
+++ b/src/Lodur.Core/PoseBehaviour.cs
@@ -0,0 +1,208 @@
+using System;
+using System.Collections.Generic;
+
+namespace Lodur
+{
+ /// The pose behaviour's tunables.
+ public sealed record HoldParameters
+ {
+ /// Muscle strength written for every muscle, in [0, 1] (above 1 an explicit PD arm sags and drifts).
+ public float HoldStrength { get; init; } = 1f;
+
+ /// How far the reflex leak pulls the pose from its base toward the flinch pose, per unit of leak.
+ public double FlinchGain { get; init; } = 0.3;
+
+ /// Strain shake amplitude (blend fraction) per unit of strain. Zero strain, no shake. Measured at the palm of the ragdoll with hands (hand mass damps the arm's response), where it makes the 3-7 cm shake in hand height the strain rule describes.
+ public double StrainShake { get; init; } = 0.08;
+
+ /// Shake frequency. A few Hz: the arm's PD filters anything faster to nothing.
+ public double ShakeHz { get; init; } = 3.5;
+ }
+
+ ///
+ /// The one behaviour a goal can have: a pose held, or a loop through pose keys, with the reflex leak and a
+ /// strain-scaled shake blending the base pose toward the flinch pose. One key is held as it is; k keys are
+ /// walked in a loop, from each to the next and the last back to the first.
+ /// It writes per-muscle strength and target rotation into the caller's spans and nothing else (invariant
+ /// body-one-interface). The poses are the consumer's data, one rotation per muscle. A release is the same
+ /// behaviour with a key and a flinch pose equal and the gains zero.
+ ///
+ public sealed record PoseBehaviour
+ {
+ private Quat[][] _keys = Array.Empty();
+ private Quat[] _flinch = Array.Empty();
+ private IReadOnlyList> _keysView = Array.AsReadOnly(Array.Empty>());
+ private IReadOnlyList _flinchView = Array.AsReadOnly(Array.Empty());
+
+ /// k keys of one rotation per muscle each. Copied when set; read back as a read-only view.
+ public IReadOnlyList> Keys
+ {
+ get => _keysView;
+ init
+ {
+ var copy = new Quat[value.Count][];
+ var views = new IReadOnlyList[copy.Length];
+ for (var k = 0; k < copy.Length; k++)
+ {
+ copy[k] = new Quat[value[k].Count];
+ for (var m = 0; m < copy[k].Length; m++)
+ {
+ copy[k][m] = value[k][m];
+ }
+
+ views[k] = Array.AsReadOnly(copy[k]);
+ }
+
+ _keys = copy;
+ _keysView = Array.AsReadOnly(views);
+ }
+ }
+
+ /// Seconds from one key to the next when there is more than one key.
+ public double SecondsPerKey { get; init; } = 1.0;
+
+ /// The pose the leak and the shake pull toward, one rotation per muscle. Copied when set; read back as a read-only view.
+ public IReadOnlyList FlinchPose
+ {
+ get => _flinchView;
+ init
+ {
+ _flinch = new Quat[value.Count];
+ for (var m = 0; m < _flinch.Length; m++)
+ {
+ _flinch[m] = value[m];
+ }
+
+ _flinchView = Array.AsReadOnly(_flinch);
+ }
+ }
+
+ public HoldParameters Hold { get; init; } = new HoldParameters();
+
+ /// Aims the neck at the committed target. Null: no layer. Layers need a BodyPlan on the Actor.
+ public LookLayer? Look { get; init; }
+
+ /// Drives one or both arms by the arm solver: reach the target, ward it off, or present the wrists. Null: no layer.
+ public ArmLayer? Arms { get; init; }
+
+ /// Shrinks the pose from the target by its bearing and proximity. Null: no layer.
+ public RecoilLayer? Recoil { get; init; }
+
+ /// Whether any orient layer is present. Such a behaviour needs the Actor to hold a and be given part poses each tick.
+ public bool HasLayers => Look != null || Arms != null || Recoil != null;
+
+ public int MuscleCount => _keys.Length == 0 ? 0 : _keys[0].Length;
+
+ internal void Validate(string goal)
+ {
+ if (_keys.Length == 0 || _keys[0].Length == 0)
+ {
+ throw new ArgumentException($"Goal {goal}: a pose behaviour needs at least one key of at least one muscle.");
+ }
+
+ foreach (var key in _keys)
+ {
+ if (key.Length != _keys[0].Length)
+ {
+ throw new ArgumentException($"Goal {goal}: every key needs one rotation per muscle.");
+ }
+ }
+
+ if (_flinch.Length != _keys[0].Length)
+ {
+ throw new ArgumentException($"Goal {goal}: the flinch pose needs one rotation per muscle.");
+ }
+
+ if (_keys.Length > 1 && !(SecondsPerKey > 0.0 && double.IsFinite(SecondsPerKey)))
+ {
+ throw new ArgumentException($"Goal {goal}: SecondsPerKey must be positive and finite.");
+ }
+
+ Look?.Validate(goal);
+ Arms?.Validate(goal);
+ Recoil?.Validate(goal, _keys[0].Length);
+ }
+
+ /// The blend toward the flinch pose: the leak and the shake, clamped to [0, 1]. is the Actor's absolute time.
+ public double Blend(double leak, double strain, double seconds)
+ {
+ var w = leak * Hold.FlinchGain + Hold.StrainShake * strain * Math.Sin(2.0 * Math.PI * Hold.ShakeHz * seconds);
+ return Math.Min(Math.Max(w, 0.0), 1.0);
+ }
+
+
+ ///
+ /// Writes one tick's strengths and targets. The strength is scaled by the
+ /// in [0, 1] (the will that powers the layer, or 1 while it is involuntary) plus the leaked
+ /// reflex, capped at 1: a reflex that gets past a failing will still moves the muscle. The target rule is
+ /// , unchanged. A behaviour with orient layers needs the Actor's part poses and refuses this overload.
+ ///
+ public void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span strengths, Span targets)
+ {
+ Write(weight, leak, strain, seconds, secondsInGoal, strengths, targets, default);
+ }
+
+ ///
+ /// The same, with the orient layers composed between the keys and the flinch: the base key pose, then recoil, look and the arms (each a
+ /// blend toward its solution), then the flinch blend over every muscle. With a rig, the arms are composed on every call, driven or
+ /// released, so an arm the goal stopped driving eases back to the base pose. Layers write joint targets only; the strength line is the pose rule's.
+ /// With no layers, the arithmetic is the key loop's, operation for operation.
+ ///
+ internal void Write(double weight, double leak, double strain, double seconds, double secondsInGoal, Span strengths, Span targets, in OrientInput orient)
+ {
+ var count = MuscleCount;
+ if (strengths.Length != count || targets.Length != count)
+ {
+ throw new ArgumentException($"strengths and targets need {count} entries, one per muscle.");
+ }
+
+ if (!(weight >= 0.0 && weight <= 1.0))
+ {
+ throw new ArgumentOutOfRangeException(nameof(weight), "The weight must be in [0, 1].");
+ }
+
+ var layered = HasLayers;
+ if (layered && orient.Rig == null)
+ {
+ throw new ArgumentException("A behaviour with orient layers needs the Actor's orient input.");
+ }
+
+ var w = (float)Blend(leak, strain, seconds);
+ var strength = Hold.HoldStrength * (float)Math.Min(1.0, weight + leak * Hold.FlinchGain);
+ var k = _keys.Length;
+ var from = 0;
+ var to = 0;
+ var phase = 0f;
+ if (k > 1)
+ {
+ var p = secondsInGoal / SecondsPerKey;
+ var whole = Math.Floor(p);
+ from = (int)(whole % k);
+ to = (from + 1) % k;
+ phase = (float)(p - whole);
+ }
+
+ for (var m = 0; m < count; m++)
+ {
+ var a = _keys[from][m];
+ if (phase > 0f)
+ {
+ a = Quat.Nlerp(_keys[from][m], _keys[to][m], phase);
+ }
+
+ strengths[m] = strength;
+ targets[m] = a;
+ }
+
+ if (orient.Rig != null)
+ {
+ orient.Rig.Compose(this, orient, targets);
+ }
+
+ for (var m = 0; m < count; m++)
+ {
+ targets[m] = Quat.Nlerp(targets[m], _flinch[m], w);
+ }
+ }
+ }
+}
diff --git a/src/Lodur.Core/WithdrawalReflex.cs b/src/Lodur.Core/WithdrawalReflex.cs
new file mode 100644
index 0000000..f20c113
--- /dev/null
+++ b/src/Lodur.Core/WithdrawalReflex.cs
@@ -0,0 +1,54 @@
+using System;
+
+namespace Lodur
+{
+ /// The withdrawal reflex's tunables.
+ public sealed record WithdrawalParameters
+ {
+ /// How much of the reflex a fully resolved will can hold down (0..1).
+ public double MaxSuppression { get; init; } = 0.95;
+ public double FlinchLeakThreshold { get; init; } = 0.3;
+ public double FlinchRefractorySeconds { get; init; } = 0.5;
+ }
+
+ ///
+ /// Layer 2 for one body region. Its gain is set ahead of time by the drive: it reads the drive state the
+ /// previous tick left, before the drive steps (invariant reflex-gain-from-drive). What the suppression holds
+ /// down is the strain load; what leaks past is the reflex command and, over the threshold, a flinch.
+ ///
+ public sealed class WithdrawalReflex
+ {
+ private readonly WithdrawalParameters _p;
+ private readonly long _refractory;
+ private long _tick;
+ private long _lastFlinch = long.MinValue / 2;
+
+ public WithdrawalReflex(WithdrawalParameters parameters, double tickSeconds)
+ {
+ _p = parameters;
+ _refractory = (long)Math.Round(parameters.FlinchRefractorySeconds / tickSeconds);
+ }
+
+ /// The part of the afferent signal that gets past the will this tick.
+ public double Leak { get; private set; }
+
+ /// The part the will holds down this tick: the strain the drive accumulates.
+ public double StrainLoad { get; private set; }
+
+ /// Steps once; returns true on a flinch (leak over the threshold, outside the refractory window).
+ public bool Step(double afferent, in DriveState drive)
+ {
+ var suppression = _p.MaxSuppression * drive.Will;
+ Leak = afferent * (1.0 - suppression);
+ StrainLoad = afferent * suppression;
+ var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory;
+ if (flinch)
+ {
+ _lastFlinch = _tick;
+ }
+
+ _tick++;
+ return flinch;
+ }
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs b/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs
new file mode 100644
index 0000000..47587d0
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ActorPhysiologyTests.cs
@@ -0,0 +1,272 @@
+using Lodur;
+using static Lodur.Core.Tests.PhysioFixtures;
+
+namespace Lodur.Core.Tests;
+
+/// The Actor steps its Physiology first, writes the Consciousness slot from it, scales strengths by the motor ceiling, and goes limp when it dies.
+public sealed class ActorPhysiologyTests
+{
+ private static readonly float[] NoPoint = { 0f };
+
+ private static Brain HoldBrain() => new()
+ {
+ Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.7f } } } },
+ };
+
+ private static Actor Make(Physiology? physiology, DriveParameters? drive = null) =>
+ new(0.01, 1, new NerveParameters(), new WithdrawalParameters(), drive ?? new DriveParameters(), HoldBrain(), physiology: physiology);
+
+ private static TickEvents Tick(Actor a, double intensity, float[] strengths, Quat[] targets)
+ {
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = intensity } };
+ return a.Tick(NoPoint, NoPoint, NoPoint, box, strengths, targets);
+ }
+
+ [Fact]
+ public void The_slot_is_the_physiologys_consciousness_every_tick_and_strengths_are_held_to_each_joints_ceiling()
+ {
+ var p = Make3();
+ Assert.True(p.Afflict(Af("Lesion"), 0, BrainLayer, 4)); // consciousness 0.6
+ Assert.True(p.Afflict(Af("MotorHalf"), 1, 0, 1)); // joint 0 at half
+ var a = Make(p, new DriveParameters { WillCurve = 0.5 });
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 50; i++)
+ {
+ Tick(a, 0.0, s, q);
+ Assert.Equal(p.Consciousness, a.Drive.Consciousness);
+ Assert.Equal(0.6, p.Consciousness, 12);
+ var raw = 0.7f * (float)Math.Sqrt(a.Drive.Will);
+ Assert.Equal(raw * (float)p.MotorCeiling(0), s[0]);
+ Assert.Equal(raw * (float)p.MotorCeiling(1), s[1]);
+ Assert.Equal(0.3, p.MotorCeiling(0), 12);
+ Assert.Equal(0.6, p.MotorCeiling(1), 12);
+ }
+ }
+
+ private static Physiology Make3() => PhysioFixtures.Make();
+
+ [Fact]
+ public void An_actor_with_no_physiology_keeps_the_slot_at_one_and_scales_nothing()
+ {
+ var a = Make(null);
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 20; i++) Tick(a, 0.0, s, q);
+ Assert.Equal(1.0, a.Drive.Consciousness);
+ Assert.Equal(0.7f, s[0]);
+ Assert.Null(a.Physiology);
+ }
+
+ [Fact]
+ public void A_physiology_bound_to_one_actor_is_refused_by_a_second_and_strengths_of_the_wrong_length_throw()
+ {
+ var p = Make3();
+ var a = Make(p);
+ Assert.Same(p, a.Physiology);
+ Assert.Throws(() => Make(p));
+
+ Assert.True(p.Afflict(Af("Bleeder"), 1, 0, 1));
+ var q = new Quat[2];
+ Assert.Throws(() => Tick(a, 0.0, new float[1], q));
+ Assert.Throws(() => Tick(a, 0.0, new float[3], q));
+ Assert.Equal(0, a.TickCount); // a refused call changes nothing, the physiology included
+ Assert.Equal(0.0, p.SlotAge(0));
+ Assert.Equal(0.005, p.BloodVolume);
+ }
+
+ [Fact]
+ public void Death_is_reported_once_and_is_limp_and_the_actor_never_changes_again()
+ {
+ var p = Make3();
+ var a = Make(p);
+ var s = new float[2];
+ var q = new Quat[2] { Quat.FromAxisAngle(1f, 0f, 0f, 0.5f), Quat.FromAxisAngle(0f, 1f, 0f, 0.5f) };
+ for (var i = 0; i < 100; i++) Assert.Equal(TickEvents.None, Tick(a, 0.8, s, q) & TickEvents.Died);
+ Assert.True(s[0] > 0f && a.Drive.Pain > 0.0);
+ q[0] = Quat.FromAxisAngle(0f, 0f, 1f, 0.3f); // a value no behaviour writes: a dead actor leaves targets as they are
+ q[1] = Quat.FromAxisAngle(0f, 1f, 0f, 0.4f);
+ var sentinel = q.ToArray();
+
+ Assert.True(p.Afflict(Af("Lesion"), 0, Heart, 10));
+ var died = Tick(a, 0.8, s, q);
+ Assert.Equal(TickEvents.Died, died);
+ Assert.Equal(DeathCause.VitalTissue, p.Cause);
+ Assert.Equal(new float[2], s);
+ Assert.Equal(sentinel, q); // targets are left as they were
+ var frozen = a.Drive;
+ var goal = a.GoalIndex;
+ var ticks = a.TickCount;
+ for (var i = 0; i < 200; i++)
+ {
+ s[0] = s[1] = 0.5f;
+ Assert.Equal(TickEvents.None, Tick(a, 0.8, s, q));
+ Assert.Equal(new float[2], s);
+ Assert.Equal(frozen, a.Drive);
+ Assert.Equal(goal, a.GoalIndex);
+ }
+
+ Assert.Equal(ticks + 200, a.TickCount);
+ Assert.Equal(sentinel, q);
+ Assert.Equal(0.0, frozen.Consciousness);
+ Assert.Equal(0.0, frozen.Will);
+ }
+
+ [Fact]
+ public void A_dead_physiologys_flows_stand_on_the_tick_it_died_and_read_zero_after()
+ {
+ var airway = InertAirway with { CoughByConsciousness = new[] { (0.0, 1.0), (1.0, 1.0) } }; // a cough that does not need consciousness, so it still runs on the step the brain lesion kills
+ var p = Bleeding(0.5, 1.0, airway, new BloodDef(1000.0, 0.5, 1e-4)); // bleeds into the airway, which coughs and drains; the blood is too deep to run out
+ var a = Make(p);
+ var s = new float[2];
+ var q = new Quat[2];
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.0 } };
+ var air = new AirwaySample(1e-6, 1e-6, airway.DrainDrop);
+ for (var i = 0; i < 10; i++) Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air) & TickEvents.Died);
+ Assert.True(p.Bleed(0) > 0.0 && p.AirwayBleed > 0.0 && p.DrawnLive > 0.0 && p.DrawnPooled > 0.0 && p.Coughed > 0.0 && p.Drained > 0.0);
+ Assert.True(p.Afflict(Af("Lesion"), 0, BrainLayer, 10)); // not the heart: a stopped heart would stop the bleed on the dying step
+ Assert.Equal(TickEvents.Died, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air));
+ Assert.True(p.Dead);
+ Assert.True(p.Bleed(0) > 0.0, "the dying step's bleed was not reported"); // Lodur reports the step it died on
+ Assert.True(p.AirwayBleed > 0.0 && p.DrawnLive > 0.0 && p.DrawnPooled > 0.0 && p.Coughed > 0.0 && p.Drained > 0.0, "a flow of the dying step was not reported");
+ Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, box, s, q, airway: air));
+ Assert.Equal(0.0, p.Bleed(0));
+ Assert.Equal(0.0, p.AirwayBleed);
+ Assert.Equal(0.0, p.DrawnLive);
+ Assert.Equal(0.0, p.DrawnPooled);
+ Assert.Equal(0.0, p.Coughed);
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ [Fact]
+ public void A_physiology_that_died_before_it_was_bound_reports_the_death_on_the_first_tick()
+ {
+ var p = Make3();
+ Assert.True(p.Afflict(Af("Lesion"), 0, Heart, 10));
+ p.Step(0.01);
+ Assert.True(p.Dead);
+ var a = Make(p);
+ var s = new float[2] { 1f, 1f };
+ Assert.Equal(TickEvents.Died, Tick(a, 0.0, s, new Quat[2]));
+ Assert.Equal(new float[2], s);
+ Assert.Equal(TickEvents.None, Tick(a, 0.0, s, new Quat[2]));
+ }
+
+ [Fact]
+ public void The_actor_reports_its_last_ticks_strength_as_effort()
+ {
+ double Oxygen(float hold)
+ {
+ var brain = new Brain
+ {
+ Goals = new[] { new GoalSpec { Id = "g", Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = hold } } } },
+ };
+ var p = Make3();
+ Assert.True(p.Afflict(Af("Choke"), 0, 0, 1e9));
+ var a = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, physiology: p);
+ var s = new float[2];
+ var q = new Quat[2];
+ for (var i = 0; i < 3000; i++) Tick(a, 0.0, s, q);
+ Assert.False(p.Dead);
+ return p.BloodOxygen;
+ }
+
+ var strong = Oxygen(0.7f);
+ var idle = Oxygen(0.0f);
+ Assert.True(strong < idle, $"strong {strong}, idle {idle}");
+ }
+
+ [Fact]
+ public void The_actor_steps_its_physiology_on_the_drives_arousal_and_the_strength_it_applied_after_the_ceiling()
+ {
+ Physiology Body()
+ {
+ var q = Make3();
+ Assert.True(q.Afflict(Af("Choke"), 0, 0, 1e9)); // the stores move every tick
+ Assert.True(q.Afflict(Af("MotorHalf"), 1, 0, 1)); // joint 0 at half: the ceiling makes the applied strength differ from the asked one
+ return q;
+ }
+
+ var p = Body();
+ var twin = Body();
+ var a = new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), HoldBrain(),
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0, physiology: p);
+ var loud = SensoryRig.One(0.55);
+ var s = new float[2];
+ var q = new Quat[2];
+ double arousalBefore = 0.0, effortBefore = 0.0, peakArousal = 0.0;
+ var peakEffort = 0.0;
+ for (var i = 0; i < 1500; i++)
+ {
+ twin.Step(0.01, new PhysiologyInput(arousalBefore, effortBefore));
+ a.Tick(NoPoint, NoPoint, NoPoint, ReadOnlySpan.Empty, s, q, loud);
+ Assert.Equal(twin.BloodOxygen, p.BloodOxygen);
+ Assert.Equal(twin.BrainOxygen, p.BrainOxygen);
+ arousalBefore = a.Drive.Arousal;
+ effortBefore = ((double)s[0] + s[1]) / 2.0;
+ peakArousal = Math.Max(peakArousal, arousalBefore);
+ peakEffort = Math.Max(peakEffort, effortBefore);
+ }
+
+ Assert.True(peakArousal > 0.1, $"arousal never rose: {peakArousal}");
+ Assert.True(peakEffort > 0.1, $"no strength was applied: {peakEffort}");
+ }
+
+ [Fact]
+ public void A_healthy_physiology_changes_nothing_bit_for_bit()
+ {
+ foreach (var seed in new ulong[] { 1, 2, 3 })
+ {
+ var plain = new PainBoxReplay(seed);
+ var with = new PainBoxReplay(seed, physiology: Make3());
+ for (var i = 0; i < 4000; i++)
+ {
+ var on = i < 2500;
+ Assert.Equal(plain.Tick(on), with.Tick(on));
+ var a = plain.Actor.Drive;
+ var b = with.Actor.Drive;
+ Assert.Equal(BitConverter.DoubleToInt64Bits(a.Pain), BitConverter.DoubleToInt64Bits(b.Pain));
+ Assert.Equal(BitConverter.DoubleToInt64Bits(a.Strain), BitConverter.DoubleToInt64Bits(b.Strain));
+ Assert.Equal(BitConverter.DoubleToInt64Bits(a.Resolve), BitConverter.DoubleToInt64Bits(b.Resolve));
+ Assert.Equal(a.Consciousness, b.Consciousness);
+ Assert.Equal(plain.Actor.GoalIndex, with.Actor.GoalIndex);
+ Assert.Equal(plain.Strengths, with.Strengths);
+ }
+
+ Assert.True(plain.Actor.Drive.Breaks > 0 && plain.Actor.GoalIndex == 1, "the replay never reached the withdraw goal");
+ }
+ }
+
+ /// The measuring loop lives here, fully optimised from its first call, so the tier-up and its first-tier instrumentation cannot allocate inside the measurement; only Actor.Tick's own bytes are counted.
+ [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining | System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization)]
+ private static long AllocatedByTicking(Actor a, BoxStimulus[] box, float[] s, Quat[] q, int n)
+ {
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < n; i++) a.Tick(NoPoint, NoPoint, NoPoint, box, s, q);
+ return GC.GetAllocatedBytesForCurrentThread() - before;
+ }
+
+ [Fact]
+ public void A_tick_with_a_physiology_and_eight_bleeding_afflictions_allocates_nothing()
+ {
+ var p = new Physiology(Body3(), Plan3(blood: new BloodDef(1000.0, 0.5, 1e-4), slots: 9, organism: new[] { Hypoxia }), 20);
+ for (var i = 0; i < 4; i++)
+ {
+ Assert.True(p.Afflict(Af("Bleeder"), 1 + i % 2, 0, 0.5 + 0.1 * i));
+ Assert.True(p.Afflict(Af("Clot"), 0, RootMuscle, 1.0));
+ }
+
+ Assert.True(p.Afflict(Af("Choke"), 0, 0, 0.8)); // the gases run and the hypoxia curve reads, through the warm-up and into the measured ticks
+
+ var a = Make(p);
+ var s = new float[2];
+ var q = new Quat[2];
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.5 } };
+ for (var i = 0; i < 2000; i++) a.Tick(NoPoint, NoPoint, NoPoint, box, s, q); // warm the JIT and the first-use paths
+
+ Assert.Equal(0L, AllocatedByTicking(a, box, s, q, 10000));
+ Assert.False(p.Dead);
+ Assert.Equal(8, Live(p));
+ Assert.True(p.Bleed(0) > 0.0 && p.Bleed(1) > 0.0);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ActorTests.cs b/tests/Lodur.Core.Tests/ActorTests.cs
new file mode 100644
index 0000000..2223437
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ActorTests.cs
@@ -0,0 +1,189 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class ActorTests
+{
+ [Fact]
+ public void Parity_seed_1_breaks_at_14730_ms_switches_goal_at_14830_ms_with_16_flinches()
+ {
+ var (broke, withdrew, flinches) = new PainBoxReplay(1).Run(120.0);
+ Assert.Equal(1473, broke);
+ Assert.Equal(1483, withdrew);
+ Assert.Equal(16, flinches);
+ }
+
+ [Fact]
+ public void Reflex_gain_is_set_ahead_of_time_suppression_uses_the_previous_resolve()
+ {
+ // Drain hard so resolve moves a lot on every tick; then the previous and the current resolve differ visibly.
+ var drive = new DriveParameters { ResolveDrainPain = 8.0, ResolveDrainStrain = 8.0 };
+ var w = new WithdrawalParameters();
+ var r = new PainBoxReplay(1, drive: drive);
+ var checkedTicks = 0;
+ while (r.Actor.TickCount < 3000 && !r.Actor.Drive.WillBroken)
+ {
+ var before = r.Actor.Drive;
+ r.Tick();
+ var after = r.Actor.Drive;
+ var afferent = r.Actor.Afferent(0);
+ if (before.Resolve < 0.9 && afferent > 0.2 && before.Resolve - after.Resolve > 1e-4 && !after.WillBroken)
+ {
+ var load = afferent * (w.MaxSuppression * before.Resolve);
+ var viaPrevious = before.Strain + PainBoxReplay.Dt * (load - 0.1 * before.Strain);
+ var viaCurrent = before.Strain + PainBoxReplay.Dt * (afferent * (w.MaxSuppression * after.Resolve) - 0.1 * before.Strain);
+ Assert.Equal(viaPrevious, after.Strain, 12);
+ Assert.True(Math.Abs(viaCurrent - after.Strain) > 1e-7);
+ checkedTicks++;
+ }
+ }
+ Assert.True(checkedTicks > 10);
+ }
+
+ [Fact]
+ public void Suppression_is_never_free_pain_is_identical_and_only_the_suppressed_run_accumulates_strain()
+ {
+ var held = new PainBoxReplay(2);
+ var free = new PainBoxReplay(2, withdrawal: new WithdrawalParameters { MaxSuppression = 0.0 });
+ for (var i = 0; i < 1000; i++)
+ {
+ held.Tick();
+ free.Tick();
+ Assert.Equal(free.Actor.Drive.Pain, held.Actor.Drive.Pain);
+ Assert.Equal(0.0, free.Actor.Drive.Strain);
+ }
+ Assert.True(held.Actor.Drive.Strain > 0.5);
+ Assert.True(held.Actor.Drive.Pain > 0.1);
+ }
+
+ [Fact]
+ public void A_broken_will_releases_suppression_and_the_deliberate_goal_switch_follows_its_latency()
+ {
+ var r = new PainBoxReplay(1);
+ long broke = -1, withdrew = -1;
+ var strain = 0.0;
+ for (long i = 0; i < 1600; i++)
+ {
+ var e = r.Tick();
+ if (broke >= 0)
+ {
+ // Nothing is held down any more: strain only decays, and a broken will stays broken.
+ Assert.True(r.Actor.Drive.WillBroken);
+ Assert.True(r.Actor.Drive.Strain < strain);
+ }
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ Assert.Equal(withdrew >= 0 ? 1 : 0, r.Actor.GoalIndex); // 0 until GoalChanged, 1 from it
+ strain = r.Actor.Drive.Strain;
+ if (withdrew >= 0) break;
+ }
+ Assert.Equal(broke + 10, withdrew); // round(0.1 s / 10 ms)
+ // From GoalChanged the behaviour is the release behaviour's: the withdraw pose whatever the leak.
+ Assert.Equal(PainBoxReplay.Withdraw[0].X, r.Targets[0].X, 5);
+ Assert.Equal(PainBoxReplay.Withdraw[1].Z, r.Targets[1].Z, 5);
+ Assert.Equal(PainBoxReplay.Withdraw[0].W, r.Targets[0].W, 5);
+ }
+
+ [Fact]
+ public void Resolve_recovers_when_the_box_goes_quiet_and_not_when_recovery_is_off()
+ {
+ static double Resolve(double recovery)
+ {
+ var r = new PainBoxReplay(1, drive: new DriveParameters { ResolveRecovery = recovery });
+ for (var i = 0; i < 400; i++) r.Tick(); // 4 s in the box: resolve is down a little, will intact
+ var low = r.Actor.Drive.Resolve;
+ Assert.InRange(low, 0.85, 0.97);
+ for (var i = 0; i < 20000; i++) r.Tick(boxOn: false); // 200 s quiet: pain falls under the recovery line
+ Assert.False(r.Actor.Drive.WillBroken);
+ return r.Actor.Drive.Resolve - low;
+ }
+ Assert.True(Resolve(0.02) > 0.04); // recovers what it lost
+ Assert.True(Resolve(0.0) <= 0.0); // with recovery off it never rises (lingering pain still drains it)
+ }
+
+ [Fact]
+ public void A_flinch_is_a_suppressed_reflex_leaking_so_none_is_reported_after_the_will_breaks()
+ {
+ // Across seeds, some runs have a leak over the threshold, outside the refractory window, in the ticks
+ // between WillBroke and Withdrew (BDS counts none there). The golden table pins the totals; this pins the rule.
+ var sawLeakAfterBreak = 0;
+ for (ulong seed = 1; seed <= 60; seed++)
+ {
+ var r = new PainBoxReplay(seed);
+ var broke = false;
+ for (var i = 0; i < 4000; i++)
+ {
+ var e = r.Tick();
+ if (broke) Assert.Equal(0, (int)(e & TickEvents.Flinch));
+ broke |= (e & TickEvents.WillBroke) != 0;
+ if ((e & TickEvents.GoalChanged) != 0) break;
+ }
+ sawLeakAfterBreak += broke ? 1 : 0;
+ }
+ Assert.Equal(60, sawLeakAfterBreak);
+ }
+
+ private static long BreakTick(double intensity, double pull)
+ {
+ var (broke, _, _) = new PainBoxReplay(1, intensity, pull).Run(3000.0);
+ return broke;
+ }
+
+ [Fact]
+ public void Break_time_is_ordered_by_intensity_and_by_pull_and_no_stimulus_never_breaks()
+ {
+ long a = BreakTick(1.0, 0.5), b = BreakTick(0.8, 0.5), c = BreakTick(0.6, 0.5);
+ Assert.True(a > 0 && a < b && b < c, $"intensity: {a} {b} {c}");
+
+ long p0 = BreakTick(0.8, 0.0), p5 = BreakTick(0.8, 0.5), p8 = BreakTick(0.8, 0.8);
+ Assert.True(p0 > 0 && p0 < p5 && p5 < p8, $"pull: {p0} {p5} {p8}");
+
+ var quiet = new PainBoxReplay(1, intensity: 0.0);
+ for (var i = 0; i < 60000; i++) Assert.Equal(TickEvents.None, quiet.Tick());
+ Assert.Equal(0.0, quiet.Actor.Drive.Pain);
+ Assert.Equal(0.0, quiet.Actor.Drive.Strain);
+ Assert.Equal(1.0, quiet.Actor.Drive.Resolve);
+ Assert.False(quiet.Actor.Drive.WillBroken);
+ }
+
+ [Fact]
+ public void Tick_allocates_nothing_in_steady_state()
+ {
+ var r = new PainBoxReplay(1);
+ r.Tick(); // warm
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) r.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ }
+
+ [Fact]
+ public void Two_actors_ticked_interleaved_equal_the_same_actors_ticked_alone()
+ {
+ const int n = 2500;
+ var a1 = new PainBoxReplay(1);
+ var b1 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
+ var a2 = new PainBoxReplay(1);
+ var b2 = new PainBoxReplay(7, intensity: 0.6, pull: 0.2);
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+
+ static void Same(PainBoxReplay x, PainBoxReplay y)
+ {
+ Assert.Equal(x.Actor.Drive.Pain, y.Actor.Drive.Pain);
+ Assert.Equal(x.Actor.Drive.Strain, y.Actor.Drive.Strain);
+ Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
+ Assert.Equal(x.Actor.Drive.WillBroken, y.Actor.Drive.WillBroken);
+ Assert.Equal(x.Actor.Afferent(0), y.Actor.Afferent(0));
+ Assert.Equal(x.Actor.Stimulus(0), y.Actor.Stimulus(0));
+ Assert.Equal(x.Actor.GoalIndex, y.Actor.GoalIndex);
+ Assert.Equal(x.Actor.TickCount, y.Actor.TickCount);
+ Assert.Equal(x.Strengths, y.Strengths);
+ Assert.Equal(x.Targets, y.Targets);
+ }
+ Same(a1, a2);
+ Same(b1, b2);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/AirwayBleedTests.cs b/tests/Lodur.Core.Tests/AirwayBleedTests.cs
new file mode 100644
index 0000000..ee67c66
--- /dev/null
+++ b/tests/Lodur.Core.Tests/AirwayBleedTests.cs
@@ -0,0 +1,344 @@
+using Lodur;
+using static Lodur.Core.Tests.PhysioFixtures;
+
+namespace Lodur.Core.Tests;
+
+///
+/// A wound in an airway tissue bleeds into the airway: the bleed splits at the tissue by its AirwayShare, the airway share enters at the caller's blood gain, and a full airway spills
+/// through the mouth (idea bds-slice-map.gain-at-circulation-boundary; rulings bds-drown-in-own-blood-first, bds-blood-gain-simulated, bds-airway-cough-hold-drain).
+/// The rule tests run on Body3 / Plan3 with a root muscle given an AirwayShare and a Bleeder (1e-3 m^3/s at severity 1, vascularity 1) on it.
+///
+public sealed class AirwayBleedTests
+{
+ private const double Dt = 0.01;
+ private const double Rate = 1e-3;
+
+ private static void Near(double expected, double actual) => Assert.InRange(Math.Abs(expected - actual), 0.0, 1e-12 * Math.Abs(expected));
+
+ [Theory]
+ [InlineData(0.25)]
+ [InlineData(0.0)]
+ [InlineData(1.0)]
+ public void A_tissues_bleed_splits_by_its_airway_share_and_the_blood_falls_by_both(double share)
+ {
+ var p = Bleeding(share, 1.0);
+ p.Step(Dt);
+ Assert.Equal(Rate * (1.0 - share), p.Bleed(0), 15);
+ Assert.Equal(Rate * share, p.AirwayBleed, 15);
+ Assert.Equal(0.0, p.Bleed(1));
+ Assert.Equal(0.0, p.Bleed(2));
+ var drop = 0.005 - p.BloodVolume;
+ Assert.Equal(Dt * (p.Bleed(0) + p.Bleed(1) + p.Bleed(2) + p.AirwayBleed), drop, 15);
+ Assert.Equal(Dt * Rate, drop, 15);
+ }
+
+ [Theory]
+ [InlineData(1.0, false)]
+ [InlineData(10.0, false)]
+ [InlineData(1.0, true)]
+ [InlineData(10.0, true)]
+ public void Blood_enters_the_airway_at_the_gain_held_breath_or_not(double gain, bool held)
+ {
+ var p = Bleeding(1.0, gain);
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, held));
+ Near(Dt * gain * p.AirwayBleed, p.AirwayLiquid);
+ Near(Dt * gain * Rate, p.AirwayLiquid);
+ Assert.Equal(0.0, p.Coughed);
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(10.0)]
+ [InlineData(0.1)]
+ public void The_gain_is_applied_once_at_airway_entry_and_not_to_the_circulation_or_the_readouts(double gain)
+ {
+ const double share = 0.25;
+ var p = Bleeding(share, gain);
+ p.Step(Dt);
+ // Real m^3/s and real blood volume are ungained at any gain; only the airway's intake is.
+ Assert.Equal(Rate * (1.0 - share), p.Bleed(0), 15);
+ Assert.Equal(Rate * share, p.AirwayBleed, 15);
+ Near(Dt * Rate, 0.005 - p.BloodVolume);
+ Near(gain * Dt * Rate * share, p.AirwayLiquid);
+ }
+
+ [Fact]
+ public void A_breath_into_a_full_airway_spills_exactly_nothing_whatever_the_draw()
+ {
+ // The spill is only what bled in: a draw into a full airway must leave Drained exactly 0, not a rounding residue (after - Capacity - drawRaw leaves up to ~1e-20).
+ for (var k = 0; k < 400; k++)
+ {
+ var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
+ var wet = new AirwaySample(1e-4 * (1.0 + 0.0371 * k), 0.0, 0.0);
+ for (var i = 0; i < 200; i++)
+ {
+ p.Step(Dt * (1.0 + 0.013 * k), new PhysiologyInput(0.0, 0.0, false, wet));
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
+ }
+ }
+
+ [Fact]
+ public void A_full_airway_spills_what_bleeds_into_it_through_the_mouth()
+ {
+ // Share 1, gain 10, a drain the sample opens (Drop at DrainDrop): fill, then 600 more steps.
+ var air = Quiet with { DrainPerSecond = 0.1 };
+ var p = Bleeding(1.0, 10.0, air, new BloodDef(1.0, 0.5, 0.0));
+ var drop = new AirwaySample(0.0, 0.0, air.DrainDrop);
+ double bledIn = 0.0, out_ = 0.0;
+ var steps = 0;
+ for (; p.AirwayLiquid < air.Capacity && steps < 100000; steps++) Step();
+ Assert.Equal(air.Capacity, p.AirwayLiquid);
+ for (var i = 0; i < 600; i++) Step();
+ Assert.Equal(air.Capacity, p.AirwayLiquid);
+ Assert.True(out_ > 0.0);
+ Near(10.0 * bledIn, out_ + p.AirwayLiquid);
+
+ void Step()
+ {
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
+ bledIn += p.AirwayBleed * Dt;
+ out_ += p.Coughed + p.Drained;
+ }
+ }
+
+ [Fact]
+ public void Every_airway_flow_is_at_least_zero_at_any_cough_rate()
+ {
+ // Drained was removed - Coughed + spill, with Coughed = removed x cough / total: for a cough that is not a power of two the product can exceed removed by an ulp and Drained read -5e-23 (BDS refuses a negative drain).
+ // Fill the airway, then clear it with drain on and off, and read every flow every step.
+ var humanoid = PhysiologyPlans.Humanoid().Airway;
+ var rates = new List { 0.3, 0.36, 0.24, 2.0, humanoid.CoughPerSecond };
+ for (var k = 1; k <= 300; k++) rates.Add(0.01 * k);
+ foreach (var rate in rates)
+ {
+ foreach (var drop in new[] { 0.0, 0.5 * humanoid.DrainDrop, humanoid.DrainDrop })
+ {
+ var air = humanoid with { CoughPerSecond = rate };
+ var p = new Physiology(Body3(), Plan3(airway: air), 20.0);
+ var flood = new AirwaySample(100.0 * air.HoldAt, 0.0, drop);
+ var clear = new AirwaySample(0.0, 0.0, drop);
+ for (var i = 0; i < 1500; i++)
+ {
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, i < 100 ? flood : clear));
+ var at = $"cough {rate} drop {drop} step {i}";
+ Assert.True(p.Coughed >= 0.0, $"{at}: Coughed {p.Coughed:R}");
+ Assert.True(p.Drained >= 0.0, $"{at}: Drained {p.Drained:R}");
+ Assert.True(p.AirwayBleed >= 0.0 && p.DrawnLive >= 0.0 && p.DrawnPooled >= 0.0, $"{at}: a flow is negative");
+ Assert.True(p.AirwayLiquid >= 0.0, $"{at}: liquid {p.AirwayLiquid:R}");
+ }
+ }
+ }
+ }
+
+ [Fact]
+ public void A_breath_draws_only_into_the_room_left()
+ {
+ var p = Make(); // no wound: nothing bleeds
+ var pp = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
+ var wet = new AirwaySample(1e-3, 0.0, 0.0);
+ for (var i = 0; i < 100 && pp.AirwayLiquid < Quiet.Capacity; i++) pp.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
+ Assert.Equal(Quiet.Capacity, pp.AirwayLiquid);
+ for (var i = 0; i < 100; i++)
+ {
+ pp.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
+ Assert.Equal(Quiet.Capacity, pp.AirwayLiquid);
+ Assert.Equal(0.0, pp.Drained);
+ Assert.Equal(0.0, pp.Coughed);
+ Assert.Equal(0.0, pp.DrawnLive);
+ Assert.Equal(0.0, pp.DrawnPooled);
+ }
+
+ Assert.Equal(0.0, p.AirwayBleed);
+ }
+
+ [Fact]
+ public void A_breath_reports_what_it_drew_split_by_the_airways_weights()
+ {
+ var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(2e-5, 6e-5, 0.0)));
+ Near(Dt * 2e-5, p.DrawnLive);
+ Near(Dt * 6e-5, p.DrawnPooled);
+
+ var half = new Physiology(Body3(), Plan3(airway: Quiet with { PooledWeight = 0.5 }), 20.0);
+ half.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(2e-5, 6e-5, 0.0)));
+ Near(Dt * 2e-5, half.DrawnLive);
+ Near(Dt * 3e-5, half.DrawnPooled);
+ }
+
+ [Fact]
+ public void A_nearly_full_airway_draws_only_the_room_left()
+ {
+ var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
+ var wet = new AirwaySample(1e-3, 3e-3, 0.0);
+ for (var i = 0; i < 100 && p.AirwayLiquid < Quiet.Capacity; i++)
+ {
+ var room = Quiet.Capacity - p.AirwayLiquid;
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
+ if (Dt * 4e-3 > room)
+ {
+ Near(room, p.DrawnLive + p.DrawnPooled);
+ Near(0.25, p.DrawnLive / (p.DrawnLive + p.DrawnPooled));
+ Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
+ }
+ }
+
+ Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
+ }
+
+ [Fact]
+ public void A_held_breath_draws_nothing_while_the_airway_bleeds()
+ {
+ var p = Bleeding(1.0, 10.0);
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, true, new AirwaySample(1e-4, 1e-4, 0.0)));
+ Assert.Equal(0.0, p.DrawnLive);
+ Assert.Equal(0.0, p.DrawnPooled);
+ Near(Dt * 10.0 * Rate, p.AirwayLiquid);
+ }
+
+ [Fact]
+ public void The_airways_liquid_is_conserved_with_the_draw()
+ {
+ var p = Bleeding(0.5, 10.0, InertAirway, new BloodDef(1.0, 0.5, 0.0));
+ var rng = new Random(7);
+ var drew = 0.0;
+ for (var i = 0; i < 2000; i++)
+ {
+ var before = p.AirwayLiquid;
+ var sample = new AirwaySample(rng.NextDouble() * 1e-4, rng.NextDouble() * 1e-4, rng.NextDouble() * InertAirway.DrainDrop);
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, rng.NextDouble() < 0.2, sample));
+ Assert.True(p.DrawnLive >= 0.0 && p.DrawnPooled >= 0.0);
+ var expected = Dt * 10.0 * p.AirwayBleed + p.DrawnLive + p.DrawnPooled - p.Coughed - p.Drained;
+ Assert.InRange(Math.Abs(p.AirwayLiquid - before - expected), 0.0, 1e-18);
+ drew += p.DrawnLive + p.DrawnPooled;
+ }
+
+ Assert.True(drew > 0.0);
+ }
+
+ [Fact]
+ public void A_dry_sample_draws_exactly_zero_not_nan()
+ {
+ var p = new Physiology(Body3(), Plan3(airway: Quiet), 20.0);
+ for (var i = 0; i < 10; i++)
+ {
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0)));
+ Assert.Equal(0.0, p.DrawnLive);
+ Assert.Equal(0.0, p.DrawnPooled);
+ }
+
+ var b = Bleeding(1.0, 10.0);
+ b.Step(Dt, new PhysiologyInput(0.0, 0.0, false));
+ Assert.Equal(0.0, b.DrawnLive);
+ Assert.Equal(0.0, b.DrawnPooled);
+ }
+
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(10.0)]
+ public void The_dying_step_into_a_full_airway_draws_nothing(double gain)
+ {
+ var p = Bleeding(0.5, gain, Quiet, new BloodDef(0.005, 0.5, 0.0));
+ var wet = new AirwaySample(1e-5, 1e-5, 0.0);
+ for (var i = 0; i < 100000 && !p.Dead; i++) p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, wet));
+ Assert.True(p.Dead);
+ Assert.Equal(Quiet.Capacity, p.AirwayLiquid);
+ Assert.Equal(0.0, p.DrawnLive);
+ Assert.Equal(0.0, p.DrawnPooled);
+ }
+
+ [Fact]
+ public void The_dying_step_reports_its_draw_and_the_next_step_none()
+ {
+ var p = Bleeding(0.5, 0.1, InertAirway);
+ var pooled = new AirwaySample(1e-6, 1e-6, InertAirway.DrainDrop);
+ for (var i = 0; i < 100000 && !p.Dead; i++) p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, pooled));
+ Assert.True(p.Dead);
+ Assert.True(p.DrawnPooled > 0.0);
+ Assert.True(p.DrawnLive > 0.0);
+
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, pooled));
+ Assert.Equal(0.0, p.DrawnLive);
+ Assert.Equal(0.0, p.DrawnPooled);
+ }
+
+ [Fact]
+ public void The_dying_step_reports_its_flows_and_the_next_step_none()
+ {
+ var p = Bleeding(0.5, 1.0, InertAirway); // cough 2/s and a drain, so Coughed and Drained read above 0 while it bleeds into the airway
+ var drop = new AirwaySample(0.0, 0.0, InertAirway.DrainDrop);
+ double lost = 0.0;
+ for (var i = 0; i < 100000 && !p.Dead; i++)
+ {
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
+ lost += Dt * (p.Bleed(0) + p.Bleed(1) + p.Bleed(2) + p.AirwayBleed);
+ }
+
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.BloodLoss, p.Cause);
+ Assert.True(p.Bleed(0) > 0.0 && p.AirwayBleed > 0.0);
+ Near(0.005 - p.BloodVolume, lost);
+ Assert.True(p.Coughed > 0.0 && p.Drained > 0.0);
+
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, drop));
+ Assert.Equal(0.0, p.Bleed(0));
+ Assert.Equal(0.0, p.AirwayBleed);
+ Assert.Equal(0.0, p.Coughed);
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ [Fact]
+ public void A_cut_larynx_fills_the_humanoids_airway_at_the_gain()
+ {
+ var body = BodyPlans.Humanoid();
+ var plan = PhysiologyPlans.Humanoid();
+ var head = body.PartIndex("Head");
+ var cut = plan.AfflictionIndex("Cut");
+
+ double Seconds(double gain)
+ {
+ var p = new Physiology(body, plan, 20.0, gain);
+ Assert.True(p.Afflict(cut, head, p.TissueIndex(head, "Larynx"), 60));
+ var input = new PhysiologyInput(0.5, 0.5);
+ for (var i = 0; i < 3.05 * 120; i++)
+ {
+ p.Step(1.0 / 120.0, input);
+ if (p.Occlusion >= 0.99) return (i + 1) / 120.0;
+ }
+
+ return double.PositiveInfinity;
+ }
+
+ Assert.True(Seconds(10.0) <= 3.05);
+ Assert.True(double.IsPositiveInfinity(Seconds(1.0))); // at gain 1 it takes 31 s (probe): a dropped gain misses the bound
+
+ // Larynx and Trachea are cores with share 1, the lungs 0.5, every other tissue 0.
+ foreach (var part in plan.Parts)
+ {
+ foreach (var t in part.Tissues)
+ {
+ if (t.Label is "Larynx" or "Trachea") { Assert.Equal(0.0, t.Thickness); Assert.Equal(1.0, t.AirwayShare); }
+ else if (t.Label is "LungLeft" or "LungRight") Assert.Equal(0.5, t.AirwayShare);
+ else Assert.Equal(0.0, t.AirwayShare);
+ }
+ }
+ }
+
+ [Fact]
+ public void Shares_and_gains_the_physiology_cannot_run_on_are_refused()
+ {
+ foreach (var bad in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity })
+ {
+ var root = new[] { new TissueDef("brain", 10, 1, Consciousness: 1) { AirwayShare = bad } };
+ Assert.Throws(() => Plan3(root: root));
+ }
+
+ foreach (var bad in new[] { 0.0, -1.0, double.PositiveInfinity, double.NaN })
+ {
+ Assert.Throws(() => new Physiology(Body3(), Plan3(), 20.0, bad));
+ }
+ }
+}
diff --git a/tests/Lodur.Core.Tests/AirwayPhysiologyTests.cs b/tests/Lodur.Core.Tests/AirwayPhysiologyTests.cs
new file mode 100644
index 0000000..66d9023
--- /dev/null
+++ b/tests/Lodur.Core.Tests/AirwayPhysiologyTests.cs
@@ -0,0 +1,459 @@
+using Lodur;
+using static Lodur.Core.Tests.PhysioFixtures;
+
+namespace Lodur.Core.Tests;
+
+///
+/// Air hunger, the struggle it drives, the breath held on will and ended by a gasp, cough and drainage (rulings bds-airway-cough-hold-drain, bds-asphyxia-real-time).
+/// The timed tests run on the real Actor over a Body3 with a lung and the humanoid's respiration and airway, at 120 Hz and slow scale 1 and 20 (the gases are on the Acute clock, so the
+/// readings are identical). Every bound is a deterministic one (ruling deterministic-bound-margin): the geometric midpoint of the shipped worst and the least claimed mutant, or the
+/// ruled literature window where that is tighter; a zero reading counts as half a unit for the shipped side and a whole unit for a mutant (ruling deterministic-bound-zero-reading).
+///
+public sealed class AirwayPhysiologyTests
+{
+ private const double Dt = 1.0 / 120.0;
+ private static readonly float[] NoPoint = { 0f };
+
+ /// The humanoid's HoldAt: the liquid at the openings at which the breath is held.
+ private static readonly double HoldAt = PhysiologyPlans.Humanoid().Airway.HoldAt;
+
+ private static readonly double Capacity = PhysiologyPlans.Humanoid().Airway.Capacity;
+
+ /// The humanoid's DrawPerSecond, a placeholder: the tests that read what a free breath draws read it from here.
+ private static readonly double Draw = PhysiologyPlans.Humanoid().Airway.DrawPerSecond;
+
+ private static Brain RestOnly() => new()
+ {
+ Goals = new[]
+ {
+ new GoalSpec
+ {
+ Id = "rest", Priority = 0.0,
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.7f } },
+ },
+ },
+ };
+
+ private static Actor Real(Physiology p, Brain brain, WithdrawalParameters? breath = null) =>
+ new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, physiology: p, breath: breath);
+
+ private static Physiology Smothered(double slowScale)
+ {
+ var p = Breather(slowScale);
+ Assert.True(p.Afflict(Af("Choke"), 0, 0, 1e9));
+ return p;
+ }
+
+ private readonly record struct Smother(double Struggle, double Out, double Dead, double Effort, double Arousal30, DeathCause Cause);
+
+ /// Smothers (Breathing 0 for good) a real Actor with no stimulus: when the struggle goal took over, when consciousness first fell to 0.1, when it died, the mean strength written while awake, and the arousal at 30 s.
+ private static Smother Suffocate(double slowScale, Brain brain)
+ {
+ var p = Smothered(slowScale);
+ var a = Real(p, brain);
+ var s = new float[2];
+ var q = new Quat[2];
+ double struggle = -1, outAt = -1, deadAt = -1, arousal = -1, effort = 0;
+ long awake = 0;
+ for (long i = 0; i < (long)(500.0 / Dt) && !p.Dead; i++)
+ {
+ var e = a.Tick(NoPoint, NoPoint, NoPoint, default, s, q);
+ var t = (i + 1) * Dt;
+ if (struggle < 0 && a.GoalIndex == 1) struggle = t;
+ if (outAt < 0 && p.Consciousness <= 0.1) outAt = t;
+ if (outAt < 0)
+ {
+ effort += (s[0] + s[1]) / 2.0;
+ awake++;
+ }
+
+ if (arousal < 0 && t >= 30.0) arousal = a.Drive.Arousal;
+ if ((e & TickEvents.Died) != 0) deadAt = t;
+ }
+
+ return new Smother(struggle, outAt, deadAt, effort / awake, arousal, p.Cause);
+ }
+
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(20.0)]
+ public void Smothered_the_real_Actor_struggles_and_is_out_in_the_ruled_window(double slowScale)
+ {
+ // Shipped (placeholder content, probe and real Actor agree): struggle at 0.11 s, out 81.6 s, dead 154.3 s, mean awake effort 0.72. The fading-effort finding: the same Actor with only the rest goal
+ // (the will broken by arousal, the goal limp) is out at 219.8 s and dead at 308.4 s; with no deficit term the smothering is out at 100.0 and dead at 188.5 (2.0 and 1.22 times shipped: claimed).
+ // Bounds: out 60 (ruling) to 90 (the ruled 90 s, tighter than the midpoint 90.3), dead 134 (ruling) to 170.6 (midpoint of 154.3 and 188.5), effort 0.6 (shipped 0.72 is 1.2 above it; the rest-only reading 0.04 is 17 below).
+ var r = Suffocate(slowScale, StruggleBrain());
+ Assert.InRange(r.Struggle, 0.0, 2.0);
+ Assert.InRange(r.Out, 60.0, 90.0);
+ Assert.InRange(r.Dead, 134.0, 170.6);
+ Assert.Equal(DeathCause.Consciousness, r.Cause);
+ Assert.True(r.Effort > 0.6, $"mean awake effort {r.Effort}");
+ }
+
+ [Fact]
+ public void Without_a_struggle_goal_the_broken_will_goes_limp_and_the_window_is_missed()
+ {
+ // The finding, kept as a claim of the content: the rest goal alone is the will-weighted goal that the oxygen tests assumed fades only with consciousness.
+ var r = Suffocate(1.0, RestOnly());
+ Assert.True(r.Out > 150.0, $"out {r.Out}");
+ Assert.True(r.Effort < 0.2, $"effort {r.Effort}");
+ }
+
+ [Fact]
+ public void Air_hunger_raises_arousal_with_no_sensory_load()
+ {
+ // Shipped 0.75 at 30 s; with hunger kept out of the drive 0.0, which counts as one unit (0.01): the bound is sqrt(0.75 x 0.01) = 0.0866 (ruling deterministic-bound-zero-reading).
+ var r = Suffocate(1.0, RestOnly());
+ Assert.True(r.Arousal30 > 0.0866, $"arousal at 30 s {r.Arousal30}");
+ }
+
+ private readonly record struct Hold(double FirstLiquid, double MaxBeforeGasp, double Gasp, double WillAtGasp, double After, double Window);
+
+ /// A real Actor, calm and awake, with liquid at the airway openings from the first tick on, no opening below the sump.
+ private static Hold HoldUnderLiquid(double slowScale, WithdrawalParameters? breath = null, double attention = 1.0)
+ {
+ var p = Breather(slowScale);
+ var a = Real(p, StruggleBrain(), breath);
+ a.SetAttention(attention);
+ var s = new float[2];
+ var q = new Quat[2];
+ var liquid = new AirwaySample(2.0 * HoldAt, 0.0, 0.0);
+ double first = -1, max = 0, gasp = -1, will = -1, after = -1, window = -1;
+ for (long i = 0; i < (long)(200.0 / Dt); i++)
+ {
+ var e = a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, liquid);
+ var t = (i + 1) * Dt;
+ if (i == 0) first = p.AirwayLiquid;
+ if (gasp < 0)
+ {
+ if ((e & TickEvents.Gasp) != 0)
+ {
+ gasp = t;
+ will = a.Drive.Will;
+ }
+ else
+ {
+ max = Math.Max(max, p.AirwayLiquid);
+ }
+ }
+ else
+ {
+ if (window < 0 && t >= gasp + 0.25) window = p.AirwayLiquid;
+ if (t >= gasp + 1.0)
+ {
+ after = p.AirwayLiquid;
+ break;
+ }
+ }
+ }
+
+ return new Hold(first, max, gasp, will, after, window);
+ }
+
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(20.0)]
+ public void A_calm_awake_Fella_holds_his_breath_under_liquid_and_gasps_in_45_to_90_s(double slowScale)
+ {
+ // Shipped gasp 60.06 s (the will gives out first, at urge 0.30); inside the ruled 45-90 s with 1.34 and 1.5 to spare. The first tick draws one tick's inflow (the Actor decides the hold from what
+ // the step found), 2.6e-7 m^3; held, nothing more enters and the cough clears it, so the airway never holds more than that until the gasp. With inflow while held it climbs to the cough's balance, 1.6e-5 (60 times).
+ var h = HoldUnderLiquid(slowScale);
+ Assert.InRange(h.Gasp, 45.0, 90.0);
+ // Draw is a placeholder and decides this reading (the first tick's inflow is Draw x Breathing x liquid x dt): it is read from the content, not written here.
+ Assert.Equal(Draw * 1.0 * 2.0 * HoldAt * Dt, h.FirstLiquid, 12);
+ Assert.True(h.MaxBeforeGasp <= h.FirstLiquid * 1.0000001, $"airway liquid {h.MaxBeforeGasp} while held");
+ Assert.Equal(0.0, h.WillAtGasp);
+ // Placeholders deciding this test: Draw (the first-tick inflow, and the 1.35e-5 after the gasp); Cough (the airway never holds more than a tick's inflow while held, since it clears at once); HoldAt is
+ // content the test reads. The gasp draws the liquid in: a second later the airway holds 1.35e-5 (the held mutant 2.6e-7); the bound is their geometric mean.
+ Assert.True(h.After > 1.8e-6, $"airway liquid a second after the gasp {h.After}");
+ }
+
+ [Fact]
+ public void The_breath_gasps_when_the_hunger_leaks_past_a_will_that_still_holds()
+ {
+ // Suppression 0 and a low leak threshold: the urge itself crosses the threshold (carbon dioxide 0.54) long before the will gives out.
+ var h = HoldUnderLiquid(1.0, new WithdrawalParameters { MaxSuppression = 0.0, FlinchLeakThreshold = 0.05 });
+ var shipped = HoldUnderLiquid(1.0);
+ Assert.True(h.Gasp > 0.0 && h.Gasp < shipped.Gasp / 1.2, $"leak gasp {h.Gasp}, will gasp {shipped.Gasp}");
+ Assert.True(h.WillAtGasp > 0.0, "the will had not given out");
+ }
+
+ [Fact]
+ public void With_no_will_there_is_no_hold()
+ {
+ // The will is 0 (attention is the seam): the breath is never held, liquid is drawn at once and no gasp is ever reported. Shipped the airway fills to the cough's balance (1.56e-5) within 5 s;
+ // a hold not gated by will stays at one tick's inflow (2.6e-7): the bound is the geometric midpoint, sqrt(1.56e-5 x 2.6e-7) = 2.0e-6.
+ var p = Breather(20.0);
+ var a = Real(p, StruggleBrain());
+ a.SetAttention(0.0);
+ var s = new float[2];
+ var q = new Quat[2];
+ var liquid = new AirwaySample(2.0 * HoldAt, 0.0, 0.0);
+ for (long i = 0; i < (long)(5.0 / Dt); i++)
+ {
+ Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, liquid) & TickEvents.Gasp);
+ }
+
+ Assert.True(p.AirwayLiquid > 2.0e-6, $"airway liquid {p.AirwayLiquid}");
+ }
+
+ ///
+ /// Fills the airway with a flood (awake, the cough cannot keep up) until it is full, then smothers calmly with no liquid left at it until consciousness first falls to 0.1; returns that physiology,
+ /// the airway full. Calm and unventilated the blood store falls by its basal use alone (0.002 per second), so the fall to 0.1 takes 334.5 s; a Fella left face up dies 125 s later.
+ ///
+ private static Physiology Drowned()
+ {
+ var p = Breather(20.0);
+ var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
+ for (long i = 0; i < (long)(600.0 / Dt) && p.Consciousness > 0.1; i++) p.Step(Dt, flood);
+ Assert.True(p.Consciousness <= 0.1 && !p.Dead, $"consciousness {p.Consciousness}");
+ Assert.Equal(Capacity, p.AirwayLiquid);
+ return p;
+ }
+
+ /// The unconscious Fella, liquid no longer at the airway, with his lowest opening rim this far (m) below the deepest sump; steps for the given seconds.
+ private static Physiology Rolled(double drop, double seconds)
+ {
+ var p = Drowned();
+ var rolled = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, drop));
+ for (long i = 0; i < (long)(seconds / Dt) && !p.Dead; i++) p.Step(Dt, rolled);
+ return p;
+ }
+
+ [Theory]
+ [InlineData(0.05)]
+ [InlineData(0.025)]
+ public void Face_down_or_on_his_side_the_airway_drains_and_he_lives(double drop)
+ {
+ // Placeholders: Drain decides nothing here but whether it is above zero (a tiny drain restarts ventilation and the awake cough then clears the airway: probed at 0.1, 0.01, 0.001); Cough decides the recovery once he wakes.
+ // Out at 0.1 with the airway full, then drained at 0.1 (drop 0.05, face down) or 0.05 (drop 0.025, on his side) per second: back above 0.5 in 7.0 and 8.5 s (the bound is the 200 s simulated; a drain that waits on consciousness never comes). Face up it never drains and he dies (below).
+ var p = Rolled(drop, 200.0);
+ Assert.False(p.Dead);
+ Assert.True(p.Consciousness > 0.5, $"consciousness {p.Consciousness}");
+ Assert.True(p.AirwayLiquid < 1e-6, $"airway liquid {p.AirwayLiquid}");
+ }
+
+ [Theory]
+ [InlineData(0.0, 0.0)]
+ [InlineData(0.0125, 0.25)]
+ [InlineData(0.025, 0.5)]
+ [InlineData(0.05, 1.0)]
+ [InlineData(0.1, 1.0)]
+ public void The_drain_is_linear_in_drop_up_to_DrainDrop(double drop, double fraction)
+ {
+ // One step on the full airway with nothing at the openings: the cough is zero below 0.3 consciousness (he is out at 0.1), so what drained is dt x DrainPerSecond x clamp01(drop / DrainDrop) x Capacity,
+ // exact arithmetic (1e-12), not a measured bound. Half the rate at a pure side pose (drop 0.025, the mouth's half-width); the binary-drain and doubled-slope mutants read 1 at 0.025, and the quarter
+ // point (0.0125) kills a step at half.
+ var p = Drowned();
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, drop)));
+ Assert.Equal(0.0, p.Coughed);
+ Assert.Equal(fraction, p.Drained / (Dt * PhysiologyPlans.Humanoid().Airway.DrainPerSecond * Capacity), 12);
+ }
+
+ [Fact]
+ public void Face_up_the_airway_stays_full_and_he_dies_through_consciousness()
+ {
+ // Decided by the Cough curve (zero below 0.3 consciousness) and by drop (0 face up: no opening rim lies below the sump); Drain and Draw decide nothing here (nothing drains face up, nothing is drawn, none at the openings).
+ var p = Rolled(0.0, 600.0);
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.Consciousness, p.Cause);
+ Assert.Equal(Capacity, p.AirwayLiquid);
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ private static Physiology Flooded(int dims)
+ {
+ var p = Breather(20.0);
+ for (var d = 0; d < dims; d++) Assert.True(p.Afflict(Af("Dim"), 0, BrainLayer, 1.0));
+ var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
+ for (long i = 0; i < (long)(2.0 / Dt); i++) p.Step(Dt, flood);
+ Assert.Equal(Capacity, p.AirwayLiquid);
+ return p;
+ }
+
+ [Fact]
+ public void An_awake_Fella_coughs_his_airway_clear()
+ {
+ // Placeholders deciding this: Cough (0.3 per second, a continuous airway bleed must beat it: ruling bds-drown-in-own-blood-first) and every bound below; Draw only fills the half airway first and decides no outcome; Drain is 0 face up and decides nothing.
+ // Half the airway, awake, face up, nothing at the openings, 20 s. Readings (deterministic, ruling deterministic-bound-margin): the time for the liquid to fall to a quarter of the capacity (half of what it held)
+ // shipped 2.425 s, a cough at half the rate 4.867 s, cough 2.0 0.417 s; the liquid left after 20 s shipped 1.9e-7 m^3, half-rate 3.864e-6, no cough 7.8e-5; the total coughed (fraction of the capacity) shipped 0.515, no cough 0.
+ // Time bound (1.005, 3.436) = sqrt(2.425 x 0.417) and sqrt(2.425 x 4.867), separation 5.8 and 2.0: it claims cough 2.0 and the half-rate cough (a cough of 0.36 or 0.24 is not claimed). Liquid bound 8.6e-7 = sqrt(1.9e-7 x 3.864e-6),
+ // separation 20: it claims the half-rate and the missing cough. Coughed bound 0.0718 = sqrt(0.515 x 0.01), the zero reading's mutant counted as one unit of 0.01 (ruling deterministic-bound-zero-reading), separation 7.2.
+ var p = Breather(20.0);
+ var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, 0.0));
+ while (p.AirwayLiquid < 0.5 * Capacity) p.Step(Dt, flood);
+ var clear = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0));
+ double coughed = 0.0, quarter = -1.0;
+ for (long i = 0; i < (long)(20.0 / Dt); i++)
+ {
+ p.Step(Dt, clear);
+ coughed += p.Coughed;
+ if (quarter < 0.0 && p.AirwayLiquid < 0.25 * Capacity) quarter = (i + 1) * Dt;
+ }
+
+ Assert.True(quarter > 1.005 && quarter < 3.436, $"quarter at {quarter} s");
+ Assert.True(p.AirwayLiquid < 8.6e-7, $"airway liquid {p.AirwayLiquid}");
+ Assert.True(coughed > 0.0718 * Capacity, $"coughed {coughed}");
+ Assert.Equal(0.0, p.Drained);
+ }
+
+ [Fact]
+ public void A_stuporous_Fella_cannot_cough()
+ {
+ // Consciousness held at 0.2 by eight Dim afflictions, below the cough's 0.3: the Cough curve's knee (a placeholder) decides this; Drain decides nothing (face up).
+ var p = Flooded(8);
+ Assert.Equal(0.2, p.Consciousness, 9);
+ var clear = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, 0.0));
+ for (long i = 0; i < (long)(10.0 / Dt); i++)
+ {
+ p.Step(Dt, clear);
+ Assert.Equal(0.0, p.Coughed);
+ }
+
+ Assert.Equal(Capacity, p.AirwayLiquid);
+ }
+
+ [Theory]
+ [InlineData(1.0)]
+ [InlineData(20.0)]
+ public void Healthy_and_one_lung_bodies_feel_no_air_hunger_at_rest(double slowScale)
+ {
+ foreach (var lungLost in new[] { false, true })
+ {
+ var p = Breather(slowScale);
+ if (lungLost) Assert.True(p.Afflict(Af("Lesion"), 0, 2, 5.0)); // half the lung layer: Breathing 0.5
+ var a = Real(p, StruggleBrain());
+ var s = new float[2];
+ var q = new Quat[2];
+ for (long i = 0; i < (long)(600.0 / Dt); i++)
+ {
+ a.Tick(NoPoint, NoPoint, NoPoint, default, s, q);
+ Assert.Equal(0.0, p.BreathUrge);
+ Assert.Equal(0.0, a.Drive.AirHunger);
+ }
+
+ Assert.Equal(lungLost ? 0.5 : 1.0, p.Breathing);
+ Assert.True(p.CarbonDioxide < 0.5, $"carbon dioxide {p.CarbonDioxide}");
+ }
+ }
+
+ [Fact]
+ public void After_a_gasp_the_breath_is_free_for_its_window_before_it_is_held_again()
+ {
+ // The leak gasp (the will still holds): a quarter second later the breath is still free and the airway holds 6.2e-6 (Draw and Cough, placeholders, decide it); with no window (_held = willing) the
+ // breath is held the very next tick and the airway holds a tick's inflow, 2.6e-7 or less: the bound is their geometric mean, 1.3e-6.
+ var h = HoldUnderLiquid(1.0, new WithdrawalParameters { MaxSuppression = 0.0, FlinchLeakThreshold = 0.05 });
+ Assert.True(h.WillAtGasp > 0.0, "the will had not given out");
+ Assert.True(h.Window > 1.3e-6, $"airway liquid a quarter second after the gasp {h.Window}");
+ }
+
+ [Fact]
+ public void Liquid_below_the_hold_threshold_is_breathed_in_and_not_held()
+ {
+ // Liquid at the openings under HoldAt: the breath is not held, so the airway draws it in and never gasps. With the hold at any liquid the breath is held from the second tick and the airway keeps a tick's draw (6.5e-8). Shipped it holds 3.9e-6 after 5 s (Draw and Cough, placeholders); the bound is the geometric mean, 5.0e-7.
+ var p = Breather(20.0);
+ var a = Real(p, StruggleBrain());
+ var s = new float[2];
+ var q = new Quat[2];
+ var low = new AirwaySample(0.5 * HoldAt, 0.0, 0.0);
+ for (long i = 0; i < (long)(5.0 / Dt); i++)
+ {
+ Assert.Equal(TickEvents.None, a.Tick(NoPoint, NoPoint, NoPoint, default, s, q, default, low) & TickEvents.Gasp);
+ }
+
+ Assert.True(p.AirwayLiquid > 5.0e-7, $"airway liquid {p.AirwayLiquid}");
+ }
+
+ [Fact]
+ public void A_breath_draws_in_what_the_lung_ventilates()
+ {
+ // One step from empty (nothing to cough or drain yet): the inflow is Draw x Breathing x liquid x dt, and a lung half lost draws half. An inflow that ignores Breathing draws the same in both.
+ double Drawn(bool lungLost)
+ {
+ var p = Breather(20.0);
+ if (lungLost) Assert.True(p.Afflict(Af("Lesion"), 0, 2, 5.0));
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.5 * HoldAt, 0.0, 0.0)));
+ Assert.Equal(lungLost ? 0.5 : 1.0, p.Breathing);
+ return p.AirwayLiquid;
+ }
+
+ Assert.Equal(Draw * 1.0 * 0.5 * HoldAt * Dt, Drawn(false), 14);
+ Assert.Equal(Draw * 0.5 * 0.5 * HoldAt * Dt, Drawn(true), 14);
+ }
+
+ [Fact]
+ public void A_dead_body_feels_no_urge()
+ {
+ var p = Smothered(20.0);
+ double last = 0.0;
+ for (long i = 0; i < (long)(500.0 / Dt) && !p.Dead; i++)
+ {
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, default));
+ if (!p.Dead) last = p.BreathUrge;
+ }
+
+ Assert.True(p.Dead);
+ Assert.True(last > 0.5, $"urge the step before he died {last}");
+ Assert.Equal(0.0, p.BreathUrge);
+ }
+
+ [Fact]
+ public void An_airway_sample_is_the_sum_of_what_is_live_and_pooled_and_the_greatest_drop()
+ {
+ var s = AirwaySample.Of(new[] { 1f, 2f }, new[] { 0.5f }, new[] { -0.5f, 0.25f, -1f });
+ Assert.Equal(new AirwaySample(3.0, 0.5, 0.25), s);
+ Assert.Equal(new AirwaySample(1.0, 1.0, 0.0), AirwaySample.Of(new[] { 1f }, new[] { 1f }, new[] { -0.5f, -1f }));
+ Assert.Equal(new AirwaySample(0.0, 0.0, 0.0), AirwaySample.Of(default, default, default));
+ }
+
+ [Fact]
+ public void A_sample_outside_its_range_is_refused_before_anything_changes()
+ {
+ var p = Breather(20.0);
+ foreach (var bad in new[] { new AirwaySample(-1e-9, 0, 0), new AirwaySample(0, double.NaN, 0), new AirwaySample(double.PositiveInfinity, 0, 0), new AirwaySample(0, 0, -1e-9), new AirwaySample(0, 0, double.NaN), new AirwaySample(0, 0, double.PositiveInfinity) })
+ {
+ Assert.Throws(() => p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, bad)));
+ }
+
+ Assert.Equal(1.0, p.BloodOxygen);
+ Assert.Equal(0.0, p.AirwayLiquid);
+ p.Step(Dt, new PhysiologyInput(0.0, 0.0, false, new AirwaySample(1.0, 1.0, 0.05)));
+ }
+
+ [Fact]
+ public void An_airway_or_urge_curve_the_physiology_cannot_run_on_is_refused()
+ {
+ var h = PhysiologyPlans.Humanoid();
+ PhysiologyPlan With(RespirationDef? r = null, AirwayDef? w = null) =>
+ new(h.Parts, h.Afflictions, h.OrganismEffects, h.Blood, r ?? h.Respiration, w ?? h.Airway, h.AfflictionSlots);
+
+ With();
+ var ok = h.Airway;
+ foreach (var bad in new[]
+ {
+ ok with { Capacity = 0.0 }, ok with { Capacity = double.NaN }, ok with { DrawPerSecond = -1.0 }, ok with { HoldAt = double.PositiveInfinity },
+ ok with { CoughPerSecond = -0.1 }, ok with { DrainPerSecond = double.NaN }, ok with { DrainDrop = 0.0 }, ok with { DrainDrop = -0.01 }, ok with { DrainDrop = double.NaN },
+ ok with { CoughByConsciousness = Array.Empty<(double X, double Y)>() }, ok with { CoughByConsciousness = new[] { (1.0, 0.0), (0.0, 1.0) } },
+ ok with { LiveWeight = -1.0 }, ok with { PooledWeight = double.NaN },
+ })
+ {
+ Assert.Throws(() => With(w: bad));
+ }
+
+ var r = h.Respiration;
+ foreach (var bad in new[]
+ {
+ r with { CarbonDioxideRise = -1.0 }, r with { CarbonDioxideClear = double.NaN },
+ r with { UrgeByCarbonDioxide = Array.Empty<(double X, double Y)>() }, r with { UrgeByVentilationDeficit = new[] { (1.0, 0.0), (0.5, 1.0) } },
+ })
+ {
+ Assert.Throws(() => With(r: bad));
+ }
+
+ // The plan owns its curves: a caller editing the array it passed changes nothing.
+ var mine = new[] { (0.0, 0.0), (1.0, 1.0) };
+ var plan = With(r: r with { UrgeByCarbonDioxide = mine });
+ mine[1] = (1.0, 5.0);
+ Assert.Equal(1.0, plan.Respiration.UrgeByCarbonDioxide[1].Y);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ArmPathTests.cs b/tests/Lodur.Core.Tests/ArmPathTests.cs
new file mode 100644
index 0000000..40950bc
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ArmPathTests.cs
@@ -0,0 +1,465 @@
+using System;
+using Lodur;
+using Xunit.Abstractions;
+
+namespace Lodur.Core.Tests;
+
+///
+/// An arm's motion across ticks, owned by : the minimum-jerk hand path through a via point ahead of the trunk, taken only
+/// when the trunk is in the way (rulings reach-clears-body-by-via-point, reach-path-blocked-only), and the hand-off into and out of the arm layer,
+/// slewed at the output rate both ways (ruling ik-output-slew-limit, follow-up orient-s4-lows).
+///
+public sealed class ArmPathTests
+{
+ private const double Dt = 0.01;
+ private const uint Thing = 7;
+ private const float Step = (float)(ArmChain.MaxAngularRate * Dt);
+ private static readonly BodyPlan Plan = BodyPlans.Humanoid();
+ private static readonly int Joints = Plan.Joints.Count;
+ private static readonly BoxStimulus[] NoBoxes = Array.Empty();
+ private static readonly float[] Origin = { 0f };
+ private readonly ITestOutputHelper _output;
+
+ public ArmPathTests(ITestOutputHelper output) => _output = output;
+
+ private static (float X, float Y, float Z) Mirror((float X, float Y, float Z) p, Side side) => side == Side.Right ? p : (-p.X, p.Y, p.Z);
+
+ private static float Gap((float X, float Y, float Z) a, (float X, float Y, float Z) b) =>
+ MathF.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y) + (a.Z - b.Z) * (a.Z - b.Z));
+
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
+ /// Drives the arm with the body at its creation pose and the wrist where it hangs, or at .
+ private static bool Drive(ArmChain arm, (float X, float Y, float Z) goal, Quat baseShoulder, Quat baseElbow, double weight, out Quat shoulder, out Quat elbow,
+ (float X, float Y, float Z)? wrist = null)
+ {
+ var parent = Plan.Parts[arm.ParentPart];
+ var w = wrist ?? arm.WristAnchor;
+ return arm.Drive(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.X, goal.Y, goal.Z, w.X, w.Y, w.Z,
+ baseShoulder, baseElbow, weight, out shoulder, out elbow);
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void Blocked_is_decided_by_the_trunk_once_per_path_start(Side side)
+ {
+ // The hanging wrist to a goal across the chest and level with the torso: the straight segment touches the trunk. To a goal out to the
+ // arm's own side it stays clear of the trunk by more than the forearm radius.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var across = Mirror((-0.04f, 1.60f, 0.24f), side);
+ var aside = Mirror((-0.30f, 1.74f, 0.26f), side);
+
+ Drive(arm, across, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(arm.PathBlocked);
+ Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"the path starts at the wrist, not {arm.Aim}");
+
+ // Decided once: the goal moving clear of the trunk does not unblock the path.
+ Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(arm.PathBlocked);
+
+ arm.Restart();
+ Drive(arm, aside, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.False(arm.PathBlocked);
+ Assert.True(Gap(arm.Aim, aside) < 1e-4f, $"an unblocked reach solves the goal itself, not {arm.Aim}");
+ }
+
+ [Fact]
+ public void The_hand_path_is_minimum_jerk_through_the_via_point_and_meets_a_moving_goal()
+ {
+ var start = (0f, 1f, 0f);
+ var via = (0.1f, 1.2f, 0.3f);
+ var seg = ArmChain.PathSegmentSeconds;
+ var g0 = (0.5f, 1.5f, 0.4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0f), start) < 1e-4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, seg), via) < 1e-4f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 2f * seg), g0) < 1e-4f);
+ var mid = ((start.Item1 + via.Item1) / 2f, (start.Item2 + via.Item2) / 2f, (start.Item3 + via.Item3) / 2f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.5f * seg), mid) < 1e-4f, "midway in the first segment is the midpoint");
+ // Zero velocity at both ends of a segment: a tick in is far less than a linear tick in.
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g0, 0.01f * seg), start) < 1e-3f * Gap(start, via));
+
+ // A goal that has moved on during the second segment is met at its end, and the via point's offset shrinks to nothing on the way.
+ var g1 = (0.7f, 1.4f, 0.5f);
+ Assert.True(Gap(ArmChain.PathPoint(start, via, g0, g1, 2f * seg), g1) < 1e-4f);
+ var half = ArmChain.PathPoint(start, via, g0, g1, 1.5f * seg);
+ var want = (g1.Item1 + 0.5f * (via.Item1 - g0.Item1), g1.Item2 + 0.5f * (via.Item2 - g0.Item2), g1.Item3 + 0.5f * (via.Item3 - g0.Item3));
+ Assert.True(Gap(half, want) < 1e-4f);
+
+ // The chain follows it from the measured wrist: the via point is (wrist x, mid y, trunk front + clearance), the trunk front 0.09 m on the humanoid.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var wrist = arm.WristAnchor;
+ (float X, float Y, float Z) goal = (-0.04f, 1.60f, 0.24f);
+ (float X, float Y, float Z) viaWant = (wrist.X, 0.5f * (wrist.Y + goal.Y), 0.09f + ArmChain.ViaClearance);
+ var ticks = (int)Math.Round(2.0 * ArmChain.PathSegmentSeconds / Dt);
+ for (var i = 0; i <= ticks + 5; i++)
+ {
+ // The goal drifts 0.1 m forward over the path.
+ (float X, float Y, float Z) g = (goal.X, goal.Y, goal.Z + 0.1f * Math.Min(1f, i / (float)ticks));
+ Drive(arm, g, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ var t = i * (float)Dt;
+ if (i == 0) Assert.True(Gap(arm.Aim, wrist) < 1e-4f);
+ if (i == (int)Math.Round(0.5 * ArmChain.PathSegmentSeconds / Dt))
+ {
+ var half1 = ((wrist.X + viaWant.X) / 2f, (wrist.Y + viaWant.Y) / 2f, (wrist.Z + viaWant.Z) / 2f);
+ Assert.True(Gap(arm.Aim, half1) < 2e-3f, $"midway to the via point at {t} s: {arm.Aim}");
+ }
+
+ if (i == (int)Math.Round(ArmChain.PathSegmentSeconds / Dt))
+ {
+ Assert.True(Gap(arm.Aim, viaWant) < 2e-3f, $"at the via point at {t} s: {arm.Aim}");
+ }
+
+ if (i >= ticks)
+ {
+ Assert.True(Gap(arm.Aim, g) < 1e-4f, $"after the path the goal itself is solved for, not {arm.Aim}");
+ }
+ }
+ }
+
+ [Fact]
+ public void Slewed_by_the_actor_the_hand_off_moves_the_written_arm_targets_at_most_the_rate_both_ways_and_ends_in_the_base()
+ {
+ // A pose goal and a ward-off goal alternate as a sound comes and goes. Every tick, the shoulder and elbow targets of both arms move at most
+ // the rate times the tick, across engaging and disengaging; and once the arms have eased back they write exactly what the pose goal does.
+ var key = new Quat[Joints];
+ for (var m = 0; m < Joints; m++) key[m] = Quat.FromAxisAngle(0f, 0f, 1f, 0.02f * (m + 1));
+ var idle = Pose(key, null);
+ var ward = Pose(key, new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = 0.3f, Spread = 0.15f });
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = idle },
+ new GoalSpec
+ {
+ Id = "ward", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
+ Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
+ Behaviour = ward,
+ },
+ },
+ };
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 0.2 }, body: Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var previous = new Quat[Joints];
+ var strengths = new float[Joints];
+ var armJoints = new[] { Plan.JointIndex("Shoulder", Side.Left), Plan.JointIndex("Elbow", Side.Left), Plan.JointIndex("Shoulder", Side.Right), Plan.JointIndex("Elbow", Side.Right) };
+ var sound = new[] { new Emitter { Channel = Channel.Audio, X = 0.3f, Y = 1.5f, Z = 0.7f, Radius = 40f, Intensity = 1.0, Id = 1, Kind = Thing } };
+ var reference = new Quat[Joints];
+ idle.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], reference);
+
+ var (worst, engaged, released, restored) = (0f, 0, 0, 0);
+ var wasWard = false;
+ for (var i = 0; i < 1800; i++)
+ {
+ var on = (i / 150) % 2 == 0;
+ actor.Tick(Origin, Origin, Origin, NoBoxes, strengths, targets, on ? sound : Array.Empty(), parts: parts);
+ var ward1 = actor.GoalIndex == 1;
+ if (ward1 && !wasWard) engaged++;
+ if (!ward1 && wasWard) released++;
+ wasWard = ward1;
+ if (i > 0)
+ {
+ foreach (var m in armJoints) worst = MathF.Max(worst, Turn(previous[m], targets[m]));
+ }
+
+ if (!ward1 && i % 150 == 149 && !on)
+ {
+ // The arms have had the rest of the off-phase to ease back.
+ var same = true;
+ for (var m = 0; m < Joints; m++) same &= targets[m].Equals(reference[m]);
+ if (same) restored++;
+ }
+
+ Array.Copy(targets, previous, Joints);
+ }
+
+ _output.WriteLine($"worst per-tick change {worst:F5} rad against {Step}; engaged {engaged}, released {released}, written the base bit for bit at {restored} phase ends");
+ Assert.True(engaged >= 5 && released >= 5, $"the goals alternated too little to test the hand-off: {engaged}, {released}");
+ Assert.True(worst <= Step + 1e-5f, $"an arm target moved {worst} rad in one tick, the bound is {Step}");
+ Assert.True(worst > 0.5f * Step, $"the arms moved at most {worst} rad a tick, so the hand-off was not slewed at the rate");
+ Assert.True(restored >= 5, $"the arms wrote the base pose bit for bit at only {restored} of the off-phases");
+
+ static PoseBehaviour Pose(Quat[] key, ArmLayer? arms) => new()
+ {
+ Keys = new[] { key }, FlinchPose = Array.ConvertAll(key, _ => Quat.Identity), Arms = arms,
+ };
+ }
+
+ [Fact]
+ public void A_released_arm_stays_the_base_and_reset_and_restart_forget_the_path_and_the_hand_off()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var baseShoulder = Quat.FromAxisAngle(0f, 0f, 1f, 0.2f);
+ var baseElbow = Quat.FromAxisAngle(0f, 0f, 1f, -0.3f);
+ var goal = (-0.04f, 1.60f, 0.24f);
+
+ // An arm never driven writes the base untouched.
+ arm.Release(baseShoulder, baseElbow, out var s0, out var e0);
+ Assert.Equal(baseShoulder, s0);
+ Assert.Equal(baseElbow, e0);
+
+ for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ var held = Quat.Identity;
+ var converged = -1;
+ for (var i = 0; i < 100; i++)
+ {
+ arm.Release(baseShoulder, baseElbow, out var s, out var e);
+ if (i > 0) Assert.True(Turn(held, s) <= Step + 1e-5f, "the release moved the shoulder faster than the rate");
+ held = s;
+ if (converged < 0 && s.Equals(baseShoulder) && e.Equals(baseElbow)) converged = i;
+ if (converged >= 0) Assert.True(s.Equals(baseShoulder) && e.Equals(baseElbow), "a released arm left the base after arriving");
+ }
+
+ Assert.True(converged > 3, $"the arm was back on the base after {converged} ticks: it was not slewed");
+
+ // Reset forgets the hand-off: the arm is idle, so the base passes through at once.
+ for (var i = 0; i < 20; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ arm.Reset();
+ arm.Release(baseShoulder, baseElbow, out var s1, out var e1);
+ Assert.Equal(baseShoulder, s1);
+ Assert.Equal(baseElbow, e1);
+
+ // At half weight the written targets are the base blended toward the output, and the hand-off is continuous in them, not in the output.
+ var half = ArmChain.Of(Plan, Side.Right, Dt);
+ var writtenHalf = Quat.Identity;
+ for (var i = 0; i < 100; i++) Drive(half, goal, baseShoulder, baseElbow, 0.5, out writtenHalf, out _);
+ var released = 0f;
+ for (var i = 0; i < 20; i++)
+ {
+ half.Release(baseShoulder, baseElbow, out var sh, out _);
+ released = MathF.Max(released, Turn(writtenHalf, sh));
+ writtenHalf = sh;
+ }
+
+ Assert.True(released <= Step + 1e-5f, $"releasing at half weight moved the written shoulder {released} rad in a tick");
+
+ // Restart starts the path again at the measured wrist, keeping the output: the aim goes back to the wrist.
+ for (var i = 0; i < 100; i++) Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ Assert.True(Gap(arm.Aim, goal) < 1e-4f);
+ arm.Restart();
+ Drive(arm, goal, baseShoulder, baseElbow, 1.0, out _, out _);
+ Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"a restarted path begins at the measured wrist, not {arm.Aim}");
+ }
+
+ [Fact]
+ public void A_commit_restarts_both_arms_paths_from_the_measured_wrist()
+ {
+ // Reach across the body with the right arm, settled; the parts do not follow, so the measured wrist stays hanging. A tick after
+ // the rig is told of a commit, the arm is on a new path from that wrist and its output turns back toward it by a step; without
+ // the commit the settled output does not move.
+ var key = new Quat[Joints];
+ Array.Fill(key, Quat.Identity);
+ var b = new PoseBehaviour { Keys = new[] { key }, FlinchPose = key, Arms = new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right } };
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
+ var parts = Rest();
+ var target = new Percept(1, Thing, 0.3f, 1.45f, 0.5f, 1.0, 0.0);
+ var shoulder = Plan.JointIndex("Shoulder", Side.Right);
+ foreach (var commit in new[] { false, true })
+ {
+ var rig = new OrientRig(Plan, brain, Dt);
+ var targets = new Quat[Joints];
+ for (var i = 0; i < 100; i++) b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
+ var settled = targets[shoulder];
+ if (commit) rig.Commit();
+ b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], targets, new OrientInput(rig, parts, target, Side.Right));
+ var moved = Turn(settled, targets[shoulder]);
+ if (commit) Assert.True(moved > 0.5f * Step, $"after a commit the arm moved only {moved} rad");
+ else Assert.True(moved < 1e-4f, $"a settled arm moved {moved} rad without a commit");
+ }
+ }
+
+ [Fact]
+ public void The_actor_restarts_the_hand_path_when_it_commits_another_target()
+ {
+ // The right arm reaches across the body to a sound, settled. The parts do not follow, so the measured wrist stays hanging. A second,
+ // sound, a millimetre nearer, is committed a latency later and the arm starts a new path from that wrist, turning back by steps; with no second sound the
+ // settled arm does not move.
+ var key = new Quat[Joints];
+ Array.Fill(key, Quat.Identity);
+ PoseBehaviour Pose(ArmLayer? arms) => new() { Keys = new[] { key }, FlinchPose = key, Arms = arms };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = Pose(null) },
+ new GoalSpec
+ {
+ Id = "reach", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
+ Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
+ Behaviour = Pose(new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right }),
+ },
+ },
+ };
+ Emitter Sound(ulong id, float x, float y, float z) => new() { Channel = Channel.Audio, X = x, Y = y, Z = z, Radius = 40f, Intensity = 1.0, Id = id, Kind = Thing };
+ var shoulder = Plan.JointIndex("Shoulder", Side.Right);
+ foreach (var retarget in new[] { false, true })
+ {
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var first = new[] { Sound(1, 0.3f, 1.45f, 0.5f) };
+ var both = new[] { Sound(1, 0.3f, 1.45f, 0.5f), Sound(2, 0.3f, 1.45f, 0.499f) };
+ for (var i = 0; i < 150; i++) actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, first, parts: parts);
+ Assert.Equal(1UL, actor.TargetId);
+ var last = targets[shoulder];
+ var worst = 0f;
+ for (var i = 0; i < 100; i++)
+ {
+ actor.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, retarget ? both : first, parts: parts);
+ worst = MathF.Max(worst, Turn(last, targets[shoulder]));
+ last = targets[shoulder];
+ }
+
+ if (retarget)
+ {
+ Assert.Equal(2UL, actor.TargetId);
+ Assert.True(worst > 0.5f * Step, $"a committed retarget moved the arm at most {worst} rad in a tick");
+ }
+ else
+ {
+ Assert.True(worst < 1e-3f, $"a settled arm moved {worst} rad in a tick with nothing new");
+ }
+ }
+ }
+
+ [Fact]
+ public void The_hand_path_has_no_break_at_the_via_point_and_ends_on_the_goal()
+ {
+ // A static blocked goal: the aim moves no more than a minimum-jerk tick all the way (peak speed 1.875 D / T), through the hand-off between
+ // the two segments, and a segment that began on the via point instead of the goal would jump 0.3 m at the segment time.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var goal = (-0.04f, 1.60f, 0.24f);
+ var previous = arm.WristAnchor;
+ var worst = 0f;
+ for (var i = 0; i < 80; i++)
+ {
+ Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ if (i > 0) worst = MathF.Max(worst, Gap(arm.Aim, previous));
+ previous = arm.Aim;
+ }
+
+ Assert.True(arm.PathBlocked);
+ Assert.True(worst < 0.05f, $"the aim moved {worst} m in one tick");
+ Assert.True(Gap(arm.Aim, goal) < 1e-4f);
+ }
+
+ [Fact]
+ public void An_arm_engaged_again_from_releasing_starts_a_new_path_from_the_measured_wrist()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var goal = (-0.04f, 1.60f, 0.24f);
+ for (var i = 0; i < 100; i++) Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(Gap(arm.Aim, goal) < 1e-4f);
+
+ // Still releasing, not yet back on the base (the slew takes more than three ticks).
+ for (var i = 0; i < 3; i++) arm.Release(Quat.Identity, Quat.Identity, out _, out _);
+ Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ Assert.True(arm.PathBlocked);
+ Assert.True(Gap(arm.Aim, arm.WristAnchor) < 1e-4f, $"an arm engaged again from releasing starts its path at the measured wrist, not {arm.Aim}");
+ }
+
+ [Fact]
+ public void Restart_keeps_the_held_swivel()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var goal = (-0.04f, 1.60f, 0.24f);
+ for (var i = 0; i < 100; i++) Drive(arm, goal, Quat.Identity, Quat.Identity, 1.0, out _, out _);
+ var held = arm.Held;
+ Assert.False(held.Equals(Quat.Identity), "the arm holds no swivel to keep");
+ arm.Restart();
+ Assert.Equal(held, arm.Held);
+ }
+
+ [Fact]
+ public void The_minimum_jerk_profile_is_the_quintic()
+ {
+ // Flash and Hogan: 10 t^3 - 15 t^4 + 6 t^5. Smoothstep shares the ends, the midpoint and the zero first velocity but not these.
+ Assert.Equal(0.103515625f, ArmChain.MinimumJerk(0.25f), 6);
+ Assert.Equal(0.896484375f, ArmChain.MinimumJerk(0.75f), 6);
+ Assert.Equal(0.00856f, ArmChain.MinimumJerk(0.1f), 5);
+ Assert.Equal(0f, ArmChain.MinimumJerk(-1f));
+ Assert.Equal(1f, ArmChain.MinimumJerk(2f));
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void Blocked_means_within_the_forearm_radius_of_the_trunk(Side side)
+ {
+ // A vertical segment in front of the trunk's front face at a distance d from it: blocked within the radius and not beyond, to a tenth.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var fore = Plan.Parts[arm.ForearmPart];
+ var radius = fore.Shape == PartShape.Box ? MathF.Min(fore.Size.X, MathF.Min(fore.Size.Y, fore.Size.Z)) : fore.Size.X;
+ const float front = 0.09f;
+ foreach (var (factor, blocked) in new[] { (0.5f, true), (0.95f, true), (1.05f, false), (1.5f, false) })
+ {
+ var z = front + factor * radius;
+ arm.Reset();
+ Drive(arm, (0f, 1.45f, z), Quat.Identity, Quat.Identity, 1.0, out _, out _, wrist: (0f, 1.25f, z));
+ Assert.Equal(blocked, arm.PathBlocked);
+ }
+ }
+
+ [Fact]
+ public void An_engaging_arm_takes_the_short_way_from_a_base_given_with_the_opposite_sign()
+ {
+ // The same rotation as q and as -q: engaging from -q must not turn the long way round to the solution q.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var fresh = ArmChain.Of(Plan, Side.Right, Dt);
+ var goal = (-0.2f, 1.4f, 0.35f);
+ var parent = Plan.Parts[arm.ParentPart];
+ fresh.Solve(parent.Rotation, parent.Position.X, parent.Position.Y, parent.Position.Z, goal.Item1, goal.Item2, goal.Item3, out var solution, out _);
+ // A base a few steps short of the solution, negated: engaging turns the step toward it, not away.
+ var toward = Quat.Nlerp(solution, Quat.Identity, 0.05f);
+ var negated = new Quat(-toward.X, -toward.Y, -toward.Z, -toward.W);
+ Drive(arm, goal, negated, Quat.Identity, 1.0, out var written, out _);
+ Assert.True(Turn(negated, written) <= Step + 1e-5f, $"engaging turned {Turn(negated, written)} rad from the base in one tick");
+ Assert.True(Turn(written, solution) < Turn(negated, solution) + 1e-4f, "engaging turned away from the solution");
+ Assert.True(Turn(negated, solution) > 0f);
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void A_goal_outrunning_the_rate_keeps_the_shoulder_target_a_unit_rotation(Side side)
+ {
+ // The goal circles the shoulder so fast that the target is always behind it: ten thousand slewed steps compose without drift.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var worst = 0f;
+ var chasing = 0;
+ var last = Quat.Identity;
+ for (var i = 0; i < 10000; i++)
+ {
+ var th = 0.9f * i;
+ arm.Solve(Plan.Parts[arm.ParentPart].Rotation, Plan.Parts[arm.ParentPart].Position.X, Plan.Parts[arm.ParentPart].Position.Y, Plan.Parts[arm.ParentPart].Position.Z,
+ s.X + 0.4f * MathF.Sin(th), s.Y - 0.1f, s.Z + 0.4f * MathF.Cos(th), out var q, out _);
+ worst = MathF.Max(worst, MathF.Abs(MathF.Sqrt(q.X * q.X + q.Y * q.Y + q.Z * q.Z + q.W * q.W) - 1f));
+ if (i > 0 && Turn(last, q) > 0.99f * Step) chasing++;
+ last = q;
+ }
+
+ _output.WriteLine($"{side}: norm error {worst:E2}, {chasing} of 10000 ticks at the rate");
+ Assert.True(chasing > 5000, $"the target was at the rate on only {chasing} ticks, so it was not outrun");
+ Assert.True(worst < 1e-5f, $"the shoulder target left the unit sphere by {worst}");
+ }
+
+ // A pose with the arms at rest, to look at the written targets of.
+ private static PartPose[] Rest()
+ {
+ var poses = new PartPose[Plan.Parts.Count];
+ for (var p = 0; p < poses.Length; p++)
+ {
+ var d = Plan.Parts[p];
+ poses[p] = new PartPose(d.Rotation, d.Position.X, d.Position.Y, d.Position.Z);
+ }
+
+ return poses;
+ }
+}
diff --git a/tests/Lodur.Core.Tests/ArousalTests.cs b/tests/Lodur.Core.Tests/ArousalTests.cs
new file mode 100644
index 0000000..16ee754
--- /dev/null
+++ b/tests/Lodur.Core.Tests/ArousalTests.cs
@@ -0,0 +1,204 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// An Actor with one region at the origin, a sensory nerve with sensitisation off, and a settable emitter list.
+internal sealed class SensoryRig
+{
+ public const double Dt = 0.01;
+
+ public readonly Actor Actor;
+ public readonly Emitter[] Emitters;
+ public readonly float[] Strengths = new float[2];
+ public readonly Quat[] Targets = new Quat[2];
+ private readonly float[] _p = { 0f };
+
+ /// False builds the Actor without senses, so the emitters have no one to reach.
+ public SensoryRig(Emitter[] emitters, double pull = 0.5, double drainTrait = 1.0, DriveParameters? drive = null, bool heard = true, Brain? brain = null)
+ {
+ Emitters = emitters;
+ Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(),
+ (drive ?? new DriveParameters()) with { DrainTrait = drainTrait }, brain ?? PainBoxBrain.Make(pull),
+ heard ? new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 } : null, 0);
+ }
+
+ /// One audio emitter on the sense region whose afferent settles at (intensity - 0.05).
+ public static Emitter[] One(double intensity) => new[] { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, intensity) };
+
+ public TickEvents Tick() => Actor.Tick(_p, _p, _p, ReadOnlySpan.Empty, Strengths, Targets, Emitters);
+
+ public long TicksToBreak(double maxSeconds)
+ {
+ var max = (long)Math.Round(maxSeconds / Dt);
+ for (long i = 0; i < max; i++)
+ {
+ if ((Tick() & TickEvents.WillBroke) != 0) return i;
+ }
+
+ return -1;
+ }
+}
+
+public sealed class ArousalTests
+{
+ private const double Load = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
+
+ [Fact]
+ public void Arousal_rises_under_constant_load_toward_its_equilibrium_and_decays_at_the_decay_rate_after_it_stops()
+ {
+ var p = new DriveParameters();
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 1.0); // pull 1: no drain, so only arousal is watched
+ double last = 0;
+ for (var i = 0; i < 20000; i++)
+ {
+ rig.Tick();
+ Assert.True(rig.Actor.Drive.Arousal >= last - 1e-15, "arousal never falls under constant load");
+ last = rig.Actor.Drive.Arousal;
+ }
+
+ Assert.Equal(Load, rig.Actor.Load, 12);
+ var equilibrium = p.ArousalRise * Load / (p.ArousalRise * Load + p.ArousalDecay);
+ Assert.Equal(equilibrium, rig.Actor.Drive.Arousal, 9);
+
+ rig.Emitters[0].Intensity = 0.0;
+ while (rig.Actor.Load > 0.0) rig.Tick(); // the last of the signal in flight arrives
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(a0 > 0.5 * equilibrium);
+ for (var i = 0; i < 1000; i++) rig.Tick();
+ Assert.Equal(a0 * Math.Pow(1.0 - SensoryRig.Dt * p.ArousalDecay, 1000), rig.Actor.Drive.Arousal, 12);
+ }
+
+ [Fact]
+ public void Under_the_same_load_a_weaker_pull_breaks_first_pull_one_never_drains_and_the_trait_scales_the_drain()
+ {
+ long Break(double pull, double trait = 1.0) => new SensoryRig(SensoryRig.One(0.55), pull, trait).TicksToBreak(3000.0);
+
+ long p3 = Break(0.3), p6 = Break(0.6);
+ Assert.True(p3 > 0 && p3 < p6, $"pull: {p3} {p6}");
+
+ var held = new SensoryRig(SensoryRig.One(0.55), pull: 1.0);
+ Assert.Equal(-1, held.TicksToBreak(3000.0));
+ Assert.Equal(1.0, held.Actor.Drive.Resolve);
+
+ long t2 = Break(0.6, 2.0);
+ Assert.True(t2 > 0 && t2 < p6, $"trait: {t2} {p6}");
+ Assert.InRange((double)t2 / p6, 0.35, 0.6); // double the drain, about half the time (arousal needs a moment to rise)
+ }
+
+ [Fact]
+ public void Resolve_does_not_recover_while_arousal_is_at_the_recovery_ceiling_or_above_and_does_after()
+ {
+ var drive = new DriveParameters { ResolveRecovery = 0.5 }; // strong enough that a gate on pain alone would show at once
+ var ceiling = drive.ResolveRecoversBelowArousal;
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5, drive: drive);
+ double minResolve = 1.0;
+ for (var i = 0; i < 2000; i++) { rig.Tick(); minResolve = Math.Min(minResolve, rig.Actor.Drive.Resolve); }
+ Assert.True(minResolve < 0.95 && !rig.Actor.Drive.WillBroken);
+
+ rig.Emitters[0].Intensity = 0.0;
+ var rosePastCeiling = false;
+ var settled = false;
+ var last = rig.Actor.Drive.Resolve;
+ for (var i = 0; i < 20000; i++)
+ {
+ rig.Tick();
+ var a = rig.Actor.Drive.Arousal;
+ var r = rig.Actor.Drive.Resolve;
+ if (a >= ceiling)
+ {
+ Assert.True(r <= last, $"resolve rose at arousal {a}");
+ settled = true;
+ }
+ else if (settled && r > last)
+ {
+ rosePastCeiling = true;
+ }
+
+ last = r;
+ }
+
+ Assert.True(settled && rosePastCeiling, "resolve recovers once arousal is below the ceiling");
+ Assert.True(rig.Actor.Drive.Resolve > minResolve);
+ }
+
+ [Fact]
+ public void Arousal_updates_before_it_drains_resolve_on_the_same_tick()
+ {
+ var rig = new SensoryRig(SensoryRig.One(0.55), pull: 0.5);
+ for (var i = 0; i < 100; i++)
+ {
+ rig.Tick();
+ if (rig.Actor.Load > 0.0) break;
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(1.0, rig.Actor.Drive.Resolve);
+ }
+
+ Assert.True(rig.Actor.Load > 0.0, "the load arrives within the conduction delay");
+ // On the tick the load first arrives, arousal has already risen and already drained: read a tick late, resolve would still be 1.
+ Assert.True(rig.Actor.Drive.Arousal > 0.0);
+ Assert.True(rig.Actor.Drive.Resolve < 1.0);
+ }
+
+ [Fact]
+ public void Without_emitters_or_without_senses_arousal_and_load_stay_exactly_zero()
+ {
+ var silent = new SensoryRig(Array.Empty());
+ var deaf = new SensoryRig(SensoryRig.One(1.0), heard: false);
+ for (var i = 0; i < 10000; i++)
+ {
+ Assert.Equal(TickEvents.None, silent.Tick());
+ Assert.Equal(TickEvents.None, deaf.Tick());
+ Assert.Equal(0.0, silent.Actor.Drive.Arousal);
+ Assert.Equal(0.0, deaf.Actor.Drive.Arousal);
+ Assert.Equal(0.0, silent.Actor.Load);
+ Assert.Equal(0.0, deaf.Actor.Load);
+ }
+
+ Assert.Equal(1.0, silent.Actor.Drive.Resolve);
+ Assert.Equal(1.0, deaf.Actor.Drive.Resolve);
+ }
+
+ private static Emitter[] Three() => new[]
+ {
+ new Emitter(Channel.Audio, 0.2f, 0f, 0f, 1f, 0.5),
+ new Emitter(Channel.Visual, 0f, 0.3f, 0f, 1f, 0.4),
+ new Emitter(Channel.Interrupt, 0f, 0f, 0f, 1f, 0.6),
+ };
+
+ [Fact]
+ public void Tick_with_three_emitters_allocates_nothing_in_steady_state_and_actors_do_not_share_state()
+ {
+ var r = new SensoryRig(Three());
+ r.Tick();
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) r.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+
+ const int n = 2500;
+ var a1 = new SensoryRig(Three());
+ var b1 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
+ var a2 = new SensoryRig(Three());
+ var b2 = new SensoryRig(SensoryRig.One(0.4), pull: 0.2, drainTrait: 1.3);
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+
+ static void Same(SensoryRig x, SensoryRig y)
+ {
+ Assert.Equal(x.Actor.Drive.Arousal, y.Actor.Drive.Arousal);
+ Assert.Equal(x.Actor.Drive.Resolve, y.Actor.Drive.Resolve);
+ Assert.Equal(x.Actor.Load, y.Actor.Load);
+ foreach (var c in new[] { Channel.Audio, Channel.Visual, Channel.Interrupt })
+ {
+ Assert.Equal(x.Actor.ChannelStimulus(c), y.Actor.ChannelStimulus(c));
+ Assert.Equal(x.Actor.ChannelAfferent(c), y.Actor.ChannelAfferent(c));
+ }
+ }
+
+ Same(a1, a2);
+ Same(b1, b2);
+ Assert.True(a1.Actor.Drive.Arousal > 0.0);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/BodyPlanTests.cs b/tests/Lodur.Core.Tests/BodyPlanTests.cs
new file mode 100644
index 0000000..1b854bb
--- /dev/null
+++ b/tests/Lodur.Core.Tests/BodyPlanTests.cs
@@ -0,0 +1,360 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class BodyPlanTests
+{
+ private static PartDef Box(string label, Side side = Side.Center) =>
+ new(label, side, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
+
+ private static JointDef Joint(string label, int parent, int child, Side side = Side.Center) =>
+ new(label, side, JointKind.Spherical, parent, child, (0f, 0f, 0f), (0f, 1f, 0f), -1f, 1f, 0.5f, new MuscleGains(1f, 1f, 1f, 1f));
+
+ private static BodyPlan Plan(PartDef[] parts, JointDef[] joints, SensePointDef[]? senses = null) =>
+ new(parts, joints, senses ?? Array.Empty());
+
+ private static BodyPlan Valid() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) });
+
+ private static void Refuses(Action build, string saying)
+ {
+ var e = Assert.Throws(build);
+ Assert.Contains(saying, e.Message);
+ }
+
+ [Fact]
+ public void A_valid_plan_resolves_labels_and_derives_the_tree_from_its_joints()
+ {
+ var plan = Valid();
+ Assert.Equal(1, plan.PartIndex("B"));
+ Assert.Equal(0, plan.JointIndex("J"));
+ Assert.Equal(new[] { -1, 0 }, new[] { plan.ParentOf(0), plan.ParentOf(1) });
+ }
+
+ // Rule 1: (label, side) unique per list, labels non-empty.
+ [Fact]
+ public void Rule1_a_repeated_label_and_side_is_refused_in_each_list_and_another_side_is_not()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("A") }, new[] { Joint("J", 0, 1) }), "two parts are labelled 'A'");
+ Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1), Joint("J", 0, 2) }), "two joints are labelled 'J'");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) },
+ new[] { new SensePointDef("S", Side.Left, 0, default), new SensePointDef("S", Side.Left, 1, default) }), "two sense points are labelled 'S'");
+ var plan = Plan(new[] { Box("A"), Box("L", Side.Left), Box("L", Side.Right) }, new[] { Joint("J", 0, 1, Side.Left), Joint("J", 0, 2, Side.Right) });
+ Assert.Equal(2, plan.PartIndex("L", Side.Right));
+ }
+
+ [Fact]
+ public void Rule1_an_empty_label_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("") }, new[] { Joint("J", 0, 1) }), "empty label");
+ }
+
+ // Rule 2: joint ends in range, parent before child.
+ [Theory]
+ [InlineData(0, 2)]
+ [InlineData(-1, 1)]
+ [InlineData(5, 1)]
+ public void Rule2_a_joint_end_that_is_not_a_part_is_refused(int parent, int child)
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", parent, child) }), "is not a part");
+ }
+
+ [Fact]
+ public void Rule2_a_parent_that_does_not_precede_its_child_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 1, 0) }), "must precede");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 1, 1) }), "must precede");
+ }
+
+ // Rule 3: part 0 the root, every other part the child of exactly one joint.
+ [Fact]
+ public void Rule3_a_part_with_no_joint_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1) }), "child of 0 joints");
+ }
+
+ [Fact]
+ public void Rule3_a_part_with_two_joints_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B"), Box("C") }, new[] { Joint("J", 0, 1), Joint("K", 0, 2), Joint("M", 1, 2) }), "child of 2 joints");
+ }
+
+ [Fact]
+ public void Rule3_a_plan_without_parts_is_refused()
+ {
+ Refuses(() => Plan(Array.Empty(), Array.Empty()), "needs a root");
+ }
+
+ // Rule 4: sense points name parts.
+ [Theory]
+ [InlineData(2)]
+ [InlineData(-1)]
+ public void Rule4_a_sense_point_on_no_part_is_refused(int part)
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) }, new[] { new SensePointDef("S", Side.Center, part, default) }), "is not a part");
+ }
+
+ // Rule 5: numbers a physics world can take.
+ [Fact]
+ public void Rule5_a_non_finite_part_number_is_refused()
+ {
+ var nan = Box("B") with { Position = (float.NaN, 0f, 0f) };
+ Refuses(() => Plan(new[] { Box("A"), nan }, new[] { Joint("J", 0, 1) }), "non-finite");
+ var inf = Box("B") with { Friction = float.PositiveInfinity };
+ Refuses(() => Plan(new[] { Box("A"), inf }, new[] { Joint("J", 0, 1) }), "non-finite");
+ }
+
+ [Fact]
+ public void Rule5_a_size_the_shape_uses_must_be_positive_and_one_it_does_not_use_may_be_zero()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0f, 0.1f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (-0.1f, 0f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
+ var capsule = Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0f) } }, new[] { Joint("J", 0, 1) });
+ Assert.Equal(2, capsule.Parts.Count);
+ }
+
+ [Fact]
+ public void Rule5_a_box_depth_that_is_not_positive_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0.1f, 0f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Size = (0.1f, 0.1f, -0.1f) } }, new[] { Joint("J", 0, 1) }), "size its shape uses");
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ public void Rule5_a_non_finite_rotation_component_is_refused(int component)
+ {
+ var q = new[] { 0f, 0f, 0f, 1f };
+ q[component] = float.NaN;
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Rotation = new Quat(q[0], q[1], q[2], q[3]) } }, new[] { Joint("J", 0, 1) }), "non-finite");
+ q[component] = float.PositiveInfinity;
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Rotation = new Quat(q[0], q[1], q[2], q[3]) } }, new[] { Joint("J", 0, 1) }), "non-finite");
+ }
+
+ [Fact]
+ public void Rule5_a_field_the_shape_cannot_carry_is_refused()
+ {
+ var turned = Quat.FromAxisAngle(0f, 0f, 1f, 0.5f);
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0f), Rotation = turned } }, new[] { Joint("J", 0, 1) }), "sphere carries no rotation");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { RollingResistance = 0.1f } }, new[] { Joint("J", 0, 1) }), "box carries no rolling resistance");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0.3f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0.2f, 0f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0.3f) } }, new[] { Joint("J", 0, 1) }), "does not use is not zero");
+ // what each shape does carry is accepted
+ var ok = Plan(new[] { Box("A") with { Rotation = turned }, Box("B") with { Shape = PartShape.Capsule, Size = (0.1f, 0.2f, 0f), Rotation = turned, RollingResistance = 0.1f },
+ Box("C") with { Shape = PartShape.Sphere, Size = (0.1f, 0f, 0f), RollingResistance = 0.1f } }, new[] { Joint("J", 0, 1), Joint("K", 0, 2) });
+ Assert.Equal(3, ok.Parts.Count);
+ }
+
+ [Fact]
+ public void Rule5_a_density_that_is_not_positive_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") with { Density = 0f } }, new[] { Joint("J", 0, 1) }), "density");
+ }
+
+ [Fact]
+ public void Rule5_a_joint_with_a_non_finite_number_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Axis = (0f, float.NaN, 0f) } }), "non-finite");
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Gains = new MuscleGains(float.PositiveInfinity, 1f, 1f, 1f) } }), "non-finite");
+ }
+
+ [Fact]
+ public void Rule5_a_lower_limit_above_the_upper_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Lower = 0.5f, Upper = 0.4f } }), "lower limit");
+ }
+
+ [Fact]
+ public void Rule5_a_negative_cone_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) with { Cone = -0.1f } }), "cone");
+ }
+
+ [Fact]
+ public void Rule5_a_non_finite_sense_offset_is_refused()
+ {
+ Refuses(() => Plan(new[] { Box("A"), Box("B") }, new[] { Joint("J", 0, 1) }, new[] { new SensePointDef("S", Side.Center, 0, (0f, float.NaN, 0f)) }), "non-finite");
+ }
+
+ [Fact]
+ public void The_plan_copies_its_lists()
+ {
+ var parts = new List { Box("A"), Box("B") };
+ var plan = Plan(parts.ToArray(), new[] { Joint("J", 0, 1) });
+ var viaList = new BodyPlan(parts, new[] { Joint("J", 0, 1) }, Array.Empty());
+ parts.Add(Box("C"));
+ Assert.Equal(2, viaList.Parts.Count);
+ Assert.Equal(2, plan.Parts.Count);
+ }
+
+ // Airway openings: rules 1, 4, 5, 6.
+ private static BodyPlan WithAirway(PartDef part, params AirwayOpeningDef[] openings) =>
+ new(new[] { part }, Array.Empty(), Array.Empty(), openings, new[] { new AirwaySumpDef("S", 0, (0f, 0f, 0f)) });
+
+ private static BodyPlan WithSumps(PartDef part, params AirwaySumpDef[] sumps) =>
+ new(new[] { part }, Array.Empty(), Array.Empty(), new[] { Opening((0f, 0f, 0.11f)) }, sumps);
+
+ private static PartDef Shaped(PartShape shape, (float, float, float) size) =>
+ new("P", Side.Center, shape, size, (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
+
+ private static AirwayOpeningDef Opening((float, float, float) offset, float radius = 0.025f, string label = "O") =>
+ new(label, Side.Center, 0, offset, radius);
+
+ [Fact]
+ public void Rule1_a_repeated_airway_label_and_side_is_refused_and_another_side_is_not()
+ {
+ var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)), Opening((0f, 0.05f, 0.1f))), "two airway openings are labelled 'O'");
+ var plan = WithAirway(part, Opening((0f, 0f, 0.11f)), Opening((0f, 0.05f, 0.1f), label: "O") with { Side = Side.Left });
+ Assert.Equal(1, plan.AirwayIndex("O", Side.Left));
+ Refuses(() => plan.AirwayIndex("O", Side.Right), "no airway opening labelled 'O' on side Right");
+ }
+
+ [Fact]
+ public void Rule4_an_airway_opening_on_no_part_is_refused()
+ {
+ var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)) with { Part = 1 }), "part 1 is not a part");
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f)) with { Part = -1 }), "part -1 is not a part");
+ }
+
+ [Fact]
+ public void Rule5_a_non_finite_offset_or_radius_and_a_radius_not_above_zero_are_refused()
+ {
+ var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ Refuses(() => WithAirway(part, Opening((0f, float.NaN, 0.11f))), "non-finite");
+ Refuses(() => WithAirway(part, Opening((float.PositiveInfinity, 0f, 0.11f))), "non-finite");
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), float.NaN)), "non-finite");
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), 0f)), "radius is not positive");
+ Refuses(() => WithAirway(part, Opening((0f, 0f, 0.11f), -0.01f)), "radius is not positive");
+ }
+
+ [Fact]
+ public void Rule6_an_opening_wholly_inside_its_part_is_refused_and_one_straddling_the_surface_is_accepted_for_each_shape()
+ {
+ // sphere r 0.11: centre at 0.05 with radius 0.025 is wholly inside (distance -0.06); at the surface it straddles.
+ var sphere = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ Refuses(() => WithAirway(sphere, Opening((0f, 0f, 0.05f))), "lies inside its part");
+ WithAirway(sphere, Opening((0f, 0f, 0.11f)));
+ WithAirway(sphere, Opening((0f, 0f, 0.12f)));
+
+ // capsule r 0.05, half length 0.2 along y: past the cap is measured from the end of the segment, beside the side from the axis.
+ var capsule = Shaped(PartShape.Capsule, (0.05f, 0.2f, 0f));
+ Refuses(() => WithAirway(capsule, Opening((0f, 0.1f, 0.01f))), "lies inside its part");
+ Refuses(() => WithAirway(capsule, Opening((0f, 0.2f, 0f))), "lies inside its part");
+ Refuses(() => WithAirway(capsule, Opening((0f, 0.22f, 0f))), "lies inside its part"); // 0.02 past the segment end, r 0.05: inside by 0.03, more than the radius 0.025
+ WithAirway(capsule, Opening((0.05f, 0.1f, 0f)));
+ WithAirway(capsule, Opening((0f, 0.25f, 0f)));
+ WithAirway(capsule, Opening((0f, 0.3f, 0f)));
+
+ // box half extents (0.1, 0.05, 0.2): the signed distance is the box's, so a point deep in one axis is not rescued by another.
+ var box = Shaped(PartShape.Box, (0.1f, 0.05f, 0.2f));
+ Refuses(() => WithAirway(box, Opening((0f, 0f, 0f))), "lies inside its part");
+ Refuses(() => WithAirway(box, Opening((0.05f, 0.01f, 0.1f))), "lies inside its part");
+ WithAirway(box, Opening((0.1f, 0f, 0f)));
+ WithAirway(box, Opening((0f, 0.05f, 0f)));
+ WithAirway(box, Opening((0.11f, 0.06f, 0.21f)));
+ }
+
+ [Fact]
+ public void Airway_openings_need_a_sump_on_a_part_with_a_finite_offset()
+ {
+ var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ Refuses(() => WithSumps(part), "need at least one airway sump");
+ Refuses(() => WithSumps(part, new AirwaySumpDef("S", 1, (0f, 0f, 0f))), "part 1 is not a part");
+ Refuses(() => WithSumps(part, new AirwaySumpDef("S", -1, (0f, 0f, 0f))), "part -1 is not a part");
+ Refuses(() => WithSumps(part, new AirwaySumpDef("S", 0, (0f, float.NaN, 0f))), "non-finite");
+ Refuses(() => WithSumps(part, new AirwaySumpDef("S", 0, (float.PositiveInfinity, 0f, 0f))), "non-finite");
+ Assert.Single(WithSumps(part, new AirwaySumpDef("S", 0, (0f, 0f, 0f))).AirwaySumps);
+ Assert.Empty(Valid().AirwaySumps);
+ }
+
+ [Fact]
+ public void The_airway_opening_list_is_copied_and_null_means_none()
+ {
+ var part = Shaped(PartShape.Sphere, (0.11f, 0f, 0f));
+ var list = new List { Opening((0f, 0f, 0.11f)) };
+ var plan = new BodyPlan(new[] { part }, Array.Empty(), Array.Empty(), list, new[] { new AirwaySumpDef("S", 0, (0f, 0f, 0f)) });
+ list.Add(Opening((0f, 0f, 0.12f), label: "P"));
+ Assert.Single(plan.AirwayOpenings);
+ Assert.Empty(Valid().AirwayOpenings);
+ }
+
+ // The humanoid.
+ [Fact]
+ public void The_humanoid_has_19_parts_18_joints_and_3_sense_points_labelled_in_build_order()
+ {
+ var plan = BodyPlans.Humanoid();
+ string Name(string label, Side side) => side == Side.Center ? label : label + side;
+ Assert.Equal(new[]
+ {
+ "Pelvis", "Torso", "Head",
+ "UpperArmLeft", "LowerArmLeft", "ThighLeft", "ShinLeft", "FootLeft",
+ "UpperArmRight", "LowerArmRight", "ThighRight", "ShinRight", "FootRight",
+ "PalmLeft", "ThumbLeft", "FingersLeft", "PalmRight", "ThumbRight", "FingersRight",
+ }, plan.Parts.Select(p => Name(p.Label, p.Side)).ToArray());
+ Assert.Equal(new[]
+ {
+ "Spine", "Neck",
+ "ShoulderLeft", "ElbowLeft", "HipLeft", "KneeLeft", "AnkleLeft",
+ "ShoulderRight", "ElbowRight", "HipRight", "KneeRight", "AnkleRight",
+ "WristLeft", "ThumbLeft", "FingersLeft", "WristRight", "ThumbRight", "FingersRight",
+ }, plan.Joints.Select(j => Name(j.Label, j.Side)).ToArray());
+ Assert.Equal(new[] { "HandLeft", "HandRight", "Head" }, plan.SensePoints.Select(s => Name(s.Label, s.Side)).ToArray());
+ Assert.Equal(new[] { plan.PartIndex("Palm", Side.Left), plan.PartIndex("Palm", Side.Right), plan.PartIndex("Head") }, plan.SensePoints.Select(s => s.Part).ToArray());
+ }
+
+ [Fact]
+ public void The_humanoid_has_a_mouth_and_a_nose_on_the_head_each_on_its_surface()
+ {
+ var plan = BodyPlans.Humanoid();
+ Assert.Equal(new[] { "Mouth", "Nose" }, plan.AirwayOpenings.Select(a => a.Label).ToArray());
+ Assert.Equal(new[] { "Pharynx", "Glottis" }, plan.AirwaySumps.Select(a => a.Label).ToArray());
+ Assert.All(plan.AirwaySumps, s => Assert.Equal(plan.PartIndex("Head"), s.Part));
+ foreach (var a in plan.AirwayOpenings)
+ {
+ Assert.Equal(plan.PartIndex("Head"), a.Part);
+ var o = a.Offset;
+ Assert.InRange(MathF.Sqrt(o.X * o.X + o.Y * o.Y + o.Z * o.Z), 0.109f, 0.111f);
+ }
+ }
+
+ [Fact]
+ public void The_humanoid_parent_tree_is_the_old_one()
+ {
+ var plan = BodyPlans.Humanoid();
+ // pelvis torso head uaL laL thL shL ftL uaR laR thR shR ftR plL thL fiL plR thR fiR
+ var old = new[] { -1, 0, 1, 1, 3, 0, 5, 6, 1, 8, 0, 10, 11, 4, 13, 13, 9, 16, 16 };
+ Assert.Equal(old, Enumerable.Range(0, plan.Parts.Count).Select(plan.ParentOf).ToArray());
+ }
+
+ [Fact]
+ public void The_humanoid_hand_joints_hang_palm_thumb_fingers_off_the_lower_arm_per_side()
+ {
+ var plan = BodyPlans.Humanoid();
+ foreach (var side in new[] { Side.Left, Side.Right })
+ {
+ Assert.Equal((plan.PartIndex("LowerArm", side), plan.PartIndex("Palm", side)),
+ (plan.Joints[plan.JointIndex("Wrist", side)].Parent, plan.Joints[plan.JointIndex("Wrist", side)].Child));
+ Assert.Equal((plan.PartIndex("Palm", side), plan.PartIndex("Thumb", side)),
+ (plan.Joints[plan.JointIndex("Thumb", side)].Parent, plan.Joints[plan.JointIndex("Thumb", side)].Child));
+ Assert.Equal((plan.PartIndex("Palm", side), plan.PartIndex("Fingers", side)),
+ (plan.Joints[plan.JointIndex("Fingers", side)].Parent, plan.Joints[plan.JointIndex("Fingers", side)].Child));
+ }
+ }
+
+ [Fact]
+ public void A_lookup_with_the_wrong_side_refuses_and_names_label_and_side()
+ {
+ var plan = BodyPlans.Humanoid();
+ Refuses(() => plan.PartIndex("Palm"), "'Palm' on side Center");
+ Refuses(() => plan.PartIndex("Pelvis", Side.Left), "'Pelvis' on side Left");
+ Refuses(() => plan.JointIndex("Knee"), "'Knee' on side Center");
+ Refuses(() => plan.SenseIndex("Head", Side.Right), "'Head' on side Right");
+ Refuses(() => plan.PartIndex("Tail"), "'Tail'");
+ }
+}
diff --git a/tests/Lodur.Core.Tests/BrainTests.cs b/tests/Lodur.Core.Tests/BrainTests.cs
new file mode 100644
index 0000000..4f7f824
--- /dev/null
+++ b/tests/Lodur.Core.Tests/BrainTests.cs
@@ -0,0 +1,639 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class BrainTests
+{
+ private const long Latency = 10; // round(0.1 s / 10 ms)
+
+ private static GoalSpec Goal(string id, double priority, double pull = 0.5, params Condition[] when) => new()
+ {
+ Id = id, Priority = priority, Pull = pull, When = when,
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ };
+
+ private static readonly Perception Deaf = new(new NerveParameters(), 0.01, 1);
+
+ private static int Pick(Brain brain, DriveState drive, int current) => brain.Select(drive, Deaf, 0f, 0f, 0f, new Choice(current, 0)).Goal;
+
+ private static Condition Pain(ConditionOp op, double t) => new(DriveQuantity.Pain, op, t);
+
+ private sealed record Run(List Changes, List Goals, long Broke, long[] Held);
+
+ /// Ticks the pain box; reports the GoalChanged ticks and goals, the WillBroke tick, and per probe the first tick its predicate held after the tick.
+ private static Run Go(PainBoxReplay r, long ticks, params Func[] probes)
+ {
+ var run = new Run(new List(), new List(), -1, Enumerable.Repeat(-1L, probes.Length).ToArray());
+ for (long i = 0; i < ticks; i++)
+ {
+ var e = r.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) { run.Changes.Add(i); run.Goals.Add(r.Actor.GoalIndex); }
+ if ((e & TickEvents.WillBroke) != 0 && run.Broke < 0) run = run with { Broke = i };
+ for (var p = 0; p < probes.Length; p++)
+ {
+ if (run.Held[p] < 0 && probes[p](r.Actor.Drive)) run.Held[p] = i;
+ }
+ }
+ return run;
+ }
+
+ [Fact]
+ public void A_brain_with_no_rule_about_the_will_never_changes_goal_when_the_will_breaks()
+ {
+ var one = new Brain { Goals = new[] { Goal("only", 0.0) } };
+ var r = new PainBoxReplay(1, brain: one);
+ var run = Go(r, 2500);
+ Assert.True(run.Broke > 0, "the will never broke");
+ Assert.Empty(run.Changes);
+ Assert.Equal(0, r.Actor.GoalIndex);
+ }
+
+ [Fact]
+ public void A_release_that_enters_on_pain_switches_long_before_the_will_breaks_exactly_the_latency_after_pain_first_reached_it()
+ {
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("objective", 0.0), Goal("release", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)) },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 2500, d => d.Pain >= 0.6);
+ Assert.True(run.Held[0] > 0);
+ Assert.Equal(new[] { run.Held[0] + Latency }, run.Changes);
+ Assert.Equal(new[] { 1 }, run.Goals);
+ Assert.True(run.Broke > run.Changes[0] + 500, $"will broke at {run.Broke}, the switch was at {run.Changes[0]}");
+ }
+
+ [Fact]
+ public void Of_several_eligible_goals_the_highest_priority_is_taken_ties_stay_put_or_go_to_the_lowest_index()
+ {
+ var calm = default(DriveState); // all zero, will intact
+ Condition Always = Pain(ConditionOp.Below, 1.0);
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 2.0, 0.5, Always), Goal("b", 5.0, 0.5, Always), Goal("c", 5.0, 0.5, Always),
+ Goal("d", 9.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)),
+ },
+ };
+ Assert.Equal(1, Pick(brain, calm, 0)); // b and c tie at the top: the lowest index
+ Assert.Equal(2, Pick(brain, calm, 2)); // the current goal wins a tie
+ Assert.Equal(1, Pick(brain, calm, 3)); // d is ineligible: current is not kept for its own sake
+ var none = new Brain { Goals = new[] { Goal("x", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)), Goal("y", 0.0, 0.5, Pain(ConditionOp.AtLeast, 0.5)) } };
+ Assert.Equal(1, Pick(none, calm, 1)); // nothing eligible: the current goal
+ Assert.Equal(0, Pick(none, calm, 0));
+ }
+
+ [Fact]
+ public void A_three_goal_brain_passes_through_the_goals_as_their_conditions_come_true_each_a_latency_after_its_own()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("calm", 0.0),
+ Goal("wary", 3.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
+ Goal("hurt", 5.0, 0.5, Pain(ConditionOp.AtLeast, 0.6)),
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 2500, d => d.Pain >= 0.3, d => d.Pain >= 0.6);
+ Assert.Equal(new[] { 1, 2 }, run.Goals);
+ Assert.Equal(new[] { run.Held[0] + Latency, run.Held[1] + Latency }, run.Changes);
+ }
+
+ [Fact]
+ public void A_revert_brain_switches_back_when_the_arousal_that_chose_the_rage_falls_and_each_switch_fires_once()
+ {
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("calm", 1.0, 1.0), Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5)) },
+ };
+ var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
+ long rose = -1, fell = -1;
+ var changes = new List<(long Tick, int Goal)>();
+ for (long i = 0; i < 20000; i++)
+ {
+ if (i == 6000) rig.Emitters[0].Intensity = 0.0;
+ var e = rig.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
+ if (rose < 0 && rig.Actor.Drive.Arousal >= 0.5) rose = i;
+ if (rose >= 0 && fell < 0 && i >= 6000 && rig.Actor.Drive.Arousal < 0.5) fell = i;
+ }
+ Assert.True(rose > 0 && fell > rose);
+ Assert.Equal(new[] { (rose + Latency, 1), (fell + Latency, 0) }, changes);
+ }
+
+ [Fact]
+ public void Resolve_drain_follows_the_pull_of_the_goal_in_force_slower_after_a_switch_to_a_goal_that_pulls_harder()
+ {
+ Brain Of(double secondPull) => new()
+ {
+ Goals = new[] { Goal("a", 0.0, 0.0), Goal("b", 1.0, secondPull, Pain(ConditionOp.AtLeast, 0.3)) },
+ };
+ var plain = new PainBoxReplay(1, brain: Of(0.0));
+ var pulled = new PainBoxReplay(1, brain: Of(0.9));
+ long switched = -1;
+ double before = 0.0, plainLoss = 0.0, pulledLoss = 0.0;
+ for (long i = 0; i < 1200; i++)
+ {
+ var ea = plain.Tick();
+ var eb = pulled.Tick();
+ if (switched < 0) Assert.Equal(ea, eb);
+ if ((eb & TickEvents.GoalChanged) != 0) { switched = i; before = plain.Actor.Drive.Resolve - pulled.Actor.Drive.Resolve; }
+ if (switched < 0) Assert.Equal(plain.Actor.Drive.Resolve, pulled.Actor.Drive.Resolve); // same pull until the switch
+ if (switched >= 0 && i == switched + 600)
+ {
+ plainLoss = 1.0 - plain.Actor.Drive.Resolve;
+ pulledLoss = 1.0 - pulled.Actor.Drive.Resolve;
+ }
+ }
+ Assert.True(switched > 0);
+ Assert.Equal(0.0, before);
+ Assert.True(pulled.Actor.Drive.Resolve > plain.Actor.Drive.Resolve);
+ Assert.True(pulledLoss < 0.25 * plainLoss, $"pull 0.9 lost {pulledLoss}, pull 0 lost {plainLoss}");
+ }
+
+ [Fact]
+ public void A_decision_in_flight_commits_at_its_tick_even_if_its_condition_has_lapsed()
+ {
+ // The band is a tick or two wide while pain rises through it; the latency is ten.
+ var brain = new Brain
+ {
+ Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long inBand = -1, lapsed = -1;
+ var changes = new List<(long Tick, int Goal)>();
+ for (long i = 0; i < 600; i++)
+ {
+ var e = r.Tick();
+ if ((e & TickEvents.GoalChanged) != 0) changes.Add((i, r.Actor.GoalIndex));
+ var p = r.Actor.Drive.Pain;
+ if (inBand < 0 && p >= 0.3) inBand = i;
+ if (inBand >= 0 && lapsed < 0 && p >= 0.305) lapsed = i;
+ }
+ Assert.True(inBand > 0 && lapsed > inBand && lapsed < inBand + Latency, $"band {inBand}..{lapsed}");
+ Assert.Equal(new[] { (inBand + Latency, 1), (inBand + Latency + 1 + Latency, 0) }, changes); // committed, then the lapse is acted on once
+ }
+
+ [Fact]
+ public void While_a_decision_is_in_flight_no_second_one_is_made_the_later_goal_waits_for_the_first_to_commit()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)), Goal("c", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.31)),
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ var run = Go(r, 600, d => d.Pain >= 0.3, d => d.Pain >= 0.31);
+ Assert.True(run.Held[1] > run.Held[0] && run.Held[1] < run.Held[0] + Latency, $"{run.Held[0]} {run.Held[1]}");
+ Assert.Equal(new[] { 1, 2 }, run.Goals);
+ Assert.Equal(new[] { run.Held[0] + Latency, run.Held[0] + Latency + 1 + Latency }, run.Changes);
+ }
+
+ [Fact]
+ public void The_brain_is_checked_when_the_actor_is_built()
+ {
+ Actor Build(Brain b) => new(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), b);
+ var g = Goal("g", 0.0);
+ Assert.Throws(() => Build(new Brain()));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g }, Start = 1 }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g }, DeliberateLatencySeconds = double.NaN }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g with { Pull = 1.5 } } }));
+ Assert.Throws(() => Build(new Brain { Goals = new[] { g with { When = new[] { Pain(ConditionOp.AtLeast, double.NaN) } } } }));
+ Assert.Throws(() => Build(new Brain
+ {
+ Goals = new[] { g, g with { Behaviour = g.Behaviour with { Keys = new[] { new[] { Quat.Identity } }, FlinchPose = new[] { Quat.Identity } } } },
+ }));
+ Assert.Equal(1, Build(new Brain { Goals = new[] { g, g }, Start = 1 }).GoalIndex);
+ }
+
+ [Fact]
+ public void A_goal_in_force_writes_its_behaviour_and_seconds_in_goal_count_from_the_tick_it_took_over()
+ {
+ var spin = new[]
+ {
+ new[] { Quat.Identity, Quat.Identity },
+ new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.8f), Quat.Identity },
+ };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0),
+ Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour
+ {
+ Keys = spin, SecondsPerKey = 0.2, FlinchPose = spin[0],
+ Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 },
+ },
+ },
+ },
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long changed = -1;
+ for (long i = 0; i < 600 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ }
+ Assert.True(changed > 0);
+ Assert.Equal(0.01, r.Actor.SecondsInGoal, 12); // the next tick sees one tick in the goal
+ for (var k = 0; k < 10; k++) r.Tick();
+ Assert.Equal(0.11, r.Actor.SecondsInGoal, 9);
+ Assert.NotEqual(0f, r.Targets[0].Z); // partway from key 0 to key 1: the loop is walking
+ }
+
+ [Fact]
+ public void Tick_with_a_three_goal_brain_and_a_four_key_behaviour_allocates_nothing_and_interleaved_actors_equal_each_alone()
+ {
+ Brain Make()
+ {
+ var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
+ return new Brain
+ {
+ Goals = new[]
+ {
+ Goal("calm", 0.0),
+ Goal("wary", 1.0, 0.4, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ Goal("hurt", 2.0, 0.8, Pain(ConditionOp.AtLeast, 0.6)),
+ },
+ };
+ }
+
+ var solo = new PainBoxReplay(1, brain: Make());
+ for (var i = 0; i < 300; i++) solo.Tick(); // warm, and through the first switches
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++) solo.Tick();
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+
+ const int n = 2500;
+ var a1 = new PainBoxReplay(1, brain: Make());
+ var b1 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
+ var a2 = new PainBoxReplay(1, brain: Make());
+ var b2 = new PainBoxReplay(7, intensity: 0.6, brain: Make());
+ var ea = new TickEvents[n];
+ var eb = new TickEvents[n];
+ for (var i = 0; i < n; i++) { ea[i] = a1.Tick(); eb[i] = b1.Tick(); }
+ for (var i = 0; i < n; i++) Assert.Equal(ea[i], a2.Tick());
+ for (var i = 0; i < n; i++) Assert.Equal(eb[i], b2.Tick());
+ Assert.Equal(a1.Actor.GoalIndex, a2.Actor.GoalIndex);
+ Assert.Equal(b1.Actor.GoalIndex, b2.Actor.GoalIndex);
+ Assert.Equal(a1.Targets, a2.Targets);
+ Assert.Equal(b1.Targets, b2.Targets);
+ Assert.Contains(ea, e => (e & TickEvents.GoalChanged) != 0);
+ }
+
+ private static double Read(DriveState d, DriveQuantity q) => q switch
+ {
+ DriveQuantity.Pain => d.Pain,
+ DriveQuantity.Strain => d.Strain,
+ DriveQuantity.Arousal => d.Arousal,
+ DriveQuantity.Resolve => d.Resolve,
+ DriveQuantity.Breaks => d.Breaks,
+ DriveQuantity.AirHunger => d.AirHunger,
+ _ => d.WillBroken ? 1.0 : 0.0,
+ };
+
+ private static Brain Gated(Condition when, double dwell = 0.0, double pull = 0.5) => new()
+ {
+ Goals = new[] { Goal("calm", 0.0, pull), Goal("gated", 1.0, pull, when) with { MinDwellSeconds = dwell } },
+ };
+
+ ///
+ /// Runs a rig whose Brain has one goal gated on the condition; the switch must land the latency after the tick the
+ /// quantity itself first crossed, and no other quantity read the same way may cross on that tick (or the scenario
+ /// could not tell a misread from the right read).
+ ///
+ private static void GateFollowsOnly(Func Tick, Func Drive)> rig, DriveQuantity q, ConditionOp op, double threshold, long ticks, DriveQuantity? sameTickOk = null)
+ {
+ var (tick, drive) = rig(Gated(new Condition(q, op, threshold)));
+ bool Crossed(DriveState d, DriveQuantity of) => op == ConditionOp.AtLeast ? Read(d, of) >= threshold : Read(d, of) < threshold;
+ var firstOf = new Dictionary();
+ long changed = -1;
+ for (long i = 0; i < ticks; i++)
+ {
+ var e = tick();
+ if ((e & TickEvents.GoalChanged) != 0 && changed < 0) changed = i;
+ foreach (var of in Enum.GetValues())
+ {
+ if (!firstOf.ContainsKey(of) && Crossed(drive(), of)) firstOf[of] = i;
+ }
+ }
+ Assert.True(firstOf.TryGetValue(q, out var own), $"{q} never crossed {threshold}");
+ Assert.Equal(own + Latency, changed);
+ foreach (var of in Enum.GetValues())
+ {
+ if (of != q && of != sameTickOk) Assert.False(firstOf.TryGetValue(of, out var other) && other == own, $"{of} crosses on the same tick as {q}: the scenario cannot tell them apart");
+ }
+ }
+
+ private static (Func, Func) PainRig(Brain b) { var r = new PainBoxReplay(1, brain: b); return (() => r.Tick(), () => r.Actor.Drive); }
+
+ private static (Func, Func) SenseRig(Brain b)
+ {
+ var r = new SensoryRig(SensoryRig.One(0.55), brain: b);
+ return (() => r.Tick(), () => r.Actor.Drive);
+ }
+
+ [Theory]
+ [InlineData(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)]
+ [InlineData(DriveQuantity.Strain, ConditionOp.AtLeast, 1.0)]
+ [InlineData(DriveQuantity.Resolve, ConditionOp.Below, 0.9)]
+ [InlineData(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0)]
+ public void Each_drive_quantity_a_condition_reads_is_that_quantity_in_the_pain_box(DriveQuantity q, ConditionOp op, double threshold) =>
+ // The first break moves Breaks and WillBroken on one tick; WillTests reads Breaks at its second break, where they part.
+ GateFollowsOnly(PainRig, q, op, threshold, 1700, DriveQuantity.Breaks);
+
+ [Fact]
+ public void Arousal_a_condition_reads_is_arousal_where_pain_strain_and_resolve_do_not_move_with_it()
+ {
+ GateFollowsOnly(SenseRig, DriveQuantity.Arousal, ConditionOp.AtLeast, 0.5, 3000);
+ }
+
+ [Fact]
+ public void Below_is_strict_and_at_least_is_inclusive_at_the_threshold()
+ {
+ var zero = default(DriveState); // pain exactly 0
+ Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.0).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.Below, 0.0).Holds(zero));
+ Assert.True(new Condition(DriveQuantity.Pain, ConditionOp.Below, 1e-300).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 1e-300).Holds(zero));
+ Assert.False(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 0.0).Holds(zero)); // unbroken reads 0
+ Assert.True(new Condition(DriveQuantity.WillBroken, ConditionOp.Below, 1.0).Holds(zero));
+ }
+
+ private static long ChangeTickAfterPain(double latencySeconds)
+ {
+ var brain = Gated(Pain(ConditionOp.AtLeast, 0.3)) with { DeliberateLatencySeconds = latencySeconds };
+ var run = Go(new PainBoxReplay(1, brain: brain), 600, d => d.Pain >= 0.3);
+ Assert.Single(run.Changes);
+ return run.Changes[0] - run.Held[0];
+ }
+
+ [Fact]
+ public void The_deliberate_latency_is_rounded_to_ticks_never_less_than_one_and_a_negative_latency_is_refused()
+ {
+ Assert.Equal(1, ChangeTickAfterPain(0.0)); // a switch never lands on the tick it was decided
+ Assert.Equal(1, ChangeTickAfterPain(0.001));
+ Assert.Equal(1, ChangeTickAfterPain(0.014));
+ Assert.Equal(2, ChangeTickAfterPain(0.016));
+ Assert.Equal(10, ChangeTickAfterPain(0.1));
+ var g = Goal("g", 0.0);
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { g }, DeliberateLatencySeconds = -0.01 }));
+ }
+
+ [Fact]
+ public void The_pending_goals_behaviour_is_not_written_during_the_latency_only_from_the_tick_it_takes_over()
+ {
+ var loud = Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw, Hold = new HoldParameters { HoldStrength = 0.25f } },
+ };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loud } });
+ long decided = -1;
+ var landed = false;
+ for (long i = 0; i < 600 && !landed; i++)
+ {
+ var e = r.Tick();
+ if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
+ if (decided < 0) continue;
+ if (i < decided + Latency)
+ {
+ Assert.Equal(1f, r.Strengths[0]);
+ Assert.Equal((i + 1) * 0.01, r.Actor.SecondsInGoal, 9); // the goal in force keeps its own clock through the decision and the latency
+ Assert.Equal(0, (int)(e & TickEvents.GoalChanged));
+ }
+ else
+ {
+ Assert.Equal(TickEvents.GoalChanged, e & TickEvents.GoalChanged);
+ Assert.Equal(0.25f, r.Strengths[0]);
+ landed = true;
+ }
+ }
+ Assert.True(landed);
+ }
+
+ [Fact]
+ public void A_behaviours_phase_restarts_from_the_time_in_the_goal_not_the_clock()
+ {
+ var keys = Enumerable.Range(0, 4).Select(k => new[] { Quat.FromAxisAngle(0f, 0f, 1f, 0.3f * k), Quat.Identity }).ToArray();
+ var loop = Goal("loop", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, SecondsPerKey = 0.1, FlinchPose = keys[0], Hold = new HoldParameters { FlinchGain = 0.0, StrainShake = 0.0 } },
+ };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), loop } });
+ long changed = -1;
+ for (long i = 0; i < 600 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ }
+ Assert.True(changed > 0 && changed % 40 != 0, $"changed at {changed}: the loop is 40 ticks, a clock-driven phase would be hidden");
+ Assert.Equal(Quat.Nlerp(keys[0][0], keys[0][0], 0f).Z, r.Targets[0].Z); // key 0 exactly, the tick it takes over
+ for (var k = 0; k < 5; k++) r.Tick();
+ Assert.Equal(Quat.Nlerp(keys[0][0], keys[1][0], 0.5f).Z, r.Targets[0].Z, 5); // half way to key 1 after half a key
+ }
+
+ private static List<(long Tick, int Goal)> Hover(double dwell, double threshold)
+ {
+ var rage = Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, threshold)) with { MinDwellSeconds = dwell };
+ var brain = new Brain { Goals = new[] { Goal("calm", 1.0, 1.0) with { MinDwellSeconds = dwell }, rage } };
+ var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
+ var changes = new List<(long, int)>();
+ for (long i = 0; i < 6000; i++)
+ {
+ rig.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0; // on 1 s, off 1 s: arousal saws around its middle
+ if ((rig.Tick() & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
+ }
+ return changes;
+ }
+
+ [Fact]
+ public void A_condition_hovering_at_its_threshold_chatters_without_a_dwell_and_with_one_the_entered_goal_is_not_left_for_a_lower_one_inside_its_window()
+ {
+ double lo = 1, hi = 0;
+ var probe = new SensoryRig(SensoryRig.One(0.55), brain: new Brain { Goals = new[] { Goal("only", 0.0, 1.0) } });
+ for (long i = 0; i < 6000; i++)
+ {
+ probe.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0;
+ probe.Tick();
+ if (i >= 3000) { lo = Math.Min(lo, probe.Actor.Drive.Arousal); hi = Math.Max(hi, probe.Actor.Drive.Arousal); }
+ }
+ var mid = 0.5 * (lo + hi);
+
+ var free = Hover(0.0, mid);
+ Assert.True(free.Count >= 15, $"{free.Count} changes with no dwell: the scenario does not chatter");
+
+ const double dwell = 3.0;
+ const long dwellTicks = 300;
+ var held = Hover(dwell, mid);
+ Assert.True(held.Count >= 2 && held.Count * 2 <= free.Count, $"{held.Count} changes with a dwell of {dwell} s against {free.Count}");
+ var leaves = 0;
+ for (var i = 1; i < held.Count; i++)
+ {
+ if (held[i].Goal != 0) continue; // only the return trip (rage to the lower calm) is gated by rage's dwell
+ leaves++;
+ Assert.True(held[i].Tick - held[i - 1].Tick >= dwellTicks + Latency, $"rage taken at {held[i - 1].Tick} and left at {held[i].Tick}");
+ }
+ Assert.True(leaves >= 2);
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = -1.0 } } }));
+ foreach (var bad in new[] { double.PositiveInfinity, double.NaN })
+ {
+ Assert.Throws(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = bad } } }));
+ }
+ }
+
+ ///
+ /// Goal 1 is the start goal, eligible while pain is below 0.3, with the dwell; goal 0 (no dwell) is the lower-priority
+ /// goal always eligible. Pain passes 0.3 early, so the decision to leave goal 1 is held to its dwell and lands exactly then.
+ ///
+ private static (long Dwell, long Changed, long PainLapsed) LeaveHeldGoal(double dwellSeconds, double priorityOfTarget = 1.0)
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("target", priorityOfTarget, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
+ Goal("held", 2.0, 0.5, Pain(ConditionOp.Below, 0.3)) with { MinDwellSeconds = dwellSeconds },
+ },
+ Start = 1,
+ };
+ var r = new PainBoxReplay(1, brain: brain);
+ long lapsed = -1, changed = -1;
+ for (long i = 0; i < 800 && changed < 0; i++)
+ {
+ if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
+ if (lapsed < 0 && r.Actor.Drive.Pain >= 0.3) lapsed = i;
+ }
+ return (0, changed, lapsed);
+ }
+
+ [Fact]
+ public void A_goal_not_outranked_is_left_exactly_a_dwell_after_it_took_over_the_decision_held_on_the_dwells_last_tick()
+ {
+ // 3.0 s is 300 ticks from tick 0 (the start goal is active from there): the decision is taken on tick 300 and lands 10 later.
+ var (_, changed, lapsed) = LeaveHeldGoal(3.0);
+ Assert.True(lapsed > 0 && lapsed < 290, $"pain lapsed the condition on tick {lapsed}");
+ Assert.Equal(300 + Latency, changed);
+ // The dwell is the held goal's own (goal 1), not goal 0's, which has none.
+ var free = LeaveHeldGoal(0.0);
+ Assert.Equal(free.PainLapsed + Latency, free.Changed);
+ }
+
+ [Fact]
+ public void A_dwell_is_rounded_to_the_nearest_tick_as_the_latency_is()
+ {
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.004).Changed); // 300.4 ticks: a ceiling would make it 301
+ Assert.Equal(301 + Latency, LeaveHeldGoal(3.006).Changed); // 300.6 ticks: a floor would make it 300
+ }
+
+ [Fact]
+ public void A_strictly_higher_priority_goal_preempts_during_the_dwell_after_the_latency_and_a_goal_that_ties_or_ranks_below_is_held()
+ {
+ // Same scene, but the goal it would move to outranks the held one: no wait for the dwell.
+ var (_, preempted, lapsed) = LeaveHeldGoal(3.0, priorityOfTarget: 3.0);
+ Assert.Equal(lapsed + Latency, preempted);
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 2.0).Changed); // a tie is not strictly higher
+ Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 1.99).Changed);
+ }
+
+ [Fact]
+ public void The_dwell_of_an_entered_goal_counts_from_the_tick_it_took_over_not_from_the_decision()
+ {
+ // Held goal b is entered on pain at least 0.3 and its condition lapses at once (a band); its dwell of 2 s runs from the takeover.
+ var band = Goal("b", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) with { MinDwellSeconds = 2.0 };
+ var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 1.0), band } });
+ long decided = -1, entered = -1, left = -1;
+ for (long i = 0; i < 800 && left < 0; i++)
+ {
+ var e = r.Tick();
+ if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
+ if ((e & TickEvents.GoalChanged) != 0) { if (entered < 0) entered = i; else left = i; }
+ }
+ Assert.Equal(decided + Latency, entered);
+ Assert.Equal(entered + 200 + Latency, left);
+ }
+
+ [Fact]
+ public void A_built_brains_getters_hand_out_read_only_views_and_writing_through_them_changes_nothing()
+ {
+ var keys = new[] { new[] { Quat.Identity, Quat.Identity } };
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 0.0),
+ Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
+ {
+ Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+ static void Sealed(IReadOnlyList view, T poison)
+ {
+ Assert.False(view is T[]);
+ if (view is IList list)
+ {
+ Assert.True(list.IsReadOnly);
+ Assert.Throws(() => list[0] = poison);
+ }
+ }
+ Sealed(brain.Goals, Goal("poison", 9.0));
+ Sealed(brain.Goals[1].When, Pain(ConditionOp.AtLeast, double.NaN));
+ Sealed(brain.Goals[1].Behaviour.Keys, (IReadOnlyList)new Quat[1]);
+ Sealed(brain.Goals[1].Behaviour.Keys[0], new Quat(7f, 7f, 7f, 7f));
+ Sealed(brain.Goals[1].Behaviour.FlinchPose, new Quat(7f, 7f, 7f, 7f));
+
+ var a = new PainBoxReplay(1, brain: brain);
+ var b = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with { Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw } } } });
+ for (var i = 0; i < 1000; i++)
+ {
+ Assert.Equal(b.Tick(), a.Tick());
+ Assert.Equal(b.Targets, a.Targets);
+ }
+ }
+
+ [Fact]
+ public void A_validated_brain_does_not_follow_later_changes_to_the_lists_and_arrays_it_was_built_from()
+ {
+ Brain Build(out List goals, out Condition[] when, out Quat[][] keys, out Quat[] flinch)
+ {
+ when = new[] { Pain(ConditionOp.AtLeast, 0.3) };
+ keys = new[] { (Quat[])PainBoxBrain.Hold.Clone() };
+ flinch = (Quat[])PainBoxBrain.Withdraw.Clone();
+ goals = new List
+ {
+ Goal("a", 0.0),
+ Goal("b", 1.0, 0.5) with { When = when, Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = flinch } },
+ };
+ return new Brain { Goals = goals };
+ }
+
+ var brain = Build(out var goals, out var when, out var keys, out var flinch);
+ var twin = Build(out _, out _, out _, out _);
+ goals.Clear();
+ when[0] = Pain(ConditionOp.AtLeast, double.NaN);
+ keys[0][0] = new Quat(9f, 9f, 9f, 9f);
+ keys[0] = new Quat[1];
+ flinch[0] = new Quat(5f, 5f, 5f, 5f);
+
+ var a = new PainBoxReplay(1, brain: brain);
+ var b = new PainBoxReplay(1, brain: twin);
+ for (var i = 0; i < 1500; i++)
+ {
+ Assert.Equal(b.Tick(), a.Tick());
+ Assert.Equal(b.Targets, a.Targets);
+ }
+ Assert.Equal(2, brain.Goals.Count);
+ Assert.Equal(1, a.Actor.GoalIndex);
+ }
+}
diff --git a/tests/Lodur.Core.Tests/CalmSensesTests.cs b/tests/Lodur.Core.Tests/CalmSensesTests.cs
new file mode 100644
index 0000000..53a01fe
--- /dev/null
+++ b/tests/Lodur.Core.Tests/CalmSensesTests.cs
@@ -0,0 +1,202 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// A goal's sensory gain (lodur:ruling:stress-bar-shows-arousal-calm-silences) gates the sense channels' afferents after the conduction delay,
+/// builds Load from the gated values, and never touches the world's stimulus or the nociceptive region afferents.
+///
+public sealed class SensoryGainTests
+{
+ private const double Dt = 0.01;
+ private static readonly float[] Zero = { 0f };
+ private static readonly BoxStimulus[] NoBoxes = System.Array.Empty();
+ private static readonly Emitter[] Loud = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.6), new Emitter(Channel.Visual, 0f, 0f, 0f, 1f, 0.4) };
+
+ private static Perception Senses(NerveParameters senses, double delay = 0.0) =>
+ new Perception(new NerveParameters(), Dt, 1, senses with { ConductionDelaySeconds = delay }, 0);
+
+ [Fact]
+ public void Gain_one_leaves_every_afferent_and_the_load_bit_identical_to_no_gain()
+ {
+ var a = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
+ var b = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0 }, 0.03);
+ for (var i = 0; i < 300; i++)
+ {
+ a.Sense(Zero, Zero, Zero, NoBoxes, Loud);
+ b.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(a.Load, b.Load);
+ Assert.Equal(a.ChannelAfferent(Channel.Audio), b.ChannelAfferent(Channel.Audio));
+ Assert.Equal(a.ChannelAfferent(Channel.Visual), b.ChannelAfferent(Channel.Visual));
+ }
+
+ Assert.True(a.Load > 0.0);
+ }
+
+ [Fact]
+ public void Gain_scales_each_channels_afferent_and_builds_the_load_from_the_scaled_afferents_while_the_stimulus_is_the_worlds()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.5);
+ double audio = (0.6 - 0.05) * 0.5, visual = (0.4 - 0.05) * 0.5;
+ Assert.Equal(audio, p.ChannelAfferent(Channel.Audio), 12);
+ Assert.Equal(visual, p.ChannelAfferent(Channel.Visual), 12);
+ Assert.Equal(1.0 - (1.0 - audio) * (1.0 - visual), p.Load, 12);
+ Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
+
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Visual));
+ Assert.Equal(0.0, p.Load);
+ Assert.Equal(0.6, p.ChannelStimulus(Channel.Audio), 12);
+ Assert.Equal(0.4, p.ChannelStimulus(Channel.Visual), 12);
+ }
+
+ [Fact]
+ public void The_gain_in_force_when_the_afferent_leaves_the_delay_applies_not_the_gain_when_the_stimulus_entered()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0.05); // 5 ticks in flight
+ for (var i = 0; i < 20; i++) p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.True(p.ChannelAfferent(Channel.Audio) > 0.5);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0); // the same signal, gated as it arrives
+ Assert.Equal(0.0, p.ChannelAfferent(Channel.Audio));
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
+ }
+
+ [Fact]
+ public void Sensitisation_follows_the_world_not_the_gain()
+ {
+ var nerve = new NerveParameters { Threshold = 0.05, SensitisationGrowth = 2.0, SensitisationCap = 4.0 };
+ var deaf = Senses(nerve);
+ var hearing = Senses(nerve);
+ for (var i = 0; i < 200; i++)
+ {
+ deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ }
+
+ deaf.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ hearing.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(hearing.ChannelAfferent(Channel.Audio), deaf.ChannelAfferent(Channel.Audio));
+ Assert.True(deaf.ChannelAfferent(Channel.Audio) > 0.55, "the channel sensitised while it was gated");
+ }
+
+ [Fact]
+ public void Sense_refuses_a_gain_outside_zero_to_one_and_leaves_its_state_alone()
+ {
+ var p = Senses(new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 });
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ foreach (var bad in new[] { double.NaN, -0.01, 1.01, double.PositiveInfinity, double.NegativeInfinity })
+ {
+ var ex = Assert.Throws(() => p.Sense(Zero, Zero, Zero, NoBoxes, Loud, bad));
+ Assert.Contains("gain", ex.Message);
+ }
+
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 0.0);
+ p.Sense(Zero, Zero, Zero, NoBoxes, Loud, 1.0);
+ Assert.Equal(0.55, p.ChannelAfferent(Channel.Audio), 12);
+ }
+
+ private static Brain GainGoal(double gain, string id = "g") => new()
+ {
+ Goals = new[] { new GoalSpec { Id = id, SensoryGain = gain, Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw } } },
+ };
+
+ [Fact]
+ public void A_goal_with_gain_zero_silences_load_and_channel_afferents_but_not_the_pain_path_or_the_world_stimulus()
+ {
+ var events = new List[2] { new(), new() };
+ var afferent = new List[2] { new(), new() };
+ var flinches = new int[2];
+ var gains = new[] { 1.0, 0.0 };
+ var p = new[] { 0f };
+ for (var k = 0; k < 2; k++)
+ {
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters() with { ResolveDrainPain = 0.0, ResolveDrainStrain = 0.0, ResolveDrainArousal = 0.0 },
+ GainGoal(gains[k]), new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
+ actor.SetAttention(0.4); // a will that holds only part of the reflex down, so flinches leak
+ Assert.Equal(gains[k], actor.Drive.SensoryGain);
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.8 } };
+ for (var i = 0; i < 600; i++)
+ {
+ var e = actor.Tick(p, p, p, box, strengths, targets, Loud);
+ events[k].Add(e);
+ afferent[k].Add(actor.Afferent(0));
+ if ((e & TickEvents.Flinch) != 0) flinches[k]++;
+ if (i >= 10)
+ {
+ Assert.Equal(0.6, actor.ChannelStimulus(Channel.Audio), 12);
+ if (k == 1)
+ {
+ Assert.Equal(0.0, actor.Load);
+ Assert.Equal(0.0, actor.ChannelAfferent(Channel.Audio));
+ }
+ else
+ {
+ Assert.True(actor.Load > 0.0);
+ }
+ }
+ }
+ }
+
+ Assert.True(flinches[1] > 0, "the fixture flinches");
+ Assert.Equal(events[0], events[1]);
+ Assert.Equal(afferent[0], afferent[1]);
+ }
+
+ [Fact]
+ public void The_start_goals_gain_holds_at_construction_and_a_later_goal_sets_it_the_tick_it_takes_over()
+ {
+ var pose = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
+ var brain = new Brain
+ {
+ Start = 0,
+ Goals = new[]
+ {
+ new GoalSpec { Id = "a", SensoryGain = 0.25, Behaviour = pose },
+ new GoalSpec { Id = "b", Priority = 1.0, SensoryGain = 0.75, When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = pose },
+ },
+ };
+ var actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain);
+ Assert.Equal(0.25, actor.Drive.SensoryGain);
+ var p = new[] { 0f };
+ var box = new[] { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) { Intensity = 0.9 } };
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ for (var i = 0; i < 2000; i++)
+ {
+ var e = actor.Tick(p, p, p, box, strengths, targets);
+ if ((e & TickEvents.GoalChanged) != 0)
+ {
+ Assert.Equal(1, actor.GoalIndex);
+ Assert.Equal(0.75, actor.Drive.SensoryGain);
+ return;
+ }
+
+ Assert.Equal(0.25, actor.Drive.SensoryGain);
+ }
+
+ Assert.Fail("the second goal never took over");
+ }
+
+ [Fact]
+ public void SensoryGain_outside_zero_to_one_or_not_a_number_is_refused_naming_the_goal()
+ {
+ void Refused(double gain)
+ {
+ var ex = Assert.Throws(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(gain, "bad")));
+ Assert.Contains("bad", ex.Message);
+ }
+
+ Refused(-0.01);
+ Refused(1.01);
+ Refused(double.NaN);
+ Refused(double.PositiveInfinity);
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(0.0));
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), GainGoal(1.0));
+ }
+}
diff --git a/tests/Lodur.Core.Tests/EntryRampTests.cs b/tests/Lodur.Core.Tests/EntryRampTests.cs
new file mode 100644
index 0000000..a5a5d64
--- /dev/null
+++ b/tests/Lodur.Core.Tests/EntryRampTests.cs
@@ -0,0 +1,249 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// The entry ramp (lodur:ruling:flinch-tail-after-stimulus): a goal's arousal and sensory-gain targets are reached linearly over EntrySeconds from
+/// their values at takeover, so the stress bar and the flinch drive tail off rather than cut; after it the drive owns arousal.
+///
+public sealed class EntryRampTests
+{
+ private const double Dt = 0.01;
+ private const double Afferent = 0.5; // an emitter of 0.55 through a 0.05 threshold, no sensitisation, gain 1
+ private static readonly PoseBehaviour Pose = new() { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw };
+
+ /// Stress is the Start goal; calm takes over once arousal reaches 0.2 and holds (its dwell outlasts every test).
+ private static Brain StressThenCalm(double entrySeconds, double gain = 0.0, double? arousal = 0.0) => new()
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "stress", Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = gain, EntryArousal = arousal, EntrySeconds = entrySeconds,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ },
+ };
+
+ private sealed class Rig
+ {
+ public readonly Actor Actor;
+ private readonly Emitter[] _emitters = { new Emitter(Channel.Audio, 0f, 0f, 0f, 1f, 0.55) };
+ private readonly BoxStimulus[] _box = { new BoxStimulus(0f, 0f, 0f, 1f, 1f, 1f) };
+ private readonly float[] _p = { 0f };
+ private readonly float[] _strengths = new float[2];
+ private readonly Quat[] _targets = new Quat[2];
+
+ public Rig(Brain brain) =>
+ Actor = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0 }, 0);
+
+ public double Pain { set => _box[0].Intensity = value; }
+
+ public TickEvents Tick() => Actor.Tick(_p, _p, _p, _box, _strengths, _targets, _emitters);
+
+ /// Ticks until the goal at takes over; the takeover tick has just run.
+ public void UntilTakeover(int goal)
+ {
+ for (var i = 0; i < 20000; i++)
+ {
+ if ((Tick() & TickEvents.GoalChanged) != 0 && Actor.GoalIndex == goal) return;
+ }
+
+ Assert.Fail("the goal never took over");
+ }
+ }
+
+ [Fact]
+ public void A_three_second_ramp_takes_arousal_and_load_linearly_to_exactly_zero_on_its_last_tick_and_not_before_and_they_stay_zero_under_steady_emitters()
+ {
+ var rig = new Rig(StressThenCalm(3.0));
+ rig.UntilTakeover(1);
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(a0 >= 0.2);
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
+ const int ticks = 300;
+ for (var k = 1; k <= ticks + 500; k++)
+ {
+ rig.Tick();
+ var ramp = Math.Max(0.0, 1.0 - (double)k / ticks);
+ // Sense reads the gain the ramp left at the end of the previous tick.
+ var senseGain = Math.Max(0.0, 1.0 - (double)(k - 1) / ticks);
+ Assert.Equal(a0 * ramp, rig.Actor.Drive.Arousal, 12);
+ Assert.Equal(ramp, rig.Actor.Drive.SensoryGain, 12);
+ Assert.Equal(Afferent * senseGain, rig.Actor.Load, 12);
+ Assert.Equal(0.55, rig.Actor.ChannelStimulus(Channel.Audio), 12); // the world keeps sounding
+ if (k < ticks) Assert.True(rig.Actor.Drive.Arousal > 0.0 && rig.Actor.Drive.SensoryGain > 0.0, $"still above zero at {k * Dt:0.00} s");
+ if (k >= ticks)
+ {
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ }
+
+ if (k > ticks) Assert.Equal(0.0, rig.Actor.Load);
+ }
+ }
+
+ [Fact]
+ public void A_ramp_of_zero_seconds_reaches_the_targets_on_the_takeover_tick()
+ {
+ var rig = new Rig(StressThenCalm(0.0));
+ rig.UntilTakeover(1);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ for (var i = 0; i < 300; i++)
+ {
+ rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Load);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+ }
+
+ [Fact]
+ public void A_ramp_ends_exactly_on_a_nonzero_target_not_a_float_step_away_from_it()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "a", SensoryGain = 0.8, Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "b", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.15, EntryArousal = 0.05, EntrySeconds = 0.5,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ },
+ };
+ var rig = new Rig(brain);
+ Assert.Equal(0.8, rig.Actor.Drive.SensoryGain);
+ rig.UntilTakeover(1);
+ for (var k = 1; k < 50; k++) rig.Tick();
+ Assert.NotEqual(0.15, rig.Actor.Drive.SensoryGain);
+ rig.Tick(); // the ramp's last tick
+ Assert.Equal(0.15, rig.Actor.Drive.SensoryGain); // 0.8 + (0.15 - 0.8) * 1 is not 0.15 in a double
+ Assert.Equal(0.05, rig.Actor.Drive.Arousal); // from the arousal at takeover, 0.2142..., a lerp lands a step off 0.05 too
+ }
+
+ [Fact]
+ public void A_huge_finite_EntrySeconds_is_an_unending_ramp_not_a_snap_or_a_wrap()
+ {
+ // 1e300 / 0.01 is past the long range. On .NET 10 the cast of such a double saturates, so the guard in the Actor is not observable here
+ // (its mutant is equivalent on this runtime); the behaviour it protects on runtimes where the cast is undefined is pinned.
+ var rig = new Rig(StressThenCalm(1e300));
+ rig.UntilTakeover(1);
+ for (var i = 0; i < 2000; i++) rig.Tick();
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain, 12);
+ Assert.True(rig.Actor.Drive.Arousal > 0.0);
+ Assert.True(rig.Actor.Load > 0.0);
+ }
+
+ [Fact]
+ public void The_ramp_length_is_rounded_to_whole_ticks_so_a_quotient_just_under_an_integer_gets_that_integer()
+ {
+ var rig = new Rig(StressThenCalm(0.29)); // 0.29 / 0.01 is 28.999999999999996 ticks, not 28
+ rig.UntilTakeover(1);
+ for (var k = 1; k <= 29; k++)
+ {
+ rig.Tick();
+ if (k < 29) Assert.True(rig.Actor.Drive.SensoryGain > 0.0, $"still ramping at tick {k}");
+ }
+
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+
+ [Fact]
+ public void A_goal_without_an_entry_arousal_ramps_only_the_gain_and_the_drive_keeps_arousal()
+ {
+ var rig = new Rig(StressThenCalm(2.0, gain: 0.0, arousal: null));
+ rig.UntilTakeover(1);
+ var before = rig.Actor.Drive.Arousal;
+ rig.Tick();
+ // One tick of the drive's own law under the gate (the sense still reads gain 1 on the first tick after takeover): arousal moves by it, not by any ramp.
+ var p = new DriveParameters();
+ var expected = Math.Min(Math.Max(before + Dt * (p.ArousalRise * Afferent * (1.0 - before) - p.ArousalDecay * before), 0.0), 1.0);
+ Assert.Equal(expected, rig.Actor.Drive.Arousal, 12);
+ for (var i = 0; i < 6000; i++) rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.True(rig.Actor.Drive.Arousal < 0.01, "with the gain at zero the drive decays arousal on its own");
+ }
+
+ [Fact]
+ public void A_goal_that_takes_over_mid_ramp_ramps_from_where_the_last_ramp_had_got_to()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "stress", Behaviour = Pose },
+ new GoalSpec
+ {
+ Id = "calm", Priority = 1.0, MinDwellSeconds = 1000.0, SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0,
+ When = new[] { new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, 0.2) }, Behaviour = Pose,
+ },
+ new GoalSpec
+ {
+ Id = "alert", Priority = 2.0, SensoryGain = 1.0, EntryArousal = 0.9, EntrySeconds = 2.0,
+ When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.05) }, Behaviour = Pose,
+ },
+ },
+ };
+ var rig = new Rig(brain);
+ rig.UntilTakeover(1);
+ for (var i = 0; i < 100; i++) rig.Tick(); // 1 s into the 3 s ramp
+ Assert.True(rig.Actor.Drive.SensoryGain is > 0.0 and < 1.0);
+ rig.Pain = 0.8;
+ rig.UntilTakeover(2);
+ var g0 = rig.Actor.Drive.SensoryGain;
+ var a0 = rig.Actor.Drive.Arousal;
+ Assert.True(g0 is > 0.0 and < 0.7, "alert took over partway down calm's ramp");
+ for (var k = 1; k <= 200; k++)
+ {
+ rig.Tick();
+ var f = k / 200.0;
+ Assert.Equal(g0 + (1.0 - g0) * f, rig.Actor.Drive.SensoryGain, 12);
+ Assert.Equal(a0 + (0.9 - a0) * f, rig.Actor.Drive.Arousal, 12);
+ }
+
+ Assert.Equal(1.0, rig.Actor.Drive.SensoryGain);
+ }
+
+ [Fact]
+ public void The_start_goals_targets_hold_from_construction_and_under_steady_emitters()
+ {
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "calm", SensoryGain = 0.0, EntryArousal = 0.0, EntrySeconds = 3.0, Behaviour = Pose } } };
+ var rig = new Rig(brain);
+ Assert.Equal(0.0, rig.Actor.Drive.SensoryGain);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ for (var i = 0; i < 600; i++)
+ {
+ rig.Tick();
+ Assert.Equal(0.0, rig.Actor.Load);
+ Assert.Equal(0.0, rig.Actor.Drive.Arousal);
+ }
+
+ var warm = new Rig(new Brain { Goals = new[] { new GoalSpec { Id = "wound", EntryArousal = 0.6, Behaviour = Pose } } });
+ Assert.Equal(0.6, warm.Actor.Drive.Arousal);
+ }
+
+ [Fact]
+ public void EntryArousal_outside_zero_to_one_and_a_negative_NaN_or_infinite_EntrySeconds_are_refused_naming_the_goal()
+ {
+ void Refused(GoalSpec g)
+ {
+ var ex = Assert.Throws(() => new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { g } }));
+ Assert.Contains("bad", ex.Message);
+ }
+
+ GoalSpec Base() => new() { Id = "bad", Behaviour = Pose };
+ Refused(Base() with { EntryArousal = -0.01 });
+ Refused(Base() with { EntryArousal = 1.01 });
+ Refused(Base() with { EntryArousal = double.NaN });
+ Refused(Base() with { EntrySeconds = -0.01 });
+ Refused(Base() with { EntrySeconds = double.NaN });
+ Refused(Base() with { EntrySeconds = double.PositiveInfinity });
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 0.0, EntrySeconds = 5.0 } } });
+ _ = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), new Brain { Goals = new[] { Base() with { EntryArousal = 1.0 } } });
+ }
+}
diff --git a/tests/Lodur.Core.Tests/GoalTargetTests.cs b/tests/Lodur.Core.Tests/GoalTargetTests.cs
new file mode 100644
index 0000000..0d0ba62
--- /dev/null
+++ b/tests/Lodur.Core.Tests/GoalTargetTests.cs
@@ -0,0 +1,475 @@
+using System;
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+public sealed class GoalTargetTests
+{
+ private const double Dt = 0.01;
+ private const uint Thing = 7;
+ private const uint Other = 9;
+ private static readonly float[] Zero = { 0f };
+ private static readonly BoxStimulus[] NoBoxes = Array.Empty();
+
+ private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Consideration[]? considerations = null, params Condition[] when) => new()
+ {
+ Id = id, Priority = priority, When = when, Target = target, Considerations = considerations ?? Array.Empty(),
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ };
+
+ private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds };
+
+ private static Consideration Nearer(double far) => new(ConsiderationInput.Distance, 0.0, far, 1.0, 0.0);
+
+ private static Emitter At(ulong id, float x, uint kind = Thing, double intensity = 1.0, float radius = 20f) =>
+ new(Channel.Audio, x, 0f, 0f, radius, intensity, id, kind);
+
+ private static Perception Ears(int capacity = 4, double memory = 5.0) =>
+ new(new NerveParameters(), Dt, 1, new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 },
+ 0, new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
+
+ private static Perception Hearing(params Emitter[] emitters)
+ {
+ var p = Ears();
+ p.Sense(Zero, Zero, Zero, NoBoxes, emitters, 1.0);
+ return p;
+ }
+
+ private static Choice Pick(Brain brain, Perception p, Choice current, DriveState drive = default) => brain.Select(drive, p, 0f, 0f, 0f, current);
+
+ private static int SlotOf(Perception p, ulong id)
+ {
+ for (var s = 0; s < p.PerceptCount; s++)
+ {
+ if (p.Percept(s).Id == id) return s;
+ }
+
+ return -1;
+ }
+
+ [Fact]
+ public void An_untargeted_brain_selects_as_before()
+ {
+ var calm = default(DriveState);
+ var always = new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0);
+ var hears = Hearing(At(1, 1f));
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("a", 2.0, when: always), Goal("b", 5.0, when: always), Goal("c", 5.0, when: always),
+ Goal("d", 9.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)),
+ },
+ };
+ // Percepts in the room change nothing for goals that name no target.
+ Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(0, 0), calm));
+ Assert.Equal(new Choice(2, 0), Pick(brain, hears, new Choice(2, 0), calm));
+ Assert.Equal(new Choice(1, 0), Pick(brain, hears, new Choice(3, 0), calm));
+ var none = new Brain { Goals = new[] { Goal("x", 1.0, when: new Condition(DriveQuantity.Pain, ConditionOp.AtLeast, 0.5)) } };
+ // Nothing eligible: the goal in force stays and lets go of its target.
+ Assert.Equal(new Choice(0, 0), Pick(none, hears, new Choice(0, 77), calm));
+ }
+
+ [Fact]
+ public void A_targeted_goal_with_no_percept_of_its_kinds_is_not_chosen()
+ {
+ var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Other)) } };
+ // A percept of another kind, and free slots (Id 0), make no pair.
+ var wrongKind = Hearing(At(1, 1f, Thing));
+ Assert.Equal(new Choice(0, 0), Pick(brain, wrongKind, new Choice(0, 0)));
+ Assert.Equal(new Choice(0, 0), Pick(brain, Ears(), new Choice(0, 0)));
+
+ var rightKind = Hearing(At(1, 1f, Thing), At(2, 3f, Other));
+ Assert.Equal(new Choice(1, 2), Pick(brain, rightKind, new Choice(0, 0)));
+
+ // Only targeted goals, none with a percept: the goal in force stays and lets go of its target (finding stale-target-without-pair).
+ var only = new Brain { Goals = new[] { Goal("chase", 5.0, Kinds(Other)) } };
+ Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 0)));
+ Assert.Equal(new Choice(0, 0), Pick(only, wrongKind, new Choice(0, 55)));
+ }
+
+ [Fact]
+ public void Considerations_multiply_priority_and_the_best_pair_wins()
+ {
+ // Distance: the nearer of two things.
+ var near = Hearing(At(1, 6f), At(2, 2f));
+ var go = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 2), Pick(go, near, default));
+
+ // Salience: the louder thing wins when the curve rises; the quieter when it falls.
+ var loud = Hearing(At(1, 1f, intensity: 0.2), At(2, 1f, intensity: 0.9));
+ var rising = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) }) } };
+ var falling = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 1.0, 0.0) }) } };
+ Assert.Equal(2UL, Pick(rising, loud, default).Target);
+ Assert.Equal(1UL, Pick(falling, loud, default).Target);
+
+ // Priority times the Drive curve: a goal at priority 4 whose Arousal curve zeroes it loses to priority 1.
+ var drained = new DriveState { Arousal = 0.0 };
+ var duel = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("brave", 4.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0, 1.0, DriveQuantity.Arousal) }),
+ Goal("plain", 1.0, Kinds(Thing)),
+ },
+ };
+ Assert.Equal(1, Pick(duel, near, default, drained).Goal);
+ Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 1.0 }).Goal);
+ Assert.Equal(0, Pick(duel, near, default, new DriveState { Arousal = 0.5 }).Goal); // 2.0 > 1.0
+
+ // The curve itself: clamped, shaped by the exponent, inverted by Y0 > Y1.
+ var c = new Consideration(ConsiderationInput.Salience, 2.0, 4.0, 0.0, 1.0, 2.0);
+ Assert.Equal(0.0, c.Response(1.0));
+ Assert.Equal(0.25, c.Response(3.0));
+ Assert.Equal(1.0, c.Response(9.0));
+ }
+
+ [Fact]
+ public void Ties_go_to_the_current_pair_then_lowest_goal_then_lowest_slot()
+ {
+ // Equal distance on either side of the observer: two equal scores in slots 0 and 1.
+ var twins = Hearing(At(10, 3f), At(20, -3f));
+ Assert.True(SlotOf(twins, 10) < SlotOf(twins, 20));
+ var one = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 10), Pick(one, twins, default)); // lowest slot
+ Assert.Equal(new Choice(0, 20), Pick(one, twins, new Choice(0, 20))); // the current pair
+ Assert.Equal(new Choice(0, 10), Pick(one, twins, new Choice(0, 10)));
+
+ var two = new Brain { Goals = new[] { Goal("a", 1.0, Kinds(Thing), new[] { Nearer(10.0) }), Goal("b", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } };
+ Assert.Equal(new Choice(0, 10), Pick(two, twins, new Choice(1, 99))); // lowest goal, then slot
+ Assert.Equal(new Choice(1, 20), Pick(two, twins, new Choice(1, 20))); // current beats the lower goal
+ }
+
+ [Fact]
+ public void Commitment_holds_the_current_target_until_a_challenger_beats_it_by_the_multiplier()
+ {
+ // Distance 2 scores 0.75, distance 4 scores 0.5 on a curve over 8.
+ var hears = Hearing(At(1, 4f), At(2, 2f));
+ Brain With(double commitment) => new() { TargetCommitment = commitment, Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }) } };
+ Assert.Equal(2UL, Pick(With(1.0), hears, new Choice(0, 1)).Target); // no commitment: the nearer wins
+ Assert.Equal(2UL, Pick(With(1.4), hears, new Choice(0, 1)).Target); // 0.5 * 1.4 = 0.70 < 0.75
+ Assert.Equal(1UL, Pick(With(1.5), hears, new Choice(0, 1)).Target); // 0.75 tie goes to the current pair
+ Assert.Equal(1UL, Pick(With(2.0), hears, new Choice(0, 1)).Target);
+ Assert.Equal(2UL, Pick(With(2.0), hears, default).Target); // the multiplier is for the current pair only
+
+ // It does not carry over to another goal's pair on the same target.
+ var rival = new Brain
+ {
+ TargetCommitment = 2.0,
+ Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(8.0) }), Goal("flee", 1.2, Kinds(Thing), new[] { Nearer(8.0) }) },
+ };
+ Assert.Equal(new Choice(0, 1), Pick(rival, hears, new Choice(0, 1))); // 0.5 * 2.0 = 1.0 beats flee's 1.2 * 0.75 = 0.9, on the same thing or the nearer
+ Assert.Equal(new Choice(1, 2), Pick(rival, hears, default)); // uncommitted, flee on the nearer wins
+ }
+
+ private static Actor Hunter(Brain brain, int capacity = 4, double memory = 5.0) =>
+ new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = capacity, MemorySeconds = memory });
+
+ private static TickEvents Tick(Actor a, params Emitter[] emitters) =>
+ a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
+
+ [Fact]
+ public void A_retarget_waits_the_latency_and_fires_no_goal_change_or_entry_effect()
+ {
+ var brain = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("idle", 0.0),
+ new GoalSpec
+ {
+ Id = "chase", Priority = 1.0, EntryResolve = 0.9, Effort = 0.1, Target = Kinds(Thing), Considerations = new[] { Nearer(30.0) },
+ When = new[] { new Condition(DriveQuantity.Pain, ConditionOp.Below, 1.0) },
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+ var a = Hunter(brain);
+ // Takes over the goal and the nearer thing, a latency after it is first heard.
+ var changes = 0;
+ for (var i = 0; i < 40; i++) changes += (Tick(a, At(1, 5f), At(2, 9f)) & TickEvents.GoalChanged) != 0 ? 1 : 0;
+ Assert.Equal(1, changes);
+ Assert.Equal(1, a.GoalIndex);
+ Assert.Equal(1UL, a.TargetId);
+ Assert.Equal(1UL, a.Target.Id);
+
+ for (var i = 0; i < 50; i++) Tick(a, At(1, 5f), At(2, 9f));
+ var inGoal = a.SecondsInGoal;
+ var resolve = a.Drive.Resolve;
+ Assert.True(resolve < 0.89, "the goal's effort should have drained resolve below its entry value by now");
+
+ // Thing 2 comes closer than thing 1: the pair changes a latency later, and nothing else does.
+ long first = -1;
+ for (var i = 0; i < 30; i++)
+ {
+ var e = Tick(a, At(1, 5f), At(2, 1f));
+ Assert.Equal(TickEvents.None, e & TickEvents.GoalChanged);
+ if (first < 0 && a.TargetId == 2) first = i;
+ if (first < 0)
+ {
+ Assert.Equal(1UL, a.TargetId);
+ Assert.Equal(1, a.GoalIndex);
+ }
+ }
+
+ Assert.Equal(10, first); // Latency: round(0.1 s / 10 ms)
+ Assert.Equal(2UL, a.Target.Id);
+ Assert.Equal(inGoal + 30 * Dt, a.SecondsInGoal, 9);
+ Assert.True(a.Drive.Resolve < resolve, "EntryResolve must not be applied again by a retarget: resolve keeps draining");
+ }
+
+ private static Emitter AtXyz(ulong id, float x, float y, float z, double intensity = 1.0) =>
+ new(Channel.Audio, x, y, z, 40f, intensity, id, Thing);
+
+ private static Perception HearingAt(params Emitter[] emitters)
+ {
+ var p = Ears(8);
+ p.Sense(Zero, Zero, Zero, NoBoxes, emitters, 1.0);
+ return p;
+ }
+
+ private static ulong Nearest(Perception p, float ox, float oy, float oz)
+ {
+ var brain = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(60.0) }) } };
+ return brain.Select(default, p, ox, oy, oz, default).Target;
+ }
+
+ [Fact]
+ public void Distance_is_euclidean_over_all_three_axes_from_the_observer_point()
+ {
+ // Each pair ranks differently under a dropped axis, a Manhattan sum, or a mixed-up observer coordinate.
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 2f, 0f, 0f), AtXyz(2, 1f, 5f, 0f)), 0f, 0f, 0f)); // dy matters
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 2f, 0f, 0f), AtXyz(2, 1f, 0f, 5f)), 0f, 0f, 0f)); // dz matters
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 0f, 2f, 0f), AtXyz(2, 5f, 1f, 0f)), 0f, 0f, 0f)); // dx matters
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 3f, 3f, 0f), AtXyz(2, 5f, 0f, 0f)), 0f, 0f, 0f)); // 4.24 < 5, though 6 > 5
+ // The observer is a point, each coordinate its own: swapping any two moves the answer.
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 6f, 3f, 0f), AtXyz(2, 3f, 1f, 0f)), 6f, 1f, 0f)); // x with y
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 6f, 0f, 3f), AtXyz(2, 3f, 0f, 1f)), 6f, 0f, 1f)); // x with z
+ Assert.Equal(1UL, Nearest(HearingAt(AtXyz(1, 0f, 6f, 3f), AtXyz(2, 0f, 3f, 1f)), 0f, 6f, 1f)); // y with z
+ }
+
+ [Fact]
+ public void A_percept_is_scored_by_its_age_and_by_every_consideration()
+ {
+ // Thing 1 (slot 0) falls silent while thing 2 keeps sounding: the fresher thing wins on a falling age curve.
+ var p = Ears(4, 5.0);
+ p.Sense(Zero, Zero, Zero, NoBoxes, new[] { At(1, 3f), At(2, 3f) }, 1.0);
+ for (var i = 0; i < 100; i++) p.Sense(Zero, Zero, Zero, NoBoxes, new[] { At(2, 3f) }, 1.0);
+ Assert.True(p.Percept(SlotOf(p, 1)).SecondsSinceSensed > 0.9);
+ var young = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 5.0, 1.0, 0.0) }) } };
+ Assert.Equal(2UL, Pick(young, p, default).Target);
+ var stale = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 5.0, 0.0, 1.0) }) } };
+ Assert.Equal(1UL, Pick(stale, p, default).Target);
+
+ // Two considerations multiply: the nearer thing is quiet, the farther loud; the second curve decides.
+ var mixed = Hearing(At(1, 2f, intensity: 0.05), At(2, 6f, intensity: 1.0));
+ Assert.Equal(1UL, Pick(new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0) }) } }, mixed, default).Target);
+ var both = new Brain { Goals = new[] { Goal("go", 1.0, Kinds(Thing), new[] { Nearer(10.0), new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) }) } };
+ Assert.Equal(2UL, Pick(both, mixed, default).Target);
+ }
+
+ [Fact]
+ public void A_filter_holds_several_kinds_and_a_free_slot_is_never_a_target_even_of_kind_zero()
+ {
+ var brain = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Other, Thing)) } };
+ Assert.Equal(new Choice(1, 1), Pick(brain, Hearing(At(1, 2f, Thing)), default));
+ var rev = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(Thing, Other)) } };
+ Assert.Equal(new Choice(1, 1), Pick(rev, Hearing(At(1, 2f, Other)), default));
+
+ // Free slots read Kind 0 and Id 0; a filter naming kind 0 still finds nothing in them.
+ var zero = new Brain { Goals = new[] { Goal("idle", 1.0), Goal("chase", 5.0, Kinds(0u)) } };
+ Assert.Equal(new Choice(0, 0), Pick(zero, Ears(), new Choice(0, 0)));
+ Assert.Equal(new Choice(0, 0), Pick(zero, Hearing(At(1, 2f, Thing)), new Choice(0, 0)));
+ }
+
+ private static Actor HunterAt(Brain brain, int regions, int senseRegion) =>
+ new(Dt, regions, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, senseRegion,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 });
+
+ [Fact]
+ public void The_actor_measures_distance_from_the_sense_region_point()
+ {
+ var brain = new Brain { Goals = new[] { Goal("idle", 0.0), Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(60.0) }) } };
+ var a = HunterAt(brain, 2, 1);
+ var x = new[] { 0f, 10f };
+ var y = new[] { 0f, 3f };
+ var z = new[] { 0f, 2f };
+ // Thing 1 is one unit from the sense region's point. Each of the others sits on the point a wrong reading would use:
+ // region 0, the point with y and z zeroed, and the point with x and y swapped.
+ var emitters = new[] { AtXyz(1, 11f, 3f, 2f), AtXyz(2, 0f, 0f, 0f), AtXyz(3, 10f, 0f, 0f), AtXyz(4, 3f, 10f, 2f) };
+ for (var i = 0; i < 40; i++) a.Tick(x, y, z, NoBoxes, new float[2], new Quat[2], emitters);
+ Assert.Equal(1UL, a.TargetId);
+ }
+
+ [Fact]
+ public void A_goal_without_a_target_clears_the_target_and_a_retarget_ignores_the_goals_dwell()
+ {
+ var brain = new Brain { Goals = new[] { Goal("idle", 0.0), Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) } };
+ var a = Hunter(brain, memory: 0.2);
+ for (var i = 0; i < 40; i++) Tick(a, At(1, 5f));
+ Assert.Equal(1, a.GoalIndex);
+ Assert.Equal(1UL, a.TargetId);
+ // The thing is forgotten; only the untargeted goal has a pair, and it takes no target with it.
+ for (var i = 0; i < 80; i++) Tick(a);
+ Assert.Equal(0, a.GoalIndex);
+ Assert.Equal(0UL, a.TargetId);
+
+ // Within a long dwell, another thing in the same goal is taken a latency later all the same.
+ var held = new Brain
+ {
+ Goals = new[]
+ {
+ Goal("idle", 0.0),
+ new GoalSpec
+ {
+ Id = "chase", Priority = 1.0, MinDwellSeconds = 5.0, Target = Kinds(Thing), Considerations = new[] { Nearer(30.0) },
+ Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw },
+ },
+ },
+ };
+ var b = Hunter(held);
+ for (var i = 0; i < 40; i++) Tick(b, At(1, 5f), At(2, 9f));
+ Assert.Equal(1UL, b.TargetId);
+ for (var i = 0; i < 30; i++) Tick(b, At(1, 5f), At(2, 1f));
+ Assert.Equal(2UL, b.TargetId);
+ Assert.True(b.SecondsInGoal < 5.0);
+ }
+
+ [Fact]
+ public void A_forgotten_target_reads_id_zero_and_the_brain_reselects()
+ {
+ var brain = new Brain { Goals = new[] { Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) } };
+ var a = Hunter(brain, capacity: 2, memory: 0.2);
+ for (var i = 0; i < 30; i++) Tick(a, At(1, 2f), At(2, 9f));
+ Assert.Equal(1UL, a.TargetId);
+
+ // Thing 1 stops sounding and is forgotten after its memory; its slot is taken by thing 3, which must not be read as the target.
+ var window = false;
+ for (var i = 0; i < 120 && a.TargetId == 1; i++)
+ {
+ Tick(a, At(2, 9f), At(3, 15f));
+ if (a.TargetId == 1 && a.Target.Id == 0) window = true;
+ Assert.NotEqual(3UL, a.Target.Id);
+ }
+
+ Assert.True(window, "the committed id outlived its percept, which should read as the default percept");
+ Assert.Equal(2UL, a.TargetId);
+ Assert.Equal(2UL, a.Target.Id);
+ }
+
+ [Fact]
+ public void Target_filters_and_considerations_are_validated()
+ {
+ static Actor Make(GoalSpec g, double commitment = 1.0) => new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
+ new Brain { Goals = new[] { g }, TargetCommitment = commitment });
+ var ok = Goal("ok", 1.0, Kinds(Thing), new[] { Nearer(5.0) });
+ Make(ok);
+
+ var bad = new Action[]
+ {
+ () => Make(Goal("g", 1.0, Kinds())),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, double.NaN, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, double.PositiveInfinity, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 2.0, 2.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, -0.1, 1.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.1) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, 0.0) })),
+ () => Make(Goal("g", 1.0, Kinds(Thing), new[] { new Consideration(ConsiderationInput.Distance, 0.0, 1.0, 0.0, 1.0, double.NaN) })),
+ () => Make(Goal("g", 1.0, null, new[] { Nearer(5.0) })),
+ () => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.SecondsSinceSensed, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(Goal("g", -1.0, Kinds(Thing))),
+ () => Make(Goal("g", -1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) })),
+ () => Make(ok, 0.99),
+ () => Make(ok, double.NaN),
+ () => Make(ok, double.PositiveInfinity),
+ };
+ for (var i = 0; i < bad.Length; i++)
+ {
+ Assert.True(Throws(bad[i]), $"case {i} was accepted");
+ }
+
+ // A negative priority stays legal on a goal with neither.
+ Make(Goal("g", -1.0));
+ Make(Goal("g", 1.0, null, new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.0, 1.0) }));
+
+ static bool Throws(Action a)
+ {
+ try { a(); return false; }
+ catch (ArgumentException e) { return e.Message.Contains("g") || e.Message.Contains("TargetCommitment"); }
+ }
+ }
+
+ [Fact]
+ public void Ticking_with_targets_allocates_nothing()
+ {
+ var brain = new Brain
+ {
+ TargetCommitment = 1.2,
+ Goals = new[]
+ {
+ Goal("idle", 0.0),
+ Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0), new Consideration(ConsiderationInput.Salience, 0.0, 1.0, 0.2, 1.0), new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.5, 1.0, 1.0, DriveQuantity.Arousal) }),
+ },
+ };
+ var a = Hunter(brain);
+ var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
+ for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++)
+ {
+ emitters[1] = At(2, 9f - (i % 8));
+ a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters);
+ }
+
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ Assert.NotEqual(0UL, a.TargetId);
+ }
+
+ [Fact]
+ public void Ticking_with_a_want_goal_allocates_nothing()
+ {
+ const int Open = 0, Locked = 1;
+ var fact = new Fact(FactSubject.This, Open, true);
+ var brain = new Brain
+ {
+ PlanDepth = 4, TargetCommitment = 1.2,
+ Goals = new[]
+ {
+ Goal("idle", 0.5),
+ Goal("chase", 1.0, Kinds(Thing), new[] { Nearer(30.0) }) with { Want = fact },
+ Goal("other", 1.0, Kinds(Other), new[] { new Consideration(ConsiderationInput.PlanSteps, 1.0, 9.0, 1.0, 0.0) }) with { Want = fact },
+ },
+ };
+ var verbs = new[]
+ {
+ new Verb { Id = "Approach", Gives = new[] { new Fact(FactSubject.This, 63, true) } },
+ new Verb { Id = "Unlock", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, true) }, Gives = new[] { new Fact(FactSubject.This, Locked, false) } },
+ new Verb { Id = "Open", This = Kinds(Thing, Other), Needs = new[] { new Fact(FactSubject.This, 63, true), new Fact(FactSubject.This, Locked, false) }, Gives = new[] { fact } },
+ };
+ var a = new Actor(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, verbs: verbs);
+ var emitters = new[] { At(1, 5f), At(2, 9f), At(3, 2f, Other) };
+ emitters[0].Facts = 1UL << Locked;
+ for (var i = 0; i < 50; i++) a.Tick(Zero, Zero, Zero, NoBoxes, new float[2], new Quat[2], emitters);
+ var strengths = new float[2];
+ var targets = new Quat[2];
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ for (var i = 0; i < 10000; i++)
+ {
+ emitters[1] = At(2, 9f - (i % 8));
+ a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, emitters, selfFacts: (ulong)(i & 3));
+ }
+
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ Assert.NotEqual(0UL, a.TargetId);
+ Assert.NotEqual(0, a.PlanLength);
+ }
+}
+
diff --git a/tests/Lodur.Core.Tests/GoldenParityTests.cs b/tests/Lodur.Core.Tests/GoldenParityTests.cs
new file mode 100644
index 0000000..6caf144
--- /dev/null
+++ b/tests/Lodur.Core.Tests/GoldenParityTests.cs
@@ -0,0 +1,65 @@
+using System.Globalization;
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+///
+/// The Actor against Bad Day Simulator's pain box at 9f59764, which that repo deletes in its next cut:
+/// pain-box-golden.tsv holds, for 7 intensity/pull settings x seeds 1-60, the outcome and a hash of the
+/// per-tick stimulus, pain, strain, resolve and goal stream. Regenerate with tools/pain-box-golden/generate.sh.
+///
+public sealed class GoldenParityTests
+{
+ private sealed record Row(ulong Seed, double Intensity, double Pull, string Outcome, long BreakMs, long EndMs, int Flinches, long Ticks, ulong Hash);
+
+ private static IEnumerable Rows()
+ {
+ foreach (var line in File.ReadLines(Path.Combine(AppContext.BaseDirectory, "pain-box-golden.tsv")))
+ {
+ if (line.StartsWith('#') || string.IsNullOrWhiteSpace(line)) continue;
+ var f = line.Trim().Split(' ');
+ yield return new Row(ulong.Parse(f[0]), double.Parse(f[1], CultureInfo.InvariantCulture), double.Parse(f[2], CultureInfo.InvariantCulture),
+ f[3], long.Parse(f[4]), long.Parse(f[5]), int.Parse(f[6]), long.Parse(f[7]), Convert.ToUInt64(f[8], 16));
+ }
+ }
+
+ [Fact]
+ public void The_actor_reproduces_the_pain_box_golden_table_exactly()
+ {
+ var rows = Rows().ToList();
+ Assert.Equal(420, rows.Count);
+ Assert.Contains(rows, r => r.Outcome == "Endured");
+ Assert.Contains(rows, r => r.Outcome == "WillBroke");
+
+ var bad = new List();
+ foreach (var row in rows)
+ {
+ var replay = new PainBoxReplay(row.Seed, row.Intensity, row.Pull);
+ var h = 14695981039346656037ul;
+ void Byte(byte b) { h ^= b; h *= 1099511628211ul; }
+ void Double(double d) { foreach (var b in BitConverter.GetBytes(BitConverter.DoubleToInt64Bits(d))) Byte(b); }
+
+ long ticks = 0, broke = -1, withdrew = -1;
+ var flinches = 0;
+ var max = (long)Math.Round(120.0 / PainBoxReplay.Dt);
+ for (long i = 0; i <= max && withdrew < 0; i++)
+ {
+ var e = replay.Tick();
+ ticks++;
+ if ((e & TickEvents.Flinch) != 0) flinches++;
+ if ((e & TickEvents.WillBroke) != 0) broke = i;
+ if ((e & TickEvents.GoalChanged) != 0) withdrew = i;
+ var d = replay.Actor.Drive;
+ Double(replay.Actor.Stimulus(0)); Double(d.Pain); Double(d.Strain); Double(d.Resolve);
+ Byte((byte)(replay.Actor.Drive.WillBroken ? 1 : 0));
+ }
+
+ var ms = (long)Math.Round(withdrew >= 0 ? withdrew * 10.0 : max * 10.0);
+ var got = $"{(broke >= 0 ? "WillBroke" : "Endured")} {(broke >= 0 ? broke * 10 : -1)} {ms} {flinches} {ticks} {h:x16}";
+ var want = $"{row.Outcome} {row.BreakMs} {row.EndMs} {row.Flinches} {row.Ticks} {row.Hash:x16}";
+ if (got != want) bad.Add($"seed {row.Seed} i={row.Intensity} p={row.Pull}: got [{got}] want [{want}]");
+ }
+
+ Assert.True(bad.Count == 0, $"{bad.Count} of {rows.Count} runs differ; first: {bad.FirstOrDefault()}");
+ }
+}
diff --git a/tests/Lodur.Core.Tests/IkTests.cs b/tests/Lodur.Core.Tests/IkTests.cs
new file mode 100644
index 0000000..8fe0712
--- /dev/null
+++ b/tests/Lodur.Core.Tests/IkTests.cs
@@ -0,0 +1,670 @@
+using Lodur;
+using Xunit.Abstractions;
+
+namespace Lodur.Core.Tests;
+
+public sealed class IkTests
+{
+ private static readonly BodyPlan Plan = BodyPlans.Humanoid();
+
+ // The tick the chains are built for; it sets the swivel step, SwivelRate * Dt.
+ private const double Dt = 0.01;
+ private readonly ITestOutputHelper _output;
+
+ public IkTests(ITestOutputHelper output) => _output = output;
+
+ private static (float X, float Y, float Z) Add((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ private static (float X, float Y, float Z) Sub((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X - b.X, a.Y - b.Y, a.Z - b.Z);
+ private static float Len((float X, float Y, float Z) a) => MathF.Sqrt(a.X * a.X + a.Y * a.Y + a.Z * a.Z);
+
+ private static (float X, float Y, float Z) Rot(Quat q, (float X, float Y, float Z) v)
+ {
+ q.Rotate(v.X, v.Y, v.Z, out var x, out var y, out var z);
+ return (x, y, z);
+ }
+
+ /// The convention applied by hand: where the wrist anchor lands for these two targets, in world coordinates.
+ private static (float X, float Y, float Z) Wrist(ArmChain arm, Quat parentRotation, (float X, float Y, float Z) parentPosition, Quat shoulder, Quat elbow)
+ {
+ var fs = Ik.JointFrame(Plan.Joints[arm.ShoulderJoint]);
+ var fe = Ik.JointFrame(Plan.Joints[arm.ElbowJoint]);
+ var rs = fs * shoulder * fs.Conjugate();
+ var re = fe * elbow * fe.Conjugate();
+ var a = Sub(arm.ElbowAnchor, arm.ShoulderAnchor);
+ var b = Sub(arm.WristAnchor, arm.ElbowAnchor);
+ var local = Add(arm.ShoulderAnchor, Rot(rs, Add(a, Rot(re, b))));
+ var centre = Plan.Parts[arm.ParentPart].Position;
+ return Add(parentPosition, Rot(parentRotation, Sub(local, centre)));
+ }
+
+ private static Quat RandomRotation(Random rng, float maxAngle)
+ {
+ var x = (float)rng.NextDouble() * 2f - 1f;
+ var y = (float)rng.NextDouble() * 2f - 1f;
+ var z = (float)rng.NextDouble() * 2f - 1f;
+ var l = MathF.Sqrt(x * x + y * y + z * z);
+ return l < 1e-3f ? Quat.Identity : Quat.FromAxisAngle(x / l, y / l, z / l, (float)rng.NextDouble() * maxAngle);
+ }
+
+ /// Seeded targets around one arm: a random direction and a distance the flex range can reach, under a random parent pose.
+ private static IEnumerable<(Quat Rotation, (float X, float Y, float Z) Position, (float X, float Y, float Z) Target)> Grid(ArmChain arm, int seed, int count)
+ {
+ var rng = new Random(seed);
+ var centre = Plan.Parts[arm.ParentPart].Position;
+ for (var i = 0; i < count; i++)
+ {
+ var rot = i % 2 == 0 ? Quat.Identity : RandomRotation(rng, 0.8f);
+ var pos = i % 2 == 0 ? centre : (centre.X + (float)rng.NextDouble() - 0.5f, centre.Y + (float)rng.NextDouble() - 0.5f, centre.Z + (float)rng.NextDouble() - 0.5f);
+ double dx, dy, dz, l;
+ do
+ {
+ dx = rng.NextDouble() * 2 - 1; dy = rng.NextDouble() * 2 - 1; dz = rng.NextDouble() * 2 - 1;
+ l = Math.Sqrt(dx * dx + dy * dy + dz * dz);
+ }
+ while (l is < 0.1 or > 1.0);
+ var r = (float)(0.23 + rng.NextDouble() * 0.32);
+ var dir = ((float)(dx / l), (float)(dy / l), (float)(dz / l));
+ // The shoulder in the world under this parent pose, then the target out along dir.
+ var shoulder = Add(pos, Rot(rot, Sub(arm.ShoulderAnchor, centre)));
+ yield return (rot, pos, (shoulder.X + dir.Item1 * r, shoulder.Y + dir.Item2 * r, shoulder.Z + dir.Item3 * r));
+ }
+ }
+
+ private static float ZTwist(Quat q) => 2f * MathF.Atan2(MathF.Abs(q.Z), MathF.Abs(q.W));
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void Arm_solve_lands_the_wrist_by_forward_kinematics(Side side)
+ {
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var reachedCount = 0;
+ foreach (var (rot, pos, target) in Grid(arm, 7 + (int)side, 600))
+ {
+ // Independent goals, not a path: each is the stateless rule.
+ arm.Reset();
+ if (!arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out var eq)) continue;
+ reachedCount++;
+ var wrist = Wrist(arm, rot, pos, sq, eq);
+ Assert.True(Len(Sub(wrist, target)) < 1e-4f, $"wrist {wrist} missed target {target} by {Len(Sub(wrist, target))} m");
+ }
+
+ Assert.True(reachedCount > 100, $"only {reachedCount} grid targets were reachable; the grid no longer exercises the solve");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void Arm_solve_twists_the_shoulder_only_where_zero_twist_would_leave_the_cone(Side side)
+ {
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var joint = Plan.Joints[arm.ShoulderJoint];
+ var (n, reached, twisted) = (0, 0, 0);
+ foreach (var (rot, pos, target) in Grid(arm, 21 + (int)side, 600))
+ {
+ arm.Reset();
+ var ok = arm.Solve(rot, pos.X, pos.Y, pos.Z, target.X, target.Y, target.Z, out var sq, out _);
+ var swing = 2f * MathF.Asin(MathF.Min(1f, MathF.Sqrt(sq.X * sq.X + sq.Y * sq.Y)));
+ var twist = 2f * MathF.Atan2(sq.Z, sq.W);
+ Assert.True(swing <= joint.Cone + 1e-4f, $"swing {swing} past the cone {joint.Cone} for {target}");
+ Assert.True(twist >= joint.Lower - 1e-4f && twist <= joint.Upper + 1e-4f, $"twist {twist} outside [{joint.Lower}, {joint.Upper}] for {target}");
+ if (MathF.Abs(twist) > 1e-5f)
+ {
+ // A twist is taken only to keep the swing inside the cone, so the swivel sits on the boundary of the feasible range; an
+ // unreached goal's least-violating swivel, clamped, sits on the cone.
+ if (ok) twisted++;
+ var onLimit = MathF.Abs(swing - joint.Cone) < 1e-3f || MathF.Abs(twist - joint.Lower) < 1e-3f || MathF.Abs(twist - joint.Upper) < 1e-3f;
+ Assert.True(onLimit, $"shoulder target twists by {twist} rad at swing {swing} for {target}, off every limit");
+ }
+
+ n++;
+ if (ok) reached++;
+ }
+
+ Assert.Equal(600, n);
+ Assert.InRange(twisted, 1, reached / 2);
+ }
+
+ [Fact]
+ public void A_wrist_goal_the_zero_twist_swivel_cannot_reach_is_reached_by_twisting_inside_the_limits()
+ {
+ // The left ward-off wrist goal for a sound at head height, ahead and to the left: zero twist saturates the cone 20 cm short.
+ var arm = ArmChain.Of(Plan, Side.Left, Dt);
+ var joint = Plan.Joints[arm.ShoulderJoint];
+ var centre = Plan.Parts[arm.ParentPart].Position;
+ var goal = (0.2988f, 1.74f, 0.2605f);
+ Assert.True(arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, goal.Item1, goal.Item2, goal.Item3, out var sq, out var eq));
+ var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
+ Assert.True(Len(Sub(wrist, goal)) < 1e-3f, $"wrist {wrist} missed {goal} by {Len(Sub(wrist, goal))} m");
+ var twist = 2f * MathF.Atan2(sq.Z, sq.W);
+ Assert.True(MathF.Abs(twist) > 0.05f && twist >= joint.Lower && twist <= joint.Upper, $"twist {twist}");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void A_goal_crossing_out_of_the_feasible_set_moves_the_targets_continuously(Side side)
+ {
+ // Two stretches of a circle about the shoulder where a goal leaves the feasible set: past the edge no swivel keeps both swing and
+ // twist inside the limits. Each stretch is 2000 steps of about 0.02 mm.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var centre = Plan.Parts[arm.ParentPart].Position;
+ var s = arm.ShoulderAnchor;
+ var (worstTurn, worstFlex, worstMove) = (0f, 0f, 0f);
+ foreach (var (from, to) in new[] { (0.25f, 0.33f), (2.65f, 2.74f) })
+ {
+ const int steps = 2000;
+ var crossings = 0;
+ var (lastReached, lastShoulder, lastElbow, lastWrist) = (false, Quat.Identity, Quat.Identity, (0f, 0f, 0f));
+ // Each stretch is its own path.
+ arm.Reset();
+ for (var i = 0; i <= steps; i++)
+ {
+ var th = from + (to - from) * i / steps;
+ var goal = (s.X + 0.45f * MathF.Cos(th), s.Y + 0.45f * MathF.Sin(th), s.Z + 0.25f + 0.1f * MathF.Sin(2f * th));
+ var reached = arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, goal.Item1, goal.Item2, goal.Item3, out var sq, out var eq);
+ var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
+ if (i > 0)
+ {
+ if (reached != lastReached) crossings++;
+ worstTurn = MathF.Max(worstTurn, Turn(sq, lastShoulder));
+ worstFlex = MathF.Max(worstFlex, Turn(eq, lastElbow));
+ worstMove = MathF.Max(worstMove, Len(Sub(wrist, lastWrist)));
+ }
+
+ (lastReached, lastShoulder, lastElbow, lastWrist) = (reached, sq, eq, wrist);
+ }
+
+ // Tripwire: the stretch still crosses the edge, so the bounds below still test a crossing.
+ Assert.Equal(1, crossings);
+ }
+
+ _output.WriteLine($"{side}: largest step of the shoulder target {worstTurn:F4} rad, of the elbow {worstFlex:F4} rad, of the wrist {worstMove * 1000f:F4} mm");
+ // The turns are bounded by the rate (StepBound). deterministic-bound-margin for the wrist: the geometric mean of the shipped worst
+ // and the least mutant. Shipped worst, both arms: 0.0216 mm. Mutant, the zero-twist swing clamped to the cone past the edge (the
+ // fallback before this test): 269.72 mm. Bound sqrt(0.0216 * 269.72) = 2.41 mm.
+ Assert.True(worstTurn <= StepBound, $"the shoulder target jumped {worstTurn} rad in one step");
+ Assert.True(worstFlex <= StepBound, $"the elbow target jumped {worstFlex} rad in one step");
+ Assert.True(worstMove < 0.00241f, $"the wrist jumped {worstMove} m in one step");
+ }
+
+ [Fact]
+ public void Out_of_reach_points_the_straight_arm_at_the_target_and_reports_not_reached()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var s = arm.ShoulderAnchor;
+ var centre = Plan.Parts[arm.ParentPart].Position;
+ var dirs = new[] { (0f, -0.5f, 0.87f), (-0.4f, -0.6f, 0.7f) };
+ foreach (var raw in dirs)
+ {
+ var l = Len(raw);
+ var dir = (raw.Item1 / l, raw.Item2 / l, raw.Item3 / l);
+ var target = (s.X + dir.Item1 * 2f, s.Y + dir.Item2 * 2f, s.Z + dir.Item3 * 2f);
+ arm.Reset();
+ var reached = arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, target.Item1, target.Item2, target.Item3, out var sq, out var eq);
+ Assert.False(reached);
+ var wrist = Wrist(arm, Quat.Identity, centre, sq, eq);
+ var reach = arm.L1 + arm.L2 - 1e-3f;
+ var want = (s.X + dir.Item1 * reach, s.Y + dir.Item2 * reach, s.Z + dir.Item3 * reach);
+ Assert.True(Len(Sub(wrist, want)) < 1e-4f, $"wrist {wrist} is not on the line to the target at full stretch {want}");
+ Assert.True(MathF.Abs(2f * MathF.Atan2(eq.Z, eq.W)) < 0.15f, "the elbow is not nearly straight");
+ }
+
+ // The same direction well inside reach is reached.
+ arm.Reset();
+ Assert.True(arm.Solve(Quat.Identity, centre.X, centre.Y, centre.Z, s.X, s.Y, s.Z + 0.4f, out _, out _));
+ }
+
+ [Fact]
+ public void Limits_clamp_swing_flex_and_look()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var cone = Plan.Joints[arm.ShoulderJoint].Cone;
+ var (lo, hi) = (Plan.Joints[arm.ElbowJoint].Lower, Plan.Joints[arm.ElbowJoint].Upper);
+
+ // Straight up is half a turn from the hanging arm: past the cone.
+ Assert.False(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y + 0.45f, s.Z, out var up, out _));
+ Assert.Equal(cone, 2f * MathF.Atan2(MathF.Sqrt(up.X * up.X + up.Y * up.Y + up.Z * up.Z), up.W), 1e-4f);
+ Assert.True(ZTwist(up) < 1e-5f);
+
+ // Near the shoulder the hinge would have to fold past its range.
+ arm.Reset();
+ Assert.False(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.1f, s.Z + 0.1f, out _, out var folded));
+ Assert.Equal(lo, 2f * MathF.Atan2(folded.Z, folded.W), 1e-4f);
+
+ // A bend inside the range is not a clamp.
+ arm.Reset();
+ Assert.True(arm.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X, s.Y - 0.25f, s.Z + 0.25f, out _, out var bent));
+ var flex = 2f * MathF.Atan2(bent.Z, bent.W);
+ Assert.InRange(flex, lo + 0.05f, hi - 0.05f);
+
+ var look = LookChain.Of(Plan);
+ var neck = Plan.Joints[look.Joint];
+ var head = Plan.Parts[look.ChildPart].Position;
+ var parent = Plan.Parts[look.ParentPart].Position;
+ (float Yaw, float Pitch) Aim(float dx, float dy, float dz, out bool reached)
+ {
+ reached = look.Solve(Quat.Identity, parent.X, parent.Y, parent.Z, head.X + dx, head.Y + dy, head.Z + dz, out var q);
+ var f = Ik.JointFrame(neck);
+ var d = Rot(f * q * f.Conjugate(), (0f, 0f, 1f));
+ return (MathF.Atan2(d.X, d.Z), -MathF.Asin(d.Y));
+ }
+
+ var (yaw, _) = Aim(2f, 0f, 0.5f, out var r1);
+ Assert.False(r1);
+ Assert.Equal(neck.Upper, yaw, 1e-4f);
+ (yaw, _) = Aim(-2f, 0f, 0.5f, out r1);
+ Assert.False(r1);
+ Assert.Equal(neck.Lower, yaw, 1e-4f);
+ var (_, pitch) = Aim(0f, 2f, 0.5f, out r1);
+ Assert.False(r1);
+ Assert.Equal(-neck.Cone, pitch, 1e-4f);
+ (_, pitch) = Aim(0f, -2f, 0.5f, out r1);
+ Assert.False(r1);
+ Assert.Equal(neck.Cone, pitch, 1e-4f);
+ Aim(0.3f, 0.2f, 1f, out r1);
+ Assert.True(r1);
+ }
+
+ [Fact]
+ public void Left_and_right_mirror()
+ {
+ var left = ArmChain.Of(Plan, Side.Left, Dt);
+ var right = ArmChain.Of(Plan, Side.Right, Dt);
+ var c = Plan.Parts[right.ParentPart].Position;
+ var n = 0;
+ foreach (var (_, _, target) in Grid(right, 5, 300))
+ {
+ right.Reset();
+ left.Reset();
+ var rReached = right.Solve(Quat.Identity, c.X, c.Y, c.Z, target.X, target.Y, target.Z, out var rs, out var re);
+ var lReached = left.Solve(Quat.Identity, c.X, c.Y, c.Z, -target.X, target.Y, target.Z, out var ls, out var le);
+ Assert.Equal(rReached, lReached);
+ // A reflection across x leaves a rotation about x alone and turns the other two components over.
+ Assert.Equal(rs.X, ls.X, 1e-5f);
+ Assert.Equal(-rs.Y, ls.Y, 1e-5f);
+ Assert.Equal(-rs.Z, ls.Z, 1e-5f);
+ Assert.Equal(rs.W, ls.W, 1e-5f);
+ Assert.Equal(re.Z, le.Z, 1e-5f);
+ Assert.Equal(re.W, le.W, 1e-5f);
+ n++;
+ }
+
+ Assert.Equal(300, n);
+ }
+
+ [Fact]
+ public void Look_aims_the_head_forward_at_the_target()
+ {
+ var look = LookChain.Of(Plan);
+ var neck = Plan.Joints[look.Joint];
+ var f = Ik.JointFrame(neck);
+ var head = Plan.Parts[look.ChildPart].Position;
+ var parentCentre = Plan.Parts[look.ParentPart].Position;
+ var rng = new Random(11);
+ var aimed = 0;
+ for (var i = 0; i < 400; i++)
+ {
+ var rot = i % 2 == 0 ? Quat.Identity : RandomRotation(rng, 0.8f);
+ (float X, float Y, float Z) pos = i % 2 == 0 ? parentCentre : (parentCentre.X + 0.3f, parentCentre.Y - 0.2f, parentCentre.Z + 0.1f);
+ // A direction inside the yaw and pitch limits, at 0.5 to 3 m, from the head's creation-pose centre.
+ var yaw = (float)(rng.NextDouble() * 2 - 1) * 0.55f;
+ var pitch = (float)(rng.NextDouble() * 2 - 1) * 0.55f;
+ var d = (MathF.Sin(yaw) * MathF.Cos(pitch), -MathF.Sin(pitch), MathF.Cos(yaw) * MathF.Cos(pitch));
+ var r = 0.5f + (float)rng.NextDouble() * 2.5f;
+ var local = Add(head, (d.Item1 * r, d.Item2 * r, d.Item3 * r));
+ var world = Add(pos, Rot(rot, Sub(local, parentCentre)));
+ Assert.True(look.Solve(rot, pos.X, pos.Y, pos.Z, world.X, world.Y, world.Z, out var q));
+ var got = Rot(f * q * f.Conjugate(), (0f, 0f, 1f));
+ var cross = (got.Y * d.Item3 - got.Z * d.Item2, got.Z * d.Item1 - got.X * d.Item3, got.X * d.Item2 - got.Y * d.Item1);
+ Assert.True(Len(cross) < 1e-4f && got.X * d.Item1 + got.Y * d.Item2 + got.Z * d.Item3 > 0f, $"head forward {got} is off the direction {d}");
+ aimed++;
+ }
+
+ Assert.Equal(400, aimed);
+ }
+
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
+ private static float Swing(Quat q) => 2f * MathF.Atan2(MathF.Sqrt(q.X * q.X + q.Y * q.Y), MathF.Sqrt(q.Z * q.Z + q.W * q.W));
+
+ // Tie lines at the shoulder's sagittal plane (goal relative to the shoulder (dx, y, z)), where two mirrored swivels tie under the
+ // stateless rule (Soul s3 on cut-lodur-orient-goals). The first four are unreached throughout; (-0.224, -0.2) is reached beyond 4 mm
+ // either side; (-0.25, -0.25) is reached throughout, two feasible intervals tying.
+ private static readonly (float Y, float Z)[] TieLines = { (0.12f, -0.4f), (0.2f, -0.2f), (0.25f, 0f), (0.3f, -0.1f), (-0.224f, -0.2f), (-0.25f, -0.25f) };
+
+ ///
+ /// Walks one chain along goals, one solve per tick, from a fresh state: the largest per-tick turn of the shoulder target, the largest
+ /// swing of the held (unclamped) target, and the largest per-tick turn of the elbow target. With the chain
+ /// is reset before every solve, so it returns the stateless solution unslewed: the claimed mutant.
+ ///
+ private static (float Turn, float HeldSwing, float Flex) Walk(ArmChain arm, IEnumerable<(float X, float Y, float Z)> goals, bool stateless, Quat[]? record = null)
+ {
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var (worst, flex, swing, last, lastE, i) = (0f, 0f, 0f, Quat.Identity, Quat.Identity, 0);
+ arm.Reset();
+ foreach (var g in goals)
+ {
+ if (stateless) arm.Reset();
+ arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var sq, out var eq);
+ if (i > 0) (worst, flex) = (MathF.Max(worst, Turn(sq, last)), MathF.Max(flex, Turn(eq, lastE)));
+ swing = MathF.Max(swing, Swing(arm.Held));
+ if (record != null) record[i] = sq;
+ (last, lastE) = (sq, eq);
+ i++;
+ }
+
+ return (worst, swing, flex);
+ }
+
+ private static IEnumerable<(float X, float Y, float Z)> Line((float X, float Y, float Z) s, float y, float z, float sign, int from, int to, float step)
+ {
+ for (var i = from; i <= to; i++) yield return (s.X + sign * i * step, s.Y + y, s.Z + z);
+ }
+
+ // The per-tick turn of either returned target is at most MaxAngularRate * Dt (0.1 rad) by construction (ruling
+ // lodur:ruling:ik-output-slew-limit); 1e-5 rad covers the float reading of the turn. Claimed mutants: no slew (the raw solution, as the
+ // stateless walk returns it), and the slew on the shoulder only (the leap test's elbow).
+ private static readonly float StepBound = ArmChain.MaxAngularRate * (float)Dt + 1e-5f;
+
+ [Fact]
+ public void Across_a_tie_line_the_arm_keeps_its_swivel_and_the_arms_mirror()
+ {
+ var left = ArmChain.Of(Plan, Side.Left, Dt);
+ var right = ArmChain.Of(Plan, Side.Right, Dt);
+ var (worst, mutant) = (0f, float.MaxValue);
+ var (lq, rq) = (new Quat[101], new Quat[101]);
+ foreach (var (y, z) in TieLines)
+ {
+ // dx from -10 to +10 mm in 0.2 mm ticks; the left arm walks the mirrored path.
+ var held = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), false, rq).Turn;
+ Walk(left, Line(left.ShoulderAnchor, y, z, -1f, -50, 50, 0.0002f), false, lq);
+ var jump = Walk(right, Line(right.ShoulderAnchor, y, z, 1f, -50, 50, 0.0002f), true).Turn;
+ _output.WriteLine($"tie line ({y}, {z}): held worst {held:F4} rad per tick, stateless {jump:F4}");
+ (worst, mutant) = (MathF.Max(worst, held), MathF.Min(mutant, jump));
+ for (var i = 0; i < 101; i++)
+ {
+ Assert.Equal(rq[i].X, lq[i].X, 1e-5f);
+ Assert.Equal(-rq[i].Y, lq[i].Y, 1e-5f);
+ Assert.Equal(-rq[i].Z, lq[i].Z, 1e-5f);
+ Assert.Equal(rq[i].W, lq[i].W, 1e-5f);
+ }
+ }
+
+ _output.WriteLine($"worst held {worst:F4}, least stateless worst {mutant:F4}");
+ // Tripwire: every line still ties under the stateless rule, so the bound still tests a tie.
+ Assert.True(mutant > 0.9f, $"a tie line no longer ties: the stateless rule turns only {mutant} rad");
+ Assert.True(worst <= StepBound, $"the shoulder target turned {worst} rad in one tick across a tie");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void The_stateless_jumps_of_random_segments_are_held(Side side)
+ {
+ // Soul's probe: random segments about the shoulder walked in 0.4 mm steps; each step the stateless rule turns over 0.5 rad is
+ // bisected to a gap under 2 microns, where it persists. The held chain walks 2 mm up to the near side, across the gap in one
+ // tick, and 2 mm on.
+ // Counted: jumps where the held target swings past HalfTurnSwing, where the clamp's swing-twist split is singular and the clamped
+ // solution itself jumps; the tripwire keeps the bound testing that band. Each of those is also walked 20 cm along its segment
+ // (1001 ticks of 0.2 mm), entering and leaving the band.
+ const float HalfTurnSwing = 3.0f;
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var rng = new Random(side == Side.Left ? 5 : 6);
+ (float X, float Y, float Z) Pt()
+ {
+ double dx, dy, dz, l;
+ do { dx = rng.NextDouble() * 2 - 1; dy = rng.NextDouble() * 2 - 1; dz = rng.NextDouble() * 2 - 1; l = Math.Sqrt(dx * dx + dy * dy + dz * dz); }
+ while (l is < 0.05 or > 1.0);
+ var r = (float)(0.05 + rng.NextDouble() * 0.7);
+ return (s.X + (float)(dx / l) * r, s.Y + (float)(dy / l) * r, s.Z + (float)(dz / l) * r);
+ }
+
+ Quat Fresh((float X, float Y, float Z) g)
+ {
+ arm.Reset();
+ arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var q, out _);
+ return q;
+ }
+
+ static (float X, float Y, float Z) Lerp((float X, float Y, float Z) a, (float X, float Y, float Z) b, float u) => (a.X + (b.X - a.X) * u, a.Y + (b.Y - a.Y) * u, a.Z + (b.Z - a.Z) * u);
+ var (found, singular, worst, mutant) = (0, 0, 0f, float.MaxValue);
+ var path = new (float X, float Y, float Z)[12];
+ var band = new (float X, float Y, float Z)[1001];
+ var (bandWorst, bandRaw) = (0f, float.MaxValue);
+ for (var k = 0; k < 400 && found < 40; k++)
+ {
+ var a = Pt();
+ var b = Pt();
+ var steps = (int)(Len(Sub(b, a)) / 0.0004f) + 1;
+ var prev = Fresh(a);
+ for (var i = 1; i <= steps; i++)
+ {
+ var q1 = Fresh(Lerp(a, b, (float)i / steps));
+ if (Turn(q1, prev) > 0.5f)
+ {
+ found++;
+ var (lo, hi, qlo, qhi) = (Lerp(a, b, (float)(i - 1) / steps), Lerp(a, b, (float)i / steps), prev, q1);
+ for (var it = 0; it < 40 && Len(Sub(hi, lo)) > 2e-6f; it++)
+ {
+ var mid = Lerp(lo, hi, 0.5f);
+ var qm = Fresh(mid);
+ if (Turn(qm, qlo) >= Turn(qm, qhi)) (hi, qhi) = (mid, qm);
+ else (lo, qlo) = (mid, qm);
+ }
+
+ Assert.True(Turn(qlo, qhi) > 0.5f, $"a stateless jump vanished on bisection: {Turn(qlo, qhi)} rad");
+ var u = Sub(b, a);
+ var step = 0.0004f / Len(u);
+ for (var j = 0; j < 6; j++) path[j] = Lerp(lo, Add(lo, u), (j - 5) * step);
+ for (var j = 0; j < 6; j++) path[6 + j] = Lerp(hi, Add(hi, u), j * step);
+ var walk = Walk(arm, path, false);
+ if (walk.HeldSwing > HalfTurnSwing)
+ {
+ singular++;
+ var uh = 1f / Len(u);
+ for (var j = 0; j < band.Length; j++)
+ {
+ var t = (j - 500) * 0.0002f * uh;
+ band[j] = (lo.X + u.X * t, lo.Y + u.Y * t, lo.Z + u.Z * t);
+ }
+
+ var through = Walk(arm, band, false);
+ bandWorst = MathF.Max(bandWorst, MathF.Max(through.Turn, through.Flex));
+ var raw = Walk(arm, band, true);
+ bandRaw = MathF.Min(bandRaw, MathF.Max(raw.Turn, raw.Flex));
+ }
+
+ worst = MathF.Max(worst, MathF.Max(walk.Turn, walk.Flex));
+ mutant = MathF.Min(mutant, Walk(arm, path, true).Turn);
+ }
+
+ prev = q1;
+ }
+ }
+
+ _output.WriteLine($"{side}: {found} stateless jumps (worst held {worst:F4} rad per tick, least stateless worst {mutant:F4}), {singular} at the half-turn swing");
+ _output.WriteLine($"{side}: 20 cm walks through the half-turn band: worst {bandWorst:F4} rad per tick, least raw worst {bandRaw:F4}");
+ Assert.True(found >= 40, $"only {found} stateless jumps found; the probe no longer finds the ties");
+ Assert.True(singular >= 5, $"only {singular} jumps at the half-turn swing; the bound no longer tests the singular clamp");
+ Assert.True(bandWorst <= StepBound, $"a target turned {bandWorst} rad in one tick on a walk through the half-turn band");
+ Assert.True(worst <= StepBound, $"a target turned {worst} rad in one tick at a stateless jump");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void A_goal_circling_the_shoulder_moves_the_targets_at_most_the_rate(Side side)
+ {
+ // Full circles about the shoulder in its horizontal plane and above and below it, 1 mm per tick, two laps each from a fresh chain.
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var (worst, raw) = (0f, 0f);
+ foreach (var (y, r) in new[] { (-0.3f, 0.35f), (0f, 0.45f), (0.2f, 0.4f) })
+ {
+ var steps = (int)(2f * MathF.PI * r / 0.001f);
+ var path = new (float X, float Y, float Z)[2 * steps + 1];
+ for (var i = 0; i < path.Length; i++)
+ {
+ var th = 2f * MathF.PI * i / steps;
+ path[i] = (s.X + r * MathF.Sin(th), s.Y + y, s.Z + r * MathF.Cos(th));
+ }
+
+ var walk = Walk(arm, path, false);
+ worst = MathF.Max(worst, MathF.Max(walk.Turn, walk.Flex));
+ var mutant = Walk(arm, path, true);
+ raw = MathF.Max(raw, MathF.Max(mutant.Turn, mutant.Flex));
+ }
+
+ _output.WriteLine($"{side}: worst {worst:F4} rad per tick; the raw solution's worst {raw:F4}");
+ // Tripwire: the raw solution jumps somewhere on the circles, so the bound tests a jump.
+ Assert.True(raw > 0.5f, $"the raw solution turns only {raw} rad per tick on the circles");
+ Assert.True(worst <= StepBound, $"a target turned {worst} rad in one tick on a circle");
+ }
+
+ [Theory]
+ [InlineData(Side.Left)]
+ [InlineData(Side.Right)]
+ public void A_leaping_goal_is_followed_at_the_rate_and_settles_on_the_solution(Side side)
+ {
+ // The goal leaps between offsets from the shoulder (mirrored for the left) and holds each for Hold ticks. Every tick both targets
+ // move at most the step; within Hold ticks they settle on the solution a fresh chain gives there. A second chain walking the same
+ // goals returns the same bits.
+ const int Hold = 200;
+ var sign = side == Side.Left ? -1f : 1f;
+ var arm = ArmChain.Of(Plan, side, Dt);
+ var twin = ArmChain.Of(Plan, side, Dt);
+ var fresh = ArmChain.Of(Plan, side, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ var offsets = new[] { (0f, -0.25f, 0.35f), (0f, -0.12f, 0.1f), (0f, 0.05f, 0.45f), (-0.15f, -0.3f, 0.25f), (0.1f, -0.1f, 0.15f), (0f, -0.25f, 0.35f) };
+ var (worstTurn, worstFlex, rawTurn, rawFlex, slowest) = (0f, 0f, 0f, 0f, 0);
+ var (last, lastE) = (Quat.Identity, Quat.Identity);
+ for (var k = 0; k < offsets.Length; k++)
+ {
+ var g = (X: s.X + sign * offsets[k].Item1, Y: s.Y + offsets[k].Item2, Z: s.Z + offsets[k].Item3);
+ fresh.Reset();
+ fresh.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var want, out var wantE);
+ if (k > 0) (rawTurn, rawFlex) = (MathF.Max(rawTurn, Turn(want, last)), MathF.Max(rawFlex, Turn(wantE, lastE)));
+ var settled = -1;
+ for (var i = 0; i < Hold; i++)
+ {
+ arm.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var q, out var e);
+ twin.Solve(Quat.Identity, c.X, c.Y, c.Z, g.X, g.Y, g.Z, out var tq, out var te);
+ Assert.Equal(q, tq);
+ Assert.Equal(e, te);
+ if (k > 0 || i > 0) (worstTurn, worstFlex) = (MathF.Max(worstTurn, Turn(q, last)), MathF.Max(worstFlex, Turn(e, lastE)));
+ if (settled < 0 && Near(q, want) && Near(e, wantE)) settled = i;
+ if (settled >= 0) Assert.True(Near(q, want) && Near(e, wantE), $"leap {k}: the targets left the solution after settling at tick {settled}");
+ (last, lastE) = (q, e);
+ }
+
+ Assert.True(settled >= 0, $"leap {k}: the targets did not settle on the solution within {Hold} ticks");
+ slowest = Math.Max(slowest, settled);
+ }
+
+ _output.WriteLine($"{side}: worst {worstTurn:F4} rad shoulder, {worstFlex:F4} elbow per tick; raw leaps up to {rawTurn:F3} and {rawFlex:F3}; settled by tick {slowest}");
+ // Tripwire: the raw solution leaps at both joints, so the slew on the shoulder only would trip the elbow's bound.
+ Assert.True(rawTurn > 0.5f && rawFlex > 0.5f, $"the leaps are too small to test the slew: {rawTurn}, {rawFlex} rad");
+ Assert.True(worstTurn <= StepBound, $"the shoulder target turned {worstTurn} rad in one tick");
+ Assert.True(worstFlex <= StepBound, $"the elbow target turned {worstFlex} rad in one tick");
+
+ static bool Near(Quat a, Quat b)
+ {
+ var sg = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f;
+ return MathF.Abs(a.X - sg * b.X) < 1e-4f && MathF.Abs(a.Y - sg * b.Y) < 1e-4f && MathF.Abs(a.Z - sg * b.Z) < 1e-4f && MathF.Abs(a.W - sg * b.W) < 1e-4f;
+ }
+ }
+
+ [Fact]
+ public void A_clearly_better_basin_is_taken_at_the_swivel_rate_and_reset_restores_the_stateless_rule()
+ {
+ // The feasible tie: goal (dx, -0.25, -0.25) from the shoulder is reached throughout, by two mirrored feasible swivels that tie at
+ // dx 0. From dx -10 mm in 0.2 mm ticks the arm holds its basin past the tie; once the stateless swivel's twist is smaller by the
+ // margin it turns there, no faster than the swivel step.
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var fresh = ArmChain.Of(Plan, Side.Right, Dt);
+ var s = arm.ShoulderAnchor;
+ var c = Plan.Parts[arm.ParentPart].Position;
+ Quat Solve(ArmChain chain, float dx, out bool reached)
+ {
+ reached = chain.Solve(Quat.Identity, c.X, c.Y, c.Z, s.X + dx, s.Y - 0.25f, s.Z - 0.25f, out var q, out _);
+ return q;
+ }
+
+ var (worst, last, heldAt, switchedAt) = (0f, Quat.Identity, float.NaN, float.NaN);
+ for (var i = -50; i <= 1000; i++)
+ {
+ var dx = i * 0.0002f;
+ var q = Solve(arm, dx, out _);
+ fresh.Reset();
+ var stateless = Solve(fresh, dx, out _);
+ if (i > -50) worst = MathF.Max(worst, Turn(q, last));
+ if (i == 10)
+ {
+ // 2 mm past the tie the arm is still in its basin, the other side of the stateless choice.
+ heldAt = Turn(q, stateless);
+ }
+
+ if (float.IsNaN(switchedAt) && i > 10 && Turn(q, stateless) < 0.01f) switchedAt = dx;
+ last = q;
+ }
+
+ _output.WriteLine($"2 mm past the tie: {heldAt:F3} rad from the stateless target; switched by dx {switchedAt * 1000f:F1} mm; worst {worst:F4} rad per tick");
+ Assert.True(heldAt > 1f, $"2 mm past the tie the arm left its basin ({heldAt} rad from the stateless target)");
+ Assert.False(float.IsNaN(switchedAt), "the arm never took the clearly better basin");
+ Assert.True(worst <= StepBound, $"the shoulder target turned {worst} rad in one tick");
+
+ // Reset forgets the swivel: the next solve is the stateless rule, bit for bit, where the held arm differs.
+ arm.Reset();
+ Solve(arm, -0.01f, out _);
+ var held = Solve(arm, 0.002f, out _);
+ arm.Reset();
+ var reset = Solve(arm, 0.002f, out var r1);
+ fresh.Reset();
+ var expected = Solve(fresh, 0.002f, out var r2);
+ Assert.Equal(expected, reset);
+ Assert.Equal(r2, r1);
+ Assert.True(Turn(held, reset) > 1f, "the held arm already matched the stateless target, so the reset proves nothing");
+ }
+
+ [Fact]
+ public void Solving_allocates_nothing()
+ {
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var look = LookChain.Of(Plan);
+ var s = arm.ShoulderAnchor;
+ var rot = Quat.FromAxisAngle(0f, 1f, 0f, 0.2f);
+ var up = Add((0f, 1.4f, 0f), Rot(rot, Sub(s, Plan.Parts[arm.ParentPart].Position)));
+ Assert.False(arm.Solve(rot, 0f, 1.4f, 0f, up.X, up.Y + 0.4f, up.Z, out _, out _));
+ void Work(int n)
+ {
+ for (var i = 0; i < n; i++)
+ {
+ var t = 0.3f + i % 7 * 0.03f;
+ arm.Solve(rot, 0f, 1.4f, 0f, s.X, s.Y - t, s.Z + t, out _, out _);
+ // Straight up from the shoulder, in reach: no swivel is feasible, so the least-violating search runs.
+ arm.Solve(rot, 0f, 1.4f, 0f, up.X, up.Y + t, up.Z, out _, out _);
+ look.Solve(rot, 0f, 1.4f, 0f, t, 1.7f, 2f, out _);
+ }
+ }
+
+ Work(2000);
+ var before = GC.GetAllocatedBytesForCurrentThread();
+ Work(2000);
+ Assert.Equal(0L, GC.GetAllocatedBytesForCurrentThread() - before);
+ }
+
+ [Fact]
+ public void A_plan_without_the_arm_is_refused()
+ {
+ var parts = new[] { new PartDef("A", Side.Center, PartShape.Sphere, (0.1f, 0f, 0f), (0f, 0f, 0f), Quat.Identity, 1f, 1f, 0f) };
+ var bare = new BodyPlan(parts, Array.Empty(), Array.Empty());
+ Assert.Throws(() => ArmChain.Of(bare, Side.Left, Dt));
+ Assert.Throws(() => LookChain.Of(bare));
+ }
+}
diff --git a/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj
new file mode 100644
index 0000000..617d2d1
--- /dev/null
+++ b/tests/Lodur.Core.Tests/Lodur.Core.Tests.csproj
@@ -0,0 +1,25 @@
+
+
+
+
+ net10.0
+ enable
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Lodur.Core.Tests/OrientTests.cs b/tests/Lodur.Core.Tests/OrientTests.cs
new file mode 100644
index 0000000..127e151
--- /dev/null
+++ b/tests/Lodur.Core.Tests/OrientTests.cs
@@ -0,0 +1,660 @@
+using System;
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// The orient layers: Look, Arms (Reach, WardOff, Present) and Recoil composed onto a pose, joint targets only.
+public sealed class OrientTests
+{
+ private const double Dt = 0.01;
+ private const uint Thing = 7;
+ private static readonly BodyPlan Plan = BodyPlans.Humanoid();
+ private static readonly int Joints = Plan.Joints.Count;
+ private static readonly int Torso = Plan.PartIndex("Torso");
+ private static readonly int Head = Plan.PartIndex("Head");
+ private static readonly int Neck = Plan.JointIndex("Neck");
+ private static readonly BoxStimulus[] NoBoxes = Array.Empty();
+
+ private static (float X, float Y, float Z) Add((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X + b.X, a.Y + b.Y, a.Z + b.Z);
+ private static (float X, float Y, float Z) Sub((float X, float Y, float Z) a, (float X, float Y, float Z) b) => (a.X - b.X, a.Y - b.Y, a.Z - b.Z);
+ private static float Len((float X, float Y, float Z) a) => MathF.Sqrt(a.X * a.X + a.Y * a.Y + a.Z * a.Z);
+
+ private static (float X, float Y, float Z) Rot(Quat q, (float X, float Y, float Z) v)
+ {
+ q.Rotate(v.X, v.Y, v.Z, out var x, out var y, out var z);
+ return (x, y, z);
+ }
+
+ /// The creation pose of every part: where an unmoved body is.
+ private static PartPose[] Rest()
+ {
+ var poses = new PartPose[Plan.Parts.Count];
+ for (var p = 0; p < poses.Length; p++)
+ {
+ var d = Plan.Parts[p];
+ poses[p] = new PartPose(d.Rotation, d.Position.X, d.Position.Y, d.Position.Z);
+ }
+
+ return poses;
+ }
+
+ /// The unmoved body with the torso turned about y and moved and the head carried with it, so a dropped conjugate or a swapped frame shows.
+ private static PartPose[] Turned()
+ {
+ var poses = Rest();
+ var rot = Quat.FromAxisAngle(0f, 1f, 0f, 0.3f);
+ var c = Plan.Parts[Torso].Position;
+ var shift = (X: 0.05f, Y: -0.02f, Z: 0.1f);
+ poses[Torso] = new PartPose(rot, c.X + shift.X, c.Y + shift.Y, c.Z + shift.Z);
+ var h = Plan.Parts[Head].Position;
+ var carried = Rot(rot, Sub(h, c));
+ poses[Head] = new PartPose(rot, c.X + shift.X + carried.X, c.Y + shift.Y + carried.Y, c.Z + shift.Z + carried.Z);
+ return poses;
+ }
+
+ /// A key pose with a distinct rotation per joint, so a layer that touches a joint it should not shows.
+ private static Quat[] Key()
+ {
+ var key = new Quat[Joints];
+ for (var m = 0; m < Joints; m++) key[m] = Quat.FromAxisAngle(0f, 0f, 1f, 0.02f * (m + 1));
+ return key;
+ }
+
+ private static Quat[] Identity() { var k = new Quat[Joints]; Array.Fill(k, Quat.Identity); return k; }
+
+ private static PoseBehaviour Behaviour(LookLayer? look = null, ArmLayer? arms = null, RecoilLayer? recoil = null, HoldParameters? hold = null) => new()
+ {
+ Keys = new[] { Key() }, FlinchPose = Identity(), Look = look, Arms = arms, Recoil = recoil, Hold = hold ?? new HoldParameters(),
+ };
+
+ private static Brain BrainOf(PoseBehaviour b) => new() { Goals = new[] { new GoalSpec { Id = "g", Behaviour = b } } };
+
+ private static OrientRig RigOf(PoseBehaviour b) => new(Plan, BrainOf(b), Dt);
+
+ private static Percept At((float X, float Y, float Z) p, ulong id = 1) => new(id, Thing, p.X, p.Y, p.Z, 1.0, 0.0);
+
+ /// Ticks enough for the arms to engage from the base pose, follow any hand path and settle on their solution (1 s at the test tick).
+ private const int Settle = 100;
+
+ private static Quat[] Run(PoseBehaviour b, PartPose[] parts, Percept target, Side arm = Side.Right, double weight = 1.0, double leak = 0.0, float[]? strengths = null, int ticks = 1)
+ {
+ var targets = new Quat[Joints];
+ var rig = RigOf(b);
+ for (var i = 0; i < ticks; i++)
+ {
+ b.Write(weight, leak, 0.0, 0.0, 0.0, strengths ?? new float[Joints], targets, new OrientInput(rig, parts, target, arm));
+ }
+
+ return targets;
+ }
+
+ /// What the layerless behaviour writes with the same keys and flinch.
+ private static Quat[] Base(PoseBehaviour b) => Run(b with { Look = null, Arms = null, Recoil = null }, Rest(), default);
+
+ private static void Same(Quat a, Quat b, float tol = 1e-6f)
+ {
+ var dot = MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W);
+ Assert.True(dot > 1f - tol, $"{a} is not {b} (dot {dot})");
+ }
+
+ private static void SameBits(Quat a, Quat b) => Assert.Equal(a, b);
+
+ /// The angle of the shortest rotation from a to b.
+ private static float Turn(Quat a, Quat b) => 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W)));
+
+ private static Quat Flinched(Quat q, Quat flinch, float w) => Quat.Nlerp(q, flinch, w);
+
+ private static (float X, float Y, float Z) Wrist(ArmChain arm, PartPose parent, Quat shoulder, Quat elbow)
+ {
+ var fs = Ik.JointFrame(Plan.Joints[arm.ShoulderJoint]);
+ var fe = Ik.JointFrame(Plan.Joints[arm.ElbowJoint]);
+ var rs = fs * shoulder * fs.Conjugate();
+ var re = fe * elbow * fe.Conjugate();
+ var a = Sub(arm.ElbowAnchor, arm.ShoulderAnchor);
+ var b = Sub(arm.WristAnchor, arm.ElbowAnchor);
+ var local = Add(arm.ShoulderAnchor, Rot(rs, Add(a, Rot(re, b))));
+ var def = Plan.Parts[arm.ParentPart];
+ var rel = parent.Rotation * def.Rotation.Conjugate();
+ return Add((parent.X, parent.Y, parent.Z), Rot(rel, Sub(local, def.Position)));
+ }
+
+ private static readonly (float X, float Y, float Z) Ahead = (0.2f, 1.45f, 0.6f);
+
+ [Fact]
+ public void A_layered_behaviour_with_no_target_writes_the_base_and_only_Present_still_writes()
+ {
+ var look = new LookLayer();
+ var reach = new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both };
+ var recoil = Recoiling();
+ var layered = Behaviour(look, reach, recoil);
+ var baseline = Base(layered);
+ var got = Run(layered, Rest(), default);
+ for (var m = 0; m < Joints; m++) SameBits(baseline[m], got[m]);
+
+ var present = Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both, Point = (-0.2f, 1.3f, 0.3f) });
+ var written = Run(present, Rest(), default);
+ var arm = new[] { Plan.JointIndex("Shoulder", Side.Left), Plan.JointIndex("Elbow", Side.Left), Plan.JointIndex("Shoulder", Side.Right), Plan.JointIndex("Elbow", Side.Right) };
+ for (var m = 0; m < Joints; m++)
+ {
+ if (Array.IndexOf(arm, m) >= 0) Assert.NotEqual(Base(present)[m], written[m]);
+ else SameBits(Base(present)[m], written[m]);
+ }
+ }
+
+ [Fact]
+ public void Look_solves_the_neck_and_blends_by_weight()
+ {
+ var look = LookChain.Of(Plan);
+ foreach (var parts in new[] { Rest(), Turned() })
+ {
+ var t = parts[Torso];
+ Assert.True(look.Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var solved));
+ var b1 = Behaviour(new LookLayer { Weight = 1.0 });
+ var baseline = Base(b1);
+ var full = Run(b1, parts, At(Ahead));
+ SameBits(Flinched(solved, Quat.Identity, 0f), full[Neck]);
+ var half = Run(Behaviour(new LookLayer { Weight = 0.5 }), parts, At(Ahead));
+ SameBits(Flinched(Quat.Nlerp(Key()[Neck], solved, 0.5f), Quat.Identity, 0f), half[Neck]);
+ var none = Run(Behaviour(new LookLayer { Weight = 0.0 }), parts, At(Ahead));
+ Same(baseline[Neck], none[Neck]);
+ for (var m = 0; m < Joints; m++)
+ {
+ if (m != Neck) SameBits(baseline[m], full[m]);
+ }
+ }
+ }
+
+ [Theory]
+ [InlineData(ArmSide.Left)]
+ [InlineData(ArmSide.Right)]
+ [InlineData(ArmSide.Both)]
+ public void Reach_solves_the_chosen_arm_and_leaves_the_other(ArmSide side)
+ {
+ var parts = Turned();
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = side });
+ var baseline = Base(b);
+ var got = Run(b, parts, At(Ahead), ticks: Settle);
+ var t = parts[Torso];
+ foreach (var s in new[] { Side.Left, Side.Right })
+ {
+ var arm = ArmChain.Of(Plan, s, Dt);
+ var used = side == ArmSide.Both || (side == ArmSide.Left) == (s == Side.Left);
+ if (used)
+ {
+ arm.Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var sh, out var el);
+ Same(Flinched(sh, Quat.Identity, 0f), got[arm.ShoulderJoint]);
+ Same(Flinched(el, Quat.Identity, 0f), got[arm.ElbowJoint]);
+ }
+ else
+ {
+ SameBits(baseline[arm.ShoulderJoint], got[arm.ShoulderJoint]);
+ SameBits(baseline[arm.ElbowJoint], got[arm.ElbowJoint]);
+ }
+ }
+
+ for (var m = 0; m < Joints; m++)
+ {
+ if (Plan.Joints[m].Label is not ("Shoulder" or "Elbow")) SameBits(baseline[m], got[m]);
+ }
+ }
+
+ [Fact]
+ public void Nearer_uses_the_arm_the_actor_holds()
+ {
+ var parts = Rest();
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
+ var baseline = Base(b);
+ var left = Plan.JointIndex("Shoulder", Side.Left);
+ var right = Plan.JointIndex("Shoulder", Side.Right);
+ var asLeft = Run(b, parts, At(Ahead), Side.Left);
+ Assert.NotEqual(baseline[left], asLeft[left]);
+ SameBits(baseline[right], asLeft[right]);
+ var asRight = Run(b, parts, At(Ahead), Side.Right);
+ Assert.NotEqual(baseline[right], asRight[right]);
+ SameBits(baseline[left], asRight[left]);
+ }
+
+ [Fact]
+ public void WardOff_puts_the_wrists_between_head_and_target()
+ {
+ var parts = Turned();
+ var distance = 0.3f;
+ var spread = 0.15f;
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Side = ArmSide.Both, Distance = distance, Spread = spread });
+ var target = (0.0f, 1.1f, 1.2f);
+ var got = Run(b, parts, At(target), ticks: Settle);
+ var h = parts[Head];
+ var head = (h.X, h.Y, h.Z);
+ var u = Sub(target, head);
+ u = (u.X / Len(u), u.Y / Len(u), u.Z / Len(u));
+ var meet = Add(head, (u.X * distance, u.Y * distance, u.Z * distance));
+ var t = parts[Torso];
+ var leftAxis = Rot(t.Rotation * Plan.Parts[Torso].Rotation.Conjugate(), (1f, 0f, 0f));
+ var wristL = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(got, Side.Left, out var elL), elL);
+ var wristR = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(got, Side.Right, out var elR), elR);
+ Assert.True(Len(Sub(wristL, meet)) < spread + 1e-3f, $"left wrist {Len(Sub(wristL, meet))} m from the meeting point");
+ Assert.True(Len(Sub(wristR, meet)) < spread + 1e-3f, $"right wrist {Len(Sub(wristR, meet))} m from the meeting point");
+ // Either side of the line, the left toward the torso's left: the across sign is what separates these from each other.
+ var leftSide = Sub(wristL, meet);
+ var rightSide = Sub(wristR, meet);
+ Assert.True(leftSide.X * leftAxis.X + leftSide.Y * leftAxis.Y + leftSide.Z * leftAxis.Z > 0.05f);
+ Assert.True(rightSide.X * leftAxis.X + rightSide.Y * leftAxis.Y + rightSide.Z * leftAxis.Z < -0.05f);
+ }
+
+ // The targets the layer wrote for one arm (the flinch blend is zero here, so they are the solution).
+ private static Quat Unflinch(Quat[] targets, Side side, out Quat elbow)
+ {
+ var arm = ArmChain.Of(Plan, side, Dt);
+ elbow = targets[arm.ElbowJoint];
+ return targets[arm.ShoulderJoint];
+ }
+
+ [Fact]
+ public void Present_ignores_the_target_and_the_left_arm_mirrors_the_right_in_x()
+ {
+ var parts = Rest();
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both, Point = (-0.2f, 1.3f, 0.3f) });
+ var without = Run(b, parts, default, ticks: Settle);
+ var with = Run(b, parts, At((3f, 1f, -2f)), ticks: Settle);
+ for (var m = 0; m < Joints; m++) SameBits(without[m], with[m]);
+ var t = parts[Torso];
+ var wl = Wrist(ArmChain.Of(Plan, Side.Left, Dt), t, Unflinch(with, Side.Left, out var el), el);
+ var wr = Wrist(ArmChain.Of(Plan, Side.Right, Dt), t, Unflinch(with, Side.Right, out var er), er);
+ Assert.True(MathF.Abs(wr.X - -0.2f) < 2e-3f && MathF.Abs(wr.Y - 1.3f) < 2e-3f && MathF.Abs(wr.Z - 0.3f) < 2e-3f, $"right wrist {wr}");
+ Assert.True(MathF.Abs(wl.X + wr.X) < 1e-4f && MathF.Abs(wl.Y - wr.Y) < 1e-4f && MathF.Abs(wl.Z - wr.Z) < 1e-4f, $"left {wl} does not mirror right {wr}");
+ }
+
+ private static Quat[] Away(float angle, float x, float y, float z)
+ {
+ var q = new Quat[Joints];
+ for (var m = 0; m < Joints; m++) q[m] = Quat.FromAxisAngle(x, y, z, angle * (1f + 0.1f * m));
+ return q;
+ }
+
+ private static RecoilLayer Recoiling() => new()
+ {
+ AwayLeft = Away(0.5f, 1f, 0f, 0f), AwayRight = Away(0.5f, 0f, 1f, 0f),
+ Proximity = new Consideration(ConsiderationInput.Distance, 0.2, 2.0, 1.0, 0.0),
+ };
+
+ // A target `r` metres from the head centre at lateral coordinate s in the torso frame (+ is the actor's left), level with the head.
+ private static (float X, float Y, float Z) Bearing(float s, float r)
+ {
+ var h = Plan.Parts[Head].Position;
+ return (h.X + s * r, h.Y, h.Z + MathF.Sqrt(1f - s * s) * r);
+ }
+
+ [Fact]
+ public void Recoil_blends_by_bearing_and_is_continuous_across_the_midline()
+ {
+ var recoil = Recoiling();
+ var b = Behaviour(recoil: recoil);
+ var baseline = Base(b);
+ var depth = (float)recoil.Proximity.Response(0.5);
+ Assert.InRange(depth, 0.5f, 0.99f);
+
+ var far = Run(b, Rest(), At(Bearing(0.6f, 3f))); // past the curve's far end: depth 0
+ for (var m = 0; m < Joints; m++) Same(baseline[m], far[m]);
+
+ var leftward = Run(b, Rest(), At(Bearing(1f, 0.5f)));
+ var rightward = Run(b, Rest(), At(Bearing(-1f, 0.5f)));
+ var ahead = Run(b, Rest(), At(Bearing(0f, 0.5f)));
+ var key = Key();
+ for (var m = 0; m < Joints; m++)
+ {
+ Same(Flinched(Quat.Nlerp(key[m], recoil.Left[m], depth), Quat.Identity, 0f), leftward[m]);
+ Same(Flinched(Quat.Nlerp(key[m], recoil.Right[m], depth), Quat.Identity, 0f), rightward[m]);
+ var half = Quat.Nlerp(Quat.Nlerp(key[m], recoil.Left[m], depth * 0.5f), recoil.Right[m], depth * 0.5f);
+ Same(Flinched(half, Quat.Identity, 0f), ahead[m]);
+ }
+
+ var a = Run(b, Rest(), At(Bearing(1e-4f, 0.5f)));
+ var c = Run(b, Rest(), At(Bearing(-1e-4f, 0.5f)));
+ for (var m = 0; m < Joints; m++)
+ {
+ Same(a[m], ahead[m], 1e-5f);
+ Same(c[m], ahead[m], 1e-5f);
+ }
+ }
+
+ [Fact]
+ public void Recoil_applies_before_look_and_arms_so_a_partial_look_or_reach_blends_from_the_recoiled_pose()
+ {
+ var recoil = Recoiling();
+ var b = Behaviour(new LookLayer { Weight = 0.5 }, new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Right, Weight = 0.5 }, recoil);
+ var parts = Rest();
+ var target = Bearing(0.5f, 0.5f);
+ var got = Run(b, parts, At(target), ticks: Settle);
+
+ var depth = (float)recoil.Proximity.Response(0.5);
+ var key = Key();
+ var recoiled = new Quat[Joints];
+ for (var m = 0; m < Joints; m++) recoiled[m] = Quat.Nlerp(Quat.Nlerp(key[m], recoil.Left[m], depth * 0.75f), recoil.Right[m], depth * 0.25f);
+
+ var t = parts[Torso];
+ LookChain.Of(Plan).Solve(t.Rotation, t.X, t.Y, t.Z, target.X, target.Y, target.Z, out var neck);
+ var arm = ArmChain.Of(Plan, Side.Right, Dt);
+ var p = parts[arm.ParentPart];
+ arm.Solve(p.Rotation, p.X, p.Y, p.Z, target.X, target.Y, target.Z, out var shoulder, out var elbow);
+ for (var m = 0; m < Joints; m++)
+ {
+ var want = m == Neck ? Quat.Nlerp(recoiled[m], neck, 0.5f)
+ : m == arm.ShoulderJoint ? Quat.Nlerp(recoiled[m], shoulder, 0.5f)
+ : m == arm.ElbowJoint ? Quat.Nlerp(recoiled[m], elbow, 0.5f)
+ : recoiled[m];
+ Same(want, got[m], 1e-5f);
+ }
+ }
+
+ [Fact]
+ public void The_layers_treat_a_phantom_target_as_they_treat_a_real_one_at_the_same_place()
+ {
+ // Stare-at-hands is Look and Reach on a phantom at the actor's own hand: the layers read the percept's place, never its id.
+ var b = Behaviour(new LookLayer(), new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both }, Recoiling());
+ foreach (var parts in new[] { Rest(), Turned() })
+ {
+ var real = Run(b, parts, At(Ahead, 1UL));
+ var phantom = Run(b, parts, At(Ahead, Perception.PhantomIdBit | 1UL));
+ for (var m = 0; m < Joints; m++) SameBits(real[m], phantom[m]);
+ Assert.NotEqual(Base(b)[Neck], phantom[Neck]);
+ }
+ }
+
+ [Fact]
+ public void The_flinch_applies_after_the_layers_and_strength_stays_the_pose_rule()
+ {
+ var parts = Rest();
+ var hold = new HoldParameters { HoldStrength = 0.8f, FlinchGain = 0.3 };
+ var flinchPose = Away(0.7f, 0f, 0f, 1f);
+ var b = Behaviour(new LookLayer(), new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both }, Recoiling(), hold) with { FlinchPose = flinchPose };
+ var tgt = At(Ahead);
+ var quiet = Run(b, parts, tgt);
+ foreach (var weight in new[] { 0.0, 0.25, 0.5, 1.0 })
+ {
+ foreach (var leak in new[] { 0.0, 0.4, 1.0 })
+ {
+ var strengths = new float[Joints];
+ var moved = Run(b, parts, tgt, weight: weight, leak: leak, strengths: strengths);
+ var w = (float)b.Blend(leak, 0.0, 0.0);
+ var want = hold.HoldStrength * (float)Math.Min(1.0, weight + leak * hold.FlinchGain);
+ for (var m = 0; m < Joints; m++)
+ {
+ Assert.Equal(want, strengths[m]);
+ // The flinch is the last blend, over the layered pose and for every joint, the solved shoulder included.
+ var layered = Run(b with { FlinchPose = Identity(), Hold = hold with { FlinchGain = 0.0 } }, parts, tgt)[m];
+ Same(Quat.Nlerp(layered, flinchPose[m], w), moved[m], 1e-5f);
+ }
+ }
+ }
+
+ var shoulder = Plan.JointIndex("Shoulder", Side.Left);
+ var leaking = Run(b, parts, tgt, leak: 1.0);
+ Assert.NotEqual(quiet[shoulder], leaking[shoulder]);
+ }
+
+ [Fact]
+ public void Validation_names_the_goal()
+ {
+ static void Refuses(PoseBehaviour b) => Assert.Contains("Goal g:", Assert.Throws(() => b.Validate("g")).Message);
+ var good = Behaviour();
+ good.Validate("g");
+ foreach (var weight in new[] { -0.1, 1.1, double.NaN, double.PositiveInfinity })
+ {
+ Refuses(Behaviour(look: new LookLayer { Weight = weight }));
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Weight = weight }));
+ }
+
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0f, Spread = 0.1f }));
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = -0.3f, Spread = 0.1f }));
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0.3f, Spread = -0.01f }));
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = float.NaN, Spread = 0.1f }));
+ Refuses(Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Nearer }));
+ Behaviour(arms: new ArmLayer { Mode = ArmMode.Present, Side = ArmSide.Both }).Validate("g");
+ Behaviour(arms: new ArmLayer { Mode = ArmMode.WardOff, Distance = 0.3f, Spread = 0f }).Validate("g");
+
+ var recoil = Recoiling();
+ Behaviour(recoil: recoil).Validate("g");
+ Refuses(Behaviour(recoil: recoil with { AwayLeft = new Quat[Joints - 1] }));
+ Refuses(Behaviour(recoil: recoil with { AwayRight = new Quat[Joints + 1] }));
+ Refuses(Behaviour(recoil: recoil with { Proximity = recoil.Proximity with { Input = ConsiderationInput.Salience } }));
+ Refuses(Behaviour(recoil: new RecoilLayer { AwayLeft = Identity(), AwayRight = Identity() }));
+ }
+
+ [Fact]
+ public void A_layered_behaviour_refuses_to_write_without_the_orient_input()
+ {
+ var b = Behaviour(new LookLayer());
+ Assert.Throws(() => b.Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], new Quat[Joints]));
+ Assert.True(b.HasLayers);
+ Assert.False(Behaviour().HasLayers);
+ Behaviour().Write(1.0, 0.0, 0.0, 0.0, 0.0, new float[Joints], new Quat[Joints]);
+ }
+
+ [Fact]
+ public void Layers_copy_their_poses_and_read_back_read_only()
+ {
+ var left = Away(0.5f, 1f, 0f, 0f);
+ var recoil = new RecoilLayer { AwayLeft = left, AwayRight = Identity(), Proximity = new Consideration(ConsiderationInput.Distance, 0, 1, 1, 0) };
+ var was = recoil.AwayLeft[0];
+ left[0] = Quat.Identity;
+ Assert.Equal(was, recoil.AwayLeft[0]);
+ Assert.False(recoil.AwayLeft is Quat[]);
+ }
+
+ // The Actor: targets come from the percepts, the layers from the goal's behaviour, the poses from the caller.
+
+ private static Emitter Emit(ulong id, (float X, float Y, float Z) p) =>
+ new() { Channel = Channel.Audio, X = p.X, Y = p.Y, Z = p.Z, Radius = 40f, Intensity = 1.0, Id = id, Kind = Thing };
+
+ private static Brain Watching(PoseBehaviour layered) => new()
+ {
+ Goals = new[]
+ {
+ new GoalSpec { Id = "idle", Priority = 0.0, Behaviour = Behaviour() },
+ new GoalSpec
+ {
+ Id = "watch", Priority = 1.0, Target = new TargetFilter { Kinds = new[] { Thing } },
+ Considerations = new[] { new Consideration(ConsiderationInput.Distance, 0.0, 60.0, 1.0, 0.0) },
+ Behaviour = layered,
+ },
+ },
+ };
+
+ private static Actor Watcher(Brain brain, BodyPlan? body) =>
+ new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain,
+ new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0,
+ new PerceptParameters { Capacity = 4, MemorySeconds = 5.0 }, body: body);
+
+ private static readonly float[] Origin = { 0f };
+
+ private static TickEvents Step(Actor a, PartPose[] parts, Quat[] targets, params Emitter[] emitters) =>
+ a.Tick(Origin, Origin, Origin, NoBoxes, new float[Joints], targets, emitters, parts: parts);
+
+ [Fact]
+ public void Nearer_holds_one_arm_per_pair_and_a_recommit_picks_again()
+ {
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
+ var a = Watcher(Watching(b), Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var baseline = Base(b);
+ var left = Plan.JointIndex("Shoulder", Side.Left);
+ var right = Plan.JointIndex("Shoulder", Side.Right);
+ var onLeft = (0.9f, 1.5f, 0.5f);
+ var onRight = (-0.9f, 1.5f, 0.5f);
+
+ for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, onLeft));
+ Assert.Equal(1UL, a.TargetId);
+ Assert.NotEqual(baseline[left], targets[left]);
+ Same(baseline[right], targets[right]);
+
+ // The same thing moves to the right: the pair is the same pair, so the arm stays.
+ for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, onRight));
+ Assert.Equal(1UL, a.TargetId);
+ Assert.NotEqual(baseline[left], targets[left]);
+ Same(baseline[right], targets[right]);
+
+ // Another thing, nearer and on the right, is another pair: it commits a latency later and picks the nearer arm again.
+ for (var i = 0; i < 60; i++) Step(a, parts, targets, Emit(1, onRight), Emit(2, (-0.5f, 1.5f, 0.3f)));
+ Assert.Equal(2UL, a.TargetId);
+ Assert.NotEqual(baseline[right], targets[right]);
+ Same(baseline[left], targets[left]);
+ }
+
+ [Theory]
+ [InlineData(Side.Right)]
+ [InlineData(Side.Left)]
+ public void ResetArms_makes_both_arms_engage_from_the_base_and_settle_on_the_stateless_rule(Side side)
+ {
+ // Reach with both arms along the feasible tie of one arm's shoulder (goal (dx, -0.25, -0.25) from it, mirrored for the left), from
+ // dx -10 mm to 2 mm past the tie: that arm holds its basin, away from the stateless target. After ResetArms both arms are idle: the
+ // next tick writes within one slew step of the base pose, and with the goal held they settle on the stateless solve.
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
+ var a = Watcher(Watching(b), Plan);
+ var parts = Rest();
+ var targets = new Quat[Joints];
+ var arms = new[] { ArmChain.Of(Plan, Side.Left, Dt), ArmChain.Of(Plan, Side.Right, Dt) };
+ var tie = side == Side.Left ? arms[0] : arms[1];
+ var sign = side == Side.Left ? -1f : 1f;
+ var s = tie.ShoulderAnchor;
+ (float X, float Y, float Z) Goal(float dx) => (s.X + sign * dx, s.Y - 0.25f, s.Z - 0.25f);
+ for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, Goal(-0.01f)));
+ Assert.Equal(1UL, a.TargetId);
+ for (var i = -50; i <= 10; i++) Step(a, parts, targets, Emit(1, Goal(i * 0.0002f)));
+ var held = (Quat[])targets.Clone();
+ a.ResetArms();
+ Step(a, parts, targets, Emit(1, Goal(0.002f)));
+ var baseline = Base(b);
+ foreach (var arm in arms)
+ {
+ Assert.True(Turn(baseline[arm.ShoulderJoint], targets[arm.ShoulderJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the shoulder jumped from the base on engaging");
+ Assert.True(Turn(baseline[arm.ElbowJoint], targets[arm.ElbowJoint]) <= ArmChain.MaxAngularRate * Dt + 1e-5f, "the elbow jumped from the base on engaging");
+ }
+
+ for (var i = 0; i < Settle; i++) Step(a, parts, targets, Emit(1, Goal(0.002f)));
+ var t = a.Target;
+ Assert.Equal(Goal(0.002f), (t.X, t.Y, t.Z));
+ foreach (var arm in arms)
+ {
+ var p = parts[arm.ParentPart];
+ arm.Solve(p.Rotation, p.X, p.Y, p.Z, t.X, t.Y, t.Z, out var shoulder, out var elbow);
+ Same(Flinched(shoulder, Quat.Identity, 0f), targets[arm.ShoulderJoint]);
+ Same(Flinched(elbow, Quat.Identity, 0f), targets[arm.ElbowJoint]);
+ }
+
+ var held2 = held[tie.ShoulderJoint];
+ var reset = targets[tie.ShoulderJoint];
+ var turn = 2f * MathF.Acos(MathF.Min(1f, MathF.Abs(held2.X * reset.X + held2.Y * reset.Y + held2.Z * reset.Z + held2.W * reset.W)));
+ Assert.True(turn > 1f, $"the held {side} arm was only {turn} rad from the stateless target, so the reset proves nothing");
+ }
+
+ [Fact]
+ public void A_tie_goes_to_the_right_arm()
+ {
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Nearer });
+ var a = Watcher(Watching(b), Plan);
+ var targets = new Quat[Joints];
+ var baseline = Base(b);
+ for (var i = 0; i < 40; i++) Step(a, Rest(), targets, Emit(1, (0f, 1.5f, 0.8f)));
+ Assert.Equal(1UL, a.TargetId);
+ Assert.NotEqual(baseline[Plan.JointIndex("Shoulder", Side.Right)], targets[Plan.JointIndex("Shoulder", Side.Right)]);
+ Same(baseline[Plan.JointIndex("Shoulder", Side.Left)], targets[Plan.JointIndex("Shoulder", Side.Left)]);
+ }
+
+ [Fact]
+ public void The_actor_gives_the_layers_the_committed_target_and_the_callers_poses()
+ {
+ var b = Behaviour(look: new LookLayer());
+ var a = Watcher(Watching(b), Plan);
+ var parts = Turned();
+ var targets = new Quat[Joints];
+ for (var i = 0; i < 40; i++) Step(a, parts, targets, Emit(1, Ahead));
+ var t = parts[Torso];
+ LookChain.Of(Plan).Solve(t.Rotation, t.X, t.Y, t.Z, Ahead.X, Ahead.Y, Ahead.Z, out var solved);
+ SameBits(Flinched(solved, Quat.Identity, 0f), targets[Neck]);
+ Assert.Same(Plan, a.Body);
+ }
+
+ [Fact]
+ public void Construction_refuses_what_the_layers_cannot_stand_on()
+ {
+ var layered = Behaviour(new LookLayer());
+ var noBody = Assert.Throws(() => Watcher(Watching(layered), null));
+ Assert.Contains("Goal watch", noBody.Message);
+
+ // One muscle too few for the body.
+ var short3 = new PoseBehaviour { Keys = new[] { new Quat[3] { Quat.Identity, Quat.Identity, Quat.Identity } }, FlinchPose = new Quat[3] { Quat.Identity, Quat.Identity, Quat.Identity }, Look = new LookLayer() };
+ var brain = new Brain { Goals = new[] { new GoalSpec { Id = "short", Behaviour = short3 } } };
+ Assert.Contains("Goal short", Assert.Throws(() => Watcher(brain, Plan)).Message);
+
+ // Layers on goals that none use build without a body when no goal is layered.
+ Watcher(Watching(Behaviour()), null);
+ }
+
+ private static BodyPlan WithJoint(string label, Side side, Func change)
+ {
+ var joints = new JointDef[Joints];
+ for (var j = 0; j < Joints; j++) joints[j] = Plan.Joints[j];
+ var i = Plan.JointIndex(label, side);
+ joints[i] = change(joints[i]);
+ return new BodyPlan(Plan.Parts, joints, Plan.SensePoints, Plan.AirwayOpenings, Plan.AirwaySumps);
+ }
+
+ [Fact]
+ public void An_arm_the_closed_form_cannot_solve_is_refused_at_construction_naming_goal_and_side()
+ {
+ var b = Behaviour(arms: new ArmLayer { Mode = ArmMode.Reach, Side = ArmSide.Both });
+
+ // Bent at creation: the elbow anchor off the shoulder-to-wrist line.
+ var bent = WithJoint("Elbow", Side.Right, j => j with { Anchor = (j.Anchor.X - 0.08f, j.Anchor.Y, j.Anchor.Z + 0.05f) });
+ var bentError = Assert.Throws(() => Watcher(Watching(b), bent)).Message;
+ Assert.Contains("Goal watch", bentError);
+ Assert.Contains("Right", bentError);
+ Assert.DoesNotContain("Left", bentError);
+
+ // An elbow range straddling zero.
+ var straddle = WithJoint("Elbow", Side.Left, j => j with { Lower = -1f, Upper = 1f });
+ var straddleError = Assert.Throws