Brain: soft commitment (a higher priority preempts the dwell), read-only getters, pinned dwell edges
A goal's minimum dwell now gates only decisions whose target does not strictly outrank it; a strictly higher-priority goal preempts after the latency. GoalSpec.When, PoseBehaviour.Keys and FlinchPose read back as read-only views (the Actor's path keeps its own arrays). Infinite dwell is refused. Tests pin the exact boundary tick, the dwell index, the rounding rule, time-in-goal from takeover, preemption both ways and that writing through a getter is impossible. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
d19fbc0794
commit
6305bd843c
4 changed files with 208 additions and 41 deletions
|
|
@ -125,11 +125,11 @@ namespace Lodur
|
|||
}
|
||||
|
||||
// A decision in flight commits at its tick even if the condition that chose it has lapsed; none is made while one is
|
||||
// pending, nor before the goal in force has had its minimum dwell.
|
||||
if (_pending < 0 && _tick - _goalSince >= _dwell[_goal])
|
||||
// pending. Within the goal in force's minimum dwell only a strictly higher-priority goal is decided on.
|
||||
if (_pending < 0)
|
||||
{
|
||||
var wanted = _brain.Select(_drive, _goal);
|
||||
if (wanted != _goal)
|
||||
if (wanted != _goal && (_tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted].Priority > _brain.Goals[_goal].Priority))
|
||||
{
|
||||
_pending = wanted;
|
||||
_switchTick = _tick + _latency;
|
||||
|
|
|
|||
|
|
@ -50,16 +50,45 @@ namespace Lodur
|
|||
public double Pull { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// A goal cannot be left until it has been active this long, counted in ticks from the tick it took over;
|
||||
/// 0 (the default) never holds a goal. It keeps a condition hovering at its threshold from making the Brain
|
||||
/// chatter: a switch away is decided only once the dwell has passed, then takes the deliberate latency.
|
||||
/// Commitment, soft: until this goal has been active this long (rounded to whole ticks like the latency, counted
|
||||
/// from the tick it took over), a goal that does not strictly outrank it cannot be decided on; a strictly
|
||||
/// higher-priority goal preempts at once, after the deliberate latency. 0 (the default) never holds a goal. It keeps
|
||||
/// a condition hovering at its threshold from making the Brain chatter: the return trip from an entered goal is
|
||||
/// gated by that goal's own dwell. The dwell holds the decision to leave; a decision already in flight commits.
|
||||
/// </summary>
|
||||
public double MinDwellSeconds { get; init; }
|
||||
|
||||
private Condition[] _when = Array.Empty<Condition>();
|
||||
private IReadOnlyList<Condition> _whenView = Array.AsReadOnly(Array.Empty<Condition>());
|
||||
|
||||
/// <summary>All must hold for the goal to be eligible; none means always eligible. Copied when set.</summary>
|
||||
public Condition[] When { get => _when; init => _when = (Condition[])value.Clone(); }
|
||||
/// <summary>All must hold for the goal to be eligible; none means always eligible. Copied when set; read back as a read-only view.</summary>
|
||||
public IReadOnlyList<Condition> When
|
||||
{
|
||||
get => _whenView;
|
||||
init
|
||||
{
|
||||
_when = new Condition[value.Count];
|
||||
for (var c = 0; c < _when.Length; c++)
|
||||
{
|
||||
_when[c] = value[c];
|
||||
}
|
||||
|
||||
_whenView = Array.AsReadOnly(_when);
|
||||
}
|
||||
}
|
||||
|
||||
internal bool Eligible(in DriveState drive)
|
||||
{
|
||||
for (var c = 0; c < _when.Length; c++)
|
||||
{
|
||||
if (!_when[c].Holds(drive))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public PoseBehaviour Behaviour { get; init; } = new PoseBehaviour();
|
||||
}
|
||||
|
|
@ -72,7 +101,7 @@ namespace Lodur
|
|||
{
|
||||
private IReadOnlyList<GoalSpec> _goals = Array.Empty<GoalSpec>();
|
||||
|
||||
/// <summary>The goals, copied when set: later changes to the caller's list or arrays do not reach a Brain.</summary>
|
||||
/// <summary>The goals, copied when set: later changes to the caller's list or arrays do not reach a Brain, and the getter is a read-only view.</summary>
|
||||
public IReadOnlyList<GoalSpec> Goals
|
||||
{
|
||||
get => _goals;
|
||||
|
|
@ -102,13 +131,7 @@ namespace Lodur
|
|||
for (var i = 0; i < Goals.Count; i++)
|
||||
{
|
||||
var goal = Goals[i];
|
||||
var eligible = true;
|
||||
for (var c = 0; c < goal.When.Length && eligible; c++)
|
||||
{
|
||||
eligible = goal.When[c].Holds(drive);
|
||||
}
|
||||
|
||||
if (!eligible)
|
||||
if (!goal.Eligible(drive))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
|
@ -150,7 +173,7 @@ namespace Lodur
|
|||
|
||||
if (!(goal.MinDwellSeconds >= 0.0 && double.IsFinite(goal.MinDwellSeconds)))
|
||||
{
|
||||
throw new ArgumentException($"Goal {goal.Id}: MinDwellSeconds must be finite and not negative.");
|
||||
throw new ArgumentException($"Goal {goal.Id}: MinDwellSeconds must be finite (not infinite) and not negative.");
|
||||
}
|
||||
|
||||
foreach (var c in goal.When)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Lodur
|
||||
{
|
||||
|
|
@ -30,54 +31,77 @@ namespace Lodur
|
|||
{
|
||||
private Quat[][] _keys = Array.Empty<Quat[]>();
|
||||
private Quat[] _flinch = Array.Empty<Quat>();
|
||||
private IReadOnlyList<IReadOnlyList<Quat>> _keysView = Array.AsReadOnly(Array.Empty<IReadOnlyList<Quat>>());
|
||||
private IReadOnlyList<Quat> _flinchView = Array.AsReadOnly(Array.Empty<Quat>());
|
||||
|
||||
/// <summary>k keys of one rotation per muscle each. Copied when set.</summary>
|
||||
public Quat[][] Keys
|
||||
/// <summary>k keys of one rotation per muscle each. Copied when set; read back as a read-only view.</summary>
|
||||
public IReadOnlyList<IReadOnlyList<Quat>> Keys
|
||||
{
|
||||
get => _keys;
|
||||
get => _keysView;
|
||||
init
|
||||
{
|
||||
var copy = new Quat[value.Length][];
|
||||
var copy = new Quat[value.Count][];
|
||||
var views = new IReadOnlyList<Quat>[copy.Length];
|
||||
for (var k = 0; k < copy.Length; k++)
|
||||
{
|
||||
copy[k] = (Quat[])value[k].Clone();
|
||||
copy[k] = new Quat[value[k].Count];
|
||||
for (var m = 0; m < copy[k].Length; m++)
|
||||
{
|
||||
copy[k][m] = value[k][m];
|
||||
}
|
||||
|
||||
views[k] = Array.AsReadOnly(copy[k]);
|
||||
}
|
||||
|
||||
_keys = copy;
|
||||
_keysView = Array.AsReadOnly(views);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Seconds from one key to the next when there is more than one key.</summary>
|
||||
public double SecondsPerKey { get; init; } = 1.0;
|
||||
|
||||
/// <summary>The pose the leak and the shake pull toward, one rotation per muscle. Copied when set.</summary>
|
||||
public Quat[] FlinchPose { get => _flinch; init => _flinch = (Quat[])value.Clone(); }
|
||||
/// <summary>The pose the leak and the shake pull toward, one rotation per muscle. Copied when set; read back as a read-only view.</summary>
|
||||
public IReadOnlyList<Quat> FlinchPose
|
||||
{
|
||||
get => _flinchView;
|
||||
init
|
||||
{
|
||||
_flinch = new Quat[value.Count];
|
||||
for (var m = 0; m < _flinch.Length; m++)
|
||||
{
|
||||
_flinch[m] = value[m];
|
||||
}
|
||||
|
||||
_flinchView = Array.AsReadOnly(_flinch);
|
||||
}
|
||||
}
|
||||
|
||||
public HoldParameters Hold { get; init; } = new HoldParameters();
|
||||
|
||||
public int MuscleCount => Keys.Length == 0 ? 0 : Keys[0].Length;
|
||||
public int MuscleCount => _keys.Length == 0 ? 0 : _keys[0].Length;
|
||||
|
||||
internal void Validate(string goal)
|
||||
{
|
||||
if (Keys.Length == 0 || Keys[0].Length == 0)
|
||||
if (_keys.Length == 0 || _keys[0].Length == 0)
|
||||
{
|
||||
throw new ArgumentException($"Goal {goal}: a pose behaviour needs at least one key of at least one muscle.");
|
||||
}
|
||||
|
||||
foreach (var key in Keys)
|
||||
foreach (var key in _keys)
|
||||
{
|
||||
if (key.Length != Keys[0].Length)
|
||||
if (key.Length != _keys[0].Length)
|
||||
{
|
||||
throw new ArgumentException($"Goal {goal}: every key needs one rotation per muscle.");
|
||||
}
|
||||
}
|
||||
|
||||
if (FlinchPose.Length != Keys[0].Length)
|
||||
if (_flinch.Length != _keys[0].Length)
|
||||
{
|
||||
throw new ArgumentException($"Goal {goal}: the flinch pose needs one rotation per muscle.");
|
||||
}
|
||||
|
||||
if (Keys.Length > 1 && !(SecondsPerKey > 0.0 && double.IsFinite(SecondsPerKey)))
|
||||
if (_keys.Length > 1 && !(SecondsPerKey > 0.0 && double.IsFinite(SecondsPerKey)))
|
||||
{
|
||||
throw new ArgumentException($"Goal {goal}: SecondsPerKey must be positive and finite.");
|
||||
}
|
||||
|
|
@ -99,7 +123,7 @@ namespace Lodur
|
|||
}
|
||||
|
||||
var w = (float)Blend(leak, strain, seconds);
|
||||
var k = Keys.Length;
|
||||
var k = _keys.Length;
|
||||
var from = 0;
|
||||
var to = 0;
|
||||
var phase = 0f;
|
||||
|
|
@ -114,14 +138,14 @@ namespace Lodur
|
|||
|
||||
for (var m = 0; m < count; m++)
|
||||
{
|
||||
var a = Keys[from][m];
|
||||
var a = _keys[from][m];
|
||||
if (phase > 0f)
|
||||
{
|
||||
a = Quat.Nlerp(Keys[from][m], Keys[to][m], phase);
|
||||
a = Quat.Nlerp(_keys[from][m], _keys[to][m], phase);
|
||||
}
|
||||
|
||||
strengths[m] = Hold.HoldStrength;
|
||||
targets[m] = Quat.Nlerp(a, FlinchPose[m], w);
|
||||
targets[m] = Quat.Nlerp(a, _flinch[m], w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -401,6 +401,7 @@ public sealed class BrainTests
|
|||
if (i < decided + Latency)
|
||||
{
|
||||
Assert.Equal(1f, r.Strengths[0]);
|
||||
Assert.Equal((i + 1) * 0.01, r.Actor.SecondsInGoal, 9); // the goal in force keeps its own clock through the decision and the latency
|
||||
Assert.Equal(0, (int)(e & TickEvents.GoalChanged));
|
||||
}
|
||||
else
|
||||
|
|
@ -433,22 +434,22 @@ public sealed class BrainTests
|
|||
Assert.Equal(Quat.Nlerp(keys[0][0], keys[1][0], 0.5f).Z, r.Targets[0].Z, 5); // half way to key 1 after half a key
|
||||
}
|
||||
|
||||
private static List<long> Hover(double dwell, double threshold)
|
||||
private static List<(long Tick, int Goal)> Hover(double dwell, double threshold)
|
||||
{
|
||||
var rage = Goal("rage", 2.0, 1.0, new Condition(DriveQuantity.Arousal, ConditionOp.AtLeast, threshold)) with { MinDwellSeconds = dwell };
|
||||
var brain = new Brain { Goals = new[] { Goal("calm", 1.0, 1.0) with { MinDwellSeconds = dwell }, rage } };
|
||||
var rig = new SensoryRig(SensoryRig.One(0.55), brain: brain);
|
||||
var changes = new List<long>();
|
||||
var changes = new List<(long, int)>();
|
||||
for (long i = 0; i < 6000; i++)
|
||||
{
|
||||
rig.Emitters[0].Intensity = (i / 100) % 2 == 0 ? 0.55 : 0.0; // on 1 s, off 1 s: arousal saws around its middle
|
||||
if ((rig.Tick() & TickEvents.GoalChanged) != 0) changes.Add(i);
|
||||
if ((rig.Tick() & TickEvents.GoalChanged) != 0) changes.Add((i, rig.Actor.GoalIndex));
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_condition_hovering_at_its_threshold_chatters_without_a_dwell_and_with_one_a_goal_is_left_at_most_once_per_window()
|
||||
public void A_condition_hovering_at_its_threshold_chatters_without_a_dwell_and_with_one_the_entered_goal_is_not_left_for_a_lower_one_inside_its_window()
|
||||
{
|
||||
double lo = 1, hi = 0;
|
||||
var probe = new SensoryRig(SensoryRig.One(0.55), brain: new Brain { Goals = new[] { Goal("only", 0.0, 1.0) } });
|
||||
|
|
@ -464,15 +465,134 @@ public sealed class BrainTests
|
|||
Assert.True(free.Count >= 15, $"{free.Count} changes with no dwell: the scenario does not chatter");
|
||||
|
||||
const double dwell = 3.0;
|
||||
const long dwellTicks = 300;
|
||||
var held = Hover(dwell, mid);
|
||||
Assert.True(held.Count >= 2 && held.Count < free.Count / 3, $"{held.Count} changes with a dwell of {dwell} s against {free.Count}");
|
||||
Assert.True(held.Count >= 2 && held.Count * 2 <= free.Count, $"{held.Count} changes with a dwell of {dwell} s against {free.Count}");
|
||||
var leaves = 0;
|
||||
for (var i = 1; i < held.Count; i++)
|
||||
{
|
||||
Assert.True(held[i] - held[i - 1] >= (long)(dwell / 0.01) + Latency, $"changes at {held[i - 1]} and {held[i]} are closer than the dwell and latency");
|
||||
if (held[i].Goal != 0) continue; // only the return trip (rage to the lower calm) is gated by rage's dwell
|
||||
leaves++;
|
||||
Assert.True(held[i].Tick - held[i - 1].Tick >= dwellTicks + Latency, $"rage taken at {held[i - 1].Tick} and left at {held[i].Tick}");
|
||||
}
|
||||
Assert.True(held[0] >= (long)(dwell / 0.01), "the start goal is held for the dwell too");
|
||||
Assert.True(leaves >= 2);
|
||||
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
|
||||
new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = -1.0 } } }));
|
||||
foreach (var bad in new[] { double.PositiveInfinity, double.NaN })
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => new Actor(0.01, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(),
|
||||
new Brain { Goals = new[] { Goal("g", 0.0) with { MinDwellSeconds = bad } } }));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Goal 1 is the start goal, eligible while pain is below 0.3, with the dwell; goal 0 (no dwell) is the lower-priority
|
||||
/// goal always eligible. Pain passes 0.3 early, so the decision to leave goal 1 is held to its dwell and lands exactly then.
|
||||
/// </summary>
|
||||
private static (long Dwell, long Changed, long PainLapsed) LeaveHeldGoal(double dwellSeconds, double priorityOfTarget = 1.0)
|
||||
{
|
||||
var brain = new Brain
|
||||
{
|
||||
Goals = new[]
|
||||
{
|
||||
Goal("target", priorityOfTarget, 0.5, Pain(ConditionOp.AtLeast, 0.3)),
|
||||
Goal("held", 2.0, 0.5, Pain(ConditionOp.Below, 0.3)) with { MinDwellSeconds = dwellSeconds },
|
||||
},
|
||||
Start = 1,
|
||||
};
|
||||
var r = new PainBoxReplay(1, brain: brain);
|
||||
long lapsed = -1, changed = -1;
|
||||
for (long i = 0; i < 800 && changed < 0; i++)
|
||||
{
|
||||
if ((r.Tick() & TickEvents.GoalChanged) != 0) changed = i;
|
||||
if (lapsed < 0 && r.Actor.Drive.Pain >= 0.3) lapsed = i;
|
||||
}
|
||||
return (0, changed, lapsed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_goal_not_outranked_is_left_exactly_a_dwell_after_it_took_over_the_decision_held_on_the_dwells_last_tick()
|
||||
{
|
||||
// 3.0 s is 300 ticks from tick 0 (the start goal is active from there): the decision is taken on tick 300 and lands 10 later.
|
||||
var (_, changed, lapsed) = LeaveHeldGoal(3.0);
|
||||
Assert.True(lapsed > 0 && lapsed < 290, $"pain lapsed the condition on tick {lapsed}");
|
||||
Assert.Equal(300 + Latency, changed);
|
||||
// The dwell is the held goal's own (goal 1), not goal 0's, which has none.
|
||||
var free = LeaveHeldGoal(0.0);
|
||||
Assert.Equal(free.PainLapsed + Latency, free.Changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_dwell_is_rounded_to_the_nearest_tick_as_the_latency_is()
|
||||
{
|
||||
Assert.Equal(300 + Latency, LeaveHeldGoal(3.004).Changed); // 300.4 ticks: a ceiling would make it 301
|
||||
Assert.Equal(301 + Latency, LeaveHeldGoal(3.006).Changed); // 300.6 ticks: a floor would make it 300
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_strictly_higher_priority_goal_preempts_during_the_dwell_after_the_latency_and_a_goal_that_ties_or_ranks_below_is_held()
|
||||
{
|
||||
// Same scene, but the goal it would move to outranks the held one: no wait for the dwell.
|
||||
var (_, preempted, lapsed) = LeaveHeldGoal(3.0, priorityOfTarget: 3.0);
|
||||
Assert.Equal(lapsed + Latency, preempted);
|
||||
Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 2.0).Changed); // a tie is not strictly higher
|
||||
Assert.Equal(300 + Latency, LeaveHeldGoal(3.0, priorityOfTarget: 1.99).Changed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_dwell_of_an_entered_goal_counts_from_the_tick_it_took_over_not_from_the_decision()
|
||||
{
|
||||
// Held goal b is entered on pain at least 0.3 and its condition lapses at once (a band); its dwell of 2 s runs from the takeover.
|
||||
var band = Goal("b", 2.0, 0.5, Pain(ConditionOp.AtLeast, 0.3), Pain(ConditionOp.Below, 0.305)) with { MinDwellSeconds = 2.0 };
|
||||
var r = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 1.0), band } });
|
||||
long decided = -1, entered = -1, left = -1;
|
||||
for (long i = 0; i < 800 && left < 0; i++)
|
||||
{
|
||||
var e = r.Tick();
|
||||
if (decided < 0 && r.Actor.Drive.Pain >= 0.3) decided = i;
|
||||
if ((e & TickEvents.GoalChanged) != 0) { if (entered < 0) entered = i; else left = i; }
|
||||
}
|
||||
Assert.Equal(decided + Latency, entered);
|
||||
Assert.Equal(entered + 200 + Latency, left);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_built_brains_getters_hand_out_read_only_views_and_writing_through_them_changes_nothing()
|
||||
{
|
||||
var keys = new[] { new[] { Quat.Identity, Quat.Identity } };
|
||||
var brain = new Brain
|
||||
{
|
||||
Goals = new[]
|
||||
{
|
||||
Goal("a", 0.0),
|
||||
Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with
|
||||
{
|
||||
Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw },
|
||||
},
|
||||
},
|
||||
};
|
||||
static void Sealed<T>(IReadOnlyList<T> view, T poison)
|
||||
{
|
||||
Assert.False(view is T[]);
|
||||
if (view is IList<T> list)
|
||||
{
|
||||
Assert.True(list.IsReadOnly);
|
||||
Assert.Throws<NotSupportedException>(() => list[0] = poison);
|
||||
}
|
||||
}
|
||||
Sealed(brain.Goals, Goal("poison", 9.0));
|
||||
Sealed(brain.Goals[1].When, Pain(ConditionOp.AtLeast, double.NaN));
|
||||
Sealed(brain.Goals[1].Behaviour.Keys, (IReadOnlyList<Quat>)new Quat[1]);
|
||||
Sealed(brain.Goals[1].Behaviour.Keys[0], new Quat(7f, 7f, 7f, 7f));
|
||||
Sealed(brain.Goals[1].Behaviour.FlinchPose, new Quat(7f, 7f, 7f, 7f));
|
||||
|
||||
var a = new PainBoxReplay(1, brain: brain);
|
||||
var b = new PainBoxReplay(1, brain: new Brain { Goals = new[] { Goal("a", 0.0), Goal("b", 1.0, 0.5, Pain(ConditionOp.AtLeast, 0.3)) with { Behaviour = new PoseBehaviour { Keys = keys, FlinchPose = PainBoxBrain.Withdraw } } } });
|
||||
for (var i = 0; i < 1000; i++)
|
||||
{
|
||||
Assert.Equal(b.Tick(), a.Tick());
|
||||
Assert.Equal(b.Targets, a.Targets);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
|
|
|||
Loading…
Reference in a new issue