Lodur.Core: perception, withdrawal reflex, drive and a hold-against-reflex stand-in, run by Actor
Layers 1-3 and a layer-4 stand-in move in from the pain box (BadDaySimulator PainBoxSimulation.cs at 9f59764), keeping its double arithmetic and in-tick order. Actor owns one character's nervous state and runs perception, reflex, drive, behaviour once per tick from caller-owned spans into caller-owned spans; it allocates only in its constructor and never touches physics. Quat gains Nlerp. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
18c4ffd0d5
commit
fd7afc1174
7 changed files with 445 additions and 0 deletions
114
src/Lodur.Core/Actor.cs
Normal file
114
src/Lodur.Core/Actor.cs
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
using System;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
/// <summary>What happened on one tick.</summary>
|
||||
[Flags]
|
||||
public enum TickEvents
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>A reflex flinched while the will still held.</summary>
|
||||
Flinch = 1,
|
||||
/// <summary>Resolve reached zero this tick.</summary>
|
||||
WillBroke = 2,
|
||||
/// <summary>Deliberate behaviour took over, the withdrawal latency after the will broke.</summary>
|
||||
Withdrew = 4,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One character's nervous state and the per-tick order: perception, reflex, drive, behaviour. The caller
|
||||
/// supplies one point per body region, the game's stimulus sources, and the spans the behaviour writes its
|
||||
/// strengths and targets into; the Actor writes nothing else of the caller's and never touches physics.
|
||||
/// Everything is allocated in the constructor, and the same inputs give the same outputs.
|
||||
/// </summary>
|
||||
public sealed class Actor
|
||||
{
|
||||
private readonly double _dt;
|
||||
private readonly DriveParameters _driveP;
|
||||
private readonly long _withdrawLatency;
|
||||
private readonly Perception _perception;
|
||||
private readonly WithdrawalReflex[] _reflexes;
|
||||
private readonly HoldAgainstReflex _behaviour;
|
||||
private DriveState _drive = DriveState.Fresh;
|
||||
private long _tick;
|
||||
private long _withdrawTick = -1;
|
||||
private bool _withdrew;
|
||||
|
||||
public Actor(
|
||||
double tickSeconds, int regionCount,
|
||||
NerveParameters nerve, WithdrawalParameters withdrawal, DriveParameters drive, HoldParameters hold,
|
||||
ReadOnlySpan<Quat> holdPose, ReadOnlySpan<Quat> withdrawPose)
|
||||
{
|
||||
_dt = tickSeconds;
|
||||
_driveP = drive;
|
||||
_withdrawLatency = Math.Max(1, (long)Math.Round(withdrawal.LatencySeconds / tickSeconds));
|
||||
_perception = new Perception(nerve, tickSeconds, regionCount);
|
||||
_reflexes = new WithdrawalReflex[regionCount];
|
||||
for (var r = 0; r < regionCount; r++)
|
||||
{
|
||||
_reflexes[r] = new WithdrawalReflex(withdrawal, tickSeconds);
|
||||
}
|
||||
|
||||
_behaviour = new HoldAgainstReflex(hold, holdPose, withdrawPose);
|
||||
}
|
||||
|
||||
public int RegionCount => _reflexes.Length;
|
||||
|
||||
/// <summary>Ticks run so far.</summary>
|
||||
public long TickCount => _tick;
|
||||
|
||||
/// <summary>A snapshot of the drive; nothing but <see cref="Tick"/> writes it.</summary>
|
||||
public DriveState Drive => _drive;
|
||||
|
||||
/// <summary>Hold until the will breaks, Withdraw from then on.</summary>
|
||||
public Goal Goal => _drive.WillBroken ? Goal.Withdraw : Goal.Hold;
|
||||
|
||||
public double Stimulus(int region) => _perception.Stimulus(region);
|
||||
|
||||
public double Afferent(int region) => _perception.Afferent(region);
|
||||
|
||||
/// <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.
|
||||
/// </summary>
|
||||
public TickEvents Tick(
|
||||
ReadOnlySpan<float> regionX, ReadOnlySpan<float> regionY, ReadOnlySpan<float> regionZ,
|
||||
ReadOnlySpan<BoxStimulus> sources, Span<float> strengths, Span<Quat> targets)
|
||||
{
|
||||
var events = TickEvents.None;
|
||||
var holding = !_drive.WillBroken;
|
||||
|
||||
_perception.Sense(regionX, regionY, regionZ, sources);
|
||||
|
||||
double afferent = 0.0, strainLoad = 0.0, leak = 0.0;
|
||||
for (var r = 0; r < _reflexes.Length; r++)
|
||||
{
|
||||
var a = _perception.Afferent(r);
|
||||
var flinch = _reflexes[r].Step(a, _drive);
|
||||
afferent += a;
|
||||
strainLoad += _reflexes[r].StrainLoad;
|
||||
leak += _reflexes[r].Leak;
|
||||
if (flinch && holding)
|
||||
{
|
||||
events |= TickEvents.Flinch;
|
||||
}
|
||||
}
|
||||
|
||||
if (_drive.Step(_driveP, _dt, afferent, strainLoad))
|
||||
{
|
||||
events |= TickEvents.WillBroke;
|
||||
_withdrawTick = _tick + _withdrawLatency;
|
||||
}
|
||||
|
||||
if (_tick == _withdrawTick)
|
||||
{
|
||||
events |= TickEvents.Withdrew;
|
||||
_withdrew = true;
|
||||
}
|
||||
|
||||
_behaviour.Write(_withdrew ? Goal.Withdraw : Goal.Hold, leak, _drive.Strain, _tick * _dt, strengths, targets);
|
||||
_tick++;
|
||||
return events;
|
||||
}
|
||||
}
|
||||
}
|
||||
59
src/Lodur.Core/DriveState.cs
Normal file
59
src/Lodur.Core/DriveState.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
/// <summary>The drive's tunables: how pain and strain accumulate, and how they drain the will.</summary>
|
||||
public sealed record DriveParameters
|
||||
{
|
||||
public double PainRise { get; init; } = 1.0;
|
||||
public double PainDecay { get; init; } = 0.05;
|
||||
public double StrainRecover { get; init; } = 0.1;
|
||||
public double ResolveDrainPain { get; init; } = 0.012;
|
||||
public double ResolveDrainStrain { get; init; } = 0.05;
|
||||
public double ResolveRecovery { get; init; } = 0.02;
|
||||
public double ResolveRecoversBelowPain { get; init; } = 0.1;
|
||||
|
||||
/// <summary>How hard the objective pulls, 0..1. It scales resolve drain by (1 - pull); it is not a second resolve bar.</summary>
|
||||
public double ObjectivePull { get; init; } = 0.5;
|
||||
|
||||
/// <summary>Per-character multiplier on resolve drain (the consumer draws its trait spread).</summary>
|
||||
public double DrainTrait { get; init; } = 1.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Layer 3: per-character state that evolves every tick. Pain rises with afferent input, strain with the
|
||||
/// reflex held down, resolve drains under both and recovers when pain is low. Resolve reaching zero breaks
|
||||
/// the will, and a broken will never mends. Only the owning <see cref="Actor"/> steps it.
|
||||
/// </summary>
|
||||
public struct DriveState
|
||||
{
|
||||
public double Pain { get; private set; }
|
||||
public double Strain { get; private set; }
|
||||
public double Resolve { get; private set; }
|
||||
public bool WillBroken { get; private set; }
|
||||
|
||||
internal static DriveState Fresh => new DriveState { Resolve = 1.0 };
|
||||
|
||||
/// <summary>Steps one tick; returns true on the tick the will breaks.</summary>
|
||||
internal bool Step(DriveParameters p, double dt, double afferent, double strainLoad)
|
||||
{
|
||||
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));
|
||||
if (WillBroken)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var drain = (p.ResolveDrainPain * Pain + p.ResolveDrainStrain * Strain) * (1.0 - p.ObjectivePull) * p.DrainTrait;
|
||||
var recovery = Pain < p.ResolveRecoversBelowPain ? p.ResolveRecovery * (1.0 - Resolve) : 0.0;
|
||||
Resolve = Math.Min(Math.Max(Resolve + dt * (recovery - drain), 0.0), 1.0);
|
||||
if (Resolve <= 0.0)
|
||||
{
|
||||
WillBroken = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
81
src/Lodur.Core/HoldAgainstReflex.cs
Normal file
81
src/Lodur.Core/HoldAgainstReflex.cs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
using System;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
/// <summary>What a character is trying to do. Today: hold against the reflex, or withdraw.</summary>
|
||||
public enum Goal
|
||||
{
|
||||
Hold,
|
||||
Withdraw,
|
||||
}
|
||||
|
||||
/// <summary>The layer-4 stand-in's tunables.</summary>
|
||||
public sealed record HoldParameters
|
||||
{
|
||||
/// <summary>Muscle strength written for every muscle, in [0, 1] (above 1 an explicit PD arm sags and drifts).</summary>
|
||||
public float HoldStrength { get; init; } = 1f;
|
||||
|
||||
/// <summary>How far the reflex leak pulls the pose from hold toward withdraw, per unit of leak.</summary>
|
||||
public double FlinchGain { get; init; } = 0.3;
|
||||
|
||||
/// <summary>Strain shake amplitude (blend fraction) per unit of strain. Zero strain, no shake.</summary>
|
||||
public double StrainShake { get; init; } = 0.03;
|
||||
|
||||
/// <summary>Shake frequency. A few Hz: the arm's PD filters anything faster to nothing.</summary>
|
||||
public double ShakeHz { get; init; } = 3.5;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Layer 4 stand-in: hold a pose against the withdrawal reflex. The target is the hold pose blended toward
|
||||
/// the withdraw pose by the reflex leak and a strain-scaled shake; once the goal is Withdraw it is the
|
||||
/// withdraw pose. It writes per-muscle strength and target rotation into the caller's spans and nothing else
|
||||
/// (invariant body-one-interface). The poses are the caller's data, one rotation per muscle.
|
||||
/// </summary>
|
||||
public sealed class HoldAgainstReflex
|
||||
{
|
||||
private readonly HoldParameters _p;
|
||||
private readonly Quat[] _hold;
|
||||
private readonly Quat[] _withdraw;
|
||||
|
||||
public HoldAgainstReflex(HoldParameters parameters, ReadOnlySpan<Quat> holdPose, ReadOnlySpan<Quat> withdrawPose)
|
||||
{
|
||||
if (holdPose.Length != withdrawPose.Length)
|
||||
{
|
||||
throw new ArgumentException("The hold and withdraw poses need one rotation per muscle each.");
|
||||
}
|
||||
|
||||
_p = parameters;
|
||||
_hold = holdPose.ToArray();
|
||||
_withdraw = withdrawPose.ToArray();
|
||||
}
|
||||
|
||||
public int MuscleCount => _hold.Length;
|
||||
|
||||
/// <summary>The blend toward the withdraw pose: 1 once withdrawing, else the clamped leak and shake.</summary>
|
||||
public double Blend(Goal goal, double leak, double strain, double seconds)
|
||||
{
|
||||
if (goal == Goal.Withdraw)
|
||||
{
|
||||
return 1.0;
|
||||
}
|
||||
|
||||
var w = leak * _p.FlinchGain + _p.StrainShake * strain * Math.Sin(2.0 * Math.PI * _p.ShakeHz * seconds);
|
||||
return Math.Min(Math.Max(w, 0.0), 1.0);
|
||||
}
|
||||
|
||||
public void Write(Goal goal, double leak, double strain, double seconds, Span<float> strengths, Span<Quat> targets)
|
||||
{
|
||||
if (strengths.Length != _hold.Length || targets.Length != _hold.Length)
|
||||
{
|
||||
throw new ArgumentException($"strengths and targets need {_hold.Length} entries, one per muscle.");
|
||||
}
|
||||
|
||||
var w = (float)Blend(goal, leak, strain, seconds);
|
||||
for (var m = 0; m < _hold.Length; m++)
|
||||
{
|
||||
strengths[m] = _p.HoldStrength;
|
||||
targets[m] = Quat.Nlerp(_hold[m], _withdraw[m], w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
7
src/Lodur.Core/IsExternalInit.cs
Normal file
7
src/Lodur.Core/IsExternalInit.cs
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// Lets C# 9 records use init accessors on netstandard2.1, which does not ship this marker type.
|
||||
namespace System.Runtime.CompilerServices
|
||||
{
|
||||
internal static class IsExternalInit
|
||||
{
|
||||
}
|
||||
}
|
||||
|
|
@ -30,6 +30,18 @@ namespace Lodur
|
|||
return new Quat(x * s, y * s, z * s, MathF.Cos(half));
|
||||
}
|
||||
|
||||
/// <summary>Normalised linear blend from <paramref name="a"/> (t = 0) to <paramref name="b"/> (t = 1), the shorter way round.</summary>
|
||||
public static Quat Nlerp(in Quat a, in Quat b, float t)
|
||||
{
|
||||
var s = a.X * b.X + a.Y * b.Y + a.Z * b.Z + a.W * b.W < 0f ? -1f : 1f;
|
||||
var x = a.X + t * (s * b.X - a.X);
|
||||
var y = a.Y + t * (s * b.Y - a.Y);
|
||||
var z = a.Z + t * (s * b.Z - a.Z);
|
||||
var w = a.W + t * (s * b.W - a.W);
|
||||
var inv = 1f / MathF.Sqrt(x * x + y * y + z * z + w * w);
|
||||
return new Quat(x * inv, y * inv, z * inv, w * inv);
|
||||
}
|
||||
|
||||
/// <summary>Rotates the vector v by this quaternion.</summary>
|
||||
public void Rotate(float vx, float vy, float vz, out float rx, out float ry, out float rz)
|
||||
{
|
||||
|
|
|
|||
115
src/Lodur.Core/Perception.cs
Normal file
115
src/Lodur.Core/Perception.cs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
using System;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
/// <summary>
|
||||
/// A game stimulus: an axis-aligned box volume with an intensity the game writes every tick. Lodur reads
|
||||
/// it and decides containment and transduction; the box is never a physics body.
|
||||
/// </summary>
|
||||
public struct BoxStimulus
|
||||
{
|
||||
public float CenterX, CenterY, CenterZ;
|
||||
public float HalfX, HalfY, HalfZ;
|
||||
|
||||
/// <summary>Noxious intensity inside the box, written by the game each tick (0..1 in the slice's scale).</summary>
|
||||
public double Intensity;
|
||||
|
||||
public BoxStimulus(float centerX, float centerY, float centerZ, float halfX, float halfY, float halfZ, double intensity = 0.0)
|
||||
{
|
||||
CenterX = centerX; CenterY = centerY; CenterZ = centerZ;
|
||||
HalfX = halfX; HalfY = halfY; HalfZ = halfZ;
|
||||
Intensity = intensity;
|
||||
}
|
||||
|
||||
/// <summary>True when the point is inside the box or on one of its faces.</summary>
|
||||
public bool Contains(float x, float y, float z) =>
|
||||
MathF.Abs(x - CenterX) <= HalfX && MathF.Abs(y - CenterY) <= HalfY && MathF.Abs(z - CenterZ) <= HalfZ;
|
||||
}
|
||||
|
||||
/// <summary>The nerve's tunables: threshold, sensitisation under sustained stimulus, conduction delay, and a per-character gain.</summary>
|
||||
public sealed record NerveParameters
|
||||
{
|
||||
public double NociceptorThreshold { get; init; } = 0.1;
|
||||
public double SensitisationGrowth { get; init; } = 0.04;
|
||||
public double SensitisationRecovery { get; init; } = 0.02;
|
||||
public double SensitisationCap { get; init; } = 2.0;
|
||||
public double ConductionDelaySeconds { get; init; } = 0.06;
|
||||
|
||||
/// <summary>Per-character nociceptor gain (the consumer draws its trait spread).</summary>
|
||||
public double Gain { get; init; } = 1.0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Layer 1 for one character, a fixed number of body regions. Each tick it takes one point per region and the
|
||||
/// game's stimulus sources and produces, per region, the stimulus there and the afferent signal after
|
||||
/// threshold, sensitisation and conduction delay. Everything is allocated in the constructor.
|
||||
/// </summary>
|
||||
public sealed class Perception
|
||||
{
|
||||
private readonly NerveParameters _p;
|
||||
private readonly double _dt;
|
||||
private readonly int _regions;
|
||||
private readonly int _slots;
|
||||
private readonly double[] _ring; // afferent signal in flight along the nerve, region-major
|
||||
private readonly double[] _sens;
|
||||
private readonly double[] _stimulus;
|
||||
private readonly double[] _afferent;
|
||||
private long _tick;
|
||||
|
||||
public Perception(NerveParameters parameters, double tickSeconds, int regionCount)
|
||||
{
|
||||
_p = parameters;
|
||||
_dt = tickSeconds;
|
||||
_regions = regionCount;
|
||||
var delayTicks = (int)Math.Round(parameters.ConductionDelaySeconds / tickSeconds);
|
||||
_slots = Math.Max(1, delayTicks);
|
||||
_ring = new double[regionCount * _slots];
|
||||
_sens = new double[regionCount];
|
||||
Array.Fill(_sens, 1.0);
|
||||
_stimulus = new double[regionCount];
|
||||
_afferent = new double[regionCount];
|
||||
}
|
||||
|
||||
public int RegionCount => _regions;
|
||||
|
||||
/// <summary>The stimulus at the region's point this tick: the largest intensity among the boxes containing it.</summary>
|
||||
public double Stimulus(int region) => _stimulus[region];
|
||||
|
||||
/// <summary>The afferent signal arriving this tick: what the nerve took in a conduction delay ago.</summary>
|
||||
public double Afferent(int region) => _afferent[region];
|
||||
|
||||
/// <summary>Senses once per physics step. The spans are the caller's, one point per region.</summary>
|
||||
public void Sense(ReadOnlySpan<float> x, ReadOnlySpan<float> y, ReadOnlySpan<float> z, ReadOnlySpan<BoxStimulus> sources)
|
||||
{
|
||||
if (x.Length != _regions || y.Length != _regions || z.Length != _regions)
|
||||
{
|
||||
throw new ArgumentException($"x, y and z need {_regions} entries, one per region.");
|
||||
}
|
||||
|
||||
var slot = (int)(_tick % _slots);
|
||||
for (var r = 0; r < _regions; r++)
|
||||
{
|
||||
var stimulus = 0.0;
|
||||
for (var i = 0; i < sources.Length; i++)
|
||||
{
|
||||
if (sources[i].Intensity > stimulus && sources[i].Contains(x[r], y[r], z[r]))
|
||||
{
|
||||
stimulus = sources[i].Intensity;
|
||||
}
|
||||
}
|
||||
|
||||
// Nociceptor: threshold, then sensitisation, then conduction delay.
|
||||
var above = Math.Max(0.0, stimulus - _p.NociceptorThreshold);
|
||||
var sens = _sens[r] + _dt * (_p.SensitisationGrowth * above - _p.SensitisationRecovery * (_sens[r] - 1.0));
|
||||
sens = Math.Min(Math.Max(sens, 1.0), _p.SensitisationCap);
|
||||
_sens[r] = sens;
|
||||
var ring = r * _slots + slot;
|
||||
_afferent[r] = _ring[ring]; // written one conduction delay ago
|
||||
_ring[ring] = above * sens * _p.Gain;
|
||||
_stimulus[r] = stimulus;
|
||||
}
|
||||
|
||||
_tick++;
|
||||
}
|
||||
}
|
||||
}
|
||||
57
src/Lodur.Core/WithdrawalReflex.cs
Normal file
57
src/Lodur.Core/WithdrawalReflex.cs
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
using System;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
/// <summary>The withdrawal reflex's tunables, and the latency of the deliberate withdrawal that takes over from it.</summary>
|
||||
public sealed record WithdrawalParameters
|
||||
{
|
||||
/// <summary>How much of the reflex a fully resolved will can hold down (0..1).</summary>
|
||||
public double MaxSuppression { get; init; } = 0.95;
|
||||
public double FlinchLeakThreshold { get; init; } = 0.3;
|
||||
public double FlinchRefractorySeconds { get; init; } = 0.5;
|
||||
|
||||
/// <summary>How long after the will breaks deliberate behaviour withdraws.</summary>
|
||||
public double LatencySeconds { get; init; } = 0.1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Layer 2 for one body region. Its gain is set ahead of time by the drive: it reads the drive state the
|
||||
/// previous tick left, before the drive steps (invariant reflex-gain-from-drive). What the suppression holds
|
||||
/// down is the strain load; what leaks past is the reflex command and, over the threshold, a flinch.
|
||||
/// </summary>
|
||||
public sealed class WithdrawalReflex
|
||||
{
|
||||
private readonly WithdrawalParameters _p;
|
||||
private readonly long _refractory;
|
||||
private long _tick;
|
||||
private long _lastFlinch = long.MinValue / 2;
|
||||
|
||||
public WithdrawalReflex(WithdrawalParameters parameters, double tickSeconds)
|
||||
{
|
||||
_p = parameters;
|
||||
_refractory = (long)Math.Round(parameters.FlinchRefractorySeconds / tickSeconds);
|
||||
}
|
||||
|
||||
/// <summary>The part of the afferent signal that gets past the will this tick.</summary>
|
||||
public double Leak { get; private set; }
|
||||
|
||||
/// <summary>The part the will holds down this tick: the strain the drive accumulates.</summary>
|
||||
public double StrainLoad { get; private set; }
|
||||
|
||||
/// <summary>Steps once; returns true on a flinch (leak over the threshold, outside the refractory window).</summary>
|
||||
public bool Step(double afferent, in DriveState drive)
|
||||
{
|
||||
var suppression = drive.WillBroken ? 0.0 : _p.MaxSuppression * drive.Resolve;
|
||||
Leak = afferent * (1.0 - suppression);
|
||||
StrainLoad = afferent * suppression;
|
||||
var flinch = Leak > _p.FlinchLeakThreshold && _tick - _lastFlinch >= _refractory;
|
||||
if (flinch)
|
||||
{
|
||||
_lastFlinch = _tick;
|
||||
}
|
||||
|
||||
_tick++;
|
||||
return flinch;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue