Puppet: the topology rule is PuppetModel, a seam the smoke drives; the build count is checked after three resets

Findings topology-rebuild-untested and build-count-check-late. PuppetModel owns the
first-sight bind, the signature and the one build; Puppet takes its shape. PuppetChecks
(run by the smoke, no scene) drive one rebuild per changed signature (joint removed,
body added or removed, size, kind, joint kind, identity), none for an unchanged one or a
body that only moved, and the bone cap. A rebuild per Reset now fails at the third Reset.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 05:26:36 +01:00
commit eb9d02cad6
4 changed files with 204 additions and 79 deletions

View file

@ -14,22 +14,12 @@ namespace BadDay.Client;
/// </summary>
public partial class Puppet : Node3D
{
/// <summary>The shader's bone array size.</summary>
private const int MaxBones = 32;
private readonly Dictionary<ulong, Node3D> _nodes = new();
private readonly HashSet<ulong> _seen = new();
private readonly ShaderMaterial _material = new() { Shader = GD.Load<Shader>("res://puppet.gdshader") };
private readonly MeshInstance3D _skin = new MeshInstance3D { Name = "Skin" };
private readonly Godot.Collections.Array _bones = new();
private readonly Dictionary<ulong, Rigid> _bind = new();
private readonly Dictionary<(uint, ulong, ulong), float3> _originLocal = new();
private readonly List<int> _shapeLanes = new();
private readonly List<int> _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<Node3D>();
private Transform3D[] _inverseBind = Array.Empty<Transform3D>();
@ -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();
/// <summary>What the puppet is made of now, or null before the first build or while it draws nothing (too many bodies).</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
private bool SignatureHolds(in Box3DSoaView view)
/// <summary>Takes up the model's new shape: the carriers that are its bones, their inverse bind, and the mesh.</summary>
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<int, int>();
var bodies = new List<PuppetBody>();
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<PuppetJoint>();
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;
}

107
client/PuppetModel.cs Normal file
View file

@ -0,0 +1,107 @@
using System.Collections.Generic;
using CultMath;
using Ymir.Box3D;
namespace BadDay.Client;
/// <summary>A qualifying joint as the lanes name it: the bodies by StableId, the joint origin in the world now.</summary>
public readonly record struct PuppetJointLane(Box3DSoaJointKind Kind, ulong A, ulong B, float3 Origin);
/// <summary>
/// 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.
/// </summary>
public sealed class PuppetModel
{
/// <summary>The skin's bone count: the shader's array size.</summary>
public const int MaxBones = 32;
private readonly float _smin, _ballScale, _boxRound;
private readonly Dictionary<ulong, Rigid> _bind = new();
private readonly Dictionary<(Box3DSoaJointKind, ulong, ulong), float3> _originLocal = new();
private readonly List<BodySignature> _bodies = new();
private readonly List<JointSignature> _joints = new();
private readonly List<PuppetBody> _laneBodies = new();
private readonly List<PuppetJointLane> _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; }
/// <summary>The shape built from the current signature, or null before the first update or while there are more than <see cref="MaxBones"/> shape bodies.</summary>
public PuppetShape? Shape { get; private set; }
/// <summary>How many meshes have been built.</summary>
public int Builds { get; private set; }
/// <summary>Reads the shape bodies and qualifying joints of the lanes and updates.</summary>
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);
}
/// <summary>
/// <paramref name="bodies"/> carry their pose now in <see cref="PuppetBody.Bind"/>; 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).
/// </summary>
public bool Update(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJointLane> 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<ulong, int>();
var bound = new List<PuppetBody>();
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<PuppetJoint>();
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<PuppetBody> bodies, IReadOnlyList<PuppetJointLane> 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;
}
}

View file

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CultMath;
using Ymir.Box3D;
namespace BadDay.Client.Tests;
/// <summary>
/// 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 <c>fail</c>.
/// </summary>
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<PuppetBody> Bodies, List<PuppetJointLane> Joints) Chain() => (
new List<PuppetBody>
{
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<PuppetJointLane>
{
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<string> 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<PuppetBody>, List<PuppetJointLane>> 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<PuppetJointLane>()) && many.Shape is null && many.Builds == 0, "more shape bodies than bones was drawn");
Check(!many.Update(crowd, new List<PuppetJointLane>()), "an over-full puppet reported a change with none");
crowd.RemoveAt(0);
Check(many.Update(crowd, new List<PuppetJointLane>()) && many.Shape is not null, "the puppet did not come back once it fit the skin");
}
}

View file

@ -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);