From 34547b65147d295184149126a94d19ab50630a86 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 20 Nov 2026 01:40:51 +0100 Subject: [PATCH] BodyPainBoxSession: an event queue the client drains; the nervous session is private; Dispose is total LastEvents is replaced by DrainEvents into a caller-owned buffer (events queue per tick), the inner PainBoxSession is no longer exposed (read-only Pain, Strain, Resolve, Goal, BoxIntensity, Chamber, TickIndex instead), and every member throws ObjectDisposedException after Dispose. Tests pin the drain intervals, the after-Finished re-drive, end on the confirmed hand-out, the rest-pose Hand, the intensity refusal and the disposed state. Co-Authored-By: Claude Sonnet 5.5 --- src/BadDay.Ymir/BodyPainBox.cs | 131 +++++++++++++++++++++++---------- tests/BadDay.Tests/Program.cs | 120 +++++++++++++++++++++++++++--- 2 files changed, 204 insertions(+), 47 deletions(-) diff --git a/src/BadDay.Ymir/BodyPainBox.cs b/src/BadDay.Ymir/BodyPainBox.cs index a1d3fbd..e5cfe87 100644 --- a/src/BadDay.Ymir/BodyPainBox.cs +++ b/src/BadDay.Ymir/BodyPainBox.cs @@ -45,23 +45,31 @@ public static class BodyPainBox var samples = new List(); while (!s.Finished) { - long before = s.Session.TickIndex; + long before = s.TickIndex; s.Step(); - if (s.Session.TickIndex != before || samples.Count == 0) samples.Add(s.Hand); + if (s.TickIndex != before || samples.Count == 0) samples.Add(s.Hand); } return new BodyPainBoxResult(s.Result(), s.Excursions, samples); } } +/// What the Actor reported on one tick of a ; only ticks that reported something are queued. +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 -/// 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 +/// 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 +/// 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. +/// while the result, and stay as they were. That free motion is +/// float arithmetic on the platform's math and is not bit-identical across operating systems; everything up to +/// is. +/// and take effect on the next tick. Events queue per tick and a +/// client drains them with , so a frame that spans several steps loses none. After +/// every member throws . /// public sealed class BodyPainBoxSession : IDisposable { @@ -76,6 +84,8 @@ public sealed class BodyPainBoxSession : IDisposable private readonly PainBoxParameters _p; private readonly Box3DSoaWorld _world; private readonly HumanoidRagdoll _ragdoll; + private readonly PainBoxSession _session; + private readonly Queue _events = new(); private readonly float[] _x = new float[HumanoidRagdoll.RegionCount]; private readonly float[] _y = new float[HumanoidRagdoll.RegionCount]; private readonly float[] _z = new float[HumanoidRagdoll.RegionCount]; @@ -84,9 +94,13 @@ public sealed class BodyPainBoxSession : IDisposable private readonly long _rampEnd; private readonly long _settleTicks; private readonly long _outHoldTicks; + private HandSample _hand; + private int _excursions; + private long? _handOutMs; 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; + private bool _disposed; public BodyPainBoxSession(PainBoxParameters p, ulong seed) { @@ -116,7 +130,7 @@ public sealed class BodyPainBoxSession : IDisposable 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); + _session = new PainBoxSession(p, seed, volume, HumanoidRagdoll.RegionCount, hold, withdraw, (int)Region.HandR); } catch { @@ -127,40 +141,51 @@ public sealed class BodyPainBoxSession : IDisposable _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(); + _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; } + public Box3DSoaView View { get { Live(); return _world.View; } } /// The right hand after the latest step (the rest pose before the first). - public HandSample Hand { get; private set; } + public HandSample Hand { get { Live(); return _hand; } } /// Times the hand left the box between the end of the ramp and the break. - public int Excursions { get; private set; } + public int Excursions { get { Live(); return _excursions; } } /// The start of the first sustained exit after the break; null if there was none (see ). - public long? HandOutMs { get; private set; } + public long? HandOutMs { get { Live(); return _handOutMs; } } - /// 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 { get { Live(); return _session.Finished; } } - public bool Finished => Session.Finished; + /// Ticks run so far; the tick the next runs. + public long TickIndex { get { Live(); return _session.TickIndex; } } + + /// The box's intensity as written on the latest tick. + public double BoxIntensity { get { Live(); return _session.Box.Intensity; } } + + /// The stimulus volume the hand is held in (a copy), for drawing the chamber. + public BoxStimulus Chamber { get { Live(); return _session.Box; } } + + /// The Actor's state at the end of the latest tick. + 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; } } /// 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; + Live(); + bool wasFinished = _session.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; + var events = TickEvents.None; if (ticked) { _ragdoll.ReadRegions(_x, _y, _z); - LastEvents = Session.Tick(_x, _y, _z, _strengths, _targets); + events = _session.Tick(_x, _y, _z, _strengths, _targets); + if (events != TickEvents.None) _events.Enqueue(new BodyEvent(tick, events)); } if (ticked || wasFinished) { @@ -169,51 +194,83 @@ public sealed class BodyPainBoxSession : IDisposable } var sample = ReadHand(); // the rest pose when the box was off at tick 0 - Hand = sample; + _hand = sample; if (!ticked) return; - if ((LastEvents & TickEvents.WillBroke) != 0) _breakTick = tick; + if ((events & TickEvents.WillBroke) != 0) _breakTick = tick; bool inBox = sample.InBox; if (_breakTick < 0) { - if (tick > _rampEnd && _wasIn && !inBox) Excursions++; + 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; + _handOutMs = null; } else { if (_outSince < 0) _outSince = tick; - if (tick - _outSince + 1 >= _outHoldTicks) HandOutMs = Session.Ms(_outSince); + 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 (_session.Withdrew) { if (_withdrewTick < 0) _withdrewTick = tick; - if (HandOutMs is not null || tick - _withdrewTick >= _settleTicks) Session.EndAt(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); + /// + /// Moves the queued events (oldest first) into and returns how many it wrote; the rest stay + /// queued for the next call. Allocation-free once the queue has grown to the client's drain interval. + /// + public int DrainEvents(Span buffer) + { + Live(); + int n = 0; + while (n < buffer.Length && _events.Count > 0) buffer[n++] = _events.Dequeue(); + return n; + } + + /// Sets the box intensity from the next tick; refuses a non-finite or negative level. + public void SetIntensity(double level) + { + Live(); + _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(); + public void SwitchOff() + { + Live(); + _session.SwitchOff(); + } /// The nervous result so far, with . - public PainBoxResult Result() => Session.Result() with { HandOutMs = HandOutMs }; + public PainBoxResult Result() + { + Live(); + return _session.Result() with { HandOutMs = _handOutMs }; + } - public void Dispose() => _world.Dispose(); + /// Frees the world; a second call does nothing. + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _world.Dispose(); + } + + private void Live() => ObjectDisposedException.ThrowIf(_disposed, this); 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)); + 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 b7474fe..4778795 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -249,7 +249,7 @@ public static class Program 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(); }); + var live = RunLive(OnBody, 1, s => { if (s.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"); @@ -258,7 +258,7 @@ public static class Program ("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); }); + var set = RunLive(OnBody, 1, s => { if (s.TickIndex == 0) s.SetIntensity(0.5); }); SameRun(BodyPainBox.Run(OnBody with { BoxIntensity = 0.5 }, 1), set, "intensity 0.5"); }), @@ -268,18 +268,20 @@ public static class Program 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}"); + double scheduled = control.BoxIntensity; + Check(scheduled > 0.3 && live.BoxIntensity == scheduled, $"before the command the tick's intensity is the schedule's: {live.BoxIntensity} against {scheduled}"); live.SetIntensity(0.0); - Check(live.Session.Box.Intensity == scheduled, "the command rewrote a tick that had already run"); + Check(live.BoxIntensity == 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}"); + Check(control.BoxIntensity > 0.3 && live.BoxIntensity == 0.0, $"next tick: control {control.BoxIntensity}, live {live.BoxIntensity}"); }), - ("body: stepping past Finished keeps the world moving and the result frozen", () => + ("body: stepping past Finished keeps the world moving, the arm driven and the result frozen", () => { using var s = new BodyPainBoxSession(OnBody, 1); while (!s.Finished) s.Step(); + var drained = new BodyEvent[64]; + s.DrainEvents(drained); string render = s.Result().Render(); long? handOut = s.HandOutMs; int excursions = s.Excursions; @@ -291,10 +293,108 @@ public static class Program 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, + // Once the arm has settled (a second), the driven arm moves 0.01 to 0.03 m in the next second; with the re-drive removed it goes limp and moves 0.3 m. + var settled = s.Hand; + float drift = 0f; + for (int i = 0; i < Hz; i++) + { + s.Step(); + drift = MathF.Max(drift, MathF.Sqrt(MathF.Pow(s.Hand.X - settled.X, 2) + MathF.Pow(s.Hand.Y - settled.Y, 2) + MathF.Pow(s.Hand.Z - settled.Z, 2))); + } + Check(drift < 0.08f, $"the hand moved {drift:F3} m in the second after settling: the arm is not being driven"); + Check(s.Result().Render() == render && s.HandOutMs == handOut && s.Excursions == excursions && s.DrainEvents(drained) == 0, "the result, hand-out, excursions or events changed after Finished"); }), + ("body: the run ends on the confirmed hand-out, not on the settle timeout", () => + { + var r = BodyPainBox.Run(OnBody, 1); + int outTick = Tick(r.Run.HandOutMs!.Value), holdTicks = (int)Math.Round(BodyPainBox.OutHoldSeconds * Hz); + Check(r.Hand.Count - 1 == outTick + holdTicks - 1, $"the last step is tick {r.Hand.Count - 1}; the hand-out at tick {outTick} is confirmed at tick {outTick + holdTicks - 1}"); + }), + + ("body: before the first Step the hand reads the rest pose, outside the box", () => + { + using var s = new BodyPainBoxSession(OnBody, 1); + Check(s.TickIndex == 0 && !s.Hand.InBox, "the fresh session's hand is not the rest pose"); + Check(s.Hand == BodyPainBox.Run(OnBody with { BoxDisableAtSeconds = 0.0 }, 1).Hand[0], "the rest pose differs from the track of a box disabled at tick 0"); + }), + + ("body: events queue per tick, so draining every 1, 2, 3 or 7 steps (or through a two-slot buffer) gives the Run's flinch, break and withdrawal rows in order", () => + { + var run = BodyPainBox.Run(OnBody, 1).Run; + var rows = run.Timeline.Where(e => e.Kind is EntryKind.Flinch or EntryKind.WillBroke or EntryKind.Withdrew).Select(e => (e.TimeMs, e.Kind)).ToList(); + Check(rows.Count >= 10, $"only {rows.Count} event rows in the Run"); + List Collect(int every, int slots) + { + using var s = new BodyPainBoxSession(OnBody, 1); + var got = new List(); + var buffer = new BodyEvent[slots]; + void Drain() { int n; while ((n = s.DrainEvents(buffer)) > 0) got.AddRange(buffer.Take(n)); } + for (int i = 1; !s.Finished; i++) + { + s.Step(); + if (i % every == 0) Drain(); + } + Drain(); + return got; + } + foreach (var (every, slots) in new[] { (1, 8), (2, 8), (3, 8), (7, 8), (7, 2) }) + { + var got = Collect(every, slots); + var expanded = new List<(long, EntryKind)>(); + foreach (var e in got) + { + 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)); + } + Check(expanded.SequenceEqual(rows), $"draining every {every} steps through {slots} slots: {expanded.Count} events against the Run's {rows.Count}, or out of order"); + } + }), + + ("body: SetIntensity refuses a non-finite or negative level before anything ticks, and a refused call changes nothing", () => + { + foreach (double bad in new[] { double.PositiveInfinity, double.NegativeInfinity, double.NaN, -0.1 }) + { + using var s = new BodyPainBoxSession(OnBody, 1); + bool threw = false; + try { s.SetIntensity(bad); } catch (ArgumentOutOfRangeException) { threw = true; } + Check(threw, $"SetIntensity({bad}) was accepted"); + } + var refused = RunLive(OnBody, 1, s => + { + if (s.TickIndex != 0) return; + foreach (double bad in new[] { double.PositiveInfinity, double.NaN, -0.1 }) + { + try { s.SetIntensity(bad); } catch (ArgumentOutOfRangeException) { } + } + }); + SameRun(BodyPainBox.Run(OnBody, 1), refused, "refused intensities"); + }), + + ("body: after Dispose every member throws ObjectDisposedException and a second Dispose does nothing", () => + { + var s = new BodyPainBoxSession(OnBody, 1); + s.Step(); + s.Dispose(); + s.Dispose(); + var members = new (string Name, Action Call)[] + { + ("Step", () => s.Step()), ("Hand", () => _ = s.Hand), ("Result", () => s.Result()), ("SetIntensity", () => s.SetIntensity(0.5)), + ("SwitchOff", () => s.SwitchOff()), ("DrainEvents", () => s.DrainEvents(new BodyEvent[4])), ("View", () => _ = s.View), + ("Finished", () => _ = s.Finished), ("TickIndex", () => _ = s.TickIndex), ("Excursions", () => _ = s.Excursions), + ("HandOutMs", () => _ = s.HandOutMs), ("BoxIntensity", () => _ = s.BoxIntensity), ("Pain", () => _ = s.Pain), + }; + foreach (var (name, call) in members) + { + bool threw = false; + try { call(); } catch (ObjectDisposedException) { threw = true; } + Check(threw, $"{name} did not throw after Dispose"); + } + }), + ("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"); @@ -610,9 +710,9 @@ public static class Program while (!s.Finished) { beforeStep(s); - long before = s.Session.TickIndex; + long before = s.TickIndex; s.Step(); - if (s.Session.TickIndex != before || hand.Count == 0) hand.Add(s.Hand); + if (s.TickIndex != before || hand.Count == 0) hand.Add(s.Hand); } return new BodyPainBoxResult(s.Result(), s.Excursions, hand); }