diff --git a/src/BadDay.Ymir/BodyPainBox.cs b/src/BadDay.Ymir/BodyPainBox.cs index be6e61a..a1d3fbd 100644 --- a/src/BadDay.Ymir/BodyPainBox.cs +++ b/src/BadDay.Ymir/BodyPainBox.cs @@ -23,11 +23,9 @@ public sealed record BodyPainBoxResult( PainBoxResult Run, int Excursions, IReadOnlyList Hand); /// -/// The pain box on the body: 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 -/// point) and steps it. Per step: the box writes its intensity, the body reports its hand points, Lodur's Actor -/// decides, the ragdoll is driven, the world steps. BDS reaches the puppet only through -/// , and . +/// The pain box on the body: is the one owner of the Ymir world and its loop, and +/// steps one to the end. BDS reaches the puppet only through , +/// and . /// public static class BodyPainBox { @@ -37,6 +35,36 @@ public static class BodyPainBox /// Centre of the box and the right hand's hold point. public static readonly (float X, float Y, float Z) HoldPoint = (-0.21f, 1.19f, 0.46f); + /// The hand is out when it has stayed outside the box this long after the break. + public const double OutHoldSeconds = 0.2; + + /// Steps a to its end and records the hand after every tick (a box disabled at tick 0 leaves the rest pose as the one sample). + public static BodyPainBoxResult Run(PainBoxParameters p, ulong seed) + { + using var s = new BodyPainBoxSession(p, seed); + var samples = new List(); + while (!s.Finished) + { + long before = s.Session.TickIndex; + s.Step(); + if (s.Session.TickIndex != before || samples.Count == 0) samples.Add(s.Hand); + } + return new BodyPainBoxResult(s.Result(), s.Excursions, samples); + } +} + +/// +/// 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 +/// point) and is its only stepper. 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 deliberate withdrawal, once the hand is out or the settle is over. After +/// only keeps the body moving: the last strengths and targets are driven again and the world steps, +/// while the result, and stay as they were. +/// and take effect on the next tick. +/// +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. @@ -45,100 +73,147 @@ public static class BodyPainBox /// After the deliberate withdrawal begins the run waits this long for the hand to come out. private const double SettleSeconds = 1.0; - /// The hand is out when it has stayed outside the box this long after the break. - public const double OutHoldSeconds = 0.2; + private readonly PainBoxParameters _p; + private readonly Box3DSoaWorld _world; + private readonly HumanoidRagdoll _ragdoll; + private readonly float[] _x = new float[HumanoidRagdoll.RegionCount]; + private readonly float[] _y = new float[HumanoidRagdoll.RegionCount]; + private readonly float[] _z = new float[HumanoidRagdoll.RegionCount]; + private readonly float[] _strengths = new float[HumanoidRagdoll.MuscleCount]; + private readonly Quat[] _targets = new Quat[HumanoidRagdoll.MuscleCount]; + private readonly long _rampEnd; + private readonly long _settleTicks; + private readonly long _outHoldTicks; + private long _outSince = -1; // first tick of the current continuous stay outside the box after the break + private bool _wasIn; + private long _breakTick = -1, _withdrewTick = -1; - public static BodyPainBoxResult Run(PainBoxParameters p, ulong seed) + public BodyPainBoxSession(PainBoxParameters p, ulong seed) { - if (Math.Abs(p.TickSeconds - TickSeconds) > 1e-12) + if (Math.Abs(p.TickSeconds - BodyPainBox.TickSeconds) > 1e-12) { throw new ArgumentException($"The body run steps at 1/120 s; got TickSeconds {p.TickSeconds}."); } - using var world = new Box3DSoaWorld(capacity: HumanoidRagdoll.LimbCount + 2, jointCapacity: HumanoidRagdoll.MuscleCount + 1); - 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)); - - // 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]; - var withdraw = new Quat[HumanoidRagdoll.MuscleCount]; - Array.Fill(hold, Quat.Identity); - Array.Fill(withdraw, Quat.Identity); - hold[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, -1.0f); - hold[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -0.6f); - withdraw[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f); - withdraw[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f); - - var volume = new BoxStimulus(HoldPoint.X, HoldPoint.Y, HoldPoint.Z, BoxHalf, BoxHalf, BoxHalf); - var session = new PainBoxSession(p, seed, volume, HumanoidRagdoll.RegionCount, hold, withdraw, (int)Region.HandR); - var x = new float[HumanoidRagdoll.RegionCount]; - var y = new float[HumanoidRagdoll.RegionCount]; - var z = new float[HumanoidRagdoll.RegionCount]; - var strengths = new float[HumanoidRagdoll.MuscleCount]; - var targets = new Quat[HumanoidRagdoll.MuscleCount]; - - var samples = new List(); - long rampEnd = (long)Math.Round(p.BoxRampSeconds / p.TickSeconds); - long outSince = -1; // first tick of the current continuous stay outside the box after the break - long? handOut = null; - int excursions = 0; - bool wasIn = false; - long breakTick = -1, withdrewTick = -1; - long settleTicks = (long)Math.Round(SettleSeconds / p.TickSeconds); - long outHoldTicks = Math.Max(1, (long)Math.Round(OutHoldSeconds / p.TickSeconds)); - - HandSample ReadHand() + _p = p; + _world = new Box3DSoaWorld(capacity: HumanoidRagdoll.LimbCount + 2, jointCapacity: HumanoidRagdoll.MuscleCount + 1); + try { - ragdoll.ReadRegions(x, y, z); - float hx = x[(int)Region.HandR], hy = y[(int)Region.HandR], hz = z[(int)Region.HandR]; - return new HandSample(hx, hy, hz, session.Box.Contains(hx, hy, hz)); + _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)); + + // 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]; + var withdraw = new Quat[HumanoidRagdoll.MuscleCount]; + Array.Fill(hold, Quat.Identity); + Array.Fill(withdraw, Quat.Identity); + hold[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, -1.0f); + hold[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -0.6f); + withdraw[(int)Muscle.ShoulderR] = Quat.FromAxisAngle(1f, 0f, 0f, 0.3f); + withdraw[(int)Muscle.ElbowR] = Quat.FromAxisAngle(0f, 0f, 1f, -2.0f); + + var hp = BodyPainBox.HoldPoint; + var volume = new BoxStimulus(hp.X, hp.Y, hp.Z, BoxHalf, BoxHalf, BoxHalf); + Session = new PainBoxSession(p, seed, volume, HumanoidRagdoll.RegionCount, hold, withdraw, (int)Region.HandR); + } + catch + { + _world.Dispose(); + throw; } - while (!session.Finished) + _rampEnd = (long)Math.Round(p.BoxRampSeconds / p.TickSeconds); + _settleTicks = (long)Math.Round(SettleSeconds / p.TickSeconds); + _outHoldTicks = Math.Max(1, (long)Math.Round(BodyPainBox.OutHoldSeconds / p.TickSeconds)); + Hand = ReadHand(); + } + + /// The live lanes of the world, for rendering. Read-only: nothing outside this session writes them. + public Box3DSoaView View => _world.View; + + /// The nervous run: the Actor's drive, the chamber, the timeline so far. + public PainBoxSession Session { get; } + + /// The right hand after the latest step (the rest pose before the first). + public HandSample Hand { get; private set; } + + /// Times the hand left the box between the end of the ramp and the break. + public int Excursions { get; private set; } + + /// The start of the first sustained exit after the break; null if there was none (see ). + public long? HandOutMs { get; private set; } + + /// The Actor's events of the latest step; none when that step did not tick the session. + public TickEvents LastEvents { get; private set; } + + public bool Finished => Session.Finished; + + /// One step of 1/120 s; see the type's summary for what it does after . + public void Step() + { + bool wasFinished = Finished; + bool ticked = !wasFinished && !Session.Disabled(); // a step that finds the box switched off ends the run without stepping the world + long tick = Session.TickIndex; + LastEvents = TickEvents.None; + if (ticked) { - if (session.Disabled()) - { - if (samples.Count == 0) samples.Add(ReadHand()); // disabled at tick 0: the track still holds the rest pose - break; - } - long tick = session.TickIndex; - ragdoll.ReadRegions(x, y, z); - var events = session.Tick(x, y, z, strengths, targets); - ragdoll.Drive(strengths, targets); - world.Step((float)p.TickSeconds, Substeps); - - if ((events & TickEvents.WillBroke) != 0) breakTick = tick; - var sample = ReadHand(); - var inBox = sample.InBox; - samples.Add(sample); - - if (breakTick < 0) - { - if (tick > rampEnd && wasIn && !inBox) excursions++; - wasIn = inBox; - } - else if (inBox) - { - outSince = -1; // back in: whatever exit this was, it was a flinch - handOut = null; - } - else - { - if (outSince < 0) outSince = tick; - if (tick - outSince + 1 >= outHoldTicks) handOut = session.Ms(outSince); - } - - // The run ends on the Actor's events, never on the hand: after the deliberate withdrawal, once the - // hand is out or the settle is over. - if (session.Withdrew) - { - if (withdrewTick < 0) withdrewTick = tick; - if (handOut is not null || tick - withdrewTick >= settleTicks) session.EndAt(tick); - } + _ragdoll.ReadRegions(_x, _y, _z); + LastEvents = Session.Tick(_x, _y, _z, _strengths, _targets); + } + if (ticked || wasFinished) + { + _ragdoll.Drive(_strengths, _targets); // after Finished: the last strengths and targets again + _world.Step((float)_p.TickSeconds, Substeps); } - return new BodyPainBoxResult(session.Result() with { HandOutMs = handOut }, excursions, samples); + var sample = ReadHand(); // the rest pose when the box was off at tick 0 + Hand = sample; + if (!ticked) return; + + if ((LastEvents & TickEvents.WillBroke) != 0) _breakTick = tick; + bool inBox = sample.InBox; + + if (_breakTick < 0) + { + if (tick > _rampEnd && _wasIn && !inBox) Excursions++; + _wasIn = inBox; + } + else if (inBox) + { + _outSince = -1; // back in: whatever exit this was, it was a flinch + HandOutMs = null; + } + else + { + if (_outSince < 0) _outSince = tick; + if (tick - _outSince + 1 >= _outHoldTicks) HandOutMs = Session.Ms(_outSince); + } + + // The run ends on the Actor's events, never on the hand. + if (Session.Withdrew) + { + if (_withdrewTick < 0) _withdrewTick = tick; + if (HandOutMs is not null || tick - _withdrewTick >= _settleTicks) Session.EndAt(tick); + } + } + + /// Sets the box intensity from the next tick. + public void SetIntensity(double level) => Session.SetIntensity(level); + + /// Switches the box off from the next tick; the run ends as BoxDisabled if the will still holds. + public void SwitchOff() => Session.SwitchOff(); + + /// The nervous result so far, with . + public PainBoxResult Result() => Session.Result() with { HandOutMs = HandOutMs }; + + public void Dispose() => _world.Dispose(); + + private HandSample ReadHand() + { + _ragdoll.ReadRegions(_x, _y, _z); + float hx = _x[(int)Region.HandR], hy = _y[(int)Region.HandR], hz = _z[(int)Region.HandR]; + return new HandSample(hx, hy, hz, Session.Box.Contains(hx, hy, hz)); } } diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs index dec2edb..b7474fe 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -242,6 +242,59 @@ public static class Program Check(r.Run.Outcome == Outcome.BoxDisabled && r.Hand.Count == 1 && !r.Hand[0].InBox, $"{r.Run.Outcome}, {r.Hand.Count} samples"); }), + ("body: a live SwitchOff at tick T equals BoxDisableAtSeconds = T/120: before the break the will holds, after it the box goes to 0 and the run still ends WillBroke", () => + { + var full = BodyPainBox.Run(OnBody, 1); + int breakTick = Tick(full.Run.TimeToBreakMs!.Value); + foreach (int t in new[] { 5 * Hz, breakTick + 2 }) + { + var scripted = BodyPainBox.Run(OnBody with { BoxDisableAtSeconds = t / (double)Hz }, 1); + var live = RunLive(OnBody, 1, s => { if (s.Session.TickIndex == t) s.SwitchOff(); }); + SameRun(scripted, live, $"switch-off at tick {t}"); + } + Check(BodyPainBox.Run(OnBody with { BoxDisableAtSeconds = 5.0 }, 1).Run.Outcome == Outcome.BoxDisabled, "a switch-off with the will holding should end BoxDisabled"); + Check(BodyPainBox.Run(OnBody with { BoxDisableAtSeconds = (breakTick + 2) / (double)Hz }, 1).Run.Outcome == Outcome.WillBroke, "a switch-off after the break should leave the run to end WillBroke"); + }), + + ("body: SetIntensity(x) before the first Step equals BoxIntensity = x", () => + { + var set = RunLive(OnBody, 1, s => { if (s.Session.TickIndex == 0) s.SetIntensity(0.5); }); + SameRun(BodyPainBox.Run(OnBody with { BoxIntensity = 0.5 }, 1), set, "intensity 0.5"); + }), + + ("body: SetIntensity mid-run takes effect on the next tick only", () => + { + const int at = 4 * Hz; // well after the 2 s ramp + using var control = new BodyPainBoxSession(OnBody, 1); + using var live = new BodyPainBoxSession(OnBody, 1); + for (int i = 0; i < at; i++) { control.Step(); live.Step(); } + double scheduled = control.Session.Box.Intensity; + Check(scheduled > 0.3 && live.Session.Box.Intensity == scheduled, $"before the command the tick's intensity is the schedule's: {live.Session.Box.Intensity} against {scheduled}"); + live.SetIntensity(0.0); + Check(live.Session.Box.Intensity == scheduled, "the command rewrote a tick that had already run"); + control.Step(); live.Step(); + Check(control.Session.Box.Intensity > 0.3 && live.Session.Box.Intensity == 0.0, $"next tick: control {control.Session.Box.Intensity}, live {live.Session.Box.Intensity}"); + }), + + ("body: stepping past Finished keeps the world moving and the result frozen", () => + { + using var s = new BodyPainBoxSession(OnBody, 1); + while (!s.Finished) s.Step(); + string render = s.Result().Render(); + long? handOut = s.HandOutMs; + int excursions = s.Excursions; + var atEnd = s.Hand; + bool moved = false; + for (int i = 0; i < Hz; i++) + { + s.Step(); + moved |= s.Hand != atEnd; + } + Check(moved, "the world did not step after Finished"); + Check(s.Result().Render() == render && s.HandOutMs == handOut && s.Excursions == excursions && s.LastEvents == Lodur.TickEvents.None, + "the result, hand-out, excursions or events changed after Finished"); + }), + ("the seed's trait multiplies the caller's nerve gain and drain trait instead of replacing them", () => { Check(PainBoxSimulation.Run(Default with { Nerve = new Lodur.NerveParameters { Gain = 0.0 }, MaxSeconds = 20.0 }, 1).Outcome == Outcome.Endured, "gain 0 should leave no pain"); @@ -549,6 +602,27 @@ public static class Program return Math.Sqrt(sum / (to - from - 1)); } + /// Steps a body session to its end, calling before every step, and records the hand per tick as does. + private static BodyPainBoxResult RunLive(PainBoxParameters p, ulong seed, Action beforeStep) + { + using var s = new BodyPainBoxSession(p, seed); + var hand = new List(); + while (!s.Finished) + { + beforeStep(s); + long before = s.Session.TickIndex; + s.Step(); + if (s.Session.TickIndex != before || hand.Count == 0) hand.Add(s.Hand); + } + return new BodyPainBoxResult(s.Result(), s.Excursions, hand); + } + + private static void SameRun(BodyPainBoxResult a, BodyPainBoxResult b, string who) + { + Check(a.Run.Render() == b.Run.Render() && a.Run.Summary() == b.Run.Summary() && a.Excursions == b.Excursions, $"{who}: results differ: '{a.Run.Summary()}' against '{b.Run.Summary()}'"); + Check(a.Hand.Count == b.Hand.Count && a.Hand.Zip(b.Hand).All(h => h.First == h.Second), $"{who}: hand tracks differ ({a.Hand.Count} and {b.Hand.Count} samples)"); + } + /// Runs every test; with an argument, only the tests whose name contains it (the body tests take minutes). public static int Main(string[] args) {