Physiology content: tissue stacks, afflictions with data effects, blood; validated at construction

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-25 20:43:15 +01:00
commit 3c1067da4b
2 changed files with 292 additions and 0 deletions

View file

@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
namespace Lodur
{
/// <summary>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).</summary>
public enum PhysiologyClock { Acute, Slow }
/// <summary>What an effect shapes. One mechanism reads each: capacities (Consciousness, BloodPumping), an affliction's bleed rate, a part's motor ceiling.</summary>
public enum EffectTarget { Consciousness, BloodPumping, Bleed, Motor }
/// <summary>How an effect's value joins its target: summed into the offsets, or multiplied into the factors.</summary>
public enum EffectOp { Offset, Factor }
/// <summary>What an effect's curve is read at: its affliction's severity or age (in its clock's seconds), or the organism's blood loss.</summary>
public enum EffectDriver { Severity, Age, BloodLoss }
/// <summary>
/// One tissue layer of a part. <paramref name="Consciousness"/>, <paramref name="BloodPumping"/> and <paramref name="Motor"/> are
/// function weights, a closed set with one reader each: a capacity is the weighted mean integrity of the tissues that carry its weight.
/// A Vital tissue at integrity 0 kills.
/// </summary>
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);
/// <summary>A part's tissue stack, outside-in, named by the body part's label and side.</summary>
public readonly record struct PartTissuesDef(string PartLabel, Side Side, IReadOnlyList<TissueDef> Tissues);
/// <summary>The blood: nominal volume in m^3, the lost fraction that kills, and the regrowth per slow second as a fraction of nominal.</summary>
public readonly record struct BloodDef(double NominalVolume, double LethalLossFraction, double RegenPerSecond);
/// <summary>
/// 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.
/// </summary>
public readonly record struct Effect(EffectTarget Target, EffectOp Op, EffectDriver Driver, IReadOnlyList<(double X, double Y)> Curve)
{
public double Eval(double x)
{
var c = Curve;
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;
}
}
/// <summary>
/// A kind of harm or condition. <paramref name="SeverityRate"/> 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.
/// </summary>
public readonly record struct AfflictionDef(string Label, PhysiologyClock Clock, double SeverityRate, bool Injures, IReadOnlyList<Effect> Effects);
/// <summary>
/// Physiology as content: tissue stacks per body part, the afflictions that can be bound, the organism-wide effects of blood
/// loss, the blood and the size of the affliction table. Validated at construction; resolved against a <see cref="BodyPlan"/> by <see cref="Physiology"/>.
/// </summary>
public sealed class PhysiologyPlan
{
private readonly Dictionary<string, int> _afflictionIndex = new Dictionary<string, int>();
public PhysiologyPlan(
IReadOnlyList<PartTissuesDef> parts, IReadOnlyList<AfflictionDef> afflictions, IReadOnlyList<Effect> organismEffects,
BloodDef blood, int afflictionSlots)
{
var ownedParts = new List<PartTissuesDef>(parts.Count);
foreach (var p in parts)
{
ownedParts.Add(p with { Tissues = new List<TissueDef>(p.Tissues).AsReadOnly() });
}
var ownedAfflictions = new List<AfflictionDef>(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;
AfflictionSlots = afflictionSlots;
Validate();
}
public IReadOnlyList<PartTissuesDef> Parts { get; }
public IReadOnlyList<AfflictionDef> Afflictions { get; }
public IReadOnlyList<Effect> OrganismEffects { get; }
public BloodDef Blood { get; }
public int AfflictionSlots { get; }
public int AfflictionIndex(string label) =>
_afflictionIndex.TryGetValue(label, out var i) ? i : throw new ArgumentException($"no affliction labelled '{label}'.");
private static IReadOnlyList<Effect> Own(IReadOnlyList<Effect> effects)
{
var list = new List<Effect>(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<string>();
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.Consciousness) && t.Consciousness >= 0.0 && IsFinite(t.BloodPumping) && t.BloodPumping >= 0.0 && IsFinite(t.Motor) && t.Motor >= 0.0))
{
throw new ArgumentException($"{where}: a function weight is not finite and at least 0.");
}
}
}
var labels = new HashSet<string>();
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)
{
throw new ArgumentException("an organism effect targets only Consciousness or BloodPumping.");
}
if (e.Driver != EffectDriver.BloodLoss)
{
throw new ArgumentException("an organism effect is driven only by BloodLoss.");
}
}
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.");
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.");
}
if (e.Curve.Count == 0) throw new ArgumentException($"{where}: an effect has an empty curve.");
for (var i = 0; i < e.Curve.Count; i++)
{
var (x, y) = e.Curve[i];
if (!IsFinite(x) || !IsFinite(y)) throw new ArgumentException($"{where}: an effect curve has a non-finite point.");
if (i > 0 && x < e.Curve[i - 1].X) throw new ArgumentException($"{where}: an effect curve's x decreases.");
}
}
}
}

View file

@ -0,0 +1,102 @@
using Lodur;
namespace Lodur.Core.Tests;
/// <summary>The physiology content is validated at construction, and resolved against a body plan by the Physiology: each rule refuses.</summary>
public sealed class PhysiologyPlanTests
{
private static readonly (double X, double Y)[] Ramp = { (0, 0), (1, 1) };
private static Effect Fx(EffectTarget t = EffectTarget.Consciousness, EffectDriver d = EffectDriver.BloodLoss, params (double X, double Y)[] curve) =>
new(t, EffectOp.Offset, d, curve.Length == 0 ? Ramp : curve);
private static BloodDef GoodBlood => new(0.005, 0.5, 0.001);
private static PhysiologyPlan Plan(
IReadOnlyList<TissueDef>? tissues = null, IReadOnlyList<AfflictionDef>? afflictions = null,
IReadOnlyList<Effect>? organism = null, BloodDef? blood = null, int slots = 4) =>
new(new[] { new PartTissuesDef("A", Side.Center, tissues ?? new[] { new TissueDef("brain", 10, 1, Consciousness: 1, Motor: 1) }) },
afflictions ?? new[] { new AfflictionDef("a", PhysiologyClock.Acute, 0, true, Array.Empty<Effect>()) },
organism ?? Array.Empty<Effect>(), blood ?? GoodBlood, slots);
private static void Refuses(Action build) => Assert.Throws<ArgumentException>(build);
[Fact]
public void A_well_formed_plan_constructs_and_finds_afflictions_by_label()
{
var plan = Plan(organism: new[] { Fx() });
Assert.Equal(0, plan.AfflictionIndex("a"));
Assert.Throws<ArgumentException>(() => plan.AfflictionIndex("b"));
}
[Fact]
public void A_curve_is_piecewise_linear_clamped_at_the_ends_and_an_equal_x_pair_is_a_step_that_holds_its_later_value_from_x()
{
var ramp = Fx(curve: new[] { (0.0, 0.0), (2.0, 1.0) });
Assert.Equal(0.0, ramp.Eval(-5));
Assert.Equal(0.25, ramp.Eval(0.5));
Assert.Equal(1.0, ramp.Eval(2));
Assert.Equal(1.0, ramp.Eval(9));
var step = Fx(curve: new[] { (0.0, 0.0), (0.15, 0.0), (0.15, -0.1), (0.30, -0.1) });
Assert.Equal(0.0, step.Eval(0.1499));
Assert.Equal(-0.1, step.Eval(0.15));
Assert.Equal(-0.1, step.Eval(1.0));
}
[Fact]
public void Each_validation_rule_refuses()
{
var t = new TissueDef("t", 10, 1, Consciousness: 1, Motor: 1);
Refuses(() => Plan(new[] { t, t })); // duplicate tissue label
Refuses(() => Plan(new[] { t with { Label = "" } })); // empty tissue label
Refuses(() => Plan(new[] { t with { Hp = 0 } }));
Refuses(() => Plan(new[] { t with { Hp = double.NaN } }));
Refuses(() => Plan(new[] { t with { Hp = double.PositiveInfinity } }));
Refuses(() => Plan(new[] { t with { Vascularity = -1 } }));
Refuses(() => Plan(new[] { t with { Vascularity = double.NaN } }));
Refuses(() => Plan(new[] { t with { Consciousness = -1 } }));
Refuses(() => Plan(new[] { t with { BloodPumping = double.NaN } }));
Refuses(() => Plan(new[] { t with { Motor = double.PositiveInfinity } }));
var a = new AfflictionDef("a", PhysiologyClock.Acute, 0, true, Array.Empty<Effect>());
Refuses(() => Plan(afflictions: new[] { a, a })); // duplicate affliction label
Refuses(() => Plan(afflictions: new[] { a with { Label = "" } }));
Refuses(() => Plan(afflictions: new[] { a with { SeverityRate = double.NaN } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.Severity, Array.Empty<(double X, double Y)>()) } } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (1.0, 0.0), (0.5, 0.0) }) } } })); // x decreases
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (0.0, double.NaN) }) } } }));
Refuses(() => Plan(afflictions: new[] { a with { Effects = new[] { Fx(curve: new[] { (double.PositiveInfinity, 0.0) }) } } }));
Refuses(() => Plan(organism: new[] { Fx(d: EffectDriver.Severity) })); // a driver only an affliction has
Refuses(() => Plan(organism: new[] { Fx(d: EffectDriver.Age) }));
Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Bleed) })); // a target only an affliction has
Refuses(() => Plan(organism: new[] { Fx(t: EffectTarget.Motor) }));
Refuses(() => Plan(blood: GoodBlood with { NominalVolume = 0 }));
Refuses(() => Plan(blood: GoodBlood with { NominalVolume = double.NaN }));
Refuses(() => Plan(blood: GoodBlood with { LethalLossFraction = 0 }));
Refuses(() => Plan(blood: GoodBlood with { LethalLossFraction = 1.5 }));
Refuses(() => Plan(blood: GoodBlood with { RegenPerSecond = -1 }));
Refuses(() => Plan(slots: 0));
}
[Fact]
public void An_affliction_may_use_every_driver_and_the_boundary_values_of_the_rules_are_accepted()
{
var effects = new[] { Fx(EffectTarget.Bleed, EffectDriver.Severity), Fx(EffectTarget.Motor, EffectDriver.Age), Fx(EffectTarget.Consciousness, EffectDriver.BloodLoss), Fx(curve: new[] { (1.0, 0.0), (1.0, 1.0) }) };
Plan(afflictions: new[] { new AfflictionDef("a", PhysiologyClock.Slow, -1, false, effects) }, blood: GoodBlood with { LethalLossFraction = 1, RegenPerSecond = 0 }, slots: 1);
}
[Fact]
public void The_plan_owns_a_copy_of_what_it_was_given()
{
var curve = new List<(double X, double Y)> { (0, 0), (1, 1) };
var tissues = new List<TissueDef> { new("t", 10, 1, Consciousness: 1, Motor: 1) };
var plan = Plan(tissues, organism: new[] { new Effect(EffectTarget.Consciousness, EffectOp.Offset, EffectDriver.BloodLoss, curve) });
curve[1] = (1, double.NaN);
tissues.Clear();
Assert.Equal(1.0, plan.OrganismEffects[0].Eval(1));
Assert.Single(plan.Parts[0].Tissues);
}
}