diff --git a/src/BadDay.Cli/Program.cs b/src/BadDay.Cli/Program.cs index 81a7391..9babd4b 100644 --- a/src/BadDay.Cli/Program.cs +++ b/src/BadDay.Cli/Program.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Globalization; using BadDay.Core; using BadDay.Ymir; -using Lodur; namespace BadDay.Cli; @@ -16,12 +15,12 @@ public static class Program baddaysim run --seed N --body [options] the same run on the Ymir ragdoll, with the hand-out time baddaysim sweep --seed N --count M [options] seeds N..N+M-1, break-time summary - baddaysim office --seed N [office options] the office: stressors fill the stress bar, one run + baddaysim office --seed N [office options] the office: stressors fill the stress bar, the will breaks, the rage follows baddaysim office-sweep --seed N --count M [office options] options (all numbers, seconds unless noted): --intensity X box intensity 0..1 (default 0.8) - --pull X objective pull 0..1 (default 0.5) + --pay DOLLARS what the volunteer is paid: the pull is pay / (pay + 100) (default 100, pull 0.5) --disable-at S box switches off at S (default never) --max S give up after S (default 120) --every S timeline sample interval (default 1) @@ -29,14 +28,14 @@ public static class Program office options: --silence ID@S silence stressor ID from S seconds (repeatable; ids: printer, ceiling-light, desk-phone, desktop-interrupt) --scale X every stressor's intensity times X (default 1) - --pull X objective pull 0..1 (default 0.6) + --pull X the job's pull 0..1 (default 0.6) --max S give up after S (default 180) --every S timeline sample interval (default 1) """; private const string Title = "Synaptic Induction Chamber (the pain box)"; - private static readonly string OfficeTitle = $"Bad day at the office, rung 3 (stress = 1 - resolve, \"{StressResult.StressBarLabel}\")"; + private static readonly string OfficeTitle = $"Bad day at the office, rung 4 (stress = 1 - resolve, \"{StressResult.StressBarLabel}\")"; public static int Main(string[] args) { @@ -57,10 +56,11 @@ public static class Program ulong seed = opts.TryGetValue("seed", out var s) ? ulong.Parse(s, CultureInfo.InvariantCulture) : throw new ArgumentException("--seed is required"); if (args[0].StartsWith("office")) return ExecuteOffice(args[0] == "office-sweep", seed, opts, output); + if (opts.ContainsKey("pull")) throw new ArgumentException("--pull applies to office; the chamber takes --pay"); var p = new PainBoxParameters { BoxIntensity = Num(opts, "intensity", 0.8), - Drive = new DriveParameters { ObjectivePull = Num(opts, "pull", 0.5) }, + Payment = Num(opts, "pay", 100), BoxDisableAtSeconds = opts.ContainsKey("disable-at") ? Num(opts, "disable-at", 0) : null, MaxSeconds = Num(opts, "max", 120), SampleEverySeconds = Num(opts, "every", 1), @@ -99,6 +99,7 @@ public static class Program private static int ExecuteOffice(bool sweep, ulong seed, Dictionary opts, System.IO.TextWriter output) { if (opts.ContainsKey("body")) throw new ArgumentException("--body applies to run"); + if (opts.ContainsKey("pay")) throw new ArgumentException("--pay applies to run and sweep; the office takes --pull"); var defaults = new StressParameters(); var p = defaults with { diff --git a/src/BadDay.Core/ChamberBrain.cs b/src/BadDay.Core/ChamberBrain.cs new file mode 100644 index 0000000..ccaef26 --- /dev/null +++ b/src/BadDay.Core/ChamberBrain.cs @@ -0,0 +1,65 @@ +using System; +using Lodur; + +namespace BadDay.Core; + +/// +/// The Synaptic Induction Chamber's Brain: what the volunteer wants to be doing, authored as data for Lodur's Actor to +/// run. He holds his hand in the box for the payment (the objective, pulling Payment / (Payment + DollarsAtHalfPull)) +/// until the will breaks, then withdraws. No session decides a switch; the Actor commits the Brain's choice, so the +/// goal column of every timeline is read back from . +/// +public static class ChamberBrain +{ + public const int HoldIndex = 0; + public const int WithdrawIndex = 1; + + /// The objective's pull for the payment: 0 for nothing, 0.5 at , toward 1 for more. + public static double Pull(PainBoxParameters p) + { + if (!(p.Payment >= 0.0 && double.IsFinite(p.Payment))) throw new ArgumentException($"Payment must be finite and not negative, got {p.Payment}."); + if (!(p.DollarsAtHalfPull > 0.0 && double.IsFinite(p.DollarsAtHalfPull))) throw new ArgumentException($"DollarsAtHalfPull must be finite and positive, got {p.DollarsAtHalfPull}."); + return p.Payment / (p.Payment + p.DollarsAtHalfPull); + } + + /// The chamber's display name for the goal at of this Brain. + public static Goal GoalAt(int index) => index == WithdrawIndex ? Goal.Withdraw : Goal.HoldHand; + + /// + /// hold-hand: always eligible, priority 0, the payment's pull, the hold pose with the reflex leak and strain shake + /// pulling toward the withdraw pose. withdraw: eligible once the will has broken, priority 1, no pull, the withdraw + /// pose with no leak or shake. + /// + public static Brain Build(PainBoxParameters p, ReadOnlySpan hold, ReadOnlySpan withdraw) + { + var holdPose = hold.ToArray(); + var withdrawPose = withdraw.ToArray(); + return new Brain + { + Start = HoldIndex, + Goals = new[] + { + new GoalSpec + { + Id = "hold-hand", + Priority = 0.0, + Pull = Pull(p), + Behaviour = new PoseBehaviour { Keys = new[] { holdPose }, FlinchPose = withdrawPose, Hold = p.Hold }, + }, + new GoalSpec + { + Id = "withdraw", + Priority = 1.0, + Pull = 0.0, + When = new[] { new Condition(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0) }, + Behaviour = new PoseBehaviour + { + Keys = new[] { withdrawPose }, + FlinchPose = withdrawPose, + Hold = p.Hold with { FlinchGain = 0.0, StrainShake = 0.0 }, + }, + }, + }, + }; + } +} diff --git a/src/BadDay.Core/OfficeBrain.cs b/src/BadDay.Core/OfficeBrain.cs new file mode 100644 index 0000000..d2363ec --- /dev/null +++ b/src/BadDay.Core/OfficeBrain.cs @@ -0,0 +1,62 @@ +using System; +using Lodur; + +namespace BadDay.Core; + +/// What the office timeline's goal column names: the goal in force, by 's index. Display only. +public enum OfficeGoal { KeepComposure, Rage } + +/// +/// The poses Office Fella's goals write, one rotation per muscle: the composed pose he holds while he keeps his +/// composure (and the pose a leak would pull toward), and the keys the rage walks in a loop. The body supplies them +/// (OfficeBody.Poses); the headless run, which has no body, takes . +/// +public sealed record OfficePoses(Quat[] Composed, Quat[] Flinch, Quat[][] RageKeys) +{ + /// One muscle, every pose the identity: the headless run's behaviour has no body to move. + public static OfficePoses Identity { get; } = new( + new[] { Quat.Identity }, new[] { Quat.Identity }, + new[] { new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity }, new[] { Quat.Identity } }); +} + +/// +/// Office Fella's Brain: keep-composure (the job, pulling with ) until the will +/// breaks, then rage (a geyser: no pull, nothing held down, the rage keys in a loop). Authored as data; the Actor +/// commits the switch, so the timeline's goal column is read back from . +/// +public static class OfficeBrain +{ + public const int ComposureIndex = 0; + public const int RageIndex = 1; + + public static OfficeGoal GoalAt(int index) => index == RageIndex ? OfficeGoal.Rage : OfficeGoal.KeepComposure; + + public static Brain Build(StressParameters p, OfficePoses poses) => new() + { + Start = ComposureIndex, + Goals = new[] + { + new GoalSpec + { + Id = "keep-composure", + Priority = 0.0, + Pull = p.Cause.ObjectivePull, + Behaviour = new PoseBehaviour { Keys = new[] { poses.Composed }, FlinchPose = poses.Flinch, Hold = p.Hold }, + }, + new GoalSpec + { + Id = "rage", + Priority = 1.0, + Pull = 0.0, + When = new[] { new Condition(DriveQuantity.WillBroken, ConditionOp.AtLeast, 1.0) }, + Behaviour = new PoseBehaviour + { + Keys = poses.RageKeys, + SecondsPerKey = p.RageKeySeconds, + FlinchPose = poses.RageKeys[0], + Hold = p.Hold with { HoldStrength = 1f, FlinchGain = 0.0, StrainShake = 0.0 }, + }, + }, + }, + }; +} diff --git a/src/BadDay.Core/PainBoxParameters.cs b/src/BadDay.Core/PainBoxParameters.cs index dc793e5..0353e59 100644 --- a/src/BadDay.Core/PainBoxParameters.cs +++ b/src/BadDay.Core/PainBoxParameters.cs @@ -19,13 +19,18 @@ public sealed record PainBoxParameters /// When set, the box switches off at this time (the game disables it). public double? BoxDisableAtSeconds { get; init; } - // The nervous model is Lodur's: nerve, drive, reflex and the hold behaviour keep their records and defaults. - // Hold matters to the body run only; the headless run ignores what it writes. + // The nervous model is Lodur's: nerve, drive and reflex keep their records and defaults. Hold is the hold goal's pose + // behaviour (the body run's; the headless run ignores what it writes). The goals themselves are ChamberBrain's. public Lodur.NerveParameters Nerve { get; init; } = new(); public Lodur.DriveParameters Drive { get; init; } = new(); public Lodur.WithdrawalParameters Reflex { get; init; } = new(); public Lodur.HoldParameters Hold { get; init; } = new(); + // The objective: the volunteer is paid, and the payment sets how hard holding the hand in the box pulls + // (ChamberBrain.Pull: Payment / (Payment + DollarsAtHalfPull), so DollarsAtHalfPull is the payment that pulls half). [P] + public double Payment { get; init; } = 100.0; + public double DollarsAtHalfPull { get; init; } = 100.0; + // Per-seed trait spread (fraction): nociceptor gain and resolve drain. The seed's draw multiplies Nerve.Gain and Drive.DrainTrait. public double TraitJitter { get; init; } = 0.2; diff --git a/src/BadDay.Core/PainBoxSession.cs b/src/BadDay.Core/PainBoxSession.cs index ce0ab64..f0189a0 100644 --- a/src/BadDay.Core/PainBoxSession.cs +++ b/src/BadDay.Core/PainBoxSession.cs @@ -39,7 +39,7 @@ public sealed class PainBoxSession double drainTrait = 1.0 + p.TraitJitter * rng.NextSigned(); Seed = seed; Actor = new Actor(p.TickSeconds, regionCount, p.Nerve with { Gain = p.Nerve.Gain * gainTrait }, p.Reflex, - p.Drive with { DrainTrait = p.Drive.DrainTrait * drainTrait }, p.Hold, holdPose, withdrawPose); + p.Drive with { DrainTrait = p.Drive.DrainTrait * drainTrait }, ChamberBrain.Build(p, holdPose, withdrawPose)); _box = new PainBox(p, rng); _sources = new[] { box }; _maxTick = Ticks(p.MaxSeconds); @@ -59,7 +59,7 @@ public sealed class PainBoxSession /// True once the run is over: the box was disabled, the time ran out, or the caller ended it. public bool Finished { get; private set; } - /// True from the tick the deliberate withdrawal begins. + /// True from the tick the Brain's withdraw goal takes over, its deliberate latency after the will breaks. public bool Withdrew { get; private set; } /// Sets the box intensity the ramp scales; it takes effect on the next . owns the range and refuses a level outside it. @@ -75,7 +75,7 @@ public sealed class PainBoxSession public bool Disabled() { long tick = TickIndex; - if (tick != _box.DisableTick || Actor.Goal != Lodur.Goal.Hold) return false; + if (tick != _box.DisableTick || Actor.Drive.WillBroken) return false; _stimulus = 0.0; _outcome = Outcome.BoxDisabled; _endTick = tick; @@ -107,7 +107,7 @@ public sealed class PainBoxSession Log(tick, EntryKind.WillBroke); } if (tick % _sampleEvery == 0) Log(tick, EntryKind.Sample); - if ((events & TickEvents.Withdrew) != 0) + if ((events & TickEvents.GoalChanged) != 0) { Withdrew = true; _outcome = Outcome.WillBroke; @@ -142,6 +142,6 @@ public sealed class PainBoxSession { var d = Actor.Drive; _timeline.Add(new TimelineEntry(Ms(tick), kind, _stimulus, d.Pain, d.Strain, d.Resolve, - Actor.Goal == Lodur.Goal.Withdraw ? Goal.Withdraw : Goal.HoldHand)); + ChamberBrain.GoalAt(Actor.GoalIndex))); } } diff --git a/src/BadDay.Core/StressParameters.cs b/src/BadDay.Core/StressParameters.cs index c74f069..642da4b 100644 --- a/src/BadDay.Core/StressParameters.cs +++ b/src/BadDay.Core/StressParameters.cs @@ -2,7 +2,7 @@ namespace BadDay.Core; /// /// Every tunable of the office stress scenario: the clock, the setting, the cause, and Lodur's parameter records -/// as members. The cause's pull and sense nerve win over Drive.ObjectivePull and are the only senses. +/// as members. The cause's pull is the keep-composure goal's, and its sense nerve is the only sense. /// Defaults are placeholders, not measured. /// public sealed record StressParameters @@ -11,10 +11,16 @@ public sealed record StressParameters public double MaxSeconds { get; init; } = 180.0; public double SampleEverySeconds { get; init; } = 1.0; + /// How long the run goes on after the rage takes over, seconds [P]: the geyser is seen, then the run ends. + public double ReleaseSeconds { get; init; } = 6.0; + + /// Seconds from one rage key to the next [P]: wind-up left, strike left, wind-up right, strike right. + public double RageKeySeconds { get; init; } = 0.25; + public Setting Setting { get; init; } = Setting.Office; public Cause Cause { get; init; } = Cause.Office; - // Lodur's records. The noxious nerve and the reflex idle here (no box); Hold is the body's, which this run ignores. + // Lodur's records. The noxious nerve and the reflex idle here (no box); Hold is the composure goal's pose behaviour, which only a body reads. public Lodur.NerveParameters Nerve { get; init; } = new(); public Lodur.DriveParameters Drive { get; init; } = new(); public Lodur.WithdrawalParameters Reflex { get; init; } = new(); diff --git a/src/BadDay.Core/StressResult.cs b/src/BadDay.Core/StressResult.cs index fe17c30..b61be4e 100644 --- a/src/BadDay.Core/StressResult.cs +++ b/src/BadDay.Core/StressResult.cs @@ -4,20 +4,21 @@ using System.Text; namespace BadDay.Core; -public enum StressEntryKind { Sample, Silenced, WillBroke, Endured } +public enum StressEntryKind { Sample, Silenced, WillBroke, GoalChanged, Endured } /// One timeline row: end-of-tick state read from the Actor. Audio, Visual and Interrupt are the stimulus that reached the head on each channel. public readonly record struct StressEntry( long TimeMs, StressEntryKind Kind, double Audio, double Visual, double Interrupt, - double Load, double Arousal, double Resolve, Goal Goal); + double Load, double Arousal, double Resolve, OfficeGoal Goal); /// A player's command to silence one stressor from on. public readonly record struct SilenceCommand(string StressorId, double AtSeconds); public sealed record StressResult( ulong Seed, - /// WillBroke or Endured; the office has no box to disable. + /// WillBroke (the run goes on through the release) or Endured; the office has no box to disable. Outcome Outcome, + /// When the run ended: the release after the rage took over, or MaxSeconds. long EndMs, /// Time resolve hit zero, ms; null unless the will broke. long? TimeToBreakMs, diff --git a/src/BadDay.Core/StressSession.cs b/src/BadDay.Core/StressSession.cs index b06fd51..829dd1a 100644 --- a/src/BadDay.Core/StressSession.cs +++ b/src/BadDay.Core/StressSession.cs @@ -9,7 +9,8 @@ namespace BadDay.Core; /// , and the recorder. The headless run, the sweep, the CLI and a client all drive it one /// per step, and the player's lever is . The session never writes drive /// state, computes load or arousal, or holds a stress field: rows are end-of-tick state read from the Actor, and -/// nothing reads them back. It ends where the will breaks (rung 4 continues past it) or at MaxSeconds. +/// nothing reads them back. The rage is the Brain's (): the session goes on past the break, logs the +/// tick the Actor commits the switch, and ends ReleaseSeconds after it, or at MaxSeconds. /// public sealed class StressSession { @@ -22,13 +23,14 @@ public sealed class StressSession private readonly List _timeline = new(); private readonly long _maxTick; private readonly long _sampleEvery; + private readonly long _releaseTicks; private long _breakTick = -1; private double _minResolve = 1.0; private Outcome _outcome = Outcome.Endured; private long _endTick; - public StressSession(StressParameters p, ulong seed, int regionCount, - ReadOnlySpan holdPose, ReadOnlySpan withdrawPose, int senseRegion = 0) + /// What the Brain's goals write, one rotation per muscle; the Actor's muscle count is theirs. + public StressSession(StressParameters p, ulong seed, int regionCount, OfficePoses poses, int senseRegion = 0) { _p = p; _stressors = new Stressor[p.Cause.Stressors.Count]; @@ -60,11 +62,12 @@ public sealed class StressSession double drainTrait = 1.0 + p.TraitJitter * _rng.NextSigned(); Seed = seed; Actor = new Actor(p.TickSeconds, regionCount, p.Nerve, p.Reflex, - p.Drive with { ObjectivePull = p.Cause.ObjectivePull, DrainTrait = p.Drive.DrainTrait * drainTrait }, - p.Hold, holdPose, withdrawPose, + p.Drive with { DrainTrait = p.Drive.DrainTrait * drainTrait }, + OfficeBrain.Build(p, poses), p.Cause.Senses with { Gain = p.Cause.Senses.Gain * gainTrait }, senseRegion); _maxTick = Ticks(p.MaxSeconds); _sampleEvery = Math.Max(1, Ticks(p.SampleEverySeconds)); + _releaseTicks = Ticks(p.ReleaseSeconds); _endTick = _maxTick; } @@ -77,7 +80,7 @@ public sealed class StressSession /// Ticks run so far; the tick the next runs. public long TickIndex => Actor.TickCount; - /// True once the will has broken or the time ran out. + /// True once the release after the rage took over is over, or the time ran out. public bool Finished { get; private set; } /// @@ -116,14 +119,17 @@ public sealed class StressSession { _breakTick = tick; _outcome = Outcome.WillBroke; - _endTick = tick; Log(tick, StressEntryKind.WillBroke); } if (tick % _sampleEvery == 0) Log(tick, StressEntryKind.Sample); - if (_outcome == Outcome.WillBroke) Finished = true; - else if (tick >= _maxTick) + if ((events & TickEvents.GoalChanged) != 0) { - Log(tick, StressEntryKind.Endured); + _endTick = Math.Min(_maxTick, tick + _releaseTicks); + Log(tick, StressEntryKind.GoalChanged); + } + if (tick >= _endTick) + { + if (_outcome == Outcome.Endured) Log(tick, StressEntryKind.Endured); Finished = true; } return events; @@ -148,6 +154,6 @@ public sealed class StressSession _timeline.Add(new StressEntry(Ms(tick), kind, Actor.ChannelStimulus(Channel.Audio), Actor.ChannelStimulus(Channel.Visual), Actor.ChannelStimulus(Channel.Interrupt), Actor.Load, d.Arousal, d.Resolve, - Actor.Goal == Lodur.Goal.Withdraw ? Goal.Withdraw : Goal.HoldHand)); + OfficeBrain.GoalAt(Actor.GoalIndex))); } } diff --git a/src/BadDay.Core/StressSimulation.cs b/src/BadDay.Core/StressSimulation.cs index d47ec51..fed0834 100644 --- a/src/BadDay.Core/StressSimulation.cs +++ b/src/BadDay.Core/StressSimulation.cs @@ -7,15 +7,14 @@ namespace BadDay.Core; /// /// The headless office: one virtual human with the head fixed at the sense point, run through -/// to the break or MaxSeconds. The silences are what a player would have done, each +/// to the end of the release after the break, or MaxSeconds. The silences are what a player would have done, each /// applied at the tick its time falls on, before that tick runs. /// public static class StressSimulation { public static StressResult Run(StressParameters p, ulong seed, IReadOnlyList? silences = null) { - var pose = new[] { Quat.Identity }; - var session = new StressSession(p, seed, 1, pose, pose); + var session = new StressSession(p, seed, 1, OfficePoses.Identity); var point = new float[1]; // the head sits at the origin var strengths = new float[1]; // the behaviour's output has no body to move var targets = new Quat[1]; diff --git a/src/BadDay.Ymir/BodyPainBox.cs b/src/BadDay.Ymir/BodyPainBox.cs index d7a2e3d..a249ebd 100644 --- a/src/BadDay.Ymir/BodyPainBox.cs +++ b/src/BadDay.Ymir/BodyPainBox.cs @@ -57,8 +57,7 @@ public static class BodyPainBox public readonly record struct BodyEvent(long Tick, TickEvents Events); /// -/// One body run, stepped by its caller: BDS creates the Ymir world (a ground, a static stool box welded to the pelvis -/// because the PD ragdoll cannot balance for 15 s, the ragdoll, the box volume around the right hand's hold +/// One body run, stepped by its caller: BDS creates the Ymir world ('s ground, stool and ragdoll, the box volume around the right hand's hold /// point) and is its only stepper; the nervous session inside it is never exposed, so nothing else can tick it. /// Per : the box writes its intensity, the body reports its hand points, Lodur's Actor decides, /// the ragdoll is driven, the world steps. The run ends on the Actor's events, never on the hand: after the @@ -75,9 +74,6 @@ public sealed class BodyPainBoxSession : IDisposable { private const float BoxHalf = 0.12f; - /// Physics substeps per 1/120 s step. The ragdoll gains were tuned against 4; the behaviour tests, not this number, are the rule. - private const int Substeps = 4; - /// After the deliberate withdrawal begins the run waits this long for the hand to come out. private const double SettleSeconds = 1.0; @@ -110,13 +106,11 @@ public sealed class BodyPainBoxSession : IDisposable } _p = p; - _world = new Box3DSoaWorld(capacity: HumanoidRagdoll.LimbCount + 2, jointCapacity: HumanoidRagdoll.MuscleCount + 1); + var needs = SeatedPuppet.Needs; + _world = new Box3DSoaWorld(capacity: needs.Bodies, jointCapacity: needs.Joints); try { - _world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f); - var stool = _world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f); - _ragdoll = HumanoidRagdoll.Build(_world, (0f, 0f), firstStableId: 100); - _world.AddJoint(Box3DSoaJointKind.Weld, stool, _ragdoll.BodyLane(Limb.Pelvis), (0f, 1.11f, -0.09f), (0f, 1f, 0f)); + _ragdoll = SeatedPuppet.Build(_world); // Hold: the right arm raised and bent so the hand sits in the box. Withdraw: the arm pulled back and folded. var hold = new Quat[HumanoidRagdoll.MuscleCount]; @@ -171,7 +165,7 @@ public sealed class BodyPainBoxSession : IDisposable public double Pain { get { Live(); return _session.Actor.Drive.Pain; } } public double Strain { get { Live(); return _session.Actor.Drive.Strain; } } public double Resolve { get { Live(); return _session.Actor.Drive.Resolve; } } - public Lodur.Goal Goal { get { Live(); return _session.Actor.Goal; } } + public Goal Goal { get { Live(); return ChamberBrain.GoalAt(_session.Actor.GoalIndex); } } /// One step of 1/120 s; see the type's summary for what it does after . public void Step() @@ -190,7 +184,7 @@ public sealed class BodyPainBoxSession : IDisposable if (ticked || wasFinished) { _ragdoll.Drive(_strengths, _targets); // after Finished: the last strengths and targets again - _world.Step((float)_p.TickSeconds, Substeps); + _world.Step((float)_p.TickSeconds, SeatedPuppet.Substeps); } var sample = ReadHand(); // the rest pose when the box was off at tick 0 diff --git a/src/BadDay.Ymir/SeatedPuppet.cs b/src/BadDay.Ymir/SeatedPuppet.cs new file mode 100644 index 0000000..06aae65 --- /dev/null +++ b/src/BadDay.Ymir/SeatedPuppet.cs @@ -0,0 +1,28 @@ +using Lodur.Body.Ymir; +using Ymir.Box3D; + +namespace BadDay.Ymir; + +/// +/// The one place BDS builds a seated puppet's world: a ground, a static stool box, the ragdoll, and the weld that +/// holds its pelvis to the stool, because the PD ragdoll cannot balance for the length of a scenario. Every body run +/// (the pain box, the office) builds through here, so no run has a world of its own. +/// +public static class SeatedPuppet +{ + /// Physics substeps per 1/120 s step. The ragdoll gains were tuned against 4; the behaviour tests, not this number, are the rule. + public const int Substeps = 4; + + /// Bodies and joints a world needs for : the ragdoll, the ground and the stool, and the weld. + public static (int Bodies, int Joints) Needs => (HumanoidRagdoll.LimbCount + 2, HumanoidRagdoll.MuscleCount + 1); + + /// Adds the ground, the stool, the ragdoll (stable ids from 100) and the pelvis weld to , which must be sized by . + public static HumanoidRagdoll Build(Box3DSoaWorld world) + { + world.AddStaticBox(1, (0f, -0.5f, 0f), (20f, 0.5f, 20f), friction: 0.8f); + var stool = world.AddStaticBox(2, (0f, 1.11f, -0.115f), (0.05f, 0.05f, 0.025f), friction: 0.8f); + var ragdoll = HumanoidRagdoll.Build(world, (0f, 0f), firstStableId: 100); + world.AddJoint(Box3DSoaJointKind.Weld, stool, ragdoll.BodyLane(Limb.Pelvis), (0f, 1.11f, -0.09f), (0f, 1f, 0f)); + return ragdoll; + } +} diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs index 53389bb..ec06252 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -54,8 +54,9 @@ public static class Program var broke = r.Timeline.Single(e => e.Kind == EntryKind.WillBroke); var out_ = r.Timeline.Single(e => e.Kind == EntryKind.Withdrew); Check(broke.TimeMs == r.TimeToBreakMs, "TimeToBreakMs disagrees with the timeline"); - Check(broke.Resolve == 0.0 && broke.Goal == Goal.Withdraw, "break entry should show resolve 0, goal Withdraw"); - Check(out_.TimeMs - broke.TimeMs == 100, $"latency {out_.TimeMs - broke.TimeMs} ms"); + // The goal is the Actor's: the withdraw goal takes over the latency after the break, not on it. + Check(broke.Resolve == 0.0 && broke.Goal == Goal.HoldHand, "break entry should show resolve 0, goal still HoldHand"); + Check(out_.TimeMs - broke.TimeMs == 100 && out_.Goal == Goal.Withdraw, $"latency {out_.TimeMs - broke.TimeMs} ms, goal {out_.Goal}"); Check(r.Timeline.Where(e => e.TimeMs < broke.TimeMs).All(e => e.Resolve > 0.0 && e.Goal == Goal.HoldHand), "resolve hit zero or goal changed before the recorded break"); }), @@ -67,11 +68,26 @@ public static class Program Check(Break(1.0) < Break(0.8) && Break(0.8) < Break(0.6), "break times not ordered by intensity"); }), - ("a stronger objective pull holds the will longer", () => + ("the volunteer's payment sets the pull: 0 pays 0, the default 100 pulls exactly half, 400 pulls 0.8, and the hold goal carries it", () => { - long Break(double pull) => - PainBoxSimulation.Run(Default with { Drive = Default.Drive with { ObjectivePull = pull } }, 5).TimeToBreakMs ?? long.MaxValue; - Check(Break(0.0) < Break(0.5) && Break(0.5) < Break(0.8), "break times not ordered by pull"); + double Pull(double pay) => ChamberBrain.Pull(Default with { Payment = pay }); + Check(Pull(0) == 0.0 && Pull(100) == 0.5 && Pull(400) == 0.8, $"pulls {Pull(0)}, {Pull(100)}, {Pull(400)}"); + Check(ChamberBrain.Pull(Default) == 0.5, "the default payment does not pull half"); + Check(ChamberBrain.Pull(Default with { Payment = 50, DollarsAtHalfPull = 50 }) == 0.5, "the pull is not the payment over the payment plus DollarsAtHalfPull"); + var brain = ChamberBrain.Build(Default with { Payment = 400 }, new[] { Quat.Identity }, new[] { Quat.Identity }); + Check(brain.Goals[ChamberBrain.HoldIndex].Pull == 0.8 && brain.Goals[ChamberBrain.WithdrawIndex].Pull == 0.0, "the Brain's pulls are not the payment's"); + foreach (var bad in new[] { Default with { Payment = -1 }, Default with { Payment = double.NaN }, Default with { Payment = double.PositiveInfinity }, Default with { DollarsAtHalfPull = 0 }, Default with { DollarsAtHalfPull = -5 } }) + { + bool threw = false; + try { PainBoxSimulation.Run(bad, 1); } catch (ArgumentException) { threw = true; } + Check(threw, $"payment {bad.Payment}, half-pull {bad.DollarsAtHalfPull} was accepted"); + } + }), + + ("a better paid volunteer holds the will longer: the break time rises strictly over payments 0, 20, 100, 400 (seed 5)", () => + { + long Break(double pay) => PainBoxSimulation.Run(Default with { Payment = pay }, 5).TimeToBreakMs ?? long.MaxValue; + Check(Break(0) < Break(20) && Break(20) < Break(100) && Break(100) < Break(400), "break times not ordered by payment"); }), ("disabling the box before the break ends the run with the will intact", () => @@ -87,6 +103,9 @@ public static class Program var plain = PainBoxSimulation.Run(Default, 1); var late = PainBoxSimulation.Run(Default with { BoxDisableAtSeconds = 60.0 }, 1); Check(plain.Render() == late.Render(), "a box disabled after the break altered the run"); + // Inside the withdrawal latency the goal is still HoldHand, but the will is broken and the box going off does not give it back. + var inLatency = PainBoxSimulation.Run(Default with { BoxDisableAtSeconds = 14.78 }, 1); + Check(inLatency.Outcome == Outcome.WillBroke && inLatency.TimeToBreakMs == plain.TimeToBreakMs && inLatency.EndMs == plain.EndMs, $"a box switched off inside the latency gave {inLatency.Outcome} ending at {inLatency.EndMs}"); }), ("no stimulus: nothing flinches and the run endures", () => @@ -348,7 +367,7 @@ public static class Program long ms = (long)Math.Round(e.Tick * 1000.0 / Hz); if ((e.Events & Lodur.TickEvents.Flinch) != 0) expanded.Add((ms, EntryKind.Flinch)); if ((e.Events & Lodur.TickEvents.WillBroke) != 0) expanded.Add((ms, EntryKind.WillBroke)); - if ((e.Events & Lodur.TickEvents.Withdrew) != 0) expanded.Add((ms, EntryKind.Withdrew)); + if ((e.Events & Lodur.TickEvents.GoalChanged) != 0) expanded.Add((ms, EntryKind.Withdrew)); } Check(expanded.SequenceEqual(rows), $"draining every {every} steps through {slots} slots: {expanded.Count} events against the Run's {rows.Count}, or out of order"); } @@ -449,6 +468,10 @@ public static class Program bool threw = false; try { Run("run"); } catch (ArgumentException) { threw = true; } Check(threw, "missing --seed should be rejected"); + threw = false; + try { Run("run", "--seed", "1", "--pull", "0.3"); } catch (ArgumentException) { threw = true; } + Check(threw, "the chamber takes --pay, not --pull"); + Check(Run("run", "--seed", "5", "--pay", "20") != Run("run", "--seed", "5", "--pay", "400"), "--pay changed nothing"); }), ("office: a stressor is silent before its onset, on for its duration, and back every period", () => @@ -610,17 +633,21 @@ public static class Program } }), - ("the pain box is untouched: run --seed 1 and sweep --seed 1 --count 20 hash to the output captured before the office existed", () => + ("pain box parity: sweep --seed 1 --count 20 hashes to the output before rung 4, and run --seed 1 does too once the break row's goal reads Withdraw as it then did", () => { - string Hash(params string[] a) + string Out(params string[] a) { var w = new StringWriter(); BadDay.Cli.Program.Execute(a, w); - var bytes = System.Text.Encoding.UTF8.GetBytes(w.ToString().Replace("\r\n", "\n")); - return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes)).ToLowerInvariant(); + return w.ToString().Replace("\r\n", "\n"); } - Check(Hash("run", "--seed", "1") == "a3a800612f1e610deb8c648ea74a0a3e2f4639541a46d92af0d1bcfbdd8cfb45", "run --seed 1 changed"); - Check(Hash("sweep", "--seed", "1", "--count", "20") == "2cc88f9ffbbf301b8264c0be600edb34b21a3b572f927ed96ea49eda20dc73db", "sweep --seed 1 --count 20 changed"); + string Hash(string s) => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(s))).ToLowerInvariant(); + Check(Hash(Out("sweep", "--seed", "1", "--count", "20")) == "2cc88f9ffbbf301b8264c0be600edb34b21a3b572f927ed96ea49eda20dc73db", "sweep --seed 1 --count 20 changed"); + var run = Out("run", "--seed", "1").Split('\n'); + int row = Array.FindIndex(run, l => l.Contains(" WillBroke ")); + Check(row > 0 && run[row].EndsWith(" HoldHand"), "the break row should read HoldHand, the goal in force"); + run[row] = run[row][..^" HoldHand".Length] + " Withdraw"; + Check(Hash(string.Join('\n', run)) == "a3a800612f1e610deb8c648ea74a0a3e2f4639541a46d92af0d1bcfbdd8cfb45", "run --seed 1 differs from the pre-rung-4 output in more than the break row's goal"); }), ("office CLI: office runs a timeline with the stress label, --silence repeats, office-sweep summarises", () => @@ -635,7 +662,7 @@ public static class Program Check(Run("office", "--seed", "1", "--scale", "0").Contains("endured to 180000 ms"), "--scale 0 should be a quiet office"); Check(Run("office", "--seed", "1", "--pull", "1").Contains("endured"), "--pull 1 never drains"); Check(Run("office-sweep", "--seed", "1", "--count", "5").Contains("min resolve of endured runs:"), "no sweep summary"); - foreach (var bad in new[] { new[] { "office" }, new[] { "office", "--seed", "1", "--silence", "printer" }, new[] { "office", "--seed", "1", "--silence", "nope@1" }, new[] { "office", "--seed", "1", "--body" } }) + foreach (var bad in new[] { new[] { "office" }, new[] { "office", "--seed", "1", "--silence", "printer" }, new[] { "office", "--seed", "1", "--silence", "nope@1" }, new[] { "office-sweep", "--seed", "1", "--body" }, new[] { "office", "--seed", "1", "--body", "--silence", "printer@1" }, new[] { "office", "--seed", "1", "--pay", "5" } }) { bool threw = false; try { Run(bad); } catch (ArgumentException) { threw = true; } @@ -684,7 +711,7 @@ public static class Program } }), - ("office golden [P]: office --seed 1 hashes to its captured bytes and the 50-seed sweep ends in its captured line", () => + ("office golden [P]: the rows up to the break are rung 3's bytes, the 50-seed sweep ends in its captured line, and the run's own bytes are captured", () => { string Out(params string[] a) { @@ -692,18 +719,53 @@ public static class Program BadDay.Cli.Program.Execute(a, w); return w.ToString().Replace("\r\n", "\n"); } - var hash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(Out("office", "--seed", "1")))).ToLowerInvariant(); - Check(hash == "66098b69834c3c8b5e5b694f0059b8ed566e31d332f36be7e57baf70ae650823", $"office --seed 1 changed: {hash}"); + string Hash(string s) => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(s))).ToLowerInvariant(); + var lines = Out("office", "--seed", "1").Split('\n', StringSplitOptions.RemoveEmptyEntries).ToList(); + int brk = lines.FindIndex(l => l.Contains(" WillBroke ")); + // Rung 3 ended at the break and named its goals HoldHand and Withdraw; what it printed up to there is what this prints, goal column aside. + var rung3 = new List { lines[0].Replace("rung 4", "rung 3"), lines[1] }; + for (int i = 2; i <= brk; i++) rung3.Add(lines[i].Replace(" KeepComposure", i == brk ? " Withdraw" : " HoldHand")); + rung3.Add(lines[^1]); + Check(Hash(string.Join('\n', rung3) + "\n") == "66098b69834c3c8b5e5b694f0059b8ed566e31d332f36be7e57baf70ae650823", "the office's rows up to the break differ from rung 3's"); + Check(Hash(string.Join('\n', lines) + "\n") == "006f712ff35052ff3f1497d67ecd6d20bd679de6bb3922714695a709fffa6ce4", $"office --seed 1 changed: {Hash(string.Join('\n', lines) + "\n")}"); var last = Out("office-sweep", "--seed", "1", "--count", "50").TrimEnd('\n').Split('\n')[^1]; Check(last == "runs 50: broke 50, endured 0; time to break min/median/max ms: 72670/86570/113420; min resolve of endured runs: -", $"sweep line changed: {last}"); }), + + ("office rage: the Actor switches once, 100 ms after the break, KeepComposure before and Rage from it, and the run ends ReleaseSeconds after the switch", () => + { + foreach (ulong seed in new ulong[] { 1, 2, 3, 4, 5 }) + { + var r = Office(new StressParameters(), seed); + var brk = r.Timeline.Single(e => e.Kind == StressEntryKind.WillBroke); + var sw = r.Timeline.Single(e => e.Kind == StressEntryKind.GoalChanged); + Check(sw.TimeMs - brk.TimeMs == 100 && brk.TimeMs == r.TimeToBreakMs, $"seed {seed}: the switch row is {sw.TimeMs - brk.TimeMs} ms after the break"); + Check(r.Timeline.Where(e => e.TimeMs < sw.TimeMs).All(e => e.Goal == OfficeGoal.KeepComposure), $"seed {seed}: a row before the switch is not KeepComposure"); + Check(r.Timeline.Where(e => e.TimeMs >= sw.TimeMs).All(e => e.Goal == OfficeGoal.Rage), $"seed {seed}: a row from the switch on is not Rage"); + Check(r.Outcome == Outcome.WillBroke && r.EndMs == sw.TimeMs + 6000, $"seed {seed}: ended at {r.EndMs}, the switch was at {sw.TimeMs}"); + Check(r.Timeline.Where(e => e.TimeMs >= brk.TimeMs).All(e => e.Resolve == 0.0), $"seed {seed}: resolve came back after the break"); + } + var short_ = Office(new StressParameters { ReleaseSeconds = 2.0 }, 1); + Check(short_.EndMs == short_.Timeline.Single(e => e.Kind == StressEntryKind.GoalChanged).TimeMs + 2000, "ReleaseSeconds did not set the length of the rage"); + var clipped = Office(new StressParameters { MaxSeconds = 85.0 }, 1); + Check(clipped.Outcome == Outcome.WillBroke && clipped.EndMs == 85000 && clipped.Timeline.All(e => e.Kind != StressEntryKind.Endured), $"a release past MaxSeconds ended at {clipped.EndMs}"); + }), + + ("office rage: a will that holds never switches, and the job's pull is the composure goal's alone", () => + { + var quiet = Office(new StressParameters { Cause = Cause.Office with { Stressors = Array.Empty() } }, 1); + Check(quiet.Timeline.All(e => e.Kind != StressEntryKind.GoalChanged && e.Goal == OfficeGoal.KeepComposure), "a will that held switched goals"); + var p = new StressParameters(); + var brain = OfficeBrain.Build(p, OfficePoses.Identity); + Check(brain.Goals[OfficeBrain.ComposureIndex].Pull == p.Cause.ObjectivePull && brain.Goals[OfficeBrain.RageIndex].Pull == 0.0, "the pulls are not the cause's and zero"); + }), + }; - private static readonly Quat[] Pose = { Quat.Identity }; private static readonly float[] Point = new float[1], Strengths = new float[1]; private static readonly Quat[] Targets = new Quat[1]; - private static StressSession NewOffice(StressParameters p, ulong seed) => new(p, seed, 1, Pose, Pose); + private static StressSession NewOffice(StressParameters p, ulong seed) => new(p, seed, 1, OfficePoses.Identity); private static void Step(StressSession s) => s.Tick(Point, Point, Point, Strengths, Targets); diff --git a/tools/PainSweep/Program.cs b/tools/PainSweep/Program.cs index f1ee1f8..b24fa62 100644 --- a/tools/PainSweep/Program.cs +++ b/tools/PainSweep/Program.cs @@ -18,7 +18,7 @@ double[] suppressions = { 0.0, 0.25, 0.5, 0.75, 0.95, 1.0 }; var inv = CultureInfo.InvariantCulture; var sb = new StringBuilder(); -sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pull {new PainBoxParameters().Drive.ObjectivePull:F2})\n"); +sb.Append($"time to break, s (median over {Seeds} seeds from {FirstSeed}; max {new PainBoxParameters().MaxSeconds:F0} s; pay ${new PainBoxParameters().Payment:F0}, pull {ChamberBrain.Pull(new PainBoxParameters()):F2})\n"); sb.Append("intensity\\suppr "); foreach (var s in suppressions) sb.Append(s.ToString("F2", inv).PadLeft(10)); sb.Append('\n');