FellaSkin draws Fella: one skinned mesh on the carriers' poses replaces the 19 drawn collision primitives

BodyRenderer keeps a carrier for every body and a primitive only for bodies SeatedPuppet.PartOf does not claim; PuppetCentre is the skin's posed bounds, the primitive AABB union is gone. FellaSkin reads the glb as bytes, rebuilds every vertex each frame from the interpolated poses and rewrites one dynamic surface in place. Smoke: all 19 parts own vertices, joint-ring copies coincide (bound 195 um, split-ring mutant 75768 um), the deform cost line, one skin build for 400 Resets. RenderCheck: a neck (bound 1.0, primitive torso 1.72, shipped 0.58) and figure-at-lanes re-bounded to 1 by the skin-unposed mutant (4); render-mutants.sh gains fella-primitives, skin-unposed and ONLY=.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 03:15:34 +01:00
commit e7a7dfea8b
6 changed files with 319 additions and 44 deletions

View file

@ -37,7 +37,7 @@ recorder. It needs sibling checkouts of Lodur and Ymir (`LODUR_ROOT`, else
- `src/BadDay.Core/Sweep.cs`: consecutive seeds, break-time min/median/max. - `src/BadDay.Core/Sweep.cs`: consecutive seeds, break-time min/median/max.
- `src/BadDay.Ymir/BodyPainBox.cs`: the same run on the Ymir ragdoll, with the hand-out time. - `src/BadDay.Ymir/BodyPainBox.cs`: the same run on the Ymir ragdoll, with the hand-out time.
- `src/BadDay.Ymir/SeatedPuppet.cs`: the stool, ground and ragdoll every body is built from (`SeatedBody` holds the world). - `src/BadDay.Ymir/SeatedPuppet.cs`: the stool, ground and ragdoll every body is built from (`SeatedBody` holds the world).
- `src/BadDay.Cli`: `baddaysim`. - `src/BadDay.Cli`: `baddaysim` (`baddaysim plan` prints the seated puppet's body plan as JSON: the skeleton `tools/FellaMesh` builds Fella's skin on).
- `tests/BadDay.Tests`: determinism, break-time, monotonicity and body tests. - `tests/BadDay.Tests`: determinism, break-time, monotonicity and body tests.
- `tools/PainSweep`: the intensity x suppression table. - `tools/PainSweep`: the intensity x suppression table.
@ -64,8 +64,10 @@ 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 `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 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 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 pose-carrying node per stable id (`BodyRenderer`), each holding its body's own `BodyPainBoxSession.Step()` once and draws Ymir's lanes: one pose-carrying node per stable id (`BodyRenderer`). Fella's 19 parts are drawn by one
primitive (a capsule, box or sphere of the lane's size; the figure is a placeholder of primitives until the anatomy meshes come). The look is skinned mesh, `FellaSkin`, on those carriers' poses (MakeHuman's androgynous base body fitted to Lodur's plan by `tools/FellaMesh`; the file is
`client/fella/fella_skin.glb`, CC0, see `client/fella/ATTRIBUTION.md`); every other body holds its own primitive (a capsule, box or sphere of the lane's
size). The look is
PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy): every surface is `ps1.gdshader` (vertices snapped to the line grid, affine texture PlayStation-1-era 3D (lodur:ruling:bds-look-ps1-anatomy): every surface is `ps1.gdshader` (vertices snapped to the line grid, affine texture
coordinates, unfiltered texels, light, glow and fog per vertex, in raw sRGB arithmetic), and `ps1_post.gdshader` on a full-screen rect under the coordinates, unfiltered texels, light, glow and fog per vertex, in raw sRGB arithmetic), and `ps1_post.gdshader` on a full-screen rect under the
HUD quantises the frame to one colour per block of a 240-line grid (`Look.Lines`, blocks of round(H / 240) pixels anchored at the screen centre) HUD quantises the frame to one colour per block of a 240-line grid (`Look.Lines`, blocks of round(H / 240) pixels anchored at the screen centre)
@ -76,6 +78,11 @@ Needs the .NET 8+ SDK, cmake and a C compiler (MinGW gcc on Windows), the siblin
(BDS's graph references no CultLib project, so Ymir's own revision check never runs here); the client was last verified against Lodur 2359142 (the gravity subtree gate) and (BDS's graph references no CultLib project, so Ymir's own revision check never runs here); the client was last verified against Lodur 2359142 (the gravity subtree gate) and
Ymir 1d27114 (its `extern/box3d` submodule initialised). Ymir 1d27114 (its `extern/box3d` submodule initialised).
Fella's skin is generated: `py -3 tools/FellaMesh/build_fella_mesh.py` (Python 3 and numpy; it runs `baddaysim plan` for the skeleton, so the siblings above must build) writes
`client/fella/fella_skin.glb` from the pinned MakeHuman files in `tools/FellaMesh/input` (see its README for source, commit, licence and SHA-256 sums), and `--check`
rebuilds and compares bytes. The file is never edited by hand. The macro arguments (`--gender`, `--age`, `--muscle`, `--weight`, `--height`, `--proportions`) default to MakeHuman's neutral
0.5 (the androgynous base, lodur:ruling:default-fella-androgynous-base); other values are refused until the macrodetails targets are pinned (lodur:follow_up:fella-body-variety).
``` ```
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 # Lodur, Ymir (cmake) and BDS, plus ymir_box3d.dll, into client/.godot/mono/temp/bin/Debug
<godot> --path client # play: Blender's navigation: middle-drag orbits the puppet, Shift+middle-drag pans, Ctrl+middle-drag and the wheel zoom; Alt+left-drag stands for the middle button (OrbitCamera.Emulate3ButtonMouse) <godot> --path client # play: Blender's navigation: middle-drag orbits the puppet, Shift+middle-drag pans, Ctrl+middle-drag and the wheel zoom; Alt+left-drag stands for the middle button (OrbitCamera.Emulate3ButtonMouse)
@ -96,11 +103,11 @@ blocks follow ps1.js's 4x4 ordered dither, that a wall at 9 m is fogged to the d
the blend of its corners' light (per vertex, not per pixel), that a minified checker that carries mipmaps still draws only black and white (nearest, no the blend of its corners' light (per vertex, not per pixel), that a minified checker that carries mipmaps still draws only black and white (nearest, no
mips), that a probe box's drawn blocks are those of its hull with the corners snapped to a coarse grid (the unsnapped hull differs in 8 blocks), that the mips), that a probe box's drawn blocks are those of its hull with the corners snapped to a coarse grid (the unsnapped hull differs in 8 blocks), that the
texel runs of a checker triangle seen at 60 degrees keep equal widths along a scanline (affine), that the chamber at full glow lights the figure by at least texel runs of a checker triangle seen at 60 degrees keep equal widths along a scanline (affine), that the chamber at full glow lights the figure by at least
1.2 levels over dark, and that each dynamic body's lane origin projects within a block of a figure pixel. The check holds at 1280x720 only: at any other 1.2 levels over dark, that each dynamic body's lane origin projects within a block of a figure pixel, and that the figure has a neck (its width a centimetre below the neck joint over its width at the head, seen from the front). The check holds at 1280x720 only: at any other
window size it fails "window" before reading a frame (the grid is round(H / 240) px, 216 lines at 1080, and `Camera3D.UnprojectPosition` answers in the window size it fails "window" before reading a frame (the grid is round(H / 240) px, 216 lines at 1080, and `Camera3D.UnprojectPosition` answers in the
stretch base's coordinates). Bounds sit at the midpoint of the shipped worst and the least claimed mutant (`lodur:ruling:deterministic-bound-margin`), stretch base's coordinates). Bounds sit at the midpoint of the shipped worst and the least claimed mutant (`lodur:ruling:deterministic-bound-margin`),
each stated in its comment; `client/tests/render-mutants.sh` applies one set of edits per claim (post off, 12-bit post, dither off, per-pixel blocks, 360 and each stated in its comment; `client/tests/render-mutants.sh` applies one set of edits per claim (post off, 12-bit post, dither off, per-pixel blocks, 360 and
120 lines, snap off, perspective-correct UVs, per-pixel light, fog off, mipmapped and linear textures, glow unwritten, carriers unposed) and wants that 120 lines, snap off, perspective-correct UVs, per-pixel light, fog off, mipmapped and linear textures, glow unwritten, carriers unposed, the primitive torso drawn again beside the skin, the skin drawn unposed) and wants that
claim's line to fail; with `UNCLAIMED=1` it runs the edits no line separates (per-pixel fog, so far), whose readings it records. It needs a display. claim's line to fail; with `UNCLAIMED=1` it runs the edits no line separates (per-pixel fog, so far), whose readings it records. It needs a display.
@ -111,7 +118,8 @@ The client's drawing pipeline, one owner per decision (the paragraphs above say
| Owner | Inputs | Outputs | Derived state | Forbidden writers | | Owner | Inputs | Outputs | Derived state | Forbidden writers |
|---|---|---|---|---| |---|---|---|---|---|
| Ymir (the session's world, ABI 8) | the session's commands and Lodur's torque lanes | pose, shape, stable-id and joint lanes, including each joint's origin in the world (the joint origin lanes) | none the client keeps | the client writes no lane; Ymir never reads the client | | Ymir (the session's world, ABI 8) | the session's commands and Lodur's torque lanes | pose, shape, stable-id and joint lanes, including each joint's origin in the world (the joint origin lanes) | none the client keeps | the client writes no lane; Ymir never reads the client |
| `BodyRenderer` | the lanes (kind, size, stable id, pose), each physics frame | one carrier per stable id with one primitive `MeshInstance3D`; `PoseOf`, `InterpolatedPoseOf`, `PuppetCentre` (the union of the dynamic bodies' carrier-placed primitive boxes), `MeshBuilds` | `MeshBuilds`, the smoke's counter: a Reset with the same ids makes no mesh | geometry derived from anything but the lane's size; writing a lane | | `BodyRenderer` | the lanes (kind, size, stable id, pose), each physics frame | one carrier per stable id, and one primitive `MeshInstance3D` for each body `SeatedPuppet.PartOf` does not claim; `PoseOf`, `InterpolatedPoseOf`, `PuppetCentre` (the skin's centre), `MeshBuilds` | `MeshBuilds`, the smoke's counter: a Reset with the same ids makes no mesh | geometry derived from anything but the lane's size; a primitive for a body the skin draws
| `FellaSkin` (a child of `BodyRenderer`) | `fella_skin.glb` (written only by `tools/FellaMesh`), `SeatedPuppet.Plan` (parts and creation frames), the carriers' interpolated poses | one dynamic skinned surface in world space; `Centre`, `MeshBuilds` (1), `RingGap`, `OwnedVertices` | the per-vertex rest data read from the glb at `_Ready`; the posed vertices, rewritten in place every frame | carriers, lanes or the session; any hand edit of the glb; Lodur reading the mesh |; writing a lane |
| `ps1.gdshader` | `Look`'s numbers and the `ps1_*` globals, the mesh's vertices, normals and UVs | every surface's colour: snapped vertices, affine texels, per-vertex light, glow and fog | none | skinning; a second light model; a `Light3D` | | `ps1.gdshader` | `Look`'s numbers and the `ps1_*` globals, the mesh's vertices, normals and UVs | every surface's colour: snapped vertices, affine texels, per-vertex light, glow and fog | none | skinning; a second light model; a `Light3D` |
| `ps1_post.gdshader` | the frame and `ps1_res` | the framebuffer at the line grid in 15-bit colour with the dither | none | a second resolution owner (viewport scaling, a SubViewport; the project's `canvas_items` stretch, base 1280x720, only scales canvas items and `Camera3D.UnprojectPosition`'s answers, and the pass reads the real pixels, so it owns no resolution) | | `ps1_post.gdshader` | the frame and `ps1_res` | the framebuffer at the line grid in 15-bit colour with the dither | none | a second resolution owner (viewport scaling, a SubViewport; the project's `canvas_items` stretch, base 1280x720, only scales canvas items and `Camera3D.UnprojectPosition`'s answers, and the pass reads the real pixels, so it owns no resolution) |
| `Look`, `Main`, `Chamber` | `Look`: constants and textures; `Main`: the window size; `Chamber`: the box's intensity | `Look`: the constant globals and `Look.Ps1` materials; `Main`: `ps1_res` and the post layer; `Chamber`: `ps1_glow_*` | `ps1_res` is the window over `Look.BlockSize`, never set elsewhere | any other writer of a `ps1_*` global | | `Look`, `Main`, `Chamber` | `Look`: constants and textures; `Main`: the window size; `Chamber`: the box's intensity | `Look`: the constant globals and `Look.Ps1` materials; `Main`: `ps1_res` and the post layer; `Chamber`: `ps1_glow_*` | `ps1_res` is the window over `Look.BlockSize`, never set elsewhere | any other writer of a `ps1_*` global |

View file

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using BadDay.Ymir;
using Godot; using Godot;
using Ymir.Box3D; using Ymir.Box3D;
@ -7,14 +8,13 @@ namespace BadDay.Client;
/// <summary> /// <summary>
/// Draws Ymir's world from its lanes and writes nothing back: one carrier Node3D per stable id, posed each frame from the lanes so /// Draws Ymir's world from its lanes and writes nothing back: one carrier Node3D per stable id, posed each frame from the lanes so
/// physics interpolation has something to interpolate, holding one MeshInstance3D of the body's own primitive (a capsule, box or sphere /// physics interpolation has something to interpolate. Fella's parts (the stable ids <see cref="SeatedPuppet.PartOf"/> claims) are drawn
/// of the lane's size). The anchor has no shape and draws nothing. /// by <see cref="Skin"/> from their carriers' poses; every other body holds one MeshInstance3D of its own primitive (a capsule, box or sphere
/// of the lane's size), and the anchor, which has no shape, draws nothing.
/// </summary> /// </summary>
public partial class BodyRenderer : Node3D public partial class BodyRenderer : Node3D
{ {
private readonly record struct Carrier(Node3D Node, MeshInstance3D? Mesh, bool Dynamic); private readonly Dictionary<ulong, Node3D> _carriers = new();
private readonly Dictionary<ulong, Carrier> _carriers = new();
private readonly HashSet<ulong> _seen = new(); private readonly HashSet<ulong> _seen = new();
private readonly ShaderMaterial _figure = Look.Ps1(Look.SkinTexture, Colors.White); private readonly ShaderMaterial _figure = Look.Ps1(Look.SkinTexture, Colors.White);
private readonly ShaderMaterial _scenery = Look.Ps1(Look.TileTexture, Colors.White, tile: 1f); private readonly ShaderMaterial _scenery = Look.Ps1(Look.TileTexture, Colors.White, tile: 1f);
@ -22,32 +22,24 @@ public partial class BodyRenderer : Node3D
/// <summary>Bodies drawn, static and dynamic.</summary> /// <summary>Bodies drawn, static and dynamic.</summary>
public int BodyCount => _carriers.Count; public int BodyCount => _carriers.Count;
/// <summary>How many MeshInstance3D this renderer has made: a Reset with the same bodies makes none.</summary> /// <summary>How many primitive MeshInstance3D this renderer has made (Fella's skin is counted by <see cref="FellaSkin.MeshBuilds"/>): a Reset with the same bodies makes none.</summary>
public int MeshBuilds { get; private set; } public int MeshBuilds { get; private set; }
public ShaderMaterial SceneryMaterial => _scenery; public ShaderMaterial SceneryMaterial => _scenery;
/// <summary>The world centre of the union of the dynamic bodies' drawn bounds (each primitive's box in its carrier's pose, interpolated), or null while there are none: where the camera orbits.</summary> /// <summary>Fella's drawn surface: the one owner of how the parts of the seated puppet look.</summary>
public Vector3? PuppetCentre public FellaSkin Skin { get; } = new() { Name = "Skin" };
{
get /// <summary>The world centre of Fella's drawn bounds as of the last frame, or null before the skin has posed once: where the camera orbits.</summary>
{ public Vector3? PuppetCentre => Skin.Centre;
Aabb? union = null;
foreach (var c in _carriers.Values) public override void _Ready() => AddChild(Skin);
{
if (!c.Dynamic || c.Mesh is null) continue;
var box = c.Node.GetGlobalTransformInterpolated() * c.Mesh.GetAabb();
union = union is { } u ? u.Merge(box) : box;
}
return union is { } b ? b.Position + b.Size / 2 : null;
}
}
/// <summary>Where body <paramref name="stableId"/> is drawn now, or null if it is not drawn.</summary> /// <summary>Where body <paramref name="stableId"/> is drawn now, or null if it is not drawn.</summary>
public Transform3D? PoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.Node.Transform : null; public Transform3D? PoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.Transform : null;
/// <summary>The same pose as rendered this frame, between the last two ticks (a static body does not move).</summary> /// <summary>The same pose as rendered this frame, between the last two ticks (a static body does not move).</summary>
public Transform3D? InterpolatedPoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.Node.GetGlobalTransformInterpolated() : null; public Transform3D? InterpolatedPoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.GetGlobalTransformInterpolated() : null;
/// <summary>Makes the carriers match the lanes (creates the missing, frees the gone, poses every one). <paramref name="teleport"/> skips the interpolation from the previous pose.</summary> /// <summary>Makes the carriers match the lanes (creates the missing, frees the gone, poses every one). <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
public void Sync(in Box3DSoaView view, bool teleport = false) public void Sync(in Box3DSoaView view, bool teleport = false)
@ -60,7 +52,7 @@ public partial class BodyRenderer : Node3D
foreach (var id in new List<ulong>(_carriers.Keys)) foreach (var id in new List<ulong>(_carriers.Keys))
{ {
if (_seen.Contains(id)) continue; if (_seen.Contains(id)) continue;
_carriers[id].Node.QueueFree(); _carriers[id].QueueFree();
_carriers.Remove(id); _carriers.Remove(id);
} }
for (int i = 0; i < ids.Length; i++) for (int i = 0; i < ids.Length; i++)
@ -68,16 +60,14 @@ public partial class BodyRenderer : Node3D
if (_carriers.ContainsKey(ids[i])) continue; if (_carriers.ContainsKey(ids[i])) continue;
var node = new Node3D { Name = $"Body{ids[i]}" }; var node = new Node3D { Name = $"Body{ids[i]}" };
var kind = (Box3DSoaKind)view.Kind[i]; var kind = (Box3DSoaKind)view.Kind[i];
MeshInstance3D? mesh = null; if (SeatedPuppet.PartOf(ids[i]) is null && PrimitiveOf(kind, view.Size0[i], view.Size1[i], view.Size2[i]) is { } primitive)
if (PrimitiveOf(kind, view.Size0[i], view.Size1[i], view.Size2[i]) is { } primitive)
{ {
var dynamic = kind != Box3DSoaKind.StaticBox; var material = kind != Box3DSoaKind.StaticBox ? _figure : _scenery;
mesh = new MeshInstance3D { Name = "Mesh", Mesh = primitive, MaterialOverride = dynamic ? _figure : _scenery }; node.AddChild(new MeshInstance3D { Name = "Mesh", Mesh = primitive, MaterialOverride = material });
node.AddChild(mesh);
MeshBuilds++; MeshBuilds++;
} }
AddChild(node); AddChild(node);
_carriers[ids[i]] = new Carrier(node, mesh, kind != Box3DSoaKind.StaticBox); _carriers[ids[i]] = node;
teleport = true; teleport = true;
} }
} }
@ -86,7 +76,7 @@ public partial class BodyRenderer : Node3D
var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW; var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW;
for (int i = 0; i < ids.Length; i++) for (int i = 0; i < ids.Length; i++)
{ {
var node = _carriers[ids[i]].Node; var node = _carriers[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])); 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(); if (teleport) node.ResetPhysicsInterpolation();
} }

214
client/FellaSkin.cs Normal file
View file

@ -0,0 +1,214 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using BadDay.Ymir;
using Godot;
using Lodur;
namespace BadDay.Client;
/// <summary>
/// Fella's drawn surface: one skinned mesh, MakeHuman's base body fitted to Lodur's plan by tools/FellaMesh (client/fella/fella_skin.glb), drawn on
/// the bones. It owns which vertices exist, where each is drawn every frame, and the drawn bounds; the plan owns the parts and their creation frames
/// (<see cref="SeatedPuppet.Plan"/>), and the carriers of <see cref="BodyRenderer"/> own where each part is. Each vertex has one part, or two at a
/// joint ring (a vertex on faces of two parts, one copy per part with the same two weights, so the copies coincide while the parts are joined).
/// Every frame the vertices are rebuilt from the carriers' interpolated poses in one pass and written into one dynamic surface in place; the pass
/// allocates nothing. The file is read as bytes (no import step decides vertex data) and is never edited: rerun the build.
/// </summary>
public partial class FellaSkin : Node3D
{
public const string AssetPath = "res://fella/fella_skin.glb";
private const int PositionBytes = 12; // three floats
private const int NormalBytes = 8; // octahedral normal and tangent, four 16-bit values each vertex; the tangent is never written
private Vector3[] _rest = Array.Empty<Vector3>();
private Vector3[] _restNormal = Array.Empty<Vector3>();
private Vector3[] _drawn = Array.Empty<Vector3>();
private int[] _partA = Array.Empty<int>(), _partB = Array.Empty<int>();
private float[] _weightA = Array.Empty<float>(), _weightB = Array.Empty<float>();
private int[][] _rings = Array.Empty<int[]>();
private int[] _owned = Array.Empty<int>();
private Transform3D[] _inverseCreation = Array.Empty<Transform3D>();
private Transform3D[] _skin = Array.Empty<Transform3D>();
private byte[] _data = Array.Empty<byte>();
private ArrayMesh _mesh = null!;
private Rid _rid;
private Aabb? _bounds;
/// <summary>The surfaces made for the session's life: 1.</summary>
public int MeshBuilds { get; private set; }
/// <summary>Vertices drawn, joint-ring copies counted once each.</summary>
public int VertexCount => _rest.Length;
/// <summary>The world centre of the drawn bounds as of the last pose, or null before the first: where the camera orbits.</summary>
public Vector3? Centre => _bounds is { } b ? b.Position + b.Size / 2 : null;
/// <summary>How many vertices part <paramref name="part"/> owns (the copies of joint-ring vertices count for the part each is emitted for).</summary>
public int OwnedVertices(int part) => _owned[part];
/// <summary>The largest distance between the drawn copies of any joint-ring vertex, in metres, as of the last pose: 0 while the parts are joined.</summary>
public float RingGap()
{
float worst = 0f;
foreach (var ring in _rings)
for (int i = 0; i < ring.Length; i++)
for (int j = i + 1; j < ring.Length; j++)
worst = Math.Max(worst, _drawn[ring[i]].DistanceTo(_drawn[ring[j]]));
return worst;
}
public override void _Ready()
{
var plan = SeatedPuppet.Plan;
var state = new GltfState();
var bytes = Godot.FileAccess.GetFileAsBytes(AssetPath);
if (bytes.Length == 0 || new GltfDocument().AppendFromBuffer(bytes, "", state) != Error.Ok) throw new InvalidOperationException($"{AssetPath} cannot be read as glTF");
var skin = state.GetSkins()[0];
var nodes = state.GetNodes();
var joints = skin.Joints;
if (joints.Length != plan.Parts.Count) throw new InvalidOperationException($"{AssetPath} has {joints.Length} joints for the plan's {plan.Parts.Count} parts");
var partOfJoint = new int[joints.Length];
var seen = new HashSet<int>();
for (int j = 0; j < joints.Length; j++)
{
var name = nodes[joints[j]].ResourceName; // "Label" for a Center part, else "Label.Left" or "Label.Right"
var dot = name.IndexOf('.');
var side = dot < 0 ? Lodur.Side.Center : Enum.Parse<Lodur.Side>(name[(dot + 1)..]);
partOfJoint[j] = plan.PartIndex(dot < 0 ? name : name[..dot], side); // throws for a name the plan has no part for
if (!seen.Add(partOfJoint[j])) throw new InvalidOperationException($"{AssetPath} names part {name} twice");
}
var surfaces = state.GetMeshes()[0].Mesh;
if (surfaces.GetSurfaceCount() != plan.Parts.Count) throw new InvalidOperationException($"{AssetPath} has {surfaces.GetSurfaceCount()} primitives for the plan's {plan.Parts.Count} parts");
var positions = new List<Vector3>(); var normals = new List<Vector3>(); var uvs = new List<Vector2>(); var indices = new List<int>();
var partA = new List<int>(); var partB = new List<int>(); var weightA = new List<float>(); var weightB = new List<float>();
_owned = new int[plan.Parts.Count];
for (int s = 0; s < surfaces.GetSurfaceCount(); s++) // the build emits one primitive per part, in the plan's order
{
var arrays = surfaces.GetSurfaceArrays(s);
var v = arrays[(int)Mesh.ArrayType.Vertex].AsVector3Array();
var n = arrays[(int)Mesh.ArrayType.Normal].AsVector3Array();
var uv = arrays[(int)Mesh.ArrayType.TexUV].AsVector2Array();
var bones = arrays[(int)Mesh.ArrayType.Bones].AsInt32Array();
var weights = arrays[(int)Mesh.ArrayType.Weights].AsFloat32Array();
var first = positions.Count;
bool owned = false;
for (int i = 0; i < v.Length; i++)
{
int a = partOfJoint[bones[4 * i]], b = partOfJoint[bones[4 * i + 1]];
float wa = weights[4 * i], wb = weights[4 * i + 1];
if (wb == 0f) b = a;
owned |= a == s || b == s;
positions.Add(v[i]); normals.Add(n[i]); uvs.Add(uv[i]);
partA.Add(a); partB.Add(b); weightA.Add(wa); weightB.Add(wb);
}
if (!owned) throw new InvalidOperationException($"{AssetPath}: primitive {s} has no vertex weighted to its part");
foreach (var index in arrays[(int)Mesh.ArrayType.Index].AsInt32Array()) indices.Add(first + index);
_owned[s] = v.Length;
}
_rest = positions.ToArray(); _restNormal = normals.ToArray(); _drawn = positions.ToArray();
_partA = partA.ToArray(); _partB = partB.ToArray(); _weightA = weightA.ToArray(); _weightB = weightB.ToArray();
var byPosition = new Dictionary<Vector3, List<int>>(); // the copies of one ring vertex have the same rest position
for (int i = 0; i < _rest.Length; i++)
{
if (!byPosition.TryGetValue(_rest[i], out var list)) byPosition[_rest[i]] = list = new List<int>();
list.Add(i);
}
var rings = new List<int[]>();
foreach (var list in byPosition.Values) if (list.Count > 1) rings.Add(list.ToArray());
_rings = rings.ToArray();
_inverseCreation = new Transform3D[plan.Parts.Count];
_skin = new Transform3D[plan.Parts.Count];
for (int p = 0; p < plan.Parts.Count; p++)
{
var def = plan.Parts[p];
var frame = new Transform3D(new Basis(new Quaternion(def.Rotation.X, def.Rotation.Y, def.Rotation.Z, def.Rotation.W)), new Vector3(def.Position.X, def.Position.Y, def.Position.Z));
_inverseCreation[p] = frame.AffineInverse();
_skin[p] = Transform3D.Identity;
}
var surface = new Godot.Collections.Array();
surface.Resize((int)Mesh.ArrayType.Max);
surface[(int)Mesh.ArrayType.Vertex] = _rest;
surface[(int)Mesh.ArrayType.Normal] = _restNormal;
surface[(int)Mesh.ArrayType.TexUV] = uvs.ToArray();
surface[(int)Mesh.ArrayType.Index] = indices.ToArray();
_mesh = new ArrayMesh();
_mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, surface, flags: Mesh.ArrayFormat.FlagUseDynamicUpdate);
_rid = _mesh.GetRid();
_data = RenderingServer.MeshGetSurface(_rid, 0)["vertex_data"].AsByteArray(); // positions, then normals and tangents: the layout this class rewrites in place
if (_data.Length != _rest.Length * (PositionBytes + NormalBytes)) throw new InvalidOperationException($"the dynamic surface holds {_data.Length} vertex bytes, not {_rest.Length * (PositionBytes + NormalBytes)}");
AddChild(new MeshInstance3D { Name = "Mesh", Mesh = _mesh, MaterialOverride = Look.Ps1(Look.SkinTexture, Colors.White) });
MeshBuilds = 1;
PhysicsInterpolationMode = PhysicsInterpolationModeEnum.Off; // the vertices are already placed from interpolated poses
}
public override void _Process(double delta) => Deform();
/// <summary>Redraws every vertex from the carriers' interpolated poses: p = sum of w (pose * creation frame inverse) p_rest, normals by the same rotation.</summary>
public void Deform()
{
var bodies = GetParent<BodyRenderer>();
for (int p = 0; p < _skin.Length; p++)
if (bodies.InterpolatedPoseOf(SeatedPuppet.FirstStableId + (ulong)p) is { } pose) _skin[p] = pose * _inverseCreation[p];
var low = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
var high = new Vector3(float.MinValue, float.MinValue, float.MinValue);
int normalBase = _rest.Length * PositionBytes;
for (int i = 0; i < _rest.Length; i++)
{
var ma = _skin[_partA[i]];
var p = ma * _rest[i];
var n = ma.Basis * _restNormal[i];
if (_weightB[i] > 0f)
{
var mb = _skin[_partB[i]];
p = p * _weightA[i] + mb * _rest[i] * _weightB[i];
n = n * _weightA[i] + mb.Basis * _restNormal[i] * _weightB[i];
}
_drawn[i] = p;
low = new Vector3(Math.Min(low.X, p.X), Math.Min(low.Y, p.Y), Math.Min(low.Z, p.Z));
high = new Vector3(Math.Max(high.X, p.X), Math.Max(high.Y, p.Y), Math.Max(high.Z, p.Z));
var at = _data.AsSpan(i * PositionBytes);
BinaryPrimitives.WriteSingleLittleEndian(at, p.X);
BinaryPrimitives.WriteSingleLittleEndian(at[4..], p.Y);
BinaryPrimitives.WriteSingleLittleEndian(at[8..], p.Z);
Octahedral(n, _data.AsSpan(normalBase + i * NormalBytes));
}
RenderingServer.MeshSurfaceUpdateVertexRegion(_rid, 0, 0, _data);
_bounds = new Aabb(low, high - low);
_mesh.CustomAabb = _bounds.Value;
}
/// <summary>The median time of <paramref name="frames"/> deforms, in microseconds: the cost line the smoke prints.</summary>
public double MedianDeformMicroseconds(int frames)
{
var ticks = new long[frames];
for (int f = 0; f < frames; f++)
{
long start = Stopwatch.GetTimestamp();
Deform();
ticks[f] = Stopwatch.GetTimestamp() - start;
}
Array.Sort(ticks);
return ticks[frames / 2] * 1e6 / Stopwatch.Frequency;
}
/// <summary>Godot's surface normal encoding: the octahedral map of the unit normal, two 16-bit values.</summary>
private static void Octahedral(Vector3 normal, Span<byte> into)
{
normal /= Math.Abs(normal.X) + Math.Abs(normal.Y) + Math.Abs(normal.Z);
float x = normal.X, y = normal.Y;
if (normal.Z < 0f)
{
x = (1f - Math.Abs(normal.Y)) * (normal.X >= 0f ? 1f : -1f);
y = (1f - Math.Abs(normal.X)) * (normal.Y >= 0f ? 1f : -1f);
}
BinaryPrimitives.WriteUInt16LittleEndian(into, (ushort)Math.Clamp((x * 0.5f + 0.5f) * 65535f, 0f, 65535f));
BinaryPrimitives.WriteUInt16LittleEndian(into[2..], (ushort)Math.Clamp((y * 0.5f + 0.5f) * 65535f, 0f, 65535f));
}
}

View file

@ -21,8 +21,8 @@ public partial class RenderCheck : Node
private const int Width = 1280, Height = 720; private const int Width = 1280, Height = 720;
private const double WatchdogSeconds = 120; private const double WatchdogSeconds = 120;
// Bounds (shipped worst, least claimed mutant, separation) are in each check's comment. // Bounds (shipped worst, least claimed mutant, separation) are in each check's comment.
private const int OddLevelFloor = 1245, FigureMisses = 3, DitherBlocks = 160; private const int OddLevelFloor = 1245, FigureMisses = 1, DitherBlocks = 160;
private const double FogLevels = 6.6, LightLevels = 11, MipPercent = 6.5; private const double NeckBound = 1.0, FogLevels = 6.6, LightLevels = 11, MipPercent = 6.5;
private readonly List<string> _failures = new(); private readonly List<string> _failures = new();
private Main _main = null!; private Main _main = null!;
@ -88,6 +88,7 @@ public partial class RenderCheck : Node
_main.Chamber.Volume.Visible = false; // the translucent box tints the hand bodies inside it _main.Chamber.Volume.Visible = false; // the translucent box tints the hand bodies inside it
CheckFigureWhereLanesAre(await Capture("play-clear")); CheckFigureWhereLanesAre(await Capture("play-clear"));
_main.Chamber.Volume.Visible = true; _main.Chamber.Volume.Visible = true;
await CheckNeck();
var home = _camera.Transform; var home = _camera.Transform;
_camera.Distance = 0.9f; _camera.Distance = 0.9f;
@ -162,8 +163,8 @@ public partial class RenderCheck : Node
/// <summary> /// <summary>
/// Each dynamic body's lane origin, projected through the camera, lands within one block (3 px) of a figure pixel (skin is red over blue; floor, /// Each dynamic body's lane origin, projected through the camera, lands within one block (3 px) of a figure pixel (skin is red over blue; floor,
/// background and chamber are blue over red). A single pixel failed under unrelated edits (dither, snap, glow, post off each moved one origin onto a /// background and chamber are blue over red). A single pixel failed under unrelated edits (dither, snap, glow, post off each moved one origin onto a
/// dithered or edge pixel), so the neighbourhood is the block. Bound 3 of 19 = sqrt(0.5 x 19): shipped 0 (counted as half a body, lodur:ruling:deterministic-bound-zero-reading), carriers left /// dithered or edge pixel), so the neighbourhood is the block. Bound 1 of 19 = sqrt(0.5 x 4) rounded down, a count: shipped 0 (counted as half a body, lodur:ruling:deterministic-bound-zero-reading), the least claimed mutant skin-unposed (the
/// unposed 19, separation 38; post off, 12-bit, dither off, snap off, glow unset, fog off, per-pixel light, mipmapped and linear textures, 360 and 120 /// skin drawn at its rest pose) 4, carriers left unposed 19, separation 8; post off, 12-bit, dither off, snap off, glow unset, fog off, per-pixel light, mipmapped and linear textures, 360 and 120
/// lines, perspective UVs and per-block sampling each read 0, so no collateral edit turns it. /// lines, perspective UVs and per-block sampling each read 0, so no collateral edit turns it.
/// </summary> /// </summary>
private void CheckFigureWhereLanesAre(Frame play) private void CheckFigureWhereLanesAre(Frame play)
@ -191,6 +192,45 @@ public partial class RenderCheck : Node
Check(checkedBodies > 5 && missed <= FigureMisses, "figure at lanes", $"{missed} of {checkedBodies} dynamic bodies' origins are not within a block of a figure pixel"); Check(checkedBodies > 5 && missed <= FigureMisses, "figure at lanes", $"{missed} of {checkedBodies} dynamic bodies' origins are not within a block of a figure pixel");
} }
/// <summary>
/// A real neck is drawn. The chamber is hidden and the camera put straight in front of the head, 1.2 m away; the reading is the figure pixels on the row
/// 1 cm below the projected neck joint (the torso's pose times the joint's local anchor) over the figure pixels on the row through the projected head origin:
/// how wide the figure is at the neck against how wide at the head. Bound 1.0 = sqrt(0.58 x 1.72): shipped 0.58 (63 px over 108), the least claimed mutant
/// fella-primitives (the primitive box torso, 0.30 m wide, drawn again beside the skin) 1.72 (186 px over 108), separation 3.0; skin-unposed reads 0.54.
/// </summary>
private async Task CheckNeck()
{
var plan = SeatedPuppet.Plan;
int head = plan.PartIndex("Head"), torso = plan.PartIndex("Torso");
var headPose = _main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)head)!.Value;
var torsoPose = _main.Bodies.PoseOf(SeatedPuppet.FirstStableId + (ulong)torso)!.Value;
var torsoDef = plan.Parts[torso];
var torsoCreation = new Transform3D(new Basis(new Quaternion(torsoDef.Rotation.X, torsoDef.Rotation.Y, torsoDef.Rotation.Z, torsoDef.Rotation.W)), new Vector3(torsoDef.Position.X, torsoDef.Position.Y, torsoDef.Position.Z));
var anchor = plan.Joints[plan.JointIndex("Neck")].Anchor;
var neck = torsoPose * (torsoCreation.AffineInverse() * new Vector3(anchor.X, anchor.Y, anchor.Z));
_main.Chamber.Visible = false;
var home = _camera.Transform;
_camera.GlobalTransform = new Transform3D(Basis.Identity, headPose.Origin + new Vector3(0, 0, 1.2f));
await Frames(3);
var frame = await Capture("neck");
var camera = GetViewport().GetCamera3D();
int neckRow = (int)camera.UnprojectPosition(neck + new Vector3(0, -0.01f, 0)).Y;
int headRow = (int)camera.UnprojectPosition(headPose.Origin).Y;
int FigureOn(int y)
{
int n = 0;
for (int x = 0; x < Width; x++) if ((frame.Rgb(x, y) >> 16 & 0xff) >= (frame.Rgb(x, y) & 0xff) + 16) n++;
return n;
}
int atNeck = FigureOn(neckRow), atHead = FigureOn(headRow);
double ratio = atHead > 0 ? atNeck / (double)atHead : double.PositiveInfinity;
Report($"neck: figure width at the neck over at the head ({atNeck} px over {atHead} px)", ratio, NeckBound);
Check(atHead > 0 && ratio <= NeckBound, "neck", $"the figure is {atNeck} px wide a centimetre below the neck joint and {atHead} px wide at the head: the ratio {ratio:0.##} is over {NeckBound}");
_camera.Transform = home;
_main.Chamber.Visible = true;
}
/// <summary> /// <summary>
/// The snap and the affine probes: the figure and floor are hidden and a probe is drawn with the client's own material under the client's camera. /// The snap and the affine probes: the figure and floor are hidden and a probe is drawn with the client's own material under the client's camera.
/// Snap: a box on a 30-line grid (blocks of 24 px), its drawn blocks against the blocks the CPU-projected hull covers with its corners snapped to /// Snap: a box on a 30-line grid (blocks of 24 px), its drawn blocks against the blocks the CPU-projected hull covers with its corners snapped to

View file

@ -18,6 +18,9 @@ public partial class Smoke : Node
{ {
private const ulong Seed = 1; private const ulong Seed = 1;
private const double WatchdogSeconds = 150; private const double WatchdogSeconds = 150;
// The joint rings' bound, in micrometres (lodur:ruling:deterministic-bound-margin and deterministic-bound-zero-reading): shipped worst 0 (counted as half a micrometre),
// the least claimed mutant (split rings: each copy weighted to its own part only) 75768 at tick 240; sqrt(0.5 x 75768) = 195, separation 1.5e5.
private const double RingGapMicrometres = 195;
private readonly List<string> _failures = new(); private readonly List<string> _failures = new();
private Main _main = null!; private Main _main = null!;
@ -94,6 +97,7 @@ public partial class Smoke : Node
await UntilTick(240); await UntilTick(240);
CheckHand(reference.Hand[239], "tick 240"); CheckHand(reference.Hand[239], "tick 240");
CheckPoses("tick 240"); CheckPoses("tick 240");
CheckSkin("tick 240");
await UntilTick(1500); await UntilTick(1500);
CheckEvents(reference, "seed 1, default intensity"); CheckEvents(reference, "seed 1, default intensity");
CheckHand(reference.Hand[^1], "tick 1500"); CheckHand(reference.Hand[^1], "tick 1500");
@ -314,13 +318,28 @@ public partial class Smoke : Node
Check(environment.Sky is null && environment.TonemapMode == Godot.Environment.ToneMapper.Linear && !environment.GlowEnabled, "the environment is not a linear colour environment with no sky and no glow"); Check(environment.Sky is null && environment.TonemapMode == Godot.Environment.ToneMapper.Linear && !environment.GlowEnabled, "the environment is not a linear colour environment with no sky and no glow");
} }
/// <summary>Every body with a shape is drawn by one mesh, made once: the anchor has none.</summary> /// <summary>Every body with a shape that Fella's skin does not draw has one primitive mesh, made once (the anchor has none); the skin is one surface, made once.</summary>
private void CheckMeshBuilds(string when) private void CheckMeshBuilds(string when)
{ {
var view = Session.View; var view = Session.View;
int shaped = 0; int shaped = 0;
for (int i = 0; i < view.Count; i++) if ((Box3DSoaKind)view.Kind[i] != Box3DSoaKind.Anchor) shaped++; for (int i = 0; i < view.Count; i++) if ((Box3DSoaKind)view.Kind[i] != Box3DSoaKind.Anchor && SeatedPuppet.PartOf(view.StableId[i]) is null) shaped++;
Check(_main.Bodies.MeshBuilds == shaped, $"{when}: {_main.Bodies.MeshBuilds} body meshes were made for {shaped} bodies with a shape; a Reset makes none"); Check(_main.Bodies.MeshBuilds == shaped, $"{when}: {_main.Bodies.MeshBuilds} body meshes were made for {shaped} bodies with a shape the skin does not draw; a Reset makes none");
Check(_main.Bodies.Skin.MeshBuilds == 1, $"{when}: the skin was built {_main.Bodies.Skin.MeshBuilds} times, not once");
}
/// <summary>
/// Fella's skin: every part of the plan owns vertices, and the copies of every joint-ring vertex are drawn together while the parts are joined.
/// The ring-gap bound is in micrometres (lodur:ruling:deterministic-bound-zero-reading: a shipped zero counts as half a micrometre).
/// </summary>
private void CheckSkin(string when)
{
var skin = _main.Bodies.Skin;
for (int part = 0; part < SeatedPuppet.Plan.Parts.Count; part++)
Check(skin.OwnedVertices(part) > 0, $"{when}: part {part} ({SeatedPuppet.Plan.Parts[part].Label}) owns no skin vertices");
double gap = skin.RingGap() * 1e6;
Check(gap < RingGapMicrometres, $"{when}: joint-ring copies are drawn {gap:F1} micrometres apart (bound {RingGapMicrometres})");
GD.Print($"SKIN {skin.VertexCount} vertices, ring gap {gap:F1} um, deform {skin.MedianDeformMicroseconds(1000):F1} us per frame (median of 1000, headless)");
} }
private void CheckPoses(string when) private void CheckPoses(string when)

View file

@ -4,6 +4,7 @@
# from a run that died harder is refused at the start). Needs a window (RenderCheck draws). Run from anywhere: # from a run that died harder is refused at the start). Needs a window (RenderCheck draws). Run from anywhere:
# GODOT=<godot console exe> bash client/tests/render-mutants.sh # every claimed mutant must fail its own line # GODOT=<godot console exe> bash client/tests/render-mutants.sh # every claimed mutant must fail its own line
# GODOT=<godot console exe> UNCLAIMED=1 bash client/tests/render-mutants.sh # the unclaimed ones below must still pass (their readings are the record) # GODOT=<godot console exe> UNCLAIMED=1 bash client/tests/render-mutants.sh # the unclaimed ones below must still pass (their readings are the record)
# ONLY="name name" bash client/tests/render-mutants.sh # just those mutants
# A mutant's edits are old@@old|new@@new pairs in one file; the line it must fail is the RenderCheck check named in its last field. # A mutant's edits are old@@old|new@@new pairs in one file; the line it must fail is the RenderCheck check named in its last field.
# #
# Readings (shipped / mutant) of the claims, from RenderCheck's bounds, which sit at the geometric midpoint of shipped worst and least mutant # Readings (shipped / mutant) of the claims, from RenderCheck's bounds, which sit at the geometric midpoint of shipped worst and least mutant
@ -42,6 +43,8 @@ MUTANTS=(
'linear-filter|ps1.gdshader|filter_nearest, repeat_enable|filter_linear, repeat_enable|mips' 'linear-filter|ps1.gdshader|filter_nearest, repeat_enable|filter_linear, repeat_enable|mips'
'glow-unset|Chamber.cs|Look.GlowLightEnergy * glow|0f|glow' 'glow-unset|Chamber.cs|Look.GlowLightEnergy * glow|0f|glow'
'carrier-unposed|BodyRenderer.cs|node.Transform = new Transform3D(new Basis(new Quaternion(rx[i]|_ = new Transform3D(new Basis(new Quaternion(rx[i]|figure at lanes' 'carrier-unposed|BodyRenderer.cs|node.Transform = new Transform3D(new Basis(new Quaternion(rx[i]|_ = new Transform3D(new Basis(new Quaternion(rx[i]|figure at lanes'
'fella-primitives|BodyRenderer.cs|SeatedPuppet.PartOf(ids[i]) is null && PrimitiveOf(|PrimitiveOf(|neck'
'skin-unposed|FellaSkin.cs|is { } pose) _skin[p] = pose * _inverseCreation[p];|is { } pose) _skin[p] = Transform3D.Identity;|figure at lanes'
) )
UNCLAIMED_MUTANTS=( UNCLAIMED_MUTANTS=(
@ -63,6 +66,7 @@ status=0
if [ "${UNCLAIMED:-}" = 1 ]; then LIST=("${UNCLAIMED_MUTANTS[@]}"); else LIST=("${MUTANTS[@]}"); fi if [ "${UNCLAIMED:-}" = 1 ]; then LIST=("${UNCLAIMED_MUTANTS[@]}"); else LIST=("${MUTANTS[@]}"); fi
for m in "${LIST[@]}"; do for m in "${LIST[@]}"; do
IFS='|' read -r name file old new want <<<"$m" IFS='|' read -r name file old new want <<<"$m"
if [ -n "${ONLY:-}" ] && [[ " $ONLY " != *" $name "* ]]; then continue; fi # ONLY="name name": just those
cp "$file" "$file.orig" cp "$file" "$file.orig"
ACTIVE="$file" ACTIVE="$file"
if ! python - "$file" "$old" "$new" <<'PY' if ! python - "$file" "$old" "$new" <<'PY'