From 425fbd285e89d96f4e4149dbabb3ecef53749142 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 26 Nov 2026 05:15:15 +0100 Subject: [PATCH] Planner frustration: a futile direct try is barred after FrustrationSeconds, reported as Frustrated, and decided again past the dwell; the bar lifts on a change or after RetrySeconds Co-Authored-By: Claude Sonnet 5.5 --- docs/goal-ai-map.md | 5 +- src/Lodur.Core/Actor.cs | 52 ++- src/Lodur.Core/Brain.cs | 23 +- src/Lodur.Core/Deliberation.cs | 69 +++ .../PlannerFrustrationTests.cs | 405 ++++++++++++++++++ 5 files changed, 549 insertions(+), 5 deletions(-) create mode 100644 tests/Lodur.Core.Tests/PlannerFrustrationTests.cs diff --git a/docs/goal-ai-map.md b/docs/goal-ai-map.md index d0e4351..6a23eb1 100644 --- a/docs/goal-ai-map.md +++ b/docs/goal-ai-map.md @@ -284,8 +284,9 @@ on its pairs, built in `Brain.Select` and the Actor's `Deliberation`: a pair who a pair planned within `PlanDepth` steps scores raw times the `PlanSteps` responses at its length; a pair with no plan (none within the depth, or the think budget gone) is tried direct at `DirectDiscount`, reading `PlanSteps` at depth + 1 (ruling `bds-unplannable-tries-direct`, which answers `bds-unplannable-goal`: he goes at the target -and fails where the player can see it; the frustration that ends a futile try is follow-up `lodur-planner-frustration`, -so until it lands a direct try lasts while it wins). One `ThinkBudget` serves a whole Select, spent by deepening +and fails where the player can see it; a direct try that reads `PlanLength` -1 for `FrustrationSeconds` bars that pair's +direct try, reports `TickEvents.Frustrated` and decides again past the dwell, and the bar lifts on forgetting the target, a changed +fact of it or of himself, or `RetrySeconds`). One `ThinkBudget` serves a whole Select, spent by deepening across the pairs (Korf's iterative deepening, anytime): round k asks every live pair for a plan of exactly k steps, by a bound on what the pair can still score, so short plans are found first and one pair's dead end cannot starve the rest; a want about himself is planned once per goal. The plan is the decision's: made by the Select that chose or diff --git a/src/Lodur.Core/Actor.cs b/src/Lodur.Core/Actor.cs index 1feac5c..961c9f6 100644 --- a/src/Lodur.Core/Actor.cs +++ b/src/Lodur.Core/Actor.cs @@ -18,6 +18,8 @@ namespace Lodur Died = 8, /// 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. Gasp = 16, + /// A futile direct try was given up this tick: its (goal, target) pair is barred from being tried direct, and the next decision is made past the goal's dwell. + Frustrated = 32, } /// @@ -65,6 +67,11 @@ namespace Lodur // The want gate's thinking space (null when no goal has a want), which also holds the plan of the decision in force, and its length as read. private readonly Deliberation? _deliberation; private int _planLength; + // Frustration (ruling bds-unplannable-tries-direct): the ticks a direct try may last and a bar lasts, the tick from which the committed pair has read PlanLength -1 without a break (-1: not), and whether the next Select is accepted past the dwell. + private readonly long _frustrationTicks; + private readonly long _retryTicks; + private long _directSince = -1; + private bool _impatient; public Actor( double tickSeconds, int regionCount, @@ -137,6 +144,12 @@ namespace Lodur _entryTicks[g] = entryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(entryTicks); } + // Rounded once to ticks like the dwell; a quotient past the long range (+infinity included) is never reached. + var frustrationTicks = brain.FrustrationSeconds / tickSeconds; + _frustrationTicks = frustrationTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(frustrationTicks); + var retryTicks = brain.RetrySeconds / tickSeconds; + _retryTicks = retryTicks >= long.MaxValue ? long.MaxValue : (long)Math.Round(retryTicks); + if (physiology != null) { var breathP = breath ?? new WithdrawalParameters(); @@ -218,7 +231,7 @@ namespace Lodur /// /// The length of the plan of the decision in force, made by the Select that chose or re-chose the pair and carried with it (a tick that decides nothing only checks it): n steps, /// -1 when he goes at it direct (no plan within , the think budget gone, or a step's thing forgotten), 0 when the goal has no want, the want holds, - /// or its target is no longer in memory. + /// or its target is no longer in memory. A -1 that lasts ends in . /// public int PlanLength => _planLength; @@ -358,6 +371,19 @@ 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. Within the goal in force's minimum dwell only a strictly higher-priority goal is decided on. + // Order: the bars lift on what he knows now, then a direct try that has lasted its time is barred (and the next decision made impatient), then the decision. + if (_deliberation != null) + { + _deliberation.Lift(_perception, selfFacts, _tick); + if (_directSince >= 0 && _tick - _directSince >= _frustrationTicks && !_deliberation.Barred(_goal, _target)) + { + _deliberation.Bar(_goal, _target, _retryTicks > long.MaxValue - _tick ? long.MaxValue : _tick + _retryTicks); + events |= TickEvents.Frustrated; + _directSince = -1; + _impatient = true; + } + } + var planned = false; if (_pending < 0) { @@ -369,8 +395,10 @@ namespace Lodur } var wanted = _brain.Select(_drive, _perception, regionX[sr], regionY[sr], regionZ[sr], now, _deliberation); + var impatient = _impatient; + _impatient = false; // one Select is impatient, whatever it returns if (wanted != new Choice(_goal, _target) - && (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority)) + && (wanted.Goal == _goal || _tick - _goalSince >= _dwell[_goal] || _brain.Goals[wanted.Goal].Priority > _brain.Goals[_goal].Priority || impatient)) { _pending = wanted.Goal; _pendingTarget = wanted.Target; @@ -394,6 +422,11 @@ namespace Lodur if (_pending >= 0 && _tick == _switchTick) { var changed = _pending != _goal; + if (changed || _pendingTarget != _target) + { + _directSince = -1; + } + _goal = _pending; _target = _pendingTarget; _pending = -1; @@ -438,6 +471,21 @@ namespace Lodur } _planLength = _deliberation.InForceLength; + if (_planLength < 0) + { + if (_directSince < 0) + { + _directSince = _tick; + } + } + else + { + _directSince = -1; + } + } + else + { + _directSince = -1; } // For EntrySeconds after a takeover the Actor, not the drive, takes the gain (and the arousal, if the goal declares one) from their values at diff --git a/src/Lodur.Core/Brain.cs b/src/Lodur.Core/Brain.cs index 431b467..e218367 100644 --- a/src/Lodur.Core/Brain.cs +++ b/src/Lodur.Core/Brain.cs @@ -328,6 +328,12 @@ namespace Lodur /// The factor on a pair's score when its goal's want has no plan within (or the think budget ran out): he goes at the target directly, in [0, 1], default 0.5 (a placeholder). public double DirectDiscount { get; init; } = 0.5; + /// How long a direct try ( -1) of one (goal, target) pair may last before the Actor gives it up: it bars the pair's direct try, reports and decides again past the goal's dwell. Not NaN, not negative; +infinity never frustrates. Default 5 (a placeholder; ruling bds-unplannable-tries-direct). + public double FrustrationSeconds { get; init; } = 5.0; + + /// How long a bar on a direct try lasts if the world he knows does not change first: the pair is tried direct again after it. Not NaN, not negative; +infinity never lifts by time. Default 30 (a placeholder). + public double RetrySeconds { get; init; } = 30.0; + /// The most groundings one Select may regress across all its plans, at least 1, default 4096: one budget per decision, spent by deepening across the want pairs, short plans first (lodur:question:bds-think-budget-per-decision). public int ThinkBudget { get; init; } = Planner.NodeBudget; @@ -374,7 +380,7 @@ namespace Lodur /// the untargeted-by-want pairs; a want pair whose want holds is not offered, the rest wait in the Deliberation. Pass 2 deepens across the waiting pairs: round k takes them by /// bound (raw times the best factor any plan longer than k - 1 steps, or going direct, could earn), asks each for a plan of exactly k steps with what is left of , /// and offers raw times the plan-length factor for one found; a pair with none of k steps waits for round k + 1, and one with no plan within PlanDepth (or the budget gone) is offered - /// at raw times the factor at PlanDepth + 1 times . A round ends when no remaining bound can beat or tie-win the best, so short plans are found + /// at raw times the factor at PlanDepth + 1 times , unless the Deliberation holds a bar on that pair's direct try (it is then not offered; it is offered when it plans). A round ends when no remaining bound can beat or tie-win the best, so short plans are found /// first and one pair's dead end cannot starve the rest. /// internal Choice Select(in DriveState drive, Perception perception, float ox, float oy, float oz, Choice current, Deliberation? d) @@ -429,6 +435,11 @@ namespace Lodur continue; } + if (length < 0 && d.Barred(pair.Goal, pair.Target)) + { + continue; // a futile direct try is barred: neither offered nor deferred + } + var factor = length > 0 ? goal.PlanFactor(length) : goal.PlanFactor(PlanDepth + 1) * DirectDiscount; if (Offer(pair.Goal, pair.Slot, pair.Target, pair.Raw * factor, pair.Current, ref best)) { @@ -525,6 +536,16 @@ namespace Lodur throw new ArgumentException("DirectDiscount must be in [0, 1]."); } + if (!(FrustrationSeconds >= 0.0)) + { + throw new ArgumentException("FrustrationSeconds must not be NaN or negative."); + } + + if (!(RetrySeconds >= 0.0)) + { + throw new ArgumentException("RetrySeconds must not be NaN or negative."); + } + if (ThinkBudget < 1) { throw new ArgumentException("ThinkBudget must be at least 1."); diff --git a/src/Lodur.Core/Deliberation.cs b/src/Lodur.Core/Deliberation.cs index 5767303..171c266 100644 --- a/src/Lodur.Core/Deliberation.cs +++ b/src/Lodur.Core/Deliberation.cs @@ -50,6 +50,10 @@ namespace Lodur private readonly int _width; // the steps a plan buffer holds private PlanStep[] _best; // the plan of the pair best so far in this Select, BestLength steps private PlanStep[] _inForce; // the plan of the decision in force + private readonly ulong[] _barTarget; // per goal: the barred target's id (0 for a Self want's untargeted goal) + private readonly ulong[] _barFacts; // per goal: the barred target's facts when barred + private readonly ulong[] _barSelf; // per goal: the actor's own facts when barred + private readonly long[] _barUntil; // per goal: the tick the bar expires at; -1 is no bar internal Deliberation(Brain brain, IReadOnlyList verbs, int capacity) { @@ -67,6 +71,11 @@ namespace Lodur _selfPlan = new PlanStep[brain.Goals.Count * _width]; _next = new WantPair[_heap.Length]; _selfDepth = new int[brain.Goals.Count]; + _barTarget = new ulong[brain.Goals.Count]; + _barFacts = new ulong[brain.Goals.Count]; + _barSelf = new ulong[brain.Goals.Count]; + _barUntil = new long[brain.Goals.Count]; + Array.Fill(_barUntil, -1L); _bound = new double[brain.Goals.Count * (_depth + 1)]; for (var g = 0; g < brain.Goals.Count; g++) { @@ -99,6 +108,66 @@ namespace Lodur /// The length of the plan of the decision in force: n steps, -1 to go direct, 0 when its want holds, it has none, or its target left memory. internal int InForceLength => _inForceLength; + /// + /// Bars the direct try of the pair (, ) until , remembering the target's facts and the actor's own as they stand now + /// (the percepts and self facts of the last Select). One bar per goal: a new one replaces it. + /// + internal void Bar(int goal, ulong target, long untilTick) + { + _barTarget[goal] = target; + _barSelf[goal] = SelfFacts; + var ids = _perception.PerceptIds; + var facts = _perception.PerceptFacts; + _barFacts[goal] = 0UL; + for (var s = 0; target != 0UL && s < ids.Length; s++) + { + if (ids[s] == target) + { + _barFacts[goal] = facts[s]; + break; + } + } + + _barUntil[goal] = untilTick; + } + + /// Whether the direct try of the pair is barred: an equal bar, live ( runs each tick before the decision). + internal bool Barred(int goal, ulong target) => _barUntil[goal] >= 0 && _barTarget[goal] == target; + + /// Clears every bar whose time has come, whose target is no longer in memory, or whose remembered facts or self facts differ from the bar's. + internal void Lift(Perception perception, ulong selfFacts, long tick) + { + var ids = perception.PerceptIds; + var facts = perception.PerceptFacts; + for (var g = 0; g < _barUntil.Length; g++) + { + if (_barUntil[g] < 0) + { + continue; + } + + var lift = tick >= _barUntil[g] || _barSelf[g] != selfFacts; + if (!lift && _barTarget[g] != 0UL) + { + lift = true; + for (var s = 0; s < ids.Length; s++) + { + if (ids[s] == _barTarget[g]) + { + lift = facts[s] != _barFacts[g]; + break; + } + } + } + + if (lift) + { + _barUntil[g] = -1; + _barTarget[g] = 0UL; + } + } + } + /// Starts a Select: nothing waits, nothing is spent, nothing is known of the Self wants. internal void Begin(Perception perception, float ox, float oy, float oz) { diff --git a/tests/Lodur.Core.Tests/PlannerFrustrationTests.cs b/tests/Lodur.Core.Tests/PlannerFrustrationTests.cs new file mode 100644 index 0000000..a7dd62d --- /dev/null +++ b/tests/Lodur.Core.Tests/PlannerFrustrationTests.cs @@ -0,0 +1,405 @@ +using System; +using System.Collections.Generic; +using Lodur; + +namespace Lodur.Core.Tests; + +/// +/// A futile direct try ends (ruling bds-unplannable-tries-direct): after FrustrationSeconds at PlanLength -1 the Actor bars the pair's direct try, reports Frustrated and decides again +/// past the dwell; the bar lifts when what he knows changes, or after RetrySeconds. +/// +public sealed class PlannerFrustrationTests +{ + private const uint Door = 1, Knife = 3; + private const int Open = 0, Locked = 1, Latched = 2, Held = 3, Fed = 4, Noise = 5; + private const int Reach = 63; + private const double Dt = 0.01; + private const int Latency = 10; + private static readonly float[] Zero = { 0f }; + private static readonly BoxStimulus[] NoBoxes = Array.Empty(); + private static readonly Emitter[] None = Array.Empty(); + + private static Fact Self(int bit, bool v = true) => new(FactSubject.Self, bit, v); + private static Fact This(int bit, bool v = true) => new(FactSubject.This, bit, v); + private static Fact Tool(int bit, bool v = true) => new(FactSubject.Tool, bit, v); + private static TargetFilter Kinds(params uint[] kinds) => new() { Kinds = kinds }; + + private static Verb[] Catalogue() => new[] + { + new Verb { Id = "Approach", Gives = new[] { This(Reach) } }, + new Verb { Id = "Unlock", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked) }, Gives = new[] { This(Locked, false) } }, + new Verb { Id = "Unlatch", This = Kinds(Door), Needs = new[] { This(Reach), This(Latched) }, Gives = new[] { This(Latched, false) } }, + new Verb { Id = "Open", This = Kinds(Door), Needs = new[] { This(Reach), This(Locked, false), This(Latched, false) }, Gives = new[] { This(Open) } }, + new Verb { Id = "Calm", This = Kinds(Knife), Needs = new[] { This(Reach) }, Gives = new[] { Self(Fed) } }, + }; + + // A knife held in the hand pries any door open in two steps (approach, pry); with no knife there is no plan at all. + private static Verb[] WithPry() => new[] + { + new Verb { Id = "Approach", Gives = new[] { This(Reach) } }, + new Verb { Id = "Pry", This = Kinds(Door), Tool = Kinds(Knife), Needs = new[] { Tool(Held), This(Reach) }, Gives = new[] { This(Open) } }, + }; + + private static GoalSpec Goal(string id, double priority, TargetFilter? target = null, Fact? want = null, double dwell = 0.0) => new() + { + Id = id, Priority = priority, Target = target, Want = want, MinDwellSeconds = dwell, + Behaviour = new PoseBehaviour { Keys = new[] { PainBoxBrain.Hold }, FlinchPose = PainBoxBrain.Withdraw }, + }; + + private static Emitter Thing(ulong id, uint kind, float x, ulong facts = 0UL) => + new(Channel.Visual, x, 0f, 0f, 100f, 1.0, id, kind, facts); + + private static Emitter BoltedDoor(ulong facts = 0UL) => Thing(1, Door, 6f, (1UL << Locked) | (1UL << Latched) | facts); + + // Idle (1) against the door goal (3, direct at the discount 0.5: 1.5); the bolted door is four steps from open, past a depth of 3. + private static Brain Make(double frustration = 1.0, double retry = 30.0, int depth = 3, double dwell = 0.0) => new() + { + PlanDepth = depth, DirectDiscount = 0.5, FrustrationSeconds = frustration, RetrySeconds = retry, + Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open), dwell) }, + }; + + private static Actor Build(Brain brain, double memory = 5.0, IReadOnlyList? verbs = null) => + new(Dt, 1, new NerveParameters(), new WithdrawalParameters(), new DriveParameters(), brain, + new NerveParameters { Threshold = 0.05, SensitisationGrowth = 0.0, ConductionDelaySeconds = 0.0 }, 0, + new PerceptParameters { Capacity = 8, MemorySeconds = memory }, verbs: verbs ?? Catalogue()); + + private sealed class Bench + { + public readonly Actor A; + public readonly float[] Strengths = new float[2]; + public readonly Quat[] Targets = new Quat[2]; + public readonly List Frustrated = new(); + + public Bench(Actor a) => A = a; + + public long Now => A.TickCount; + + public TickEvents Step(Emitter[] emitters, ulong selfFacts = 0UL) + { + var t = A.TickCount; + var events = A.Tick(Zero, Zero, Zero, NoBoxes, Strengths, Targets, emitters, selfFacts: selfFacts); + if ((events & TickEvents.Frustrated) != 0) + { + Frustrated.Add(t); + } + + return events; + } + + public void Run(int ticks, Emitter[] emitters, ulong selfFacts = 0UL) + { + for (var i = 0; i < ticks; i++) + { + Step(emitters, selfFacts); + } + } + + // Runs until the first tick that leaves PlanLength -1 and returns that tick's number (the pair's first direct tick). + public long RunToDirect(Emitter[] emitters, ulong selfFacts = 0UL) + { + for (var i = 0; i < 500; i++) + { + var t = A.TickCount; + Step(emitters, selfFacts); + if (A.PlanLength == -1) + { + return t; + } + } + + throw new InvalidOperationException("He never went direct."); + } + + // Runs until Frustrated and returns its tick. + public long RunToFrustration(Emitter[] emitters, ulong selfFacts = 0UL) + { + for (var i = 0; i < 2000; i++) + { + if ((Step(emitters, selfFacts) & TickEvents.Frustrated) != 0) + { + return Frustrated[^1]; + } + } + + throw new InvalidOperationException("He never frustrated."); + } + } + + [Fact] + public void A_bolted_door_tried_direct_frustrates_exactly_on_time() + { + var b = new Bench(Build(Make())); + var door = new[] { BoltedDoor() }; + var direct = b.RunToDirect(door); + Assert.Equal(1, b.A.GoalIndex); + Assert.Equal(-1, b.A.PlanLength); + var frustrated = direct + 100; // FrustrationSeconds 1.0 is 100 ticks + while (b.Now < frustrated) // none a tick early + { + Assert.Equal(TickEvents.None, b.Step(door) & TickEvents.Frustrated); + Assert.Equal(1, b.A.GoalIndex); + } + + Assert.Equal(TickEvents.Frustrated, b.Step(door) & TickEvents.Frustrated); // once, on the tick + Assert.Equal(new[] { frustrated }, b.Frustrated); + for (var i = 0; i < Latency - 1; i++) + { + b.Step(door); + Assert.Equal(1, b.A.GoalIndex); // the decision commits a latency later, not before + } + + b.Step(door); + Assert.Equal(0, b.A.GoalIndex); + Assert.Equal(0UL, b.A.TargetId); + b.Run(300, door); + Assert.Equal(0, b.A.GoalIndex); // barred: he does not go back + Assert.Single(b.Frustrated); + } + + [Fact] + public void Frustration_decides_again_past_the_dwell() + { + var b = new Bench(Build(Make(dwell: 60.0))); + var door = new[] { BoltedDoor() }; + b.RunToFrustration(door); + b.Run(Latency, door); + Assert.Equal(0, b.A.GoalIndex); // MinDwellSeconds 60 would have held the goal for 6000 ticks + } + + [Fact] + public void Alone_he_lets_go_of_the_target_and_does_not_frustrate_again() + { + var brain = new Brain + { + PlanDepth = 3, FrustrationSeconds = 1.0, RetrySeconds = 30.0, + Goals = new[] { Goal("open", 3.0, Kinds(Door), This(Open)) }, + }; + var b = new Bench(Build(brain)); + var door = new[] { BoltedDoor() }; + b.RunToFrustration(door); + b.Run(Latency, door); + Assert.Equal(0, b.A.GoalIndex); + Assert.Equal(0UL, b.A.TargetId); + Assert.Equal(0, b.A.PlanLength); + b.Run(1000, door); + Assert.Equal(0UL, b.A.TargetId); + Assert.Single(b.Frustrated); + } + + [Fact] + public void The_door_is_tried_again_after_the_retry() + { + var b = new Bench(Build(Make(retry: 2.0))); + var door = new[] { BoltedDoor() }; + var first = b.RunToFrustration(door); + b.Run(1000, door); + // The bar lifts 200 ticks on, the decision commits a latency later, and 100 ticks of direct try end in the next frustration. + Assert.Equal(first + 200 + Latency + 100, b.Frustrated[1]); + Assert.Equal(first + 2 * (200 + Latency + 100), b.Frustrated[2]); + } + + [Fact] + public void Infinite_seconds_never_frustrate_and_never_retry() + { + var door = new[] { BoltedDoor() }; + var never = new Bench(Build(Make(frustration: double.PositiveInfinity))); + never.Run(3000, door); + Assert.Empty(never.Frustrated); + Assert.Equal(1, never.A.GoalIndex); + Assert.Equal(-1, never.A.PlanLength); + + var stuck = new Bench(Build(Make(retry: double.PositiveInfinity))); + stuck.Run(5000, door); + Assert.Single(stuck.Frustrated); + Assert.Equal(0, stuck.A.GoalIndex); + } + + [Fact] + public void A_changed_fact_a_changed_self_fact_or_a_forgotten_door_lifts_the_bar_at_once() + { + // Barred, idle in force; then the change; the door goal is back in force a latency (and a tick) later. + void Lifts(Action change) + { + var b = new Bench(Build(Make(), memory: 0.5)); + var door = new[] { BoltedDoor() }; + b.RunToFrustration(door); + b.Run(Latency + 20, door); + Assert.Equal(0, b.A.GoalIndex); + change(b, door); + Assert.Equal(1, b.A.GoalIndex); + Assert.Equal(1UL, b.A.TargetId); + } + + Lifts((b, _) => b.Run(Latency + 2, new[] { BoltedDoor(1UL << Noise) })); // an unrelated bit of the door's facts + Lifts((b, door) => b.Run(Latency + 2, door, 1UL << Noise)); // an unrelated self fact + Lifts((b, _) => + { + b.Run(60, None); // the door leaves memory (0.5 s) + b.Run(Latency + 2, new[] { BoltedDoor() }); // and is sensed again, unchanged + }); + + // With nothing changed the bar holds well past all of that. + var held = new Bench(Build(Make(), memory: 0.5)); + var same = new[] { BoltedDoor() }; + held.RunToFrustration(same); + held.Run(Latency + 200, same); + Assert.Equal(0, held.A.GoalIndex); + } + + [Fact] + public void A_barred_pair_that_now_plans_is_offered() + { + var b = new Bench(Build(Make(), verbs: WithPry())); + var door = new[] { BoltedDoor() }; + b.RunToFrustration(door); + b.Run(Latency + 20, door); + Assert.Equal(0, b.A.GoalIndex); + // A held knife appears: the door's facts and his own are unchanged, so the bar stands, but the pair now plans (approach, pry) and is not a direct try. + b.Run(Latency + 2, new[] { BoltedDoor(), Thing(2, Knife, 1f, 1UL << Held) }); + Assert.Equal(1, b.A.GoalIndex); + Assert.Equal(1UL, b.A.TargetId); + Assert.Equal(2, b.A.PlanLength); + Assert.Single(b.Frustrated); + } + + [Fact] + public void Impatience_lasts_one_select() + { + // Calm and idle tie on priority (1), so a switch between them is never accepted on priority; calm scores 1 direct, idle 0.9. + var brain = new Brain + { + PlanDepth = 3, DirectDiscount = 1.0, FrustrationSeconds = 1.0, RetrySeconds = 30.0, Start = 0, + Goals = new[] + { + Goal("calm", 1.0, null, Self(Fed), 60.0), + Goal("idle", 1.0, dwell: 60.0) with { Considerations = new[] { new Consideration(ConsiderationInput.Drive, 0.0, 1.0, 0.9, 0.9, 1.0, DriveQuantity.Pain) } }, + }, + }; + var b = new Bench(Build(brain)); + b.RunToFrustration(None); + b.Run(Latency, None); + Assert.Equal(1, b.A.GoalIndex); // past calm's 60 s dwell, by impatience + b.Run(Latency + 2, None, 1UL << Held); // the bar lifts, calm scores 1 against idle's 0.9, but idle's own dwell holds and there is no impatience left + Assert.Equal(1, b.A.GoalIndex); + } + + [Fact] + public void The_timer_starts_again_when_one_direct_try_replaces_another() + { + var brain = new Brain + { + PlanDepth = 3, DirectDiscount = 0.5, FrustrationSeconds = 1.0, RetrySeconds = 30.0, + Goals = new[] { Goal("idle", 1.0), Goal("open", 3.0, Kinds(Door), This(Open)), Goal("calm", 4.0, null, Self(Fed)) }, + }; + var b = new Bench(Build(brain)); + var door = new[] { BoltedDoor() }; + b.RunToDirect(door, 1UL << Fed); // fed, so only the door is tried + b.Run(60, door, 1UL << Fed); + long calmSince; + for (; ; ) + { + var t = b.Now; + b.Step(door); // hungry: calm outranks and replaces him at the door, direct as well + if (b.A.GoalIndex == 2) + { + calmSince = t; + break; + } + } + + Assert.Equal(-1, b.A.PlanLength); + Assert.Equal(calmSince + 100, b.RunToFrustration(door)); + } + + [Fact] + public void Depth_zero_frustrates_like_any_direct_try() + { + var b = new Bench(Build(Make(depth: 0))); + var door = new[] { Thing(1, Door, 6f) }; // even a plain door is direct at depth 0 + var direct = b.RunToDirect(door); + var f = b.RunToFrustration(door); + Assert.Equal(direct + 100, f); + b.Run(Latency, door); + Assert.Equal(0, b.A.GoalIndex); + } + + [Fact] + public void A_self_want_with_no_target_frustrates_and_lifts_on_a_self_fact() + { + var brain = new Brain + { + PlanDepth = 3, DirectDiscount = 0.5, FrustrationSeconds = 1.0, RetrySeconds = 30.0, + Goals = new[] { Goal("idle", 1.0), Goal("calm", 3.0, null, Self(Fed)) }, + }; + var b = new Bench(Build(brain)); + b.RunToFrustration(None); + b.Run(Latency + 20, None); + Assert.Equal(0, b.A.GoalIndex); + b.Run(Latency + 2, None, 1UL << Held); // a self fact changes: the bar lifts, the try resumes + Assert.Equal(1, b.A.GoalIndex); + Assert.Equal(0UL, b.A.TargetId); + Assert.Equal(-1, b.A.PlanLength); + } + + [Fact] + public void Zero_seconds_frustrate_once_not_every_tick() + { + var b = new Bench(Build(Make(frustration: 0.0))); + var door = new[] { BoltedDoor() }; + b.Run(400, door); + Assert.Single(b.Frustrated); + Assert.Equal(0, b.A.GoalIndex); + } + + [Fact] + public void Frustration_is_deterministic_and_allocates_nothing_in_a_cycle() + { + List Trace(out int goal) + { + var b = new Bench(Build(Make(frustration: 0.5, retry: 1.0))); + b.Run(1500, new[] { BoltedDoor() }); + goal = b.A.GoalIndex; + return b.Frustrated; + } + + var one = Trace(out var goalOne); + var two = Trace(out var goalTwo); + Assert.True(one.Count >= 5); + Assert.Equal(one, two); + Assert.Equal(goalOne, goalTwo); + + // Frustrate, lift by retry, try again: the cycle repeats every 160 ticks. Nothing is allocated once it has run. + var a = Build(Make(frustration: 0.5, retry: 1.0)); + var door = new[] { BoltedDoor() }; + var strengths = new float[2]; + var targets = new Quat[2]; + for (var i = 0; i < 1000; i++) + { + a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, door); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + var events = TickEvents.None; + for (var i = 0; i < 1000; i++) + { + events |= a.Tick(Zero, Zero, Zero, NoBoxes, strengths, targets, door); + } + + var after = GC.GetAllocatedBytesForCurrentThread(); + Assert.True((events & TickEvents.Frustrated) != 0); // the window held at least one full cycle + Assert.Equal(0L, after - before); + } + + [Fact] + public void Validation_refuses_NaN_and_negatives_and_accepts_infinity() + { + foreach (var bad in new[] { double.NaN, -1.0, double.NegativeInfinity }) + { + Assert.Throws(() => Build(Make(frustration: bad))); + Assert.Throws(() => Build(Make(retry: bad))); + } + + Build(Make(frustration: double.PositiveInfinity, retry: double.PositiveInfinity)); + Build(Make(frustration: 0.0, retry: 0.0)); + } +}