diff --git a/client/Puppet.cs b/client/Puppet.cs
index c740c7f..e808d63 100644
--- a/client/Puppet.cs
+++ b/client/Puppet.cs
@@ -14,22 +14,12 @@ namespace BadDay.Client;
///
public partial class Puppet : Node3D
{
- /// The shader's bone array size.
- private const int MaxBones = 32;
-
private readonly Dictionary _nodes = new();
private readonly HashSet _seen = new();
private readonly ShaderMaterial _material = new() { Shader = GD.Load("res://puppet.gdshader") };
private readonly MeshInstance3D _skin = new MeshInstance3D { Name = "Skin" };
private readonly Godot.Collections.Array _bones = new();
- private readonly Dictionary _bind = new();
- private readonly Dictionary<(uint, ulong, ulong), float3> _originLocal = new();
- private readonly List _shapeLanes = new();
- private readonly List _jointLanes = new();
- private (ulong Id, uint Kind, float S0, float S1, float S2)[] _bodySig = Array.Empty<(ulong, uint, float, float, float)>();
- private (uint Kind, ulong A, ulong B)[] _jointSig = Array.Empty<(uint, ulong, ulong)>();
- private bool _signed;
- private int _builds;
+ private readonly PuppetModel _model = new(Look.SminRadius, Look.JointBallScale, Look.BoxRound);
private ArrayMesh? _mesh;
private Node3D[] _boneNodes = Array.Empty();
private Transform3D[] _inverseBind = Array.Empty();
@@ -37,7 +27,7 @@ public partial class Puppet : Node3D
public Puppet()
{
_material.SetShaderParameter("albedo", Look.Figure);
- for (int i = 0; i < MaxBones; i++) _bones.Add(new Projection(Transform3D.Identity));
+ for (int i = 0; i < PuppetModel.MaxBones; i++) _bones.Add(new Projection(Transform3D.Identity));
_skin.MaterialOverride = _material;
}
@@ -47,7 +37,7 @@ public partial class Puppet : Node3D
public Color Color => _material.GetShaderParameter("albedo").AsColor();
/// What the puppet is made of now, or null before the first build or while it draws nothing (too many bodies).
- public PuppetShape? Shape { get; private set; }
+ public PuppetShape? Shape => _model.Shape;
public override void _Ready() => AddChild(_skin);
@@ -95,12 +85,9 @@ public partial class Puppet : Node3D
var node = _nodes[ids[i]];
node.Transform = new Transform3D(new Basis(new Quaternion(rx[i], ry[i], rz[i], rw[i])), new Vector3(px[i], py[i], pz[i]));
if (teleport) node.ResetPhysicsInterpolation();
- // A body's bind is its pose the first time the puppet sees it: the creation pose, every joint's zero.
- if (PuppetField.HasShape((Box3DSoaKind)kind[i]) && !_bind.ContainsKey(ids[i]))
- _bind[ids[i]] = Rigid.FromQuaternion(rx[i], ry[i], rz[i], rw[i], new float3(px[i], py[i], pz[i]));
}
- if (!SignatureHolds(view)) Rebuild(view);
+ if (_model.Update(view)) Rebuild();
}
public override void _Process(double delta)
@@ -134,72 +121,17 @@ public partial class Puppet : Node3D
return true;
}
- ///
- /// Collects the shape bodies and the qualifying joints of the lanes and says whether they are the ordered
- /// (StableId, Kind, Size0..2) and (JointKind, StableId A, StableId B) the mesh was built from.
- ///
- private bool SignatureHolds(in Box3DSoaView view)
+ /// Takes up the model's new shape: the carriers that are its bones, their inverse bind, and the mesh.
+ private void Rebuild()
{
- _shapeLanes.Clear(); _jointLanes.Clear();
- var kind = view.Kind;
- for (int i = 0; i < kind.Length; i++) if (PuppetField.HasShape((Box3DSoaKind)kind[i])) _shapeLanes.Add(i);
- for (int j = 0; j < view.JointCount; j++)
+ if (_model.Shape is not { } shape)
{
- int a = view.JointBodyA[j], b = view.JointBodyB[j];
- if (a >= 0 && b >= 0 && PuppetField.Qualifies((Box3DSoaJointKind)view.JointKind[j], (Box3DSoaKind)kind[a], (Box3DSoaKind)kind[b])) _jointLanes.Add(j);
- }
- if (!_signed || _shapeLanes.Count != _bodySig.Length || _jointLanes.Count != _jointSig.Length) return false;
- for (int k = 0; k < _shapeLanes.Count; k++)
- {
- int i = _shapeLanes[k];
- if (_bodySig[k] != (view.StableId[i], kind[i], view.Size0[i], view.Size1[i], view.Size2[i])) return false;
- }
- for (int k = 0; k < _jointLanes.Count; k++)
- {
- int j = _jointLanes[k];
- if (_jointSig[k] != (view.JointKind[j], view.StableId[view.JointBodyA[j]], view.StableId[view.JointBodyB[j]])) return false;
- }
- return true;
- }
-
- private void Rebuild(in Box3DSoaView view)
- {
- var kind = view.Kind;
- _bodySig = new (ulong, uint, float, float, float)[_shapeLanes.Count];
- var indexOf = new Dictionary();
- var bodies = new List();
- for (int k = 0; k < _shapeLanes.Count; k++)
- {
- int i = _shapeLanes[k];
- _bodySig[k] = (view.StableId[i], kind[i], view.Size0[i], view.Size1[i], view.Size2[i]);
- indexOf[i] = k;
- bodies.Add(new PuppetBody(view.StableId[i], (Box3DSoaKind)kind[i], new float3(view.Size0[i], view.Size1[i], view.Size2[i]), _bind[view.StableId[i]]));
- }
- _jointSig = new (uint, ulong, ulong)[_jointLanes.Count];
- var joints = new List();
- for (int k = 0; k < _jointLanes.Count; k++)
- {
- int j = _jointLanes[k], a = view.JointBodyA[j], b = view.JointBodyB[j];
- var key = (view.JointKind[j], view.StableId[a], view.StableId[b]);
- _jointSig[k] = key;
- // The joint origin is body A's, kept in A's frame so it follows A; the first sight is the creation pose.
- if (!_originLocal.TryGetValue(key, out var local))
- _originLocal[key] = local = _bind[key.Item2].Inverse().Apply(new float3(view.JointOriginX[j], view.JointOriginY[j], view.JointOriginZ[j]));
- joints.Add(new PuppetJoint((Box3DSoaJointKind)key.Item1, indexOf[a], indexOf[b], local));
- }
- _signed = true;
-
- if (bodies.Count > MaxBones)
- {
- GD.PushError($"BadDay: the puppet has {bodies.Count} shape bodies and the skin has {MaxBones} bones; drawing no puppet.");
- Shape = null; _mesh = null; _skin.Mesh = null;
+ GD.PushError($"BadDay: the puppet has more than {PuppetModel.MaxBones} shape bodies, which is the skin's bone count; drawing no puppet.");
+ _mesh = null; _skin.Mesh = null;
return;
}
- var shape = PuppetField.Build(bodies, joints, Look.SminRadius, Look.JointBallScale, Look.BoxRound);
- shape.Builds = ++_builds;
- Shape = shape;
- _boneNodes = new Node3D[bodies.Count]; _inverseBind = new Transform3D[bodies.Count];
- for (int i = 0; i < bodies.Count; i++) { _boneNodes[i] = _nodes[shape.Ids[i]]; _inverseBind[i] = ToTransform(shape.SpreadBind[i].Inverse()); }
+ _boneNodes = new Node3D[shape.Ids.Length]; _inverseBind = new Transform3D[shape.Ids.Length];
+ for (int i = 0; i < shape.Ids.Length; i++) { _boneNodes[i] = _nodes[shape.Ids[i]]; _inverseBind[i] = ToTransform(shape.SpreadBind[i].Inverse()); }
_mesh = MeshOf(shape);
_skin.Mesh = _mesh;
}
diff --git a/client/PuppetModel.cs b/client/PuppetModel.cs
new file mode 100644
index 0000000..9a3d335
--- /dev/null
+++ b/client/PuppetModel.cs
@@ -0,0 +1,107 @@
+using System.Collections.Generic;
+using CultMath;
+using Ymir.Box3D;
+
+namespace BadDay.Client;
+
+/// A qualifying joint as the lanes name it: the bodies by StableId, the joint origin in the world now.
+public readonly record struct PuppetJointLane(Box3DSoaJointKind Kind, ulong A, ulong B, float3 Origin);
+
+///
+/// Owns the puppet's shape and the one rule for when it is rebuilt, engine-free so the rule can be tested without a scene:
+/// the mesh is built from the first update and again only when the topology signature changes, which is the ordered
+/// (StableId, Kind, Size0..2) of the shape bodies and the ordered (JointKind, StableId A, StableId B) of the qualifying joints.
+/// A body's bind is its pose the first time it is seen (the creation pose); a joint's origin is kept in body A's frame from then.
+/// Poses and joint origins alone never rebuild.
+///
+public sealed class PuppetModel
+{
+ /// The skin's bone count: the shader's array size.
+ public const int MaxBones = 32;
+
+ private readonly float _smin, _ballScale, _boxRound;
+ private readonly Dictionary _bind = new();
+ private readonly Dictionary<(Box3DSoaJointKind, ulong, ulong), float3> _originLocal = new();
+ private readonly List _bodies = new();
+ private readonly List _joints = new();
+ private readonly List _laneBodies = new();
+ private readonly List _laneJoints = new();
+ private bool _signed;
+
+ private readonly record struct BodySignature(ulong Id, Box3DSoaKind Kind, float S0, float S1, float S2);
+ private readonly record struct JointSignature(Box3DSoaJointKind Kind, ulong A, ulong B);
+
+ public PuppetModel(float smin, float ballScale, float boxRound) { _smin = smin; _ballScale = ballScale; _boxRound = boxRound; }
+
+ /// The shape built from the current signature, or null before the first update or while there are more than shape bodies.
+ public PuppetShape? Shape { get; private set; }
+
+ /// How many meshes have been built.
+ public int Builds { get; private set; }
+
+ /// Reads the shape bodies and qualifying joints of the lanes and updates.
+ public bool Update(in Box3DSoaView view)
+ {
+ var kind = view.Kind;
+ var bodies = _laneBodies; bodies.Clear();
+ for (int i = 0; i < kind.Length; i++)
+ {
+ if (!PuppetField.HasShape((Box3DSoaKind)kind[i])) continue;
+ bodies.Add(new PuppetBody(view.StableId[i], (Box3DSoaKind)kind[i], new float3(view.Size0[i], view.Size1[i], view.Size2[i]),
+ Rigid.FromQuaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i], new float3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]))));
+ }
+ var joints = _laneJoints; joints.Clear();
+ for (int j = 0; j < view.JointCount; j++)
+ {
+ int a = view.JointBodyA[j], b = view.JointBodyB[j];
+ if (a < 0 || b < 0 || !PuppetField.Qualifies((Box3DSoaJointKind)view.JointKind[j], (Box3DSoaKind)kind[a], (Box3DSoaKind)kind[b])) continue;
+ joints.Add(new PuppetJointLane((Box3DSoaJointKind)view.JointKind[j], view.StableId[a], view.StableId[b], new float3(view.JointOriginX[j], view.JointOriginY[j], view.JointOriginZ[j])));
+ }
+ return Update(bodies, joints);
+ }
+
+ ///
+ /// carry their pose now in ; the model keeps the first one it saw.
+ /// Returns whether the signature changed, which is whether the shape was rebuilt (or dropped, past the bone cap).
+ ///
+ public bool Update(IReadOnlyList bodies, IReadOnlyList joints)
+ {
+ foreach (var b in bodies) _bind.TryAdd(b.Id, b.Bind);
+ if (_signed && SignatureHolds(bodies, joints)) return false;
+
+ _bodies.Clear(); _joints.Clear();
+ var index = new Dictionary();
+ var bound = new List();
+ foreach (var b in bodies)
+ {
+ index[b.Id] = bound.Count;
+ _bodies.Add(new BodySignature(b.Id, b.Kind, b.Size.x, b.Size.y, b.Size.z));
+ bound.Add(b with { Bind = _bind[b.Id] });
+ }
+ var built = new List();
+ foreach (var j in joints)
+ {
+ var key = (j.Kind, j.A, j.B);
+ _joints.Add(new JointSignature(j.Kind, j.A, j.B));
+ // The origin is body A's, kept in A's frame so it follows A; the first sight is the creation pose.
+ if (!_originLocal.TryGetValue(key, out var local)) _originLocal[key] = local = _bind[j.A].Inverse().Apply(j.Origin);
+ built.Add(new PuppetJoint(j.Kind, index[j.A], index[j.B], local));
+ }
+ _signed = true;
+
+ if (bound.Count > MaxBones) { Shape = null; return true; }
+ Shape = PuppetField.Build(bound, built, _smin, _ballScale, _boxRound);
+ Shape.Builds = ++Builds;
+ return true;
+ }
+
+ private bool SignatureHolds(IReadOnlyList bodies, IReadOnlyList joints)
+ {
+ if (bodies.Count != _bodies.Count || joints.Count != _joints.Count) return false;
+ for (int i = 0; i < bodies.Count; i++)
+ if (_bodies[i] != new BodySignature(bodies[i].Id, bodies[i].Kind, bodies[i].Size.x, bodies[i].Size.y, bodies[i].Size.z)) return false;
+ for (int i = 0; i < joints.Count; i++)
+ if (_joints[i] != new JointSignature(joints[i].Kind, joints[i].A, joints[i].B)) return false;
+ return true;
+ }
+}
diff --git a/client/tests/PuppetChecks.cs b/client/tests/PuppetChecks.cs
new file mode 100644
index 0000000..ac58fe8
--- /dev/null
+++ b/client/tests/PuppetChecks.cs
@@ -0,0 +1,78 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using CultMath;
+using Ymir.Box3D;
+
+namespace BadDay.Client.Tests;
+
+///
+/// The puppet's rules that need no scene, run by the smoke before its scenario: when the model rebuilds the shape.
+/// Each check reports what broke through fail.
+///
+public static class PuppetChecks
+{
+ private static readonly float3 Zero = new(0, 0, 0);
+
+ private static PuppetBody Body(ulong id, Box3DSoaKind kind, float s0, float s1, float y) =>
+ new(id, kind, new float3(s0, s1, 0), Rigid.FromQuaternion(0, 0, 0, 1, new float3(0, y, 0)));
+
+ private static (List Bodies, List Joints) Chain() => (
+ new List
+ {
+ Body(10, Box3DSoaKind.Capsule, 0.06f, 0.15f, 0.3f),
+ Body(11, Box3DSoaKind.Capsule, 0.05f, 0.12f, 0.7f),
+ Body(12, Box3DSoaKind.Sphere, 0.09f, 0f, 1.0f),
+ },
+ new List
+ {
+ new(Box3DSoaJointKind.Spherical, 10, 11, new float3(0, 0.5f, 0)),
+ new(Box3DSoaJointKind.Revolute, 11, 12, new float3(0, 0.85f, 0)),
+ });
+
+ public static void Run(Action fail)
+ {
+ void Check(bool ok, string what) { if (!ok) fail(what); }
+ PuppetModel Fresh() => new(Look.SminRadius, Look.JointBallScale, Look.BoxRound);
+
+ // The first update builds; the same signature again, even from new lists, never does.
+ var m = Fresh();
+ var (bodies, joints) = Chain();
+ Check(m.Update(bodies, joints) && m.Builds == 1 && m.Shape is not null, "the first update did not build the puppet once");
+ var (again, againJoints) = Chain();
+ Check(!m.Update(again, againJoints) && m.Builds == 1, "an unchanged signature rebuilt the puppet");
+
+ // Poses and joint origins alone are not topology: the bind is the first sight.
+ var moved = Chain();
+ for (int i = 0; i < moved.Bodies.Count; i++) moved.Bodies[i] = moved.Bodies[i] with { Bind = Rigid.FromQuaternion(0, 0, 0, 1, new float3(0.5f, 2f + i, 0)) };
+ moved.Joints[0] = moved.Joints[0] with { Origin = new float3(9, 9, 9) };
+ var before = m.Shape;
+ Check(!m.Update(moved.Bodies, moved.Joints) && m.Builds == 1 && ReferenceEquals(m.Shape, before), "bodies that only moved rebuilt the puppet");
+
+ // Each change of topology rebuilds exactly once, and then holds.
+ void Changes(string what, Action, List> edit)
+ {
+ var model = Fresh();
+ var (b, j) = Chain();
+ model.Update(b, j);
+ edit(b, j);
+ Check(model.Update(b, j) && model.Builds == 2, $"{what}: the signature changed and the puppet was not rebuilt once");
+ Check(!model.Update(b, j) && model.Builds == 2, $"{what}: the new signature rebuilt again");
+ }
+ Changes("a joint removed", (b, j) => j.RemoveAt(1));
+ Changes("a body added", (b, j) => b.Add(Body(13, Box3DSoaKind.Sphere, 0.05f, 0f, 1.3f)));
+ Changes("a body removed", (b, j) => { b.RemoveAt(2); j.RemoveAt(1); });
+ Changes("a size changed", (b, j) => b[0] = b[0] with { Size = new float3(0.07f, 0.15f, 0f) });
+ Changes("a shape kind changed", (b, j) => b[2] = b[2] with { Kind = Box3DSoaKind.Capsule, Size = new float3(0.09f, 0.05f, 0f) });
+ Changes("a joint's kind changed", (b, j) => j[0] = j[0] with { Kind = Box3DSoaJointKind.Weld });
+ Changes("a body's identity changed", (b, j) => { b[1] = b[1] with { Id = 21 }; j[0] = j[0] with { B = 21 }; j[1] = j[1] with { A = 21 }; });
+
+ // Past the skin's bone count nothing is drawn, once, and the signature still decides.
+ var many = Fresh();
+ var crowd = Enumerable.Range(0, PuppetModel.MaxBones + 1).Select(i => Body((ulong)(100 + i), Box3DSoaKind.Sphere, 0.05f, 0f, i * 0.2f)).ToList();
+ Check(many.Update(crowd, new List()) && many.Shape is null && many.Builds == 0, "more shape bodies than bones was drawn");
+ Check(!many.Update(crowd, new List()), "an over-full puppet reported a change with none");
+ crowd.RemoveAt(0);
+ Check(many.Update(crowd, new List()) && many.Shape is not null, "the puppet did not come back once it fit the skin");
+ }
+}
diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs
index 912b07c..2d29a1c 100644
--- a/client/tests/Smoke.cs
+++ b/client/tests/Smoke.cs
@@ -57,6 +57,8 @@ public partial class Smoke : Node
private async Task Scenario()
{
CheckEngineAndScene();
+ PuppetChecks.Run(failure => Check(false, "puppet: " + failure));
+ if (_failures.Count > 0) return;
// Slow motion, by wall clock: a quarter of the session steps per real second, the same run.
await Frames(10);
@@ -70,6 +72,12 @@ public partial class Smoke : Node
// The rest runs the physics clock fast; the session still steps 1/120 s per frame.
Engine.PhysicsTicksPerSecond = 1200;
+ // A Reset is not a topology change: the mesh stays the one built at startup. Checked after three resets so a rebuild per
+ // Reset fails here, not after hundreds.
+ for (ulong seed = 1; seed <= 3; seed++) { PressReset(seed); await Frame(); }
+ Check(_main.Bodies.PuppetShape?.Builds == 1, $"the puppet mesh was built {_main.Bodies.PuppetShape?.Builds} times by the third Reset; the signature never changed, so once");
+ if (_failures.Count > 0) return;
+
// Seed 1 at the default intensity against the headless run: events, and the hand at ticks 240 and 1500.
PressReset(1);
var reference = Run(new PainBoxParameters().BoxIntensity, 1, 1500);