Client: the puppet is one skinned SDF isosurface mesh, flat-shaded
PuppetField (engine-free, CultMath): primitives from the shape lanes, a joint ball and smooth-min per qualifying joint (Revolute, Spherical, Weld), the bind pose spread 20 degrees at each Spherical joint, surface nets at a 40 mm cell, two Newton steps onto the isosurface, flatter-diagonal quad split, two-bone skin weights from the winning term. Puppet builds it once, on a topology signature change only, and skins it in puppet.gdshader from the pose carriers' interpolated transforms. Smoke: triangle count, one connected piece, no skinned edge past 4x its bind length at the intensity-6 run's end and with each Spherical joint swung 90 degrees, one build across 400 resets. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b6d4495abc
commit
fa4610ffe5
7 changed files with 596 additions and 12 deletions
10
README.md
10
README.md
|
|
@ -64,12 +64,14 @@ session, `BodyPainBoxSession` (create, `Step`, read `Hand` and the world's lanes
|
|||
`client/` is a Godot 4.7.2 (mono) project that renders the body run and takes the player's commands: the
|
||||
Synaptic Induction Chamber, the dummy strapped to a stool with its right hand in the box. It owns presentation and
|
||||
input only. Godot's physics engine is set to Dummy; each 120 Hz physics frame the client calls
|
||||
`BodyPainBoxSession.Step()` once and draws Ymir's lanes (one node per stable id, shapes from the Kind and Size lanes).
|
||||
Needs the .NET 8+ SDK, cmake and a C compiler (MinGW gcc on Windows), the sibling Lodur and Ymir checkouts
|
||||
(`..\Lodur`, `..\Ymir`, or `LODUR_ROOT` and `YMIR_ROOT`), and Godot 4.7.2 mono.
|
||||
`BodyPainBoxSession.Step()` once and draws Ymir's lanes: one pose-carrying node per stable id, and the body drawn as one
|
||||
skinned SDF mesh (a surface-nets isosurface of the shape lanes, limbs smooth-blended into the body they hang from and
|
||||
joined by a ball at each joint, built once at startup and rebuilt only when the bodies or joints change; flat-shaded).
|
||||
Needs the .NET 8+ SDK, cmake and a C compiler (MinGW gcc on Windows), the sibling Lodur, Ymir (with joint origin lanes, ABI 8) and CultLib
|
||||
checkouts (`..\Lodur`, `..\Ymir`, `..\CultLib`, or `LODUR_ROOT`, `YMIR_ROOT` and `CULTLIB_ROOT`), and Godot 4.7.2 mono.
|
||||
|
||||
```
|
||||
dotnet build client/BadDay.Client.csproj # Lodur, Ymir (cmake) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug
|
||||
dotnet build client/BadDay.Client.csproj # CultLib Geometry, Lodur, Ymir (cmake) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug
|
||||
<godot> --path client # play: right-drag orbits, the wheel zooms
|
||||
<godot> --headless --path client res://tests/Smoke.tscn # the smoke; exit code 0 passes
|
||||
```
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ namespace BadDay.Client;
|
|||
|
||||
/// <summary>
|
||||
/// Draws Ymir's world from its lanes and writes nothing back. The static bodies (floor, stool) are plain boxes drawn
|
||||
/// here; every dynamic body belongs to the <see cref="Puppet"/>, the one swappable owner of the puppet's mesh.
|
||||
/// here; every dynamic body belongs to the <see cref="Puppet"/>, which draws them as one skinned SDF mesh.
|
||||
/// </summary>
|
||||
public partial class BodyRenderer : Node3D
|
||||
{
|
||||
|
|
@ -19,6 +19,9 @@ public partial class BodyRenderer : Node3D
|
|||
|
||||
/// <summary>The colour the puppet is drawn in.</summary>
|
||||
public Color PuppetColor => _puppet.Color;
|
||||
/// <summary>What the puppet's mesh is made of now, or null while it draws none.</summary>
|
||||
public PuppetShape? PuppetShape => _puppet.Shape;
|
||||
|
||||
public BaseMaterial3D SceneryMaterial => _material;
|
||||
|
||||
/// <summary>Where body <paramref name="stableId"/> is drawn now, or null if it is not drawn.</summary>
|
||||
|
|
|
|||
|
|
@ -10,6 +10,15 @@ public static class Look
|
|||
public static readonly Color Figure = new(0.9f, 0.9f, 0.88f);
|
||||
public static readonly Color Glow = new(0.85f, 0.95f, 1f);
|
||||
|
||||
/// <summary>The puppet's blend radius (m): how far limbs flow into the body they hang from.</summary>
|
||||
public const float SminRadius = 0.025f;
|
||||
|
||||
/// <summary>The joint ball's radius beyond what touches both limbs, in units of the thinner limb's thickness.</summary>
|
||||
public const float JointBallScale = 0.5f;
|
||||
|
||||
/// <summary>The radius (m) the puppet's boxes are rounded by, so the isosurface has no sawtooth bands on their edges.</summary>
|
||||
public const float BoxRound = 0.03f;
|
||||
|
||||
public static Godot.Environment Environment() => new()
|
||||
{
|
||||
BackgroundMode = Godot.Environment.BGMode.Color,
|
||||
|
|
|
|||
165
client/Puppet.cs
165
client/Puppet.cs
|
|
@ -1,22 +1,55 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CultMath;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// The puppet: one pose carrier per dynamic body, posed from the lanes, so physics interpolation has a node to
|
||||
/// interpolate. This commit draws nothing; the next gives it the one skinned SDF mesh.
|
||||
/// The puppet: its drawn surface is one skinned SDF isosurface mesh (<see cref="PuppetField"/>) over the dynamic bodies,
|
||||
/// flat-shaded, built once and rebuilt only when the topology signature (the shape bodies and the joints that blend them)
|
||||
/// changes. Per-StableId Node3D carriers hold the pose lanes so physics interpolation has something to interpolate, and
|
||||
/// every frame the bones are those carriers' interpolated transforms relative to the spread bind pose.
|
||||
/// </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 ArrayMesh? _mesh;
|
||||
private Node3D[] _boneNodes = Array.Empty<Node3D>();
|
||||
private Transform3D[] _inverseBind = Array.Empty<Transform3D>();
|
||||
|
||||
public Puppet()
|
||||
{
|
||||
_material.SetShaderParameter("albedo", Look.Figure);
|
||||
for (int i = 0; i < MaxBones; i++) _bones.Add(new Projection(Transform3D.Identity));
|
||||
_skin.MaterialOverride = _material;
|
||||
}
|
||||
|
||||
public int BodyCount => _nodes.Count;
|
||||
|
||||
/// <summary>The colour the puppet is drawn in.</summary>
|
||||
public Color Color => Look.Figure;
|
||||
/// <summary>The colour the puppet is drawn in: the shader's albedo.</summary>
|
||||
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 override void _Ready() => AddChild(_skin);
|
||||
|
||||
/// <summary>Where the puppet draws body <paramref name="stableId"/> now (world), or null if it draws no such body.</summary>
|
||||
public Transform3D? PoseOf(ulong stableId) => _nodes.TryGetValue(stableId, out var n) ? n.Transform : null;
|
||||
|
|
@ -24,7 +57,12 @@ public partial class Puppet : Node3D
|
|||
/// <summary>The same pose as it is rendered this frame, between the last two ticks.</summary>
|
||||
public Transform3D? InterpolatedPoseOf(ulong stableId) => _nodes.TryGetValue(stableId, out var n) ? n.GetGlobalTransformInterpolated() : null;
|
||||
|
||||
/// <summary>Makes the carriers match the lanes: creates the missing, frees the gone, then poses every one. <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
|
||||
/// <summary>The Godot transform of a <see cref="Rigid"/>.</summary>
|
||||
public static Transform3D ToTransform(Rigid r) => new(
|
||||
new Basis(new Vector3(r.R._m00, r.R._m10, r.R._m20), new Vector3(r.R._m01, r.R._m11, r.R._m21), new Vector3(r.R._m02, r.R._m12, r.R._m22)),
|
||||
new Vector3(r.T.x, r.T.y, r.T.z));
|
||||
|
||||
/// <summary>Makes the carriers match the lanes (creates the missing, frees the gone, poses every one), then rebuilds the mesh if the topology changed. <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
|
||||
public void Sync(in Box3DSoaView view, bool teleport = false)
|
||||
{
|
||||
var ids = view.StableId;
|
||||
|
|
@ -57,21 +95,134 @@ 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);
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (Shape is null) return;
|
||||
var lo = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
|
||||
var hi = new Vector3(float.MinValue, float.MinValue, float.MinValue);
|
||||
for (int i = 0; i < _boneNodes.Length; i++)
|
||||
{
|
||||
var t = _boneNodes[i].GetGlobalTransformInterpolated();
|
||||
_bones[i] = new Projection(t * _inverseBind[i]);
|
||||
lo = lo.Min(t.Origin); hi = hi.Max(t.Origin);
|
||||
}
|
||||
_material.SetShaderParameter("bones", _bones);
|
||||
var pad = new Vector3(Shape.Reach, Shape.Reach, Shape.Reach);
|
||||
_mesh!.CustomAabb = new Aabb(lo - pad, hi - lo + 2 * pad);
|
||||
}
|
||||
|
||||
private static bool IsPuppet(uint kind) => (Box3DSoaKind)kind != Box3DSoaKind.StaticBox;
|
||||
|
||||
private static int CountDynamic(System.ReadOnlySpan<uint> kind)
|
||||
private static int CountDynamic(ReadOnlySpan<uint> kind)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var k in kind) if (IsPuppet(k)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
private bool AllPresent(System.ReadOnlySpan<ulong> ids, System.ReadOnlySpan<uint> kind)
|
||||
private bool AllPresent(ReadOnlySpan<ulong> ids, ReadOnlySpan<uint> kind)
|
||||
{
|
||||
for (int i = 0; i < ids.Length; i++) if (IsPuppet(kind[i]) && !_nodes.ContainsKey(ids[i])) return false;
|
||||
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)
|
||||
{
|
||||
_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++)
|
||||
{
|
||||
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;
|
||||
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()); }
|
||||
_mesh = MeshOf(shape);
|
||||
_skin.Mesh = _mesh;
|
||||
}
|
||||
|
||||
/// <summary>The shape as one surface: VERTEX in the spread bind, the facet NORMAL, and CUSTOM1 (bone A, bone B, weight A).</summary>
|
||||
private static ArrayMesh MeshOf(PuppetShape s)
|
||||
{
|
||||
int n = s.Positions.Length;
|
||||
var vertex = new Vector3[n]; var normal = new Vector3[n]; var skin = new float[3 * n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
vertex[i] = new Vector3(s.Positions[i].x, s.Positions[i].y, s.Positions[i].z);
|
||||
normal[i] = new Vector3(s.Normals[i].x, s.Normals[i].y, s.Normals[i].z);
|
||||
skin[3 * i] = s.BoneA[i]; skin[3 * i + 1] = s.BoneB[i]; skin[3 * i + 2] = s.WeightA[i];
|
||||
}
|
||||
var arrays = new Godot.Collections.Array();
|
||||
arrays.Resize((int)Mesh.ArrayType.Max);
|
||||
arrays[(int)Mesh.ArrayType.Vertex] = vertex;
|
||||
arrays[(int)Mesh.ArrayType.Normal] = normal;
|
||||
arrays[(int)Mesh.ArrayType.Custom1] = skin;
|
||||
var format = (Mesh.ArrayFormat)((int)Mesh.ArrayCustomFormat.RgbFloat << (int)Mesh.ArrayFormat.FormatCustom1Shift);
|
||||
var mesh = new ArrayMesh();
|
||||
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays, null, null, format);
|
||||
return mesh;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
325
client/PuppetField.cs
Normal file
325
client/PuppetField.cs
Normal file
|
|
@ -0,0 +1,325 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using CultMath;
|
||||
using GameCult.Geometry;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>A rigid transform: <c>world = R * local + T</c>.</summary>
|
||||
public readonly struct Rigid
|
||||
{
|
||||
public readonly float3x3 R;
|
||||
public readonly float3 T;
|
||||
|
||||
public Rigid(float3x3 r, float3 t) { R = r; T = t; }
|
||||
|
||||
public static Rigid FromQuaternion(float x, float y, float z, float w, float3 t) => new(new float3x3(
|
||||
1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
|
||||
2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
|
||||
2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)), t);
|
||||
|
||||
/// <summary>The turn by <paramref name="radians"/> about the unit <paramref name="axis"/> through <paramref name="point"/>.</summary>
|
||||
public static Rigid About(float3 point, float3 axis, float radians)
|
||||
{
|
||||
float c = MathF.Cos(radians), s = MathF.Sin(radians), u = 1 - c;
|
||||
var r = new float3x3(
|
||||
c + axis.x * axis.x * u, axis.x * axis.y * u - axis.z * s, axis.x * axis.z * u + axis.y * s,
|
||||
axis.y * axis.x * u + axis.z * s, c + axis.y * axis.y * u, axis.y * axis.z * u - axis.x * s,
|
||||
axis.z * axis.x * u - axis.y * s, axis.z * axis.y * u + axis.x * s, c + axis.z * axis.z * u);
|
||||
return new Rigid(r, point - math.mul(r, point));
|
||||
}
|
||||
|
||||
public float3 Apply(float3 local) => math.mul(R, local) + T;
|
||||
|
||||
public Rigid Inverse()
|
||||
{
|
||||
var rt = new float3x3(R._m00, R._m10, R._m20, R._m01, R._m11, R._m21, R._m02, R._m12, R._m22);
|
||||
return new Rigid(rt, -math.mul(rt, T));
|
||||
}
|
||||
|
||||
/// <summary>The transform that applies <paramref name="inner"/> first, then this.</summary>
|
||||
public Rigid After(Rigid inner) => new(math.mul(R, inner.R), math.mul(R, inner.T) + T);
|
||||
}
|
||||
|
||||
/// <summary>A shape body as the lanes name it: its creation pose is the bind.</summary>
|
||||
public readonly record struct PuppetBody(ulong Id, Box3DSoaKind Kind, float3 Size, Rigid Bind);
|
||||
|
||||
/// <summary>A qualifying joint: body A and B by index into the bodies, the joint origin in body A's frame.</summary>
|
||||
public readonly record struct PuppetJoint(Box3DSoaJointKind Kind, int A, int B, float3 LocalOrigin);
|
||||
|
||||
/// <summary>
|
||||
/// What the puppet is made of, read-only: the spread bind per shape body (bone i is body i), the joints, and the
|
||||
/// mesh as unwelded flat triangles (three entries per triangle) with each vertex's two bones and the first one's weight.
|
||||
/// </summary>
|
||||
public sealed class PuppetShape
|
||||
{
|
||||
public required ulong[] Ids { get; init; }
|
||||
public required Rigid[] SpreadBind { get; init; }
|
||||
public required (Box3DSoaJointKind Kind, int A, int B, float3 Origin)[] Joints { get; init; }
|
||||
public required float3[] Positions { get; init; }
|
||||
public required float3[] Normals { get; init; }
|
||||
public required int[] BoneA { get; init; }
|
||||
public required int[] BoneB { get; init; }
|
||||
public required float[] WeightA { get; init; }
|
||||
|
||||
/// <summary>How far a skinned vertex can lie from its bone's origin.</summary>
|
||||
public required float Reach { get; init; }
|
||||
|
||||
/// <summary>How many times the mesh has been built; Puppet counts.</summary>
|
||||
public int Builds { get; internal set; }
|
||||
|
||||
public int Triangles => Positions.Length / 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The puppet's surface, engine-free: every shape body is an SDF primitive; a body that is the child of a joint is
|
||||
/// smooth-min'd with its parent and a ball at the joint; the field is meshed once (surface nets) at a spread bind
|
||||
/// pose and each vertex keeps the two bones of the term that won it.
|
||||
/// </summary>
|
||||
public static class PuppetField
|
||||
{
|
||||
/// <summary>The grid cell, the minimum that resolves the thinnest limb (radius 40 mm).</summary>
|
||||
public const float Cell = 0.04f;
|
||||
|
||||
/// <summary>How far a Spherical joint's child subtree swings in the bind pose, so a limb hanging beside the trunk is not webbed to it.</summary>
|
||||
public const float SpreadDegrees = 20f;
|
||||
|
||||
private const int Newton = 2;
|
||||
|
||||
/// <summary>The bodies of the lanes that are drawn: a shape, not an Anchor or a StaticBox.</summary>
|
||||
public static bool HasShape(Box3DSoaKind kind) => kind is Box3DSoaKind.Sphere or Box3DSoaKind.Capsule or Box3DSoaKind.Box;
|
||||
|
||||
/// <summary>A joint that blends two bodies: Revolute, Spherical or Weld (never Motor), both bodies with shapes.</summary>
|
||||
public static bool Qualifies(Box3DSoaJointKind joint, Box3DSoaKind a, Box3DSoaKind b) =>
|
||||
joint is Box3DSoaJointKind.Revolute or Box3DSoaJointKind.Spherical or Box3DSoaJointKind.Weld && HasShape(a) && HasShape(b);
|
||||
|
||||
public static PuppetShape Build(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJoint> joints, float smin, float ballScale, float boxRound)
|
||||
{
|
||||
int n = bodies.Count;
|
||||
// The first qualifying joint with body b as its B decides b's blend (lane order); every other joint of b is ignored.
|
||||
var up = new int[n]; var jointOf = new int[n];
|
||||
Array.Fill(up, -1); Array.Fill(jointOf, -1);
|
||||
for (int j = 0; j < joints.Count; j++) if (jointOf[joints[j].B] < 0) { jointOf[joints[j].B] = j; up[joints[j].B] = joints[j].A; }
|
||||
|
||||
// Spread, parents first: each Spherical joint swings B's subtree about its origin.
|
||||
var t = new Rigid[n];
|
||||
for (int i = 0; i < n; i++) t[i] = bodies[i].Bind;
|
||||
var order = new List<int>();
|
||||
for (int i = 0; i < n; i++) if (jointOf[i] >= 0) order.Add(i);
|
||||
order.Sort((x, y) => Depth(up, x) != Depth(up, y) ? Depth(up, x).CompareTo(Depth(up, y)) : x.CompareTo(y));
|
||||
foreach (int b in order)
|
||||
{
|
||||
var joint = joints[jointOf[b]];
|
||||
if (joint.Kind != Box3DSoaJointKind.Spherical) continue;
|
||||
var o = t[joint.A].Apply(joint.LocalOrigin);
|
||||
var axis = math.cross(t[joint.A].T - o, t[b].T - o);
|
||||
if (math.length(axis) < 1e-4f) continue;
|
||||
var swing = Rigid.About(o, math.normalize(axis), SpreadDegrees * MathF.PI / 180f);
|
||||
for (int i = 0; i < n; i++) if (IsUnder(up, i, b)) t[i] = swing.After(t[i]);
|
||||
}
|
||||
|
||||
var field = new Field(bodies, t, joints, jointOf, smin, ballScale, boxRound);
|
||||
return Mesh(field, bodies, t, joints, smin);
|
||||
}
|
||||
|
||||
private static int Depth(int[] up, int i)
|
||||
{
|
||||
int d = 0;
|
||||
for (; up[i] >= 0 && d <= up.Length; i = up[i]) d++;
|
||||
return d;
|
||||
}
|
||||
|
||||
private static bool IsUnder(int[] up, int i, int root)
|
||||
{
|
||||
for (int d = 0; d <= up.Length; d++)
|
||||
{
|
||||
if (i == root) return true;
|
||||
if (up[i] < 0) return false;
|
||||
i = up[i];
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static PuppetShape Mesh(Field f, IReadOnlyList<PuppetBody> bodies, Rigid[] t, IReadOnlyList<PuppetJoint> joints, float smin)
|
||||
{
|
||||
int n = bodies.Count;
|
||||
var lo = new float3(float.MaxValue, float.MaxValue, float.MaxValue); var hi = new float3(float.MinValue, float.MinValue, float.MinValue);
|
||||
float reach = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
float r = f.Extent(i);
|
||||
lo = math.min(lo, t[i].T - r); hi = math.max(hi, t[i].T + r);
|
||||
reach = MathF.Max(reach, r);
|
||||
if (f.BallR[i] > 0) { lo = math.min(lo, f.Ball[i] - f.BallR[i]); hi = math.max(hi, f.Ball[i] + f.BallR[i]); }
|
||||
}
|
||||
float pad = smin + 2 * Cell;
|
||||
lo -= pad; hi += pad;
|
||||
int nx = (int)MathF.Ceiling((hi.x - lo.x) / Cell) + 1, ny = (int)MathF.Ceiling((hi.y - lo.y) / Cell) + 1, nz = (int)MathF.Ceiling((hi.z - lo.z) / Cell) + 1;
|
||||
var samples = new float[nx, ny, nz];
|
||||
for (int x = 0; x < nx; x++)
|
||||
for (int y = 0; y < ny; y++)
|
||||
for (int z = 0; z < nz; z++)
|
||||
samples[x, y, z] = f.Eval(lo + new float3(x, y, z) * Cell, out _, out _, out _).w;
|
||||
var nets = CultGeometrySurfaceNets.Extract(samples, 0f, lo, Cell);
|
||||
|
||||
// Two Newton steps put each net vertex on the isosurface.
|
||||
var v = new float3[nets.VertexCount];
|
||||
for (int i = 0; i < v.Length; i++)
|
||||
{
|
||||
var p = new float3(nets.Positions[3 * i], nets.Positions[3 * i + 1], nets.Positions[3 * i + 2]);
|
||||
for (int it = 0; it < Newton; it++) { var e = f.Eval(p, out _, out _, out _); p -= e.w * new float3(e.x, e.y, e.z); }
|
||||
v[i] = p;
|
||||
}
|
||||
|
||||
var pos = new List<float3>(); var nor = new List<float3>();
|
||||
var ba = new List<int>(); var bb = new List<int>(); var wa = new List<float>();
|
||||
void Triangle(float3 a, float3 b, float3 c)
|
||||
{
|
||||
var cross = math.cross(b - a, c - a);
|
||||
float len = math.length(cross);
|
||||
if (len < 1e-12f) return;
|
||||
var g = f.Eval((a + b + c) / 3f, out _, out _, out _);
|
||||
// Godot's front face is clockwise: the counter-clockwise normal points into the body.
|
||||
if (math.dot(cross, new float3(g.x, g.y, g.z)) > 0) { (b, c) = (c, b); cross = -cross; }
|
||||
var normal = -cross / len;
|
||||
foreach (var q in new[] { a, b, c })
|
||||
{
|
||||
f.Eval(q, out int bone, out int other, out float w);
|
||||
pos.Add(q); nor.Add(normal); ba.Add(bone); bb.Add(other); wa.Add(w);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < nets.Quads.Length; i += 4)
|
||||
{
|
||||
var a = v[nets.Quads[i]]; var b = v[nets.Quads[i + 1]]; var c = v[nets.Quads[i + 2]]; var d = v[nets.Quads[i + 3]];
|
||||
// Split on the flatter diagonal.
|
||||
bool ac = math.dot(Unit(math.cross(b - a, c - a)), Unit(math.cross(c - a, d - a))) >= math.dot(Unit(math.cross(b - a, d - a)), Unit(math.cross(c - b, d - b)));
|
||||
if (ac) { Triangle(a, b, c); Triangle(a, c, d); }
|
||||
else { Triangle(a, b, d); Triangle(b, c, d); }
|
||||
}
|
||||
|
||||
float maxBall = 0;
|
||||
for (int i = 0; i < n; i++) maxBall = MathF.Max(maxBall, f.BallR[i]);
|
||||
var ids = new ulong[n];
|
||||
for (int i = 0; i < n; i++) ids[i] = bodies[i].Id;
|
||||
var js = new (Box3DSoaJointKind, int, int, float3)[joints.Count];
|
||||
for (int j = 0; j < js.Length; j++) js[j] = (joints[j].Kind, joints[j].A, joints[j].B, t[joints[j].A].Apply(joints[j].LocalOrigin));
|
||||
return new PuppetShape
|
||||
{
|
||||
Ids = ids, SpreadBind = t, Joints = js,
|
||||
Positions = pos.ToArray(), Normals = nor.ToArray(), BoneA = ba.ToArray(), BoneB = bb.ToArray(), WeightA = wa.ToArray(),
|
||||
Reach = 2 * reach + 2 * maxBall + smin,
|
||||
};
|
||||
}
|
||||
|
||||
private static float3 Unit(float3 v)
|
||||
{
|
||||
float l = math.length(v);
|
||||
return l > 1e-12f ? v / l : new float3(0, 0, 0);
|
||||
}
|
||||
|
||||
/// <summary>The field in the spread bind: value and gradient (float4: gradient, value), and the bones of the winning term.</summary>
|
||||
private sealed class Field
|
||||
{
|
||||
private readonly int _n;
|
||||
private readonly Box3DSoaKind[] _kind;
|
||||
private readonly float3[] _size;
|
||||
private readonly Rigid[] _t;
|
||||
private readonly Rigid[] _inverse;
|
||||
private readonly int[] _up;
|
||||
private readonly float _smin, _round;
|
||||
public readonly float3[] Ball;
|
||||
public readonly float[] BallR;
|
||||
|
||||
public Field(IReadOnlyList<PuppetBody> bodies, Rigid[] spread, IReadOnlyList<PuppetJoint> joints, int[] jointOf, float smin, float ballScale, float boxRound)
|
||||
{
|
||||
_n = bodies.Count; _smin = smin; _round = boxRound; _t = spread;
|
||||
_kind = new Box3DSoaKind[_n]; _size = new float3[_n]; _inverse = new Rigid[_n]; _up = new int[_n];
|
||||
Ball = new float3[_n]; BallR = new float[_n];
|
||||
for (int i = 0; i < _n; i++)
|
||||
{
|
||||
_kind[i] = bodies[i].Kind; _size[i] = bodies[i].Size; _inverse[i] = spread[i].Inverse();
|
||||
_up[i] = jointOf[i] >= 0 ? joints[jointOf[i]].A : -1;
|
||||
}
|
||||
for (int i = 0; i < _n; i++)
|
||||
{
|
||||
if (jointOf[i] < 0) continue;
|
||||
var j = joints[jointOf[i]];
|
||||
var o = spread[j.A].Apply(j.LocalOrigin);
|
||||
Ball[i] = o;
|
||||
BallR[i] = MathF.Max(MathF.Max(Prim(j.A, o).w, Prim(i, o).w), 0f) + ballScale * MathF.Min(Thickness(j.A), Thickness(i));
|
||||
}
|
||||
}
|
||||
|
||||
public float Thickness(int i) => _kind[i] == Box3DSoaKind.Box ? math.min(_size[i].x, math.min(_size[i].y, _size[i].z)) : _size[i].x;
|
||||
|
||||
/// <summary>The body's reach from its origin: the farthest the primitive extends.</summary>
|
||||
public float Extent(int i) => _kind[i] == Box3DSoaKind.Box ? math.length(_size[i]) : _size[i].x + _size[i].y;
|
||||
|
||||
/// <summary>One primitive's gradient and signed distance at world point <paramref name="p"/>.</summary>
|
||||
private float4 Prim(int i, float3 p)
|
||||
{
|
||||
var q = _inverse[i].Apply(p);
|
||||
var s = _size[i];
|
||||
float3 g; float d;
|
||||
switch (_kind[i])
|
||||
{
|
||||
case Box3DSoaKind.Sphere:
|
||||
{
|
||||
float l = math.length(q);
|
||||
d = l - s.x; g = l > 0 ? q / l : new float3(0, 1, 0);
|
||||
break;
|
||||
}
|
||||
case Box3DSoaKind.Capsule:
|
||||
{
|
||||
var w = q - new float3(0, math.clamp(q.y, -s.y, s.y), 0);
|
||||
float l = math.length(w);
|
||||
d = l - s.x; g = l > 0 ? w / l : new float3(1, 0, 0);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
float rr = math.min(_round, math.min(s.x, math.min(s.y, s.z)));
|
||||
var a = math.abs(q) - (s - rr);
|
||||
var o = math.max(a, 0f);
|
||||
float ol = math.length(o);
|
||||
d = ol + math.min(math.max(a.x, math.max(a.y, a.z)), 0f) - rr;
|
||||
var sg = new float3(q.x < 0 ? -1 : 1, q.y < 0 ? -1 : 1, q.z < 0 ? -1 : 1);
|
||||
if (ol > 0) g = sg * o / ol;
|
||||
else if (a.x >= a.y && a.x >= a.z) g = new float3(sg.x, 0, 0);
|
||||
else if (a.y >= a.z) g = new float3(0, sg.y, 0);
|
||||
else g = new float3(0, 0, sg.z);
|
||||
break;
|
||||
}
|
||||
}
|
||||
g = math.mul(_t[i].R, g);
|
||||
return new float4(g.x, g.y, g.z, d);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The field at <paramref name="p"/>: the minimum over the bodies' terms. A body that is a joint's B contributes
|
||||
/// smin(smin(itself, the joint ball), its parent), blended by that outer smin's weight; any other body is itself.
|
||||
/// The winning term names the vertex's bones: the body and its parent, with the body's weight.
|
||||
/// </summary>
|
||||
public float4 Eval(float3 p, out int bone, out int other, out float weight)
|
||||
{
|
||||
Span<float4> each = stackalloc float4[_n];
|
||||
for (int i = 0; i < _n; i++) each[i] = Prim(i, p);
|
||||
var best = new float4(0, 0, 0, float.MaxValue);
|
||||
bone = 0; other = 0; weight = 1;
|
||||
for (int i = 0; i < _n; i++)
|
||||
{
|
||||
var term = each[i]; float h = 1;
|
||||
if (_up[i] >= 0)
|
||||
{
|
||||
var dp = p - Ball[i]; float l = math.length(dp);
|
||||
var child = math.smin_grad(each[i], new float4(l > 0 ? dp / l : new float3(0, 1, 0), l - BallR[i]), _smin);
|
||||
term = math.smin_grad(child, each[_up[i]], _smin);
|
||||
h = math.saturate(0.5f + 0.5f * (each[_up[i]].w - child.w) / _smin);
|
||||
}
|
||||
if (term.w < best.w) { best = term; bone = i; other = _up[i] >= 0 ? _up[i] : i; weight = h; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
}
|
||||
24
client/puppet.gdshader
Normal file
24
client/puppet.gdshader
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
shader_type spatial;
|
||||
render_mode cull_back;
|
||||
|
||||
// The puppet is one mesh skinned to the bodies: each vertex carries two bones and the first one's weight in CUSTOM1
|
||||
// (x: bone A, y: bone B, z: weight of A). bones[i] is world-from-spread-bind for body i. The shadow and depth passes
|
||||
// run vertex() too, so they skin the same way. NORMAL is the facet normal, so the shading is flat.
|
||||
const int MAX_BONES = 32;
|
||||
uniform mat4 bones[MAX_BONES];
|
||||
uniform vec3 albedo : source_color = vec3(0.9, 0.9, 0.88);
|
||||
|
||||
void vertex() {
|
||||
int a = int(CUSTOM1.x + 0.5);
|
||||
int b = int(CUSTOM1.y + 0.5);
|
||||
float w = CUSTOM1.z;
|
||||
mat4 m = bones[a] * w + bones[b] * (1.0 - w);
|
||||
VERTEX = (m * vec4(VERTEX, 1.0)).xyz;
|
||||
NORMAL = normalize(mat3(m) * NORMAL);
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
ALBEDO = albedo;
|
||||
ROUGHNESS = 1.0;
|
||||
SPECULAR = 0.0;
|
||||
}
|
||||
|
|
@ -88,6 +88,7 @@ public partial class Smoke : Node
|
|||
await UntilTick(1500);
|
||||
CheckEvents(reference, "seed 3, intensity 6");
|
||||
Check(Session.Finished && _main.Events.Any(e => (e.Events & Lodur.TickEvents.WillBroke) != 0), "intensity 6 did not break the will");
|
||||
CheckPuppetMesh("intensity 6, tick 1500");
|
||||
|
||||
// A reset puts every body at its pose now, not on the way from where the last run left it. A reset from the UI
|
||||
// lands between physics frames, and on a slow physics clock the next render frame comes before the next tick.
|
||||
|
|
@ -121,6 +122,7 @@ public partial class Smoke : Node
|
|||
await Frame();
|
||||
}
|
||||
Check(_main.Seed == 1399, $"after 400 resets the seed is {_main.Seed}");
|
||||
Check(_main.Bodies.PuppetShape?.Builds == 1, $"the puppet mesh was built {_main.Bodies.PuppetShape?.Builds} times; the signature never changed, so once");
|
||||
|
||||
// Box off, through the HUD button, at tick 600: the run ends with the will intact and the screen shows the box off.
|
||||
PressReset(Seed);
|
||||
|
|
@ -166,6 +168,74 @@ public partial class Smoke : Node
|
|||
Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey");
|
||||
}
|
||||
|
||||
/// <summary>No skinned triangle edge may be longer than this many times its bind length.</summary>
|
||||
private const float StretchLimit = 4f;
|
||||
|
||||
/// <summary>The puppet's one mesh: size, one piece, and not stretched into a web by the pose it is in or by a joint swung 90 degrees.</summary>
|
||||
private void CheckPuppetMesh(string when)
|
||||
{
|
||||
if (_main.Bodies.PuppetShape is not { } shape) { Check(false, $"{when}: the puppet has no mesh"); return; }
|
||||
Check(shape.Triangles is >= 2000 and <= 6000, $"{when}: the puppet mesh has {shape.Triangles} triangles, not 2000 to 6000");
|
||||
int pieces = Pieces(shape);
|
||||
Check(pieces == 1, $"{when}: the puppet mesh is {pieces} pieces, not one");
|
||||
|
||||
var posed = new Transform3D[shape.Ids.Length];
|
||||
for (int i = 0; i < posed.Length; i++)
|
||||
posed[i] = (_main.Bodies.PoseOf(shape.Ids[i]) ?? Transform3D.Identity) * Puppet.ToTransform(shape.SpreadBind[i].Inverse());
|
||||
float stretch = MaxStretch(shape, posed);
|
||||
Check(stretch <= StretchLimit, $"{when}: a skinned edge is {stretch:F1}x its bind length, over {StretchLimit}x");
|
||||
|
||||
// Every Spherical joint swung 90 degrees: its child subtree turns about the joint origin.
|
||||
var up = Enumerable.Repeat(-1, shape.Ids.Length).ToArray();
|
||||
foreach (var j in shape.Joints) if (up[j.B] < 0) up[j.B] = j.A;
|
||||
foreach (var j in shape.Joints.Where(j => j.Kind == global::Ymir.Box3D.Box3DSoaJointKind.Spherical))
|
||||
{
|
||||
var origin = new Vector3(j.Origin.x, j.Origin.y, j.Origin.z);
|
||||
var swing = new Transform3D(new Basis(Vector3.Right, Mathf.Pi / 2), origin) * new Transform3D(Basis.Identity, -origin);
|
||||
var bones = new Transform3D[shape.Ids.Length];
|
||||
for (int i = 0; i < bones.Length; i++)
|
||||
{
|
||||
bool under = false;
|
||||
for (int k = i, d = 0; k >= 0 && d <= bones.Length; k = up[k], d++) if (k == j.B) { under = true; break; }
|
||||
bones[i] = under ? swing : Transform3D.Identity;
|
||||
}
|
||||
stretch = MaxStretch(shape, bones);
|
||||
Check(stretch <= StretchLimit, $"{when}: with body {shape.Ids[j.B]} swung 90 degrees a skinned edge is {stretch:F1}x its bind length, over {StretchLimit}x");
|
||||
}
|
||||
}
|
||||
|
||||
private static float MaxStretch(PuppetShape shape, Transform3D[] bones)
|
||||
{
|
||||
Vector3 Bind(int v) => new(shape.Positions[v].x, shape.Positions[v].y, shape.Positions[v].z);
|
||||
Vector3 Skin(int v) { var p = Bind(v); float w = shape.WeightA[v]; return bones[shape.BoneA[v]] * p * w + bones[shape.BoneB[v]] * p * (1 - w); }
|
||||
float worst = 0;
|
||||
for (int t = 0; t < shape.Positions.Length; t += 3)
|
||||
for (int e = 0; e < 3; e++)
|
||||
{
|
||||
int a = t + e, b = t + (e + 1) % 3;
|
||||
float bind = (Bind(a) - Bind(b)).Length();
|
||||
if (bind > 1e-5f) worst = Mathf.Max(worst, (Skin(a) - Skin(b)).Length() / bind);
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
|
||||
/// <summary>Connected components of the mesh with its triangles' coincident corners welded.</summary>
|
||||
private static int Pieces(PuppetShape shape)
|
||||
{
|
||||
var id = new Dictionary<(long, long, long), int>();
|
||||
var corner = new int[shape.Positions.Length];
|
||||
for (int i = 0; i < corner.Length; i++)
|
||||
{
|
||||
var p = shape.Positions[i];
|
||||
var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5));
|
||||
if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count;
|
||||
}
|
||||
var parent = Enumerable.Range(0, id.Count).ToArray();
|
||||
int Find(int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; }
|
||||
for (int t = 0; t < corner.Length; t += 3) { parent[Find(corner[t + 1])] = Find(corner[t]); parent[Find(corner[t + 2])] = Find(corner[t]); }
|
||||
return corner.Select(Find).Distinct().Count();
|
||||
}
|
||||
|
||||
private void CheckPoses(string when)
|
||||
{
|
||||
var view = Session.View;
|
||||
|
|
|
|||
Loading…
Reference in a new issue