diff --git a/src/BadDay.Ymir/Blood.cs b/src/BadDay.Ymir/Blood.cs index b9a777d..752a158 100644 --- a/src/BadDay.Ymir/Blood.cs +++ b/src/BadDay.Ymir/Blood.cs @@ -39,3 +39,170 @@ public sealed record BloodParameters /// One drop's volume in m^3. public double DropVolume => Math.Pow(2.0 * DropRadius, 3.0); } + +/// +/// The blood of a , and the one writer of fluid particles and wet patches in BDS. Lodur's +/// physiology alone decides how much bleeds; this decides how that volume is drawn: each wound point gathers +/// times its part's bleed (shared by the part's points) as visible volume and sheds +/// it as drops of from where the wound is, carried by the part's pose, at most +/// a tick; volume that cannot be shed yet waits as backlog and none is +/// dropped. After every step a drop that has rested on something for ticks +/// settles into a wet patch, and the oldest supported drops settle until there is room for a full tick of emission, so +/// the live drops stay under . Ymir never settles by itself; this is the policy. +/// Allocation-free once the wound points are open. +/// +public sealed class Blood +{ + private struct WoundPoint + { + public int Part; + public float Px, Py, Pz, Nx, Ny, Nz; // the part's frame + public double Volume; // visible m^3 gathered and not yet shed + } + + private readonly Box3DSoaWorld _world; + private readonly Ragdoll _ragdoll; + private readonly BloodParameters _p; + private readonly double _dropVolume; + private readonly float _mass; + private readonly uint _phase; + private readonly int[] _pointsOnPart; + private WoundPoint[] _points = new WoundPoint[8]; + private int _pointCount, _cursor; + // The live drops, oldest first. + private readonly Box3DSoaParticleHandle[] _live; + private readonly int[] _calm; + private readonly bool[] _supported, _chosen; + private int _liveCount; + private readonly Box3DSoaParticleDesc[] _descs; + private readonly Box3DSoaParticleHandle[] _created; + private readonly Box3DSoaParticleHandle[] _settling; + + internal Blood(Box3DSoaWorld world, Ragdoll ragdoll, BloodParameters parameters) + { + _world = world; + _ragdoll = ragdoll; + _p = parameters; + _dropVolume = parameters.DropVolume; + _mass = (float)(parameters.Density * _dropVolume); + _phase = Box3DSoaPhase.Of(1, fluid: true); + _pointsOnPart = new int[ragdoll.Plan.Parts.Count]; + _live = new Box3DSoaParticleHandle[parameters.LiveCap]; + _calm = new int[parameters.LiveCap]; + _supported = new bool[parameters.LiveCap]; + _chosen = new bool[parameters.LiveCap]; + _descs = new Box3DSoaParticleDesc[parameters.MaxDropsPerTick]; + _created = new Box3DSoaParticleHandle[parameters.MaxDropsPerTick]; + _settling = new Box3DSoaParticleHandle[parameters.LiveCap]; + } + + /// Visible volume (m^3) shed as drops so far, settled or live. + public double Emitted { get; private set; } + + /// Visible volume (m^3) gathered at the wounds and not yet shed. + public double Backlog { get { double b = 0.0; for (int i = 0; i < _pointCount; i++) b += _points[i].Volume; return b; } } + + /// Drops in the air or resting, not yet settled. + public int Live => _liveCount; + + /// Opens a wound point on , in the part's frame; from now on it gathers its share of the part's bleed. + internal void Open(int part, float px, float py, float pz, float nx, float ny, float nz) + { + if ((uint)part >= (uint)_pointsOnPart.Length) throw new ArgumentOutOfRangeException(nameof(part)); + if (_pointCount == _points.Length) Array.Resize(ref _points, _points.Length * 2); + _points[_pointCount++] = new WoundPoint { Part = part, Px = px, Py = py, Pz = pz, Nx = nx, Ny = ny, Nz = nz }; + _pointsOnPart[part]++; + } + + /// Gathers this tick's volume from (real m^3/s per part, empty for none) and sheds what whole drops it makes, before the step. + internal void BeforeStep(ReadOnlySpan bleedPerPart, double dt) + { + if (_pointCount == 0) return; + for (int i = 0; i < _pointCount; i++) + { + ref var w = ref _points[i]; + if ((uint)w.Part < (uint)bleedPerPart.Length) w.Volume += _p.Gain * bleedPerPart[w.Part] / _pointsOnPart[w.Part] * dt; + } + + // A lane Settle freed is reusable only after the next Step, so the room is what the world says, not the cap alone. + int budget = Math.Min(_p.MaxDropsPerTick, Math.Min(_world.FreeParticleSlots, _p.LiveCap - _liveCount)); + int n = 0; + var v = _world.View; + float r = _p.DropRadius; + for (int pass = 0; n < budget; pass++) + { + bool any = false; + for (int k = 0; k < _pointCount && n < budget; k++) + { + ref var w = ref _points[(_cursor + k) % _pointCount]; + if (w.Volume < _dropVolume) continue; + w.Volume -= _dropVolume; + any = true; + + int lane = _ragdoll.BodyLane(w.Part); + var q = new Quat(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]); + q.Rotate(w.Px, w.Py, w.Pz, out var px, out var py, out var pz); + q.Rotate(w.Nx, w.Ny, w.Nz, out var nx, out var ny, out var nz); + // Outside the surface, and a drop shed in the same tick one diameter further out so none starts inside another. + float lift = r + 0.002f + pass * 2f * r; + var at = (v.PositionX[lane] + px + nx * lift, v.PositionY[lane] + py + ny * lift, v.PositionZ[lane] + pz + nz * lift); + var velocity = (v.VelocityX[lane] + nx * _p.ExitSpeed, v.VelocityY[lane] + ny * _p.ExitSpeed, v.VelocityZ[lane] + nz * _p.ExitSpeed); + _descs[n++] = new Box3DSoaParticleDesc(at, _mass, r, _phase, (uint)_p.Material, velocity: velocity); + } + if (!any) break; + } + _cursor = (_cursor + 1) % _pointCount; + if (n == 0) return; + + _world.CreateParticles(_descs.AsSpan(0, n), _created.AsSpan(0, n)); + for (int i = 0; i < n; i++) + { + _live[_liveCount] = _created[i]; + _calm[_liveCount] = 0; + _liveCount++; + } + Emitted += n * _dropVolume; + } + + /// Settles the drops that have come to rest, then the oldest supported ones down to room for a full tick, after the step. + internal void AfterStep() + { + if (_liveCount == 0) return; + var v = _world.View; + var support = v.SupportBody; + var onParticle = v.SupportParticle; + var vx = v.ParticleVx; var vy = v.ParticleVy; var vz = v.ParticleVz; + float slow2 = _p.SettleSpeed * _p.SettleSpeed; + int settling = 0; + for (int i = 0; i < _liveCount; i++) + { + int lane = _live[i].Lane; + bool supported = support[lane] >= 0 || onParticle[lane] >= 0; + bool still = vx[lane] * vx[lane] + vy[lane] * vy[lane] + vz[lane] * vz[lane] < slow2; + _calm[i] = supported && still ? _calm[i] + 1 : 0; + _supported[i] = supported; + _chosen[i] = supported && _calm[i] >= _p.SettleTicks; + if (_chosen[i]) settling++; + } + int room = _p.LiveCap - _p.MaxDropsPerTick; + for (int i = 0; i < _liveCount && _liveCount - settling > room; i++) + { + if (_chosen[i] || !_supported[i]) continue; + _chosen[i] = true; + settling++; + } + if (settling == 0) return; + + int s = 0, kept = 0; + for (int i = 0; i < _liveCount; i++) if (_chosen[i]) _settling[s++] = _live[i]; + _world.Settle(_settling.AsSpan(0, s)); + for (int i = 0; i < _liveCount; i++) + { + if (_chosen[i]) continue; + _live[kept] = _live[i]; + _calm[kept] = _calm[i]; + kept++; + } + _liveCount = kept; + } +} diff --git a/src/BadDay.Ymir/OfficeBodySession.cs b/src/BadDay.Ymir/OfficeBodySession.cs index a9d0ca0..0788aa0 100644 --- a/src/BadDay.Ymir/OfficeBodySession.cs +++ b/src/BadDay.Ymir/OfficeBodySession.cs @@ -22,6 +22,7 @@ public sealed class OfficeBodySession : IDisposable private readonly StressSession _session; private readonly Physiology _physiology; private readonly double _tickSeconds; + private readonly double[] _bleeds; private readonly int _handL, _handR, _pelvisLane; private bool _disposed; @@ -37,6 +38,7 @@ public sealed class OfficeBodySession : IDisposable try { var plan = _body.Plan; + _bleeds = new double[plan.Parts.Count]; _body.ReadSenses(); int head = plan.SenseIndex("Head"); _handL = plan.SenseIndex("Hand", Side.Left); @@ -71,6 +73,14 @@ public sealed class OfficeBodySession : IDisposable public double Consciousness { get { Live(); return _physiology.Consciousness; } } public double BloodLoss { get { Live(); return _physiology.BloodLoss; } } public bool Dead { get { Live(); return _physiology.Dead; } } + /// The liquid in the airway (m^3), the fraction of it filled, and whether the last sample found liquid at an opening: Lodur's numbers. + public double AirwayLiquid { get { Live(); return _physiology.AirwayLiquid; } } + public double Occlusion { get { Live(); return _physiology.Occlusion; } } + public bool LiquidAtAirway { get { Live(); return _physiology.LiquidAtAirway; } } + /// The blood the body has shed as drops, the volume still waiting to be shed (visible m^3, the gain applied) and the drops not yet settled: the body's, display only. + public double BloodEmitted { get { Live(); return _body.BloodEmitted; } } + public double BloodBacklog { get { Live(); return _body.BloodBacklog; } } + public int LiveDrops { get { Live(); return _body.LiveDrops; } } public DeathCause DeathCause { get { Live(); return _physiology.Cause; } } public OfficeGoal Goal { get { Live(); return OfficeBrain.GoalAt(_session.Actor.GoalIndex); } } @@ -97,8 +107,12 @@ public sealed class OfficeBodySession : IDisposable _body.ReadSenses(); var events = _session.Tick(_body.X, _body.Y, _body.Z, _body.Strengths, _body.Targets); if (events != TickEvents.None) _body.Enqueue(tick, events); + for (int part = 0; part < _bleeds.Length; part++) _bleeds[part] = _physiology.Bleed(part); + _body.DriveAndStep(_tickSeconds, _bleeds); + return; } - _body.DriveAndStep(_tickSeconds); // after Finished: the last strengths and targets again + // After Finished the physiology no longer steps, so its last rates would run forever: no bleeds, and what is in flight settles. + _body.DriveAndStep(_tickSeconds); // the last strengths and targets again } /// Moves the queued events (oldest first) into ; see . @@ -115,11 +129,23 @@ public sealed class OfficeBodySession : IDisposable _session.Silence(stressorId); } - /// Wounds the body's part from the next tick; false when refused (see ). - public bool Wound(int part, WoundTool tool) + /// The part of the body a ray meets first; see . + public PartHit? Pick(BodyPoint origin, BodyPoint translation) { Live(); - return _session.Wound(part, tool); + return _body.Pick(origin, translation); + } + + /// + /// Wounds the part names from the next tick, and opens the wound at the point it hit so the blood leaves from there; + /// false when refused (see ), and then nothing is opened. + /// + public bool Wound(in PartHit hit, WoundTool tool) + { + Live(); + if (!_session.Wound(hit.Part, tool)) return false; + _body.OpenWound(hit.Part, hit.Point, hit.Normal); + return true; } /// The nervous result so far, with the death if there was one. diff --git a/src/BadDay.Ymir/SeatedBody.cs b/src/BadDay.Ymir/SeatedBody.cs index b9dcc68..a5df203 100644 --- a/src/BadDay.Ymir/SeatedBody.cs +++ b/src/BadDay.Ymir/SeatedBody.cs @@ -6,12 +6,15 @@ using Ymir.Box3D; namespace BadDay.Ymir; +/// A part of the body met by a ray: its plan ordinal, the world point and the outward surface normal there. +public readonly record struct PartHit(int Part, BodyPoint Point, BodyPoint Normal); + /// What the Actor reported on one tick of a body run; only ticks that reported something are queued. public readonly record struct BodyEvent(long Tick, TickEvents Events); /// /// The one owner of a BDS body world: the sized by , the -/// ragdoll puts in it, the sense-point, strength and target lanes, and the queue of +/// ragdoll puts in it, the body's blood (, the one writer of fluid particles and wet patches in the world), the sense-point, strength and target lanes, and the queue of /// the Actor's events. Every body run (the pain box, the office) holds one and decides nothing here: per tick the run /// calls , lets its scenario write and from the /// points, then . No other code in BDS creates or steps a world. After @@ -24,6 +27,8 @@ public sealed class SeatedBody : IDisposable private readonly float[] _x, _y, _z; private readonly float[] _strengths; private readonly Quat[] _targets; + private readonly Blood _blood; + private readonly float[] _airLive, _airPooled, _airDrop; private readonly Queue _events = new(); private bool _disposed; @@ -39,6 +44,10 @@ public sealed class SeatedBody : IDisposable _world.SetMaterial(blood.Material, blood.Friction, viscosity: blood.Viscosity, wetFriction: blood.WetFriction); _ragdoll = SeatedPuppet.Build(_world); var plan = _ragdoll.Plan; + _blood = new Blood(_world, _ragdoll, blood); + _airLive = new float[plan.AirwayOpenings.Count]; + _airPooled = new float[plan.AirwayOpenings.Count]; + _airDrop = new float[plan.AirwayOpenings.Count]; _x = new float[plan.SensePoints.Count]; _y = new float[plan.SensePoints.Count]; _z = new float[plan.SensePoints.Count]; @@ -81,13 +90,51 @@ public sealed class SeatedBody : IDisposable } /// Drives the ragdoll with the current strengths and targets, then steps the world one seconds. - public void DriveAndStep(double dt) + public void DriveAndStep(double dt, ReadOnlySpan bleedPerPart = default) { Live(); + _blood.BeforeStep(bleedPerPart, dt); _ragdoll.Drive(_strengths, _targets); _world.Step((float)dt, SeatedPuppet.Substeps); + _blood.AfterStep(); } + /// What the world holds at the airway openings now: Lodur's sample of the liquid sensors and the body's pose, down being the world's gravity. + public AirwaySample ReadAirway() + { + Live(); + _ragdoll.ReadAirway(_airLive, _airPooled, _airDrop, _world.Gravity); + return AirwaySample.Of(_airLive, _airPooled, _airDrop); + } + + /// The part of the body a ray from along meets first, with the point and surface normal; null for a miss or when the first thing met is not a part of the body. + public PartHit? Pick(BodyPoint origin, BodyPoint translation) + { + Live(); + var hit = _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z)); + if (!hit.Hit || hit.StableId < SeatedPuppet.FirstStableId) return null; + ulong ordinal = hit.StableId - SeatedPuppet.FirstStableId; + if (ordinal >= (ulong)Plan.Parts.Count || _ragdoll.BodyLane((int)ordinal) != hit.Lane) return null; + return new PartHit((int)ordinal, new BodyPoint(hit.Point.X, hit.Point.Y, hit.Point.Z), new BodyPoint(hit.Normal.X, hit.Normal.Y, hit.Normal.Z)); + } + + /// Opens a wound at a world point and normal on : from now on it sheds its share of the part's bleed, carried by the part. + public void OpenWound(int part, BodyPoint point, BodyPoint normal) + { + Live(); + int lane = _ragdoll.BodyLane(part); + var v = _world.View; + var inverse = new Quat(v.RotationX[lane], v.RotationY[lane], v.RotationZ[lane], v.RotationW[lane]).Conjugate(); + inverse.Rotate(point.X - v.PositionX[lane], point.Y - v.PositionY[lane], point.Z - v.PositionZ[lane], out var px, out var py, out var pz); + inverse.Rotate(normal.X, normal.Y, normal.Z, out var nx, out var ny, out var nz); + _blood.Open(part, px, py, pz, nx, ny, nz); + } + + /// Visible blood volume (m^3) shed so far and still gathered at the wounds, and the drops not yet settled. + public double BloodEmitted { get { Live(); return _blood.Emitted; } } + public double BloodBacklog { get { Live(); return _blood.Backlog; } } + public int LiveDrops { get { Live(); return _blood.Live; } } + public void Enqueue(long tick, TickEvents events) { Live(); diff --git a/tests/BadDay.Tests/Program.cs b/tests/BadDay.Tests/Program.cs index ac5fd1e..e052464 100644 --- a/tests/BadDay.Tests/Program.cs +++ b/tests/BadDay.Tests/Program.cs @@ -1123,7 +1123,7 @@ public static class Program for (int run = 0; run < 2; run++) { using var s = new OfficeBodySession(p, 1); - Check(s.Wound(arm, WoundTool.Knife), "the knife was refused on the lower arm"); + Check(s.Wound(Hit(s, arm), WoundTool.Knife), "the knife was refused on the lower arm"); var buffer = new BodyEvent[16]; int died = 0; bool deadBefore = false; @@ -1176,7 +1176,7 @@ public static class Program var p = new StressParameters { TickSeconds = OfficeBody.TickSeconds }; using (var s = new OfficeBodySession(p, 1)) { - Check(!s.Wound(-1, WoundTool.Knife) && !s.Wound(SeatedPuppet.Plan.Parts.Count, WoundTool.Knife), "an out-of-range part was wounded"); + Check(!s.Wound(new PartHit(-1, default, default), WoundTool.Knife) && !s.Wound(new PartHit(SeatedPuppet.Plan.Parts.Count, default, default), WoundTool.Knife), "an out-of-range part was wounded"); } Check(!NewOffice(p, 1).Wound(0, WoundTool.Knife), "a headless session was wounded"); @@ -1200,7 +1200,7 @@ public static class Program long Recovered(double scale) { using var s = new OfficeBodySession(p with { SlowScale = scale }, 1); - Check(s.Wound(arm, new WoundTool(new[] { "Skin" }, 0.006)), "the skin wound was refused"); + Check(s.Wound(Hit(s, arm), new WoundTool(new[] { "Skin" }, 0.006)), "the skin wound was refused"); bool bled = false; while (!s.Finished) { @@ -1239,7 +1239,7 @@ public static class Program } using (var s = new OfficeBodySession(p, 1)) { - Check(s.Wound(SeatedPuppet.Plan.PartIndex("Torso", Lodur.Side.Center), new WoundTool(new[] { "LungLeft", "LungRight" }, 15.0)), "the lungs were refused"); + Check(s.Wound(Hit(s, SeatedPuppet.Plan.PartIndex("Torso", Lodur.Side.Center)), new WoundTool(new[] { "LungLeft", "LungRight" }, 15.0)), "the lungs were refused"); double maxHunger = 0.0; while (!s.Finished) { @@ -1275,17 +1275,19 @@ public static class Program var leg = plan.PartIndex("Shin", Lodur.Side.Left); using (var s = new OfficeBodySession(p, 1)) { - Check(s.Wound(arm, WoundTool.Knife), "the knife was refused"); + var legHit = Hit(s, leg); + Check(s.Wound(Hit(s, arm), WoundTool.Knife), "the knife was refused"); while (!s.Dead) s.Step(); Check(!s.Finished, "the run finished at the death"); - Check(!s.Wound(leg, WoundTool.Knife), "a dead body was wounded"); + Check(!s.Wound(legHit, WoundTool.Knife), "a dead body was wounded"); while (!s.Finished) s.Step(); - Check(!s.Wound(leg, WoundTool.Knife), "a finished run was wounded"); + Check(!s.Wound(legHit, WoundTool.Knife), "a finished run was wounded"); } using (var s = new OfficeBodySession(p, 1)) { + var legHit = Hit(s, leg); while (!s.Finished) s.Step(); - Check(!s.Dead && !s.Wound(leg, WoundTool.Knife), "a finished, living run was wounded"); + Check(!s.Dead && !s.Wound(legHit, WoundTool.Knife), "a finished, living run was wounded"); } var physiologyPlan = Lodur.PhysiologyPlans.Humanoid(); @@ -1347,11 +1349,155 @@ public static class Program Check(!s.Dead && s.DeathCause == Lodur.DeathCause.None && r.DiedAtMs is null && r.Outcome != Outcome.Died && s.Consciousness == 1.0, $"seed {seed}: dead {s.Dead}, cause {s.DeathCause}, consciousness {s.Consciousness}"); } }), + + ("office blood is the gain times the spill: one Knife at Hit(s, LowerArm L), 10 s; Emitted + Backlog == 10 x (nominal - BloodVolume) within 1e-9 m^3, the backlog is under one drop, and two runs are equal", () => + { + var p = new StressParameters { TickSeconds = OfficeBody.TickSeconds }; + var blood = Lodur.PhysiologyPlans.Humanoid().Blood; + var bloodParameters = new BloodParameters(); + var arm = SeatedPuppet.Plan.PartIndex("LowerArm", Lodur.Side.Left); + var seen = new List<(double Emitted, double Backlog, int Live)>(); + for (int run = 0; run < 2; run++) + { + using var s = new OfficeBodySession(p, 1); + Check(s.Wound(Hit(s, arm), WoundTool.Knife), "the knife was refused"); + for (int t = 0; t < 10 * Hz; t++) s.Step(); + double spilled = blood.NominalVolume * s.BloodLoss * blood.LethalLossFraction; // nominal - BloodVolume + double visible = bloodParameters.Gain * spilled; + Check(visible > 0.005, $"only {visible * 1000.0:F1} L was spilled in 10 s"); + Check(Math.Abs(s.BloodEmitted + s.BloodBacklog - visible) < 1e-9, $"emitted {s.BloodEmitted} + backlog {s.BloodBacklog} is not {visible} m^3"); + Check(s.BloodBacklog >= 0.0 && s.BloodBacklog < bloodParameters.DropVolume, $"backlog {s.BloodBacklog} m^3 is not under one drop"); + Console.WriteLine($" blood: {visible * 1000.0:F2} L visible in 10 s, {s.BloodEmitted / bloodParameters.DropVolume:F0} drops, backlog {s.BloodBacklog * 1e6:F2} mL, live {s.LiveDrops}"); + seen.Add((s.BloodEmitted, s.BloodBacklog, s.LiveDrops)); + } + Check(seen[0] == seen[1], "two runs shed different blood"); + }), + + ("office blood settles under the cap: six Knife cuts; LiveDrops <= LiveCap - MaxDropsPerTick after every Step, no refused CreateParticles, WetCount > 0 by 15 s, and wet volume + live drops == Emitted within 1e-6 m^3", () => + { + var p = new StressParameters { TickSeconds = OfficeBody.TickSeconds }; + var bloodParameters = new BloodParameters(); + using var s = SixCuts(p); + var clock = System.Diagnostics.Stopwatch.StartNew(); + int wetAt15 = -1, peak = 0; + for (int t = 0; t < 40 * Hz; t++) + { + s.Step(); // a refused CreateParticles or Settle throws here + Check(s.LiveDrops <= bloodParameters.LiveCap - bloodParameters.MaxDropsPerTick, $"tick {t}: {s.LiveDrops} drops live"); + peak = Math.Max(peak, s.LiveDrops); + if (t == 15 * Hz) wetAt15 = s.View.WetCount; + } + clock.Stop(); + Check(wetAt15 > 0, "no wet patch by 15 s"); + double wet = 0.0; + var volume = s.View.WetPatchVolume; + var live = s.View.WetLive; + for (int i = 0; i < volume.Length; i++) if (live[i] != 0u) wet += volume[i]; + double held = wet + s.LiveDrops * bloodParameters.DropVolume; + Check(Math.Abs(held - s.BloodEmitted) < 1e-6, $"wet {wet} + live {s.LiveDrops} x drop is {held}, emitted {s.BloodEmitted} m^3"); + Console.WriteLine($" blood: {s.BloodEmitted * 1000.0:F1} L shed, backlog {s.BloodBacklog * 1000.0:F2} L, peak live {peak}, {s.View.WetCount} wet patches, {clock.Elapsed.TotalMilliseconds / (40 * Hz):F2} ms a tick whole (probe: +0.56 ms at 256 live)"); + }), + + ("office blood lands where it falls: every patch's support is the ground, the stool or a Fella lane, and six cuts give a ground patch (stable id 1) by 40 s", () => + { + var p = new StressParameters { TickSeconds = OfficeBody.TickSeconds }; + using var s = SixCuts(p); + for (int t = 0; t < 40 * Hz; t++) s.Step(); + var view = s.View; + var ids = view.StableId; + var patches = new SortedDictionary(); + for (int i = 0; i < view.WetCount; i++) + { + if (view.WetLive[i] == 0u) continue; + Check(view.WetParticle[i] < 0 && view.WetBody[i] >= 0, $"patch {i} is held by no body ({view.WetBody[i]}, particle {view.WetParticle[i]})"); + ulong id = ids[view.WetBody[i]]; + Check(id == 1 || id == 2 || (id >= SeatedPuppet.FirstStableId && id < SeatedPuppet.FirstStableId + (ulong)SeatedPuppet.Plan.Parts.Count), $"patch {i} sits on stable id {id}"); + patches[id] = patches.GetValueOrDefault(id) + 1; + } + Check(patches.GetValueOrDefault(1UL) > 0, "no patch reached the ground"); + Console.WriteLine(" patches per support (stable id): " + string.Join(", ", patches.Select(kv => $"{kv.Key}: {kv.Value}"))); + }), + + ("seated world identity: a SeatedBody (a particle system, no wound) steps to the same positions and rotations as the same world with no particle system, 1200 driven ticks", () => + { + using var body = new SeatedBody(); + var needs = SeatedPuppet.Needs; + using var control = new global::Ymir.Box3D.Box3DSoaWorld(capacity: needs.Bodies, jointCapacity: needs.Joints); + var ragdoll = SeatedPuppet.Build(control); + var strengths = new float[SeatedPuppet.Plan.Joints.Count]; + var targets = new Quat[strengths.Length]; + for (int i = 0; i < strengths.Length; i++) { strengths[i] = 0.4f; targets[i] = Quat.FromAxisAngle(0f, 0f, 1f, 0.05f * (i % 5)); body.Strengths[i] = strengths[i]; body.Targets[i] = targets[i]; } + for (int t = 0; t < 1200; t++) + { + ragdoll.Drive(strengths, targets); + control.Step(1f / Hz, SeatedPuppet.Substeps); + body.DriveAndStep(1.0 / Hz); + var a = body.View; + var b = control.View; + Check(a.Count == b.Count, "the lane counts differ"); + for (int i = 0; i < a.Count; i++) + { + Check(a.PositionX[i] == b.PositionX[i] && a.PositionY[i] == b.PositionY[i] && a.PositionZ[i] == b.PositionZ[i] && + a.RotationX[i] == b.RotationX[i] && a.RotationY[i] == b.RotationY[i] && a.RotationZ[i] == b.RotationZ[i] && a.RotationW[i] == b.RotationW[i], + $"tick {t}, lane {i}: the particle world moved a body"); + } + } + }), }; private static readonly float[] Point = new float[1], Strengths = new float[1]; private static readonly Quat[] Targets = new Quat[1]; + /// An office session with six Knife cuts at tick 0: both lower arms, both thighs, both shins. + private static OfficeBodySession SixCuts(StressParameters p) + { + var plan = SeatedPuppet.Plan; + var s = new OfficeBodySession(p, 1); + try + { + foreach (var label in new[] { "LowerArm", "Thigh", "Shin" }) + { + foreach (var side in new[] { Lodur.Side.Left, Lodur.Side.Right }) + { + Check(s.Wound(Hit(s, plan.PartIndex(label, side)), WoundTool.Knife), $"the knife was refused on {label} {side}"); + } + } + return s; + } + catch + { + s.Dispose(); + throw; + } + } + + /// + /// A hit on : rays from 1 m outside the part's rest centre along -X, +X, -Y, +Y, -Z, +Z toward it, the first that meets that part first. + /// Taken at the start of a run, while the body is where the plan puts it. + /// + private static PartHit Hit(OfficeBodySession s, int part) + { + var c = SeatedPuppet.Plan.Parts[part].Position; + foreach (var (dx, dy, dz) in new[] { (1f, 0f, 0f), (-1f, 0f, 0f), (0f, 1f, 0f), (0f, -1f, 0f), (0f, 0f, 1f), (0f, 0f, -1f) }) + { + var hit = s.Pick(new BodyPoint(c.X - dx, c.Y - dy, c.Z - dz), new BodyPoint(dx, dy, dz)); + if (hit is { } h && h.Part == part) return h; + } + throw new InvalidOperationException($"no ray from outside meets part {part} first"); + } + + /// A hit on the head at the plan's Mouth opening: a ray from 1 m in front of it, straight back. + private static PartHit MouthHit(OfficeBodySession s) + { + var plan = SeatedPuppet.Plan; + var mouth = plan.AirwayOpenings.First(a => a.Label == "Mouth"); + var c = plan.Parts[mouth.Part].Position; + var at = new BodyPoint(c.X + mouth.Offset.X, c.Y + mouth.Offset.Y, c.Z + mouth.Offset.Z); + var ray = s.Pick(new BodyPoint(at.X, at.Y, at.Z + 1f), new BodyPoint(0f, 0f, -1f)); + Check(ray is { } h && h.Part == mouth.Part, "a ray at the mouth did not meet the head first"); + return ray!.Value; + } + 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);