Airway physiology and air hunger: CO2 and a ventilation deficit drive the urge, the urge drives arousal and a struggle goal; a will-held breath ends in a gasp; cough and drainage
Physiology gains the airway (liquid, occlusion), carbon dioxide and BreathUrge; DriveState.AirHunger (written only by the Actor) raises arousal under max(load, AirHunger) and DriveQuantity.AirHunger lets a goal read it. The Actor holds the breath on will while liquid is at the airway, in contest with the urge through WithdrawalReflex, and reports TickEvents.Gasp. The struggle is content, a goal under When AirHunger, so a broken will cannot stop it. Oxygen constants are unchanged; new constants are marked placeholders. Pins the fading-effort window on the real Actor at slow scale 1 and 20: out 81.6 s, dead 154.3 s, mean awake effort 0.72. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a02ab2d424
commit
bd5ba7fecd
12 changed files with 628 additions and 28 deletions
|
|
@ -15,6 +15,8 @@ namespace Lodur
|
|||
GoalChanged = 4,
|
||||
/// <summary>The physiology died this tick (reported once, on the tick it died).</summary>
|
||||
Died = 8,
|
||||
/// <summary>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.</summary>
|
||||
Gasp = 16,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -35,6 +37,11 @@ namespace Lodur
|
|||
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;
|
||||
|
|
@ -54,7 +61,8 @@ namespace Lodur
|
|||
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)
|
||||
NerveParameters? senses = null, int senseRegion = 0, PerceptParameters? percepts = null, Physiology? physiology = null,
|
||||
WithdrawalParameters? breath = null)
|
||||
{
|
||||
brain.Validate();
|
||||
drive.Validate();
|
||||
|
|
@ -95,6 +103,13 @@ namespace Lodur
|
|||
_entryTicks[g] = entryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(entryTicks);
|
||||
}
|
||||
|
||||
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);
|
||||
_reflexes = new WithdrawalReflex[regionCount];
|
||||
for (var r = 0; r < regionCount; r++)
|
||||
|
|
@ -171,12 +186,12 @@ namespace Lodur
|
|||
/// <summary>
|
||||
/// 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.
|
||||
/// sources, sensed at the sense region's point. The airway is what the caller finds at the body's airway openings; nothing by default.
|
||||
/// </summary>
|
||||
public TickEvents Tick(
|
||||
ReadOnlySpan<float> regionX, ReadOnlySpan<float> regionY, ReadOnlySpan<float> regionZ,
|
||||
ReadOnlySpan<BoxStimulus> sources, Span<float> strengths, Span<Quat> targets,
|
||||
ReadOnlySpan<Emitter> emitters = default)
|
||||
ReadOnlySpan<Emitter> emitters = default, in AirwaySample airway = default)
|
||||
{
|
||||
var events = TickEvents.None;
|
||||
if (_physiology != null)
|
||||
|
|
@ -189,8 +204,9 @@ namespace Lodur
|
|||
// The physiology steps first, on the drive as the last tick left it, and its consciousness is the slot's only writer.
|
||||
if (!_physiology.Dead)
|
||||
{
|
||||
_physiology.Step(_dt, new PhysiologyInput(_drive.Arousal, _effort));
|
||||
_physiology.Step(_dt, new PhysiologyInput(_drive.Arousal, _effort, _held, airway));
|
||||
_drive.Consciousness = _physiology.Consciousness;
|
||||
_drive.AirHunger = _physiology.BreathUrge;
|
||||
}
|
||||
|
||||
if (_physiology.Dead)
|
||||
|
|
@ -223,6 +239,31 @@ namespace Lodur
|
|||
}
|
||||
}
|
||||
|
||||
// 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;
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ namespace Lodur
|
|||
WillBroken,
|
||||
/// <summary>How many times the will has broken: the one-way latch, for a goal that must hold after a mend.</summary>
|
||||
Breaks,
|
||||
/// <summary>Air hunger, 0..1: the physiology's urge to breathe, carried by the Actor.</summary>
|
||||
AirHunger,
|
||||
}
|
||||
|
||||
public enum ConditionOp
|
||||
|
|
@ -31,6 +33,7 @@ namespace Lodur
|
|||
DriveQuantity.Arousal => drive.Arousal,
|
||||
DriveQuantity.Resolve => drive.Resolve,
|
||||
DriveQuantity.Breaks => (double)drive.Breaks,
|
||||
DriveQuantity.AirHunger => drive.AirHunger,
|
||||
_ => drive.WillBroken ? 1.0 : 0.0,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,6 +102,9 @@ namespace Lodur
|
|||
/// <summary>The gain on the sense channels in force, 0..1: the goal in force's <see cref="GoalSpec.SensoryGain"/> as the Actor has reached it. Written only by the Actor.</summary>
|
||||
public double SensoryGain { get; internal set; }
|
||||
|
||||
/// <summary>Air hunger, 0..1: written each tick by the Actor from its <see cref="Physiology"/> (the only writer), 0 for an Actor with no physiology. It raises arousal like sensory load does.</summary>
|
||||
public double AirHunger { get; internal set; }
|
||||
|
||||
internal static DriveState Fresh => new DriveState { Resolve = 1.0, Attention = 1.0, Consciousness = 1.0, SensoryGain = 1.0 };
|
||||
|
||||
/// <summary>A goal's entry effect: sets resolve, then the mend check runs (a break the entry lifts past <see cref="DriveParameters.WillMendsAt"/> is mended). It is not a break and counts none.</summary>
|
||||
|
|
@ -117,7 +120,7 @@ namespace Lodur
|
|||
/// <summary>Steps one tick; returns true on the tick the will breaks (each break, not only the first). <paramref name="pull"/> is the active goal's: it scales resolve drain by (1 - pull). <paramref name="effort"/> 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.</summary>
|
||||
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 * load * (1.0 - Arousal) - p.ArousalDecay * Arousal), 0.0), 1.0);
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -6,8 +6,30 @@ namespace Lodur
|
|||
/// <summary>Why a body died; the first rule that held at the end of the step that killed it (ruling bds-death).</summary>
|
||||
public enum DeathCause { None, VitalTissue, BloodLoss, Consciousness }
|
||||
|
||||
/// <summary>What the stepping Actor reports each step, each in [0, 1]: Arousal is the sensory load carried over time, 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). The default is rest.</summary>
|
||||
public readonly record struct PhysiologyInput(double Arousal, double Effort);
|
||||
/// <summary>
|
||||
/// 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 Facing, the greatest cosine between an opening's outward direction and down, in [-1, 1] (1: an opening faces straight down).
|
||||
/// The default is nothing at the airway.
|
||||
/// </summary>
|
||||
public readonly record struct AirwaySample(double Live, double Pooled, double Facing)
|
||||
{
|
||||
/// <summary>One entry per opening: Live and Pooled summed, Facing the largest (-1 with no opening).</summary>
|
||||
public static AirwaySample Of(ReadOnlySpan<float> live, ReadOnlySpan<float> pooled, ReadOnlySpan<float> facing)
|
||||
{
|
||||
double l = 0.0, p = 0.0, f = -1.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 < facing.Length; i++) f = Math.Max(f, facing[i]);
|
||||
return new AirwaySample(l, p, f);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public readonly record struct PhysiologyInput(double Arousal, double Effort, bool BreathHeld = false, AirwaySample Airway = default);
|
||||
|
||||
/// <summary>
|
||||
/// The body's physiology: tissue integrity, bound afflictions, blood and its oxygen, the capacities they fold into, the motor ceiling and death.
|
||||
|
|
@ -30,6 +52,7 @@ namespace Lodur
|
|||
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
|
||||
|
|
@ -45,6 +68,13 @@ namespace Lodur
|
|||
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 bool _atAirway;
|
||||
private long _steps;
|
||||
private bool _bound;
|
||||
|
||||
|
|
@ -57,6 +87,7 @@ namespace Lodur
|
|||
_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];
|
||||
|
|
@ -152,6 +183,27 @@ namespace Lodur
|
|||
/// <summary>The brain's oxygen, 0..1, starting full: it relaxes toward what the pumping delivers from the blood store. Content turns it into consciousness.</summary>
|
||||
public double BrainOxygen => _brainOxygen;
|
||||
|
||||
/// <summary>The liquid in the airway in m^3, 0 to the airway's capacity; integrated by <see cref="Step"/>.</summary>
|
||||
public double AirwayLiquid => _airwayLiquid;
|
||||
|
||||
/// <summary>The fraction of the airway the liquid fills, 0..1; it takes that share of the ventilation. Derived from the liquid each step.</summary>
|
||||
public double Occlusion => _occlusion;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public double CarbonDioxide => _carbonDioxide;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public double BreathUrge => Dead ? 0.0 : _urge;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public bool LiquidAtAirway => _atAirway;
|
||||
|
||||
/// <summary>The liquid in m^3 the last step coughed out of the airway.</summary>
|
||||
public double Coughed => _coughed;
|
||||
|
||||
/// <summary>The liquid in m^3 the last step drained out of the airway (facing down).</summary>
|
||||
public double Drained => _drained;
|
||||
|
||||
/// <summary>The tissue's remaining fraction, 0..1, as of the last step.</summary>
|
||||
public double Integrity(int part, int layer) => _integrity[Flat(part, layer)];
|
||||
|
||||
|
|
@ -229,6 +281,12 @@ namespace Lodur
|
|||
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.Facing >= -1.0 && air.Facing <= 1.0))
|
||||
{
|
||||
throw new ArgumentException("the airway sample's liquid must be finite and not negative and its facing in [-1, 1].");
|
||||
}
|
||||
|
||||
if (Dead) return;
|
||||
var slowDt = dt * _slowScale;
|
||||
|
||||
|
|
@ -259,6 +317,24 @@ namespace Lodur
|
|||
_pumping = Capacity(EffectTarget.BloodPumping);
|
||||
_breathing = Capacity(EffectTarget.Breathing);
|
||||
|
||||
// 3b. The airway, a quantity (not particles): liquid at the openings is drawn in by a free breath, never by a held one; a cough clears it by this step's
|
||||
// consciousness, and it drains by facing. What a step removes is reported as Coughed and Drained; 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.Facing - aw.DrainFacingStart) / (1.0 - aw.DrainFacingStart));
|
||||
var total = cough + drain;
|
||||
var avail = _airwayLiquid + dt * inflow;
|
||||
var want = dt * total * _airwayLiquid;
|
||||
var removed = want < avail ? want : avail;
|
||||
_coughed = total > 0.0 ? removed * cough / total : 0.0;
|
||||
_drained = removed - _coughed;
|
||||
_airwayLiquid = Math.Min(aw.Capacity, avail - removed);
|
||||
_occlusion = Clamp01(_airwayLiquid / aw.Capacity);
|
||||
|
||||
// 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;
|
||||
|
|
@ -283,8 +359,14 @@ namespace Lodur
|
|||
// 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 use = r.BasalUsePerSecond * (1.0 + r.ArousalUse * input.Arousal + r.EffortUse * input.Effort);
|
||||
_bloodOxygen = Clamp01(_bloodOxygen + dt * (r.UptakePerSecond * _breathing * (1.0 - _bloodOxygen) - use));
|
||||
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.
|
||||
|
|
|
|||
|
|
@ -52,9 +52,27 @@ namespace Lodur
|
|||
/// The gases, all on the Acute clock (ruling bds-asphyxia-real-time): the blood oxygen store S refills at
|
||||
/// <paramref name="UptakePerSecond"/> x ventilation x (1 - S) per second and is used at <paramref name="BasalUsePerSecond"/> x
|
||||
/// (1 + <paramref name="ArousalUse"/> x arousal + <paramref name="EffortUse"/> x effort); the brain oxygen relaxes toward BloodPumping x S
|
||||
/// with time constant <paramref name="BrainSeconds"/>. Both stores run 0..1.
|
||||
/// with time constant <paramref name="BrainSeconds"/>. Both stores run 0..1. Carbon dioxide C (0 at rest, about 1 at the break point) rises at
|
||||
/// <paramref name="CarbonDioxideRise"/> x (1 + ArousalUse x arousal + EffortUse x effort) per second, the load that uses oxygen, and is blown off at
|
||||
/// <paramref name="CarbonDioxideClear"/> x ventilation x C. Air hunger is the larger of two curves: <paramref name="UrgeByCarbonDioxide"/> read at C and
|
||||
/// <paramref name="UrgeByVentilationDeficit"/> read at the deficit, 1 - Breathing x (1 - occlusion), a breath tried and not got (zero while the breath is held).
|
||||
/// </summary>
|
||||
public readonly record struct RespirationDef(double UptakePerSecond, double BasalUsePerSecond, double ArousalUse, double EffortUse, double BrainSeconds);
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// The airway as a quantity, not as particles: it holds <paramref name="Capacity"/> m^3 of liquid at most. Liquid at the airway is
|
||||
/// <paramref name="LiveWeight"/> x the live liquid plus <paramref name="PooledWeight"/> x the pooled; at <paramref name="HoldAt"/> or more it is "at the airway"
|
||||
/// and the Actor holds the breath. A free breath draws <paramref name="DrawPerSecond"/> x Breathing x (liquid at the airway) per second into it; a cough
|
||||
/// removes <paramref name="CoughPerSecond"/> x <paramref name="CoughByConsciousness"/>(consciousness) x contents per second; and it drains at
|
||||
/// <paramref name="DrainPerSecond"/> x clamp01((facing - <paramref name="DrainFacingStart"/>) / (1 - DrainFacingStart)) x contents, facing being the cosine of an
|
||||
/// opening's outward direction with down, -1..1.
|
||||
/// </summary>
|
||||
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 DrainFacingStart);
|
||||
|
||||
/// <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
|
||||
|
|
@ -62,9 +80,11 @@ namespace Lodur
|
|||
/// </summary>
|
||||
public readonly record struct Effect(EffectTarget Target, EffectOp Op, EffectDriver Driver, IReadOnlyList<(double X, double Y)> Curve)
|
||||
{
|
||||
public double Eval(double x)
|
||||
public double Eval(double x) => EvalCurve(Curve, x);
|
||||
|
||||
/// <summary>The evaluation every curve of the plan shares: clamped at the ends, an equal-x pair a step.</summary>
|
||||
internal static double EvalCurve(IReadOnlyList<(double X, double Y)> c, double x)
|
||||
{
|
||||
var c = Curve;
|
||||
if (x < c[0].X)
|
||||
{
|
||||
return c[0].Y;
|
||||
|
|
@ -100,7 +120,7 @@ namespace Lodur
|
|||
|
||||
public PhysiologyPlan(
|
||||
IReadOnlyList<PartTissuesDef> parts, IReadOnlyList<AfflictionDef> afflictions, IReadOnlyList<Effect> organismEffects,
|
||||
BloodDef blood, RespirationDef respiration, int afflictionSlots)
|
||||
BloodDef blood, RespirationDef respiration, AirwayDef airway, int afflictionSlots)
|
||||
{
|
||||
var ownedParts = new List<PartTissuesDef>(parts.Count);
|
||||
foreach (var p in parts)
|
||||
|
|
@ -118,7 +138,8 @@ namespace Lodur
|
|||
Afflictions = ownedAfflictions.AsReadOnly();
|
||||
OrganismEffects = Own(organismEffects);
|
||||
Blood = blood;
|
||||
Respiration = respiration;
|
||||
Respiration = respiration with { UrgeByCarbonDioxide = OwnCurve(respiration.UrgeByCarbonDioxide), UrgeByVentilationDeficit = OwnCurve(respiration.UrgeByVentilationDeficit) };
|
||||
Airway = airway with { CoughByConsciousness = OwnCurve(airway.CoughByConsciousness) };
|
||||
AfflictionSlots = afflictionSlots;
|
||||
Validate();
|
||||
}
|
||||
|
|
@ -128,6 +149,7 @@ namespace Lodur
|
|||
public IReadOnlyList<Effect> OrganismEffects { get; }
|
||||
public BloodDef Blood { get; }
|
||||
public RespirationDef Respiration { get; }
|
||||
public AirwayDef Airway { get; }
|
||||
public int AfflictionSlots { get; }
|
||||
|
||||
public int AfflictionIndex(string label) =>
|
||||
|
|
@ -170,6 +192,9 @@ namespace Lodur
|
|||
return stackOf;
|
||||
}
|
||||
|
||||
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<Effect> Own(IReadOnlyList<Effect> effects)
|
||||
{
|
||||
var list = new List<Effect>(effects.Count);
|
||||
|
|
@ -258,6 +283,23 @@ namespace Lodur
|
|||
}
|
||||
|
||||
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.DrainFacingStart >= -1.0 && w.DrainFacingStart < 1.0)) throw new ArgumentException("airway: DrainFacingStart is not in [-1, 1).");
|
||||
ValidateCurve(w.CoughByConsciousness, "airway: the cough curve");
|
||||
if (AfflictionSlots < 1) throw new ArgumentException("the affliction table needs at least one slot.");
|
||||
}
|
||||
|
||||
|
|
@ -268,12 +310,17 @@ namespace Lodur
|
|||
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++)
|
||||
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) = 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.");
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -82,7 +82,19 @@ namespace Lodur
|
|||
|
||||
// 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), 64);
|
||||
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 2 per second of what is there and fails below 0.3
|
||||
// consciousness, and the airway drains at 0.1 per second once the face points down (facing from 0: on his side halves it). Liquid and pooled liquid count alike.
|
||||
new AirwayDef(150e-6, 1.0, 1.0, 1.0, 15.6e-6, 2.0, new[] { (0.3, 0.0), (0.6, 1.0) }, 0.1, 0.0), 64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
364
tests/Lodur.Core.Tests/AirwayPhysiologyTests.cs
Normal file
364
tests/Lodur.Core.Tests/AirwayPhysiologyTests.cs
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
using Lodur;
|
||||
using static Lodur.Core.Tests.PhysioFixtures;
|
||||
|
||||
namespace Lodur.Core.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public sealed class AirwayPhysiologyTests
|
||||
{
|
||||
private const double Dt = 1.0 / 120.0;
|
||||
private static readonly float[] NoPoint = { 0f };
|
||||
|
||||
/// <summary>The humanoid's HoldAt: the liquid at the openings at which the breath is held.</summary>
|
||||
private static readonly double HoldAt = PhysiologyPlans.Humanoid().Airway.HoldAt;
|
||||
|
||||
private static readonly double Capacity = PhysiologyPlans.Humanoid().Airway.Capacity;
|
||||
|
||||
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);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>A real Actor, calm and awake, with liquid at the airway openings from the first tick on, facing down.</summary>
|
||||
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, -1.0);
|
||||
double first = -1, max = 0, gasp = -1, will = -1, after = -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 (t >= gasp + 1.0)
|
||||
{
|
||||
after = p.AirwayLiquid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new Hold(first, max, gasp, will, after);
|
||||
}
|
||||
|
||||
[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);
|
||||
Assert.Equal(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);
|
||||
// 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 midpoint, 6.4e-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, -1.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 > 6.4e-6, $"airway liquid {p.AirwayLiquid}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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, -1.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;
|
||||
}
|
||||
|
||||
/// <summary>The unconscious Fella, liquid no longer at the airway, with his face this way; steps for the given seconds.</summary>
|
||||
private static Physiology Rolled(double facing, double seconds)
|
||||
{
|
||||
var p = Drowned();
|
||||
var rolled = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(0.0, 0.0, facing));
|
||||
for (long i = 0; i < (long)(seconds / Dt) && !p.Dead; i++) p.Step(Dt, rolled);
|
||||
return p;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(1.0)]
|
||||
[InlineData(0.5)]
|
||||
public void Face_down_or_on_his_side_the_airway_drains_and_he_lives(double facing)
|
||||
{
|
||||
// Out at 0.1 with the airway full, then drained at 0.1 (facing 1) or 0.05 (facing 0.5) 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(facing, 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}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Face_up_the_airway_stays_full_and_he_dies_through_consciousness()
|
||||
{
|
||||
var p = Rolled(-1.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, -1.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()
|
||||
{
|
||||
// Half the airway, awake, face up, nothing at the openings: gone (below 1e-6, a 75-fold fall) in 10 s; shipped it takes 2.2 s. Without the cough (or with one gated by something else) it never falls.
|
||||
var p = Breather(20.0);
|
||||
var flood = new PhysiologyInput(0.0, 0.0, false, new AirwaySample(100.0 * HoldAt, 0.0, -1.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, -1.0));
|
||||
double coughed = 0.0;
|
||||
for (long i = 0; i < (long)(10.0 / Dt); i++)
|
||||
{
|
||||
p.Step(Dt, clear);
|
||||
coughed += p.Coughed;
|
||||
}
|
||||
|
||||
Assert.True(p.AirwayLiquid < 1e-6, $"airway liquid {p.AirwayLiquid}");
|
||||
Assert.True(coughed > 0.4 * 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.
|
||||
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, -1.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 An_airway_sample_is_the_sum_of_what_is_live_and_pooled_and_the_greatest_facing()
|
||||
{
|
||||
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(0.0, 0.0, -1.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, 1.01), new AirwaySample(0, 0, -1.01), new AirwaySample(0, 0, double.NaN) })
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => 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, 1.0)));
|
||||
}
|
||||
|
||||
[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 { DrainFacingStart = 1.0 }, ok with { DrainFacingStart = -1.5 },
|
||||
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<ArgumentException>(() => 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<ArgumentException>(() => 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);
|
||||
}
|
||||
}
|
||||
|
|
@ -297,6 +297,7 @@ public sealed class BrainTests
|
|||
DriveQuantity.Arousal => d.Arousal,
|
||||
DriveQuantity.Resolve => d.Resolve,
|
||||
DriveQuantity.Breaks => d.Breaks,
|
||||
DriveQuantity.AirHunger => d.AirHunger,
|
||||
_ => d.WillBroken ? 1.0 : 0.0,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ public sealed class OxygenTests
|
|||
var choke = new AfflictionDef("Choke", PhysiologyClock.Acute, -1.0 / 40.0, false,
|
||||
new[] { new Effect(EffectTarget.Breathing, EffectOp.Factor, EffectDriver.Severity, new[] { (0.0, 0.0), (1.0, 0.0) }) });
|
||||
var defs = new List<AfflictionDef>(h.Afflictions) { choke };
|
||||
var plan = new PhysiologyPlan(h.Parts, defs, h.OrganismEffects, h.Blood, h.Respiration, h.AfflictionSlots);
|
||||
var plan = new PhysiologyPlan(h.Parts, defs, h.OrganismEffects, h.Blood, h.Respiration, h.Airway, h.AfflictionSlots);
|
||||
var p = new Physiology(Body, plan, 20);
|
||||
Assert.True(p.Afflict(plan.AfflictionIndex("Choke"), Body.PartIndex("Torso"), 0, 1e9));
|
||||
return p;
|
||||
|
|
|
|||
|
|
@ -48,13 +48,16 @@ internal static class PhysioFixtures
|
|||
public static BloodDef DefaultBlood => new(0.005, 0.5, 0.0);
|
||||
|
||||
/// <summary>The same literature-shaped placeholders as the humanoid's content.</summary>
|
||||
public static RespirationDef DefaultRespiration => new(1.0, 0.002, 0.5, 4.0, 9.5);
|
||||
public static RespirationDef DefaultRespiration => PhysiologyPlans.Humanoid().Respiration;
|
||||
|
||||
/// <summary>No liquid ever counts as at the airway: the airway stays empty and the hold is never wanted.</summary>
|
||||
public static AirwayDef InertAirway => new(150e-6, 1.0, 1.0, 1.0, 1e9, 2.0, new[] { (0.3, 0.0), (0.6, 1.0) }, 0.1, 0.0);
|
||||
|
||||
/// <summary>The humanoid's hypoxia curve: brain oxygen to consciousness, flat 1 above 0.70.</summary>
|
||||
public static Effect Hypoxia => new(EffectTarget.Consciousness, EffectOp.Factor, EffectDriver.BrainOxygen, new[] { (0.10, 0.0), (0.35, 0.1), (0.70, 1.0) });
|
||||
|
||||
/// <summary>Root: brain (weight 1), heart (pumping 1, vital unless asked otherwise), a muscle; A and B: a muscle each. Every tissue has Hp 10.</summary>
|
||||
public static PhysiologyPlan Plan3(bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList<Effect>? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null)
|
||||
public static PhysiologyPlan Plan3(bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList<Effect>? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null, AirwayDef? airway = null)
|
||||
{
|
||||
var stack = root ?? new[]
|
||||
{
|
||||
|
|
@ -65,12 +68,56 @@ internal static class PhysioFixtures
|
|||
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, limbA ?? limb), new PartTissuesDef("B", Side.Center, limb) },
|
||||
Defs, organism ?? Array.Empty<Effect>(), blood ?? DefaultBlood, DefaultRespiration, slots);
|
||||
Defs, organism ?? Array.Empty<Effect>(), blood ?? DefaultBlood, DefaultRespiration, airway ?? InertAirway, slots);
|
||||
}
|
||||
|
||||
public static Physiology Make(double slowScale = 20.0, bool heartVital = true, BloodDef? blood = null, int slots = 8, IReadOnlyList<Effect>? organism = null, TissueDef[]? root = null, TissueDef[]? limbA = null) =>
|
||||
new(Body3(), Plan3(heartVital, blood, slots, organism, root, limbA), slowScale);
|
||||
|
||||
/// <summary>
|
||||
/// Body3 with a lung on the root (Breathing 1), the hypoxia curve, the humanoid's respiration and airway, and the test afflictions (Choke lifts at 40 s at severity 1;
|
||||
/// the airway tests bind it at 1e9 to keep it). A real Actor over it needs a brain with a goal that reads air hunger: <see cref="StruggleBrain"/>.
|
||||
/// </summary>
|
||||
public static Physiology Breather(double slowScale = 20.0)
|
||||
{
|
||||
var h = PhysiologyPlans.Humanoid();
|
||||
var root = new[]
|
||||
{
|
||||
new TissueDef("brain", 10, 1, Consciousness: 1),
|
||||
new TissueDef("heart", 10, 4, true, BloodPumping: 1),
|
||||
new TissueDef("lung", 10, 2, Breathing: 1),
|
||||
new TissueDef("muscle", 10, 1, Motor: 1),
|
||||
};
|
||||
var limb = new[] { new TissueDef("muscle", 10, 1, Motor: 1) };
|
||||
var plan = new PhysiologyPlan(
|
||||
new[] { new PartTissuesDef("Root", Side.Center, root), new PartTissuesDef("A", Side.Center, limb), new PartTissuesDef("B", Side.Center, limb) },
|
||||
Defs, new[] { Hypoxia }, DefaultBlood, h.Respiration, h.Airway, 8);
|
||||
return new Physiology(Body3(), plan, slowScale);
|
||||
}
|
||||
|
||||
/// <summary>The goal that hunger drives: rest holds the pose at 0.7; the struggle, eligible at air hunger 0.3 and above, outranks it, runs involuntary throughout (nothing to break) and loops the two poses at full strength.</summary>
|
||||
public static Brain StruggleBrain() => 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 } },
|
||||
},
|
||||
new GoalSpec
|
||||
{
|
||||
Id = "struggle", Priority = 1.0, InvoluntarySeconds = double.PositiveInfinity,
|
||||
When = new[] { new Condition(DriveQuantity.AirHunger, ConditionOp.AtLeast, 0.3) },
|
||||
Behaviour = new PoseBehaviour
|
||||
{
|
||||
Keys = new[] { PainBoxBrain.Hold, PainBoxBrain.Withdraw }, FlinchPose = PainBoxBrain.Withdraw, SecondsPerKey = 0.5,
|
||||
Hold = new HoldParameters { HoldStrength = 1f, FlinchGain = 0.0, StrainShake = 0.0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
public static int Live(Physiology p)
|
||||
{
|
||||
var n = 0;
|
||||
|
|
|
|||
|
|
@ -12,14 +12,14 @@ public sealed class PhysiologyPlanTests
|
|||
|
||||
private static BloodDef GoodBlood => new(0.005, 0.5, 0.001);
|
||||
|
||||
private static RespirationDef GoodRespiration => new(1.0, 0.002, 0.5, 4.0, 9.5);
|
||||
private static RespirationDef GoodRespiration => PhysioFixtures.DefaultRespiration;
|
||||
|
||||
private static PhysiologyPlan Plan(
|
||||
IReadOnlyList<TissueDef>? tissues = null, IReadOnlyList<AfflictionDef>? afflictions = null,
|
||||
IReadOnlyList<Effect>? organism = null, BloodDef? blood = null, int slots = 4, RespirationDef? respiration = null) =>
|
||||
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, respiration ?? GoodRespiration, slots);
|
||||
organism ?? Array.Empty<Effect>(), blood ?? GoodBlood, respiration ?? GoodRespiration, PhysioFixtures.InertAirway, slots);
|
||||
|
||||
private static void Refuses(Action build) => Assert.Throws<ArgumentException>(build);
|
||||
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ public sealed class PhysiologyTests
|
|||
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<AfflictionDef>(), Array.Empty<Effect>(), DefaultBlood, DefaultRespiration, 4);
|
||||
new(parts, Array.Empty<AfflictionDef>(), Array.Empty<Effect>(), DefaultBlood, DefaultRespiration, InertAirway, 4);
|
||||
|
||||
private static readonly TissueDef BrainT = new("brain", 10, 1, Consciousness: 1);
|
||||
private static readonly TissueDef MuscleT = new("muscle", 10, 1, Motor: 1);
|
||||
|
|
|
|||
Loading…
Reference in a new issue