diff --git a/src/Lodur.Core/Physiology.cs b/src/Lodur.Core/Physiology.cs
new file mode 100644
index 0000000..0d9af91
--- /dev/null
+++ b/src/Lodur.Core/Physiology.cs
@@ -0,0 +1,362 @@
+using System;
+using System.Collections.Generic;
+
+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 body's physiology: tissue integrity, bound afflictions, blood, 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. 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 _consciousnessWeight;
+ private readonly double _pumpingWeight;
+ 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
+ private readonly double[] _motor; // per joint
+ private double _volume;
+ private double _consciousness;
+ private double _pumping = 1.0;
+ private long _steps;
+ private bool _bound;
+
+ public Physiology(BodyPlan body, PhysiologyPlan plan, double slowScale)
+ {
+ if (!(slowScale > 0.0 && !double.IsInfinity(slowScale))) throw new ArgumentException("the slow scale must be finite and above 0.");
+ _body = body;
+ _slowScale = slowScale;
+ _nominal = plan.Blood.NominalVolume;
+ _lethalLoss = plan.Blood.LethalLossFraction;
+ _regen = plan.Blood.RegenPerSecond;
+ _volume = _nominal;
+
+ _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];
+
+ // Resolve: every body part has exactly one stack and every stack names a body part, by (label, side).
+ 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 < plan.Parts.Count; s++)
+ {
+ var def = plan.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;
+ }
+
+ _partStart = new int[parts + 1];
+ var total = 0;
+ for (var p = 0; p < parts; p++)
+ {
+ if (stackOf[p] < 0) throw new ArgumentException($"body part '{body.Parts[p].Label}' {body.Parts[p].Side} has no tissue stack.");
+ _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;
+ _consciousnessWeight += t.Consciousness;
+ _pumpingWeight += t.BloodPumping;
+ _motorWeight[p] += t.Motor;
+ }
+ }
+
+ if (!(_consciousnessWeight > 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 was full.
+ 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 tissue's remaining fraction, 0..1, as of the last step.
+ public double Integrity(int part, int layer) => _integrity[Flat(part, layer)];
+
+ /// The part's blood loss in m^3/s as of the last step; 0 once dead.
+ public double Bleed(int part) => Dead ? 0.0 : _bleed[part];
+
+ /// 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)
+ {
+ if ((uint)affliction >= (uint)_defs.Length) throw new ArgumentException("not an affliction.");
+ var tissue = Flat(part, layer);
+ if (!(severity > 0.0 && !double.IsInfinity(severity))) throw new ArgumentException("severity must be finite and above 0.");
+ for (var s = 0; s < _slotDef.Length; s++)
+ {
+ if (_slotDef[s] >= 0) continue;
+ _slotDef[s] = affliction;
+ _slotPart[s] = part;
+ _slotTissue[s] = tissue;
+ _slotSeverity[s] = severity;
+ _slotAge[s] = 0.0;
+ return true;
+ }
+
+ Refused++;
+ return false;
+ }
+
+ ///
+ /// 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 death is judged once. A dead physiology does not change.
+ ///
+ public void Step(double dt)
+ {
+ if (Dead) 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 they read is the volume the step began with.
+ var bloodLoss = BloodLoss;
+ _consciousness = Capacity(EffectTarget.Consciousness, bloodLoss);
+ _pumping = Capacity(EffectTarget.BloodPumping, bloodLoss);
+
+ // 4. Bleeding: each affliction's bleed effects, through its tissue's vascularity and the pumping.
+ Array.Clear(_bleed, 0, _bleed.Length);
+ var totalBleed = 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], bloodLoss, ref offset, ref factor);
+ var rate = Math.Max(0.0, offset * factor) * _tissues[_slotTissue[s]].Vascularity * _pumping;
+ _bleed[_slotPart[s]] += rate;
+ totalBleed += rate;
+ }
+
+ _volume -= totalBleed * dt;
+
+ // 5. Regrowth, on the slow clock, only while nothing bleeds.
+ if (totalBleed == 0.0)
+ {
+ _volume = Math.Min(_nominal, _volume + _regen * _nominal * slowDt);
+ }
+
+ // 6. 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], bloodLoss, ref offset, ref factor);
+ }
+ }
+
+ _motor[j] = Clamp01((mean / _motorWeight[part] + offset) * factor) * _consciousness;
+ }
+
+ // 7. 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 double Capacity(EffectTarget target, double bloodLoss)
+ {
+ var weightSum = target == EffectTarget.Consciousness ? _consciousnessWeight : _pumpingWeight;
+ var mean = 1.0;
+ if (weightSum > 0.0)
+ {
+ var acc = 0.0;
+ for (var i = 0; i < _tissues.Length; i++)
+ {
+ var w = target == EffectTarget.Consciousness ? _tissues[i].Consciousness : _tissues[i].BloodPumping;
+ 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, bloodLoss, 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], bloodLoss, ref offset, ref factor);
+ }
+
+ return Clamp01((mean + offset) * factor);
+ }
+
+ private static void Fold(IReadOnlyList effects, EffectTarget target, double severity, double age, double bloodLoss, ref double offset, ref double factor)
+ {
+ for (var i = 0; i < effects.Count; i++)
+ {
+ Fold(effects[i], target, severity, age, bloodLoss, ref offset, ref factor);
+ }
+ }
+
+ private static void Fold(Effect e, EffectTarget target, double severity, double age, double bloodLoss, ref double offset, ref double factor)
+ {
+ if (e.Target != target) return;
+ var x = e.Driver == EffectDriver.Severity ? severity : e.Driver == EffectDriver.Age ? age : bloodLoss;
+ 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/tests/Lodur.Core.Tests/PhysiologyFixtures.cs b/tests/Lodur.Core.Tests/PhysiologyFixtures.cs
new file mode 100644
index 0000000..b702287
--- /dev/null
+++ b/tests/Lodur.Core.Tests/PhysiologyFixtures.cs
@@ -0,0 +1,70 @@
+using Lodur;
+
+namespace Lodur.Core.Tests;
+
+/// A three-part, two-joint body and a plain physiology over it, for the tests that are about a rule rather than about the humanoid's content.
+internal static class PhysioFixtures
+{
+ public static BodyPlan Body3()
+ {
+ PartDef P(string label) => new(label, Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
+ JointDef J(string label, int child) => new(label, Side.Center, JointKind.Spherical, 0, child, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
+ return new BodyPlan(new[] { P("Root"), P("A"), P("B") }, new[] { J("J0", 1), J("J1", 2) }, Array.Empty());
+ }
+
+ public const int BrainLayer = 0, Heart = 1, RootMuscle = 2;
+
+ private static Effect Const(EffectTarget t, EffectOp op, double v) => new(t, op, EffectDriver.Severity, new[] { (0.0, v), (1.0, v) });
+
+ private static AfflictionDef Def(string label, double rate, bool injures, PhysiologyClock clock, params Effect[] effects) => new(label, clock, rate, injures, effects);
+
+ public static readonly AfflictionDef[] Defs =
+ {
+ Def("Lesion", 0, true, PhysiologyClock.Acute),
+ Def("Mark", 0, false, PhysiologyClock.Acute),
+ Def("Heal", -1, true, PhysiologyClock.Acute),
+ Def("SlowHeal", -1, true, PhysiologyClock.Slow),
+ Def("Bleeder", 0, false, PhysiologyClock.Acute, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-3) })),
+ Def("Dim", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Consciousness, EffectOp.Offset, -0.1)),
+ Def("Halve", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Consciousness, EffectOp.Factor, 0.5)),
+ Def("MotorHalf", 0, false, PhysiologyClock.Acute, Const(EffectTarget.Motor, EffectOp.Factor, 0.5)),
+ Def("Clot", 0, false, PhysiologyClock.Acute,
+ Const(EffectTarget.Bleed, EffectOp.Offset, 1e-3),
+ new Effect(EffectTarget.Bleed, EffectOp.Factor, EffectDriver.Age, new[] { (0.0, 1.0), (60.0, 0.5), (300.0, 0.1) })),
+ Def("Fading", -0.1, false, PhysiologyClock.Acute, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-5) })),
+ Def("SlowBleeder", 0, false, PhysiologyClock.Slow, new Effect(EffectTarget.Bleed, EffectOp.Offset, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 1e-3) })),
+ };
+
+ public static int Af(string label)
+ {
+ for (var i = 0; i < Defs.Length; i++) if (Defs[i].Label == label) return i;
+ throw new ArgumentException(label);
+ }
+
+ public static BloodDef DefaultBlood => new(0.005, 0.5, 0.0);
+
+ /// Root: brain (weight 1), heart (pumping 1, vital unless asked otherwise), a muscle; A and B: a muscle each. Every tissue has Hp 10.
+ public static PhysiologyPlan Plan3(bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList? organism = null, TissueDef[]? root = null)
+ {
+ var stack = root ?? new[]
+ {
+ new TissueDef("brain", 10, 1, Consciousness: 1),
+ new TissueDef("heart", 10, 4, heartVital, BloodPumping: 1),
+ new TissueDef("muscle", 10, 1, Motor: 1),
+ };
+ var limb = new[] { new TissueDef("muscle", 10, 1, Motor: 1) };
+ return new PhysiologyPlan(
+ new[] { new PartTissuesDef("Root", Side.Center, stack), new PartTissuesDef("A", Side.Center, limb), new PartTissuesDef("B", Side.Center, limb) },
+ Defs, organism ?? Array.Empty(), blood ?? DefaultBlood, slots);
+ }
+
+ public static Physiology Make(double slowScale = 20.0, bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList? organism = null, TissueDef[]? root = null) =>
+ new(Body3(), Plan3(heartVital, blood, slots, organism, root), slowScale);
+
+ public static int Live(Physiology p)
+ {
+ var n = 0;
+ for (var s = 0; s < p.SlotCount; s++) if (p.SlotDef(s) >= 0) n++;
+ return n;
+ }
+}
diff --git a/tests/Lodur.Core.Tests/PhysiologyTests.cs b/tests/Lodur.Core.Tests/PhysiologyTests.cs
new file mode 100644
index 0000000..83daf25
--- /dev/null
+++ b/tests/Lodur.Core.Tests/PhysiologyTests.cs
@@ -0,0 +1,501 @@
+using Lodur;
+using static Lodur.Core.Tests.PhysioFixtures;
+
+namespace Lodur.Core.Tests;
+
+/// The Physiology's rules: resolution against a body, integrity from injuries, capacities, the clocks, bleeding, death, the bounded table.
+public sealed class PhysiologyTests
+{
+ private static void Afflict(Physiology p, string label, int part, int layer, double severity) =>
+ Assert.True(p.Afflict(Af(label), part, layer, severity));
+
+ // Resolution against a body.
+
+ private static BodyPlan Tiny()
+ {
+ PartDef P(string label) => new(label, Side.Center, PartShape.Box, (0.1f, 0.1f, 0.1f), (0f, 0f, 0f), Quat.Identity, 1000f, 0.8f, 0f);
+ var joint = new JointDef("J", Side.Center, JointKind.Spherical, 0, 1, (0f, 0f, 0f), (0f, 1f, 0f), 0f, 0f, 0f, new MuscleGains(1f, 1f, 1f, 1f));
+ return new BodyPlan(new[] { P("Root"), P("Kid") }, new[] { joint }, Array.Empty());
+ }
+
+ private static PartTissuesDef Stack(string part, params TissueDef[] tissues) => new(part, Side.Center, tissues);
+
+ private static PhysiologyPlan Over(params PartTissuesDef[] parts) =>
+ new(parts, Array.Empty(), Array.Empty(), DefaultBlood, 4);
+
+ private static readonly TissueDef BrainT = new("brain", 10, 1, Consciousness: 1);
+ private static readonly TissueDef MuscleT = new("muscle", 10, 1, Motor: 1);
+
+ [Fact]
+ public void A_physiology_resolves_a_plan_whose_stacks_cover_the_body_parts_exactly()
+ {
+ var ok = new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT)), 20);
+ Assert.Equal(1, ok.JointCount);
+ Assert.Equal(1.0, ok.Consciousness);
+ Assert.Equal(1.0, ok.MotorCeiling(0));
+ }
+
+ [Fact]
+ public void A_physiology_refuses_a_body_part_with_no_stack_a_stack_naming_no_part_and_a_part_with_two_stacks()
+ {
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", BrainT)), 20));
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Ghost", MuscleT)), 20));
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT), Stack("Kid", MuscleT)), 20));
+ Assert.Throws(() => new Physiology(Tiny(),
+ Over(Stack("Root", BrainT), Stack("Kid", MuscleT) with { Side = Side.Left }), 20)); // the side is part of the name
+ }
+
+ [Fact]
+ public void A_physiology_refuses_a_body_with_no_consciousness_tissue_or_a_joint_child_with_no_motor_tissue()
+ {
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", MuscleT), Stack("Kid", MuscleT)), 20));
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", BrainT)), 20));
+ }
+
+ [Fact]
+ public void A_physiology_refuses_a_slow_scale_that_is_not_finite_and_above_zero()
+ {
+ foreach (var bad in new[] { 0.0, -1.0, double.NaN, double.PositiveInfinity })
+ {
+ Assert.Throws(() => new Physiology(Tiny(), Over(Stack("Root", BrainT), Stack("Kid", MuscleT)), bad));
+ }
+ }
+
+ // Integrity.
+
+ [Fact]
+ public void Integrity_is_derived_from_the_injuries_bound_to_a_tissue()
+ {
+ var p = Make();
+ Afflict(p, "Lesion", 1, 0, 3);
+ Afflict(p, "Lesion", 1, 0, 2); // a second instance, never merged
+ Assert.Equal(2, Live(p));
+ Assert.Equal(1.0, p.Integrity(1, 0)); // nothing has stepped: integrity is a step's output
+ p.Step(0.01);
+ Assert.Equal(0.5, p.Integrity(1, 0));
+ Assert.Equal(1.0, p.Integrity(2, 0));
+ Assert.Equal(1.0, p.Integrity(0, p.TissueIndex(0, "brain")));
+ }
+
+ [Fact]
+ public void An_affliction_that_does_not_injure_leaves_integrity_whole()
+ {
+ var p = Make();
+ Afflict(p, "Mark", 1, 0, 9);
+ p.Step(0.01);
+ Assert.Equal(1.0, p.Integrity(1, 0));
+ }
+
+ [Fact]
+ public void Healing_to_zero_severity_frees_the_slot_and_restores_integrity()
+ {
+ var p = Make();
+ Afflict(p, "Heal", 1, 0, 1.0); // rate -1 per second
+ p.Step(0.5);
+ Assert.Equal(0.95, p.Integrity(1, 0), 12);
+ Assert.Equal(1, Live(p));
+ p.Step(0.5); // severity reaches 0: freed
+ Assert.Equal(0, Live(p));
+ Assert.Equal(1.0, p.Integrity(1, 0));
+ }
+
+ [Fact]
+ public void A_wound_past_the_tissues_hp_leaves_integrity_at_zero_not_below()
+ {
+ var p = Make();
+ Afflict(p, "Lesion", 1, 0, 25);
+ p.Step(0.01);
+ Assert.Equal(0.0, p.Integrity(1, 0));
+ Assert.Equal(0.0, p.MotorCeiling(0));
+ }
+
+ [Fact]
+ public void Afflict_refuses_a_severity_that_is_not_finite_and_above_zero_and_names_that_are_not_there()
+ {
+ var p = Make();
+ foreach (var bad in new[] { 0.0, -1.0, double.NaN, double.PositiveInfinity })
+ {
+ Assert.Throws(() => p.Afflict(Af("Lesion"), 1, 0, bad));
+ }
+
+ Assert.Throws(() => p.Afflict(-1, 1, 0, 1));
+ Assert.Throws(() => p.Afflict(Defs.Length, 1, 0, 1));
+ Assert.Throws(() => p.Afflict(0, 3, 0, 1));
+ Assert.Throws(() => p.Afflict(0, 1, 1, 1));
+ Assert.Throws(() => p.Afflict(0, 1, -1, 1));
+ Assert.Throws(() => p.TissueIndex(1, "brain"));
+ Assert.Equal(0, Live(p));
+ Assert.Equal(0, p.Refused);
+ }
+
+ // Capacities.
+
+ [Fact]
+ public void Capacities_fold_offsets_then_factors()
+ {
+ var p = Make();
+ var brain = p.TissueIndex(0, "brain");
+ Afflict(p, "Lesion", 0, brain, 6);
+ p.Step(0.01);
+ Assert.Equal(0.4, p.Consciousness, 12);
+
+ Afflict(p, "Dim", 0, brain, 1); // Offset -0.1
+ Afflict(p, "Halve", 0, brain, 1); // Factor 0.5
+ p.Step(0.01);
+ Assert.Equal((0.4 - 0.1) * 0.5, p.Consciousness, 12); // not 0.4 x 0.5 - 0.1
+ }
+
+ [Fact]
+ public void A_capacity_is_the_weighted_mean_integrity_of_the_tissues_that_carry_it()
+ {
+ var root = new[]
+ {
+ new TissueDef("left", 10, 1, Consciousness: 1),
+ new TissueDef("right", 10, 1, Consciousness: 3),
+ new TissueDef("skin", 10, 1, Motor: 1),
+ new TissueDef("heart", 10, 4, BloodPumping: 1),
+ };
+ var p = Make(root: root);
+ Afflict(p, "Lesion", 0, 0, 5); // left at 0.5, right whole
+ p.Step(0.01);
+ Assert.Equal((0.5 * 1 + 1.0 * 3) / 4, p.Consciousness, 12);
+ Assert.Equal(1.0, p.BloodPumping);
+ Afflict(p, "Lesion", 0, 2, 10); // a tissue with no consciousness weight does not touch it
+ p.Step(0.01);
+ Assert.Equal((0.5 * 1 + 1.0 * 3) / 4, p.Consciousness, 12);
+ }
+
+ [Fact]
+ public void Blood_pumping_is_one_when_no_tissue_pumps()
+ {
+ var p = Make(root: new[] { new TissueDef("brain", 10, 1, Consciousness: 1), new TissueDef("muscle", 10, 1, Motor: 1) });
+ Afflict(p, "Bleeder", 0, 1, 1);
+ p.Step(0.01);
+ Assert.Equal(1.0, p.BloodPumping);
+ Assert.Equal(1e-3, p.Bleed(0), 15);
+ }
+
+ [Fact]
+ public void An_organism_effect_reads_the_blood_loss_as_the_step_began()
+ {
+ var organism = new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss, new[] { (0.0, 0.0), (0.2, 0.0), (0.2, -0.3), (1.0, -0.3) }) };
+ var p = Make(organism: organism);
+ Afflict(p, "Bleeder", 2, 0, 1);
+ while (p.BloodLoss < 0.2) p.Step(0.01);
+ Assert.True(p.Consciousness == 1.0, "the step that crosses the stage has not read it yet");
+ p.Step(0.01);
+ Assert.Equal(0.7, p.Consciousness, 12);
+ }
+
+ // Motor ceiling.
+
+ [Fact]
+ public void The_motor_ceiling_is_the_child_parts_integrity_and_its_effects_times_consciousness()
+ {
+ var p = Make();
+ Afflict(p, "Lesion", 1, 0, 4); // A's muscle at 0.6
+ Afflict(p, "MotorHalf", 2, 0, 1); // Factor 0.5 on B
+ p.Step(0.01);
+ Assert.Equal(0.6, p.MotorCeiling(0), 12);
+ Assert.Equal(0.5, p.MotorCeiling(1), 12);
+
+ Afflict(p, "Lesion", 0, BrainLayer, 4); // consciousness 0.6 scales every ceiling
+ p.Step(0.01);
+ Assert.Equal(0.6, p.Consciousness, 12);
+ Assert.Equal(0.6 * 0.6, p.MotorCeiling(0), 12);
+ Assert.Equal(0.5 * 0.6, p.MotorCeiling(1), 12);
+ }
+
+ [Fact]
+ public void A_motor_effect_binds_to_the_part_it_was_afflicted_on_not_to_the_body()
+ {
+ var p = Make();
+ Afflict(p, "MotorHalf", 1, 0, 1);
+ p.Step(0.01);
+ Assert.Equal(0.5, p.MotorCeiling(0));
+ Assert.Equal(1.0, p.MotorCeiling(1));
+ Assert.Equal(1.0, p.Consciousness);
+ }
+
+ // Clocks.
+
+ [Fact]
+ public void A_slow_affliction_moves_on_the_scaled_clock_and_an_acute_one_on_the_callers()
+ {
+ var p = Make(slowScale: 20);
+ Afflict(p, "SlowHeal", 1, 0, 5);
+ Afflict(p, "Heal", 2, 0, 5);
+ for (var i = 0; i < 10; i++) p.Step(0.01);
+ var slow = 0;
+ var acute = 0;
+ for (var s = 0; s < p.SlotCount; s++)
+ {
+ if (p.SlotDef(s) == Af("SlowHeal")) slow = s;
+ if (p.SlotDef(s) == Af("Heal")) acute = s;
+ }
+
+ Assert.Equal(5 - 10 * 20 * 1 * 0.01, p.SlotSeverity(slow), 12);
+ Assert.Equal(5 - 10 * 1 * 0.01, p.SlotSeverity(acute), 12);
+ Assert.Equal(10 * 20 * 0.01, p.SlotAge(slow), 12); // age counts the clock's seconds
+ Assert.Equal(10 * 0.01, p.SlotAge(acute), 12);
+ }
+
+ [Fact]
+ public void Bleeding_is_real_time_whatever_the_slow_scale()
+ {
+ double Remaining(double scale)
+ {
+ var p = Make(slowScale: scale);
+ Afflict(p, "Bleeder", 1, 0, 1);
+ for (var i = 0; i < 200; i++) p.Step(0.01);
+ return p.BloodVolume;
+ }
+
+ Assert.Equal(Remaining(1), Remaining(20));
+ Assert.Equal(0.005 - 1e-3 * 2.0, Remaining(1), 12);
+ }
+
+ [Fact]
+ public void Blood_regrows_only_while_nothing_bleeds_and_on_the_slow_clock()
+ {
+ double Regrown(double scale)
+ {
+ var p = Make(slowScale: scale, blood: DefaultBlood with { RegenPerSecond = 1e-5 });
+ Afflict(p, "Fading", 1, 0, 1); // bleeds, shrinking by 0.1 severity per second, until it is gone
+ var last = p.BloodVolume;
+ while (Live(p) > 0)
+ {
+ p.Step(0.01);
+ if (Live(p) > 0) Assert.True(p.BloodVolume <= last, "blood grew while something bled");
+ last = p.BloodVolume;
+ }
+
+ var settled = p.BloodVolume;
+ for (var i = 0; i < 100; i++) p.Step(0.01);
+ Assert.True(p.BloodVolume < 0.005);
+ return (p.BloodVolume - settled) / scale;
+ }
+
+ Assert.Equal(1e-5 * 0.005 * 100 * 0.01, Regrown(1), 12);
+ Assert.Equal(Regrown(1), Regrown(20), 12);
+ }
+
+ [Fact]
+ public void Regrowth_is_capped_at_the_nominal_volume()
+ {
+ var p = Make(blood: DefaultBlood with { RegenPerSecond = 10 });
+ Afflict(p, "Fading", 1, 0, 1);
+ for (var i = 0; i < 2000; i++) p.Step(0.01);
+ Assert.Equal(0.005, p.BloodVolume);
+ }
+
+ // Bleeding.
+
+ [Fact]
+ public void Volume_falls_by_the_sum_of_the_parts_bleed_times_dt()
+ {
+ var p = Make();
+ Afflict(p, "Bleeder", 1, 0, 1);
+ Afflict(p, "Bleeder", 2, 0, 0.5);
+ Afflict(p, "Bleeder", 0, RootMuscle, 0.25);
+ for (var i = 0; i < 20; i++)
+ {
+ var before = p.BloodVolume;
+ p.Step(0.05);
+ var sum = p.Bleed(0) + p.Bleed(1) + p.Bleed(2);
+ Assert.Equal(before - sum * 0.05, p.BloodVolume, 15);
+ }
+
+ Assert.Equal(1e-3, p.Bleed(1), 15); // severity 1 x vascularity 1 x pumping 1
+ Assert.Equal(1e-3 * 0.5, p.Bleed(2), 15);
+ Assert.Equal(1e-3 * 0.25, p.Bleed(0), 15);
+ }
+
+ [Fact]
+ public void Bleeding_reads_the_pumping_so_a_stopped_non_vital_heart_bleeds_nothing()
+ {
+ var p = Make(heartVital: false);
+ Afflict(p, "Bleeder", 1, 0, 1);
+ p.Step(0.01);
+ Assert.Equal(1e-3, p.Bleed(1), 15);
+ Afflict(p, "Lesion", 0, Heart, 10);
+ p.Step(0.01);
+ Assert.False(p.Dead);
+ Assert.Equal(0.0, p.BloodPumping);
+ Assert.Equal(0.0, p.Bleed(1));
+ var v = p.BloodVolume;
+ p.Step(0.01);
+ Assert.Equal(v, p.BloodVolume);
+ }
+
+ [Fact]
+ public void An_age_factor_halves_a_bleed_at_its_age()
+ {
+ var p = Make(blood: new BloodDef(10.0, 0.5, 0.0));
+ Afflict(p, "Clot", 1, 0, 1);
+ for (var i = 0; i < 60; i++) p.Step(1.0);
+ Assert.Equal(0.5e-3, p.Bleed(1), 15);
+ for (var i = 0; i < 240; i++) p.Step(1.0);
+ Assert.Equal(0.1e-3, p.Bleed(1), 15);
+ }
+
+ // Death.
+
+ [Fact]
+ public void A_vital_tissue_at_zero_integrity_kills_on_that_step_and_one_short_is_alive()
+ {
+ var p = Make();
+ Afflict(p, "Lesion", 0, Heart, 9.5);
+ p.Step(0.01);
+ Assert.False(p.Dead);
+ Assert.Equal(DeathCause.None, p.Cause);
+ Assert.Equal(-1, p.DiedAtStep);
+ Afflict(p, "Lesion", 0, Heart, 0.5);
+ p.Step(0.01);
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.VitalTissue, p.Cause);
+ Assert.Equal(1, p.DiedAtStep);
+ }
+
+ [Fact]
+ public void Blood_loss_to_the_lethal_fraction_kills_with_that_cause()
+ {
+ var p = Make();
+ Afflict(p, "Bleeder", 1, 0, 1);
+ for (var i = 0; i < 100 && !p.Dead; i++)
+ {
+ Assert.True(p.BloodLoss < 1.0);
+ p.Step(0.1);
+ }
+
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.BloodLoss, p.Cause);
+ Assert.True(p.BloodLoss >= 1.0 && p.BloodLoss < 1.1);
+ }
+
+ [Fact]
+ public void A_non_vital_brain_at_zero_integrity_kills_by_consciousness_and_one_short_is_alive()
+ {
+ var p = Make();
+ Afflict(p, "Lesion", 0, BrainLayer, 9.5);
+ p.Step(0.01);
+ Assert.False(p.Dead);
+ Assert.Equal(0.05, p.Consciousness, 12);
+ Afflict(p, "Lesion", 0, BrainLayer, 0.5);
+ p.Step(0.01);
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.Consciousness, p.Cause);
+ }
+
+ [Fact]
+ public void Consciousness_driven_to_zero_by_effects_kills_too_and_the_first_rule_names_the_cause()
+ {
+ var p = Make(slots: 16);
+ for (var i = 0; i < 10; i++) Afflict(p, "Dim", 0, BrainLayer, 1);
+ p.Step(0.01);
+ Assert.False(p.Dead); // ten offsets of -0.1 leave a hair above zero in doubles
+ Afflict(p, "Dim", 0, BrainLayer, 1);
+ p.Step(0.01);
+ Assert.True(p.Dead);
+ Assert.Equal(DeathCause.Consciousness, p.Cause);
+
+ var both = Make();
+ Afflict(both, "Lesion", 0, BrainLayer, 10);
+ Afflict(both, "Lesion", 0, Heart, 10);
+ both.Step(0.01);
+ Assert.Equal(DeathCause.VitalTissue, both.Cause); // the vital rule comes first
+ }
+
+ [Fact]
+ public void Death_is_permanent_and_limp_and_nothing_changes_after_it_but_the_table_still_takes_wounds()
+ {
+ var p = Make();
+ Afflict(p, "Bleeder", 1, 0, 1);
+ Afflict(p, "Clot", 2, 0, 1);
+ Afflict(p, "Lesion", 0, Heart, 10);
+ p.Step(0.01);
+ Assert.True(p.Dead);
+ Assert.Equal(0, p.DiedAtStep);
+ Assert.Equal(0.0, p.Consciousness);
+ Assert.Equal(0.0, p.BloodPumping);
+ Assert.Equal(0.0, p.Bleed(1));
+ Assert.Equal(0.0, p.MotorCeiling(0));
+ Assert.Equal(0.0, p.MotorCeiling(1));
+
+ var volume = p.BloodVolume;
+ var severity = new double[p.SlotCount];
+ var age = new double[p.SlotCount];
+ for (var s = 0; s < p.SlotCount; s++) { severity[s] = p.SlotSeverity(s); age[s] = p.SlotAge(s); }
+ var integrity = p.Integrity(0, Heart);
+ for (var i = 0; i < 100; i++) p.Step(1.0);
+ Assert.Equal(volume, p.BloodVolume);
+ Assert.Equal(0, p.DiedAtStep);
+ Assert.Equal(DeathCause.VitalTissue, p.Cause);
+ for (var s = 0; s < p.SlotCount; s++) { Assert.Equal(severity[s], p.SlotSeverity(s)); Assert.Equal(age[s], p.SlotAge(s)); }
+ Assert.Equal(integrity, p.Integrity(0, Heart));
+
+ Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1)); // the wound is recorded, nothing steps
+ Assert.Equal(4, Live(p));
+ p.Step(1.0);
+ Assert.Equal(1.0, p.Integrity(1, 0));
+ }
+
+ // The table.
+
+ [Fact]
+ public void A_full_table_refuses_the_next_wound_and_overwrites_nothing()
+ {
+ var p = Make(slots: 4);
+ for (var i = 0; i < 4; i++) Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1 + i));
+ Assert.False(p.Afflict(Af("Lesion"), 1, 0, 50));
+ Assert.Equal(1, p.Refused);
+ for (var s = 0; s < 4; s++) Assert.Equal(1.0 + s, p.SlotSeverity(s));
+ Assert.False(p.Afflict(Af("Lesion"), 2, 0, 50));
+ Assert.Equal(2, p.Refused);
+ p.Step(0.01);
+ Assert.Equal(0.0, p.Integrity(1, 0)); // 1+2+3+4 = 10 of 10
+ Assert.Equal(1.0, p.Integrity(2, 0));
+ }
+
+ [Fact]
+ public void A_freed_slot_takes_the_next_wound()
+ {
+ var p = Make(slots: 1);
+ Assert.True(p.Afflict(Af("Heal"), 1, 0, 0.5));
+ Assert.False(p.Afflict(Af("Lesion"), 1, 0, 1));
+ p.Step(1.0);
+ Assert.Equal(0, Live(p));
+ Assert.True(p.Afflict(Af("Lesion"), 1, 0, 1));
+ }
+
+ // Determinism.
+
+ private static (long Volume, long Consciousness, long Motor) Bits(Physiology p) =>
+ (BitConverter.DoubleToInt64Bits(p.BloodVolume), BitConverter.DoubleToInt64Bits(p.Consciousness), BitConverter.DoubleToInt64Bits(p.MotorCeiling(0)));
+
+ [Fact]
+ public void Two_identical_runs_agree_bit_for_bit_every_step()
+ {
+ Physiology Run()
+ {
+ var p = Make(slowScale: 20, blood: new BloodDef(1.0, 0.5, 1e-4));
+ Afflict(p, "Bleeder", 1, 0, 0.7);
+ Afflict(p, "Clot", 2, 0, 1);
+ Afflict(p, "SlowHeal", 0, BrainLayer, 3);
+ Afflict(p, "Fading", 0, RootMuscle, 1);
+ return p;
+ }
+
+ var a = Run();
+ var b = Run();
+ for (var i = 0; i < 3000; i++)
+ {
+ a.Step(0.01);
+ b.Step(0.01);
+ Assert.Equal(Bits(a), Bits(b));
+ }
+
+ Assert.True(a.BloodVolume < 1.0 && !a.Dead);
+ Assert.True(a.Consciousness > 0.9);
+ }
+}