diff --git a/client/Look.cs b/client/Look.cs index dbe0640..1b055cc 100644 --- a/client/Look.cs +++ b/client/Look.cs @@ -23,11 +23,16 @@ public static class Look public const float BoxRound = 0.03f; /// - /// The width (m) each side of a puppet edge over which the facet normal turns to the edge's bisector: 4 mm, the recommended - /// option of the open question lodur:question:bds-puppet-bevel-width (0 keeps hard facets; 10 mm makes curved limbs read as smooth). - /// An answer changes this constant and nothing else. + /// The bevel's width each side of a puppet edge, as a fraction of the viewport's height: 2 px of a 720-line screen. The recommended + /// option (screen-2px) of the open question lodur:question:bds-puppet-bevel-look-width: at the play camera a pixel is about 3.5 mm + /// and the facets about 11 px, so a fixed 4 mm bevel is one pixel and reads as hard facets, while a width on the screen keeps the soft + /// edge visible there and narrow close up. 0 with as the width is a world width; an answer changes these two + /// constants and nothing else. /// - public const float BevelWidth = 0.004f; + public const float BevelScreen = 2f / 720f; + + /// The narrowest bevel (m) however near the camera is: 3 mm, so a puppet filling the screen still has soft edges. + public const float BevelMin = 0.003f; public static Godot.Environment Environment() => new() { diff --git a/client/Puppet.cs b/client/Puppet.cs index a257195..9330280 100644 --- a/client/Puppet.cs +++ b/client/Puppet.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Runtime.InteropServices; using CultMath; using Godot; using Ymir.Box3D; @@ -7,28 +8,34 @@ using Ymir.Box3D; namespace BadDay.Client; /// -/// The puppet: its drawn surface is one skinned SDF isosurface mesh () 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. +/// The puppet: its drawn surface is one SDF isosurface mesh () over the dynamic bodies, flat-shaded +/// with a soft bevel, 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 skins the surface on the CPU by those carriers' interpolated transforms relative to the spread +/// bind pose and derives its facets, creases and vertex normals; this class uploads the result into the mesh's two streams in place. /// public partial class Puppet : Node3D { + /// Bytes per triangle corner in the vertex stream (VERTEX, float3) and in the attribute stream (CUSTOM0 float4, CUSTOM1..3 float3 each). + private const int VertexBytes = 12, AttributeBytes = 52; + private readonly Dictionary _nodes = new(); private readonly HashSet _seen = new(); private readonly ShaderMaterial _material = new() { Shader = GD.Load("res://puppet.gdshader") }; private readonly MeshInstance3D _skin = new MeshInstance3D { Name = "Skin" }; - private readonly Godot.Collections.Array _bones = new(); private readonly PuppetModel _model = new(Look.SminRadius, Look.JointBallScale, Look.BoxRound); private ArrayMesh? _mesh; private Node3D[] _boneNodes = Array.Empty(); private Transform3D[] _inverseBind = Array.Empty(); + private Rigid[] _bones = Array.Empty(); + private PuppetSkin? _surface; + private byte[] _vertexStream = Array.Empty(), _attributeStream = Array.Empty(); public Puppet() { _material.SetShaderParameter("albedo", Look.Figure); - _material.SetShaderParameter("bevel_width", Look.BevelWidth); - for (int i = 0; i < PuppetModel.MaxBones; i++) _bones.Add(new Projection(Transform3D.Identity)); + _material.SetShaderParameter("bevel_screen", Look.BevelScreen); + _material.SetShaderParameter("bevel_min", Look.BevelMin); _skin.MaterialOverride = _material; } @@ -104,22 +111,18 @@ public partial class Puppet : Node3D public override void _Process(double delta) { - if (Shape is null) return; - // The bones take a body from the spread bind to its world pose. VERTEX is in the skin's model space, which Godot then - // carries to the world with the skin's own transform, so the bones are taken into that space first: the puppet is right - // under any parent, not only at the origin. + if (_surface is null || _mesh is null) return; + // The bones take a body from the spread bind to its pose in the skin's model space, which Godot then carries to the world with + // the skin's own transform: the puppet is right under any parent, not only at the origin. var toModel = _skin.GetGlobalTransformInterpolated().AffineInverse(); - 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 = toModel * _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); + for (int i = 0; i < _boneNodes.Length; i++) _bones[i] = ToRigid(toModel * _boneNodes[i].GetGlobalTransformInterpolated() * _inverseBind[i]); + _surface.Update(_bones); + Pack(_surface, Shape!.Corners, _vertexStream, _attributeStream); + var rid = _mesh.GetRid(); + RenderingServer.MeshSurfaceUpdateVertexRegion(rid, 0, 0, _vertexStream); + RenderingServer.MeshSurfaceUpdateAttributeRegion(rid, 0, 0, _attributeStream); + var lo = _surface.Lo; var hi = _surface.Hi; + _mesh.CustomAabb = new Aabb(new Vector3(lo.x, lo.y, lo.z), new Vector3(hi.x - lo.x, hi.y - lo.y, hi.z - lo.z)); } private static bool IsPuppet(uint kind) => (Box3DSoaKind)kind != Box3DSoaKind.StaticBox; @@ -137,65 +140,73 @@ public partial class Puppet : Node3D return true; } - /// Takes up the model's new shape: the carriers that are its bones, their inverse bind, and the mesh. + /// Takes up the model's new shape: the carriers that are its bones, their inverse bind, the skin's buffers and the mesh layout. private void Rebuild() { if (_model.Shape is not { } shape) { - 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; + GD.PushError($"BadDay: the puppet has more than {PuppetModel.MaxBones} shape bodies, which is the most it draws; drawing no puppet."); + _mesh = null; _surface = null; _skin.Mesh = null; return; } - _boneNodes = new Node3D[shape.Ids.Length]; _inverseBind = new Transform3D[shape.Ids.Length]; + _boneNodes = new Node3D[shape.Ids.Length]; _inverseBind = new Transform3D[shape.Ids.Length]; _bones = new Rigid[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); + _surface = new PuppetSkin(shape); + _vertexStream = new byte[VertexBytes * shape.Corners.Length]; _attributeStream = new byte[AttributeBytes * shape.Corners.Length]; + _mesh = LayoutOf(shape.Corners.Length); + var surface = RenderingServer.MeshGetSurface(_mesh.GetRid(), 0); + int vertexLength = surface["vertex_data"].AsByteArray().Length, attributeLength = surface["attribute_data"].AsByteArray().Length; + if (vertexLength != _vertexStream.Length || attributeLength != _attributeStream.Length) + throw new InvalidOperationException($"BadDay: the puppet mesh holds {vertexLength} and {attributeLength} bytes of vertex and attribute data, not the {_vertexStream.Length} and {_attributeStream.Length} it is filled with."); MeshBuilds++; _skin.Mesh = _mesh; } /// - /// The shape as one surface: VERTEX in the spread bind, the facet NORMAL, CUSTOM0 (the edge-distance basis: vertex k of a triangle holds - /// its altitude h_k = 2 * area / |edge k| in component k and 0 in the others, the triangle's smallest altitude in w), CUSTOM1 (bone A, - /// bone B, weight A) and CUSTOM2 (the triangle's three creases: zero until PuppetSkin derives them, so the bevel does nothing here). + /// A surface of vertices that only fixes the layout the frames fill in place (nothing is rebuilt per frame): + /// the vertex stream is VERTEX alone, the attribute stream CUSTOM0 (RgbaFloat: component k holds the altitude h_k of corner k, w the + /// triangle's smallest altitude), CUSTOM1 (the triangle's three creases), CUSTOM2 (the facet normal) and CUSTOM3 (the corner's vertex + /// normal), all in the skin's model space. /// - private static ArrayMesh MeshOf(PuppetShape s) + private static ArrayMesh LayoutOf(int corners) { - int n = s.Corners.Length; - var vertex = new Vector3[n]; var normal = new Vector3[n]; var edge = new float[4 * n]; var skin = new float[3 * n]; var crease = new float[3 * n]; - for (int t = 0; t < n; t += 3) - { - var p = new[] { s.Vertices[s.Corners[t]], s.Vertices[s.Corners[t + 1]], s.Vertices[s.Corners[t + 2]] }; - var cross = CultMath.math.cross(p[1] - p[0], p[2] - p[0]); - float twiceArea = CultMath.math.length(cross); - var facet = -cross / twiceArea; - var h = new float[3]; - for (int k = 0; k < 3; k++) - { - float length = CultMath.math.length(p[(k + 1) % 3] - p[(k + 2) % 3]); - h[k] = length > 0 ? twiceArea / length : 0; - } - float smallest = Mathf.Min(h[0], Mathf.Min(h[1], h[2])); - for (int k = 0; k < 3; k++) - { - int i = t + k, c = s.Corners[i]; - vertex[i] = new Vector3(p[k].x, p[k].y, p[k].z); - normal[i] = new Vector3(facet.x, facet.y, facet.z); - skin[3 * i] = s.BoneA[c]; skin[3 * i + 1] = s.BoneB[c]; skin[3 * i + 2] = s.WeightA[c]; - edge[4 * i + k] = h[k]; edge[4 * i + 3] = smallest; - } - } 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.Custom0] = edge; - arrays[(int)Mesh.ArrayType.Custom1] = skin; - arrays[(int)Mesh.ArrayType.Custom2] = crease; + arrays[(int)Mesh.ArrayType.Vertex] = new Vector3[corners]; + arrays[(int)Mesh.ArrayType.Custom0] = new float[4 * corners]; + arrays[(int)Mesh.ArrayType.Custom1] = new float[3 * corners]; + arrays[(int)Mesh.ArrayType.Custom2] = new float[3 * corners]; + arrays[(int)Mesh.ArrayType.Custom3] = new float[3 * corners]; var format = (Mesh.ArrayFormat)(((int)Mesh.ArrayCustomFormat.RgbaFloat << (int)Mesh.ArrayFormat.FormatCustom0Shift) | ((int)Mesh.ArrayCustomFormat.RgbFloat << (int)Mesh.ArrayFormat.FormatCustom1Shift) - | ((int)Mesh.ArrayCustomFormat.RgbFloat << (int)Mesh.ArrayFormat.FormatCustom2Shift)); + | ((int)Mesh.ArrayCustomFormat.RgbFloat << (int)Mesh.ArrayFormat.FormatCustom2Shift) + | ((int)Mesh.ArrayCustomFormat.RgbFloat << (int)Mesh.ArrayFormat.FormatCustom3Shift)); var mesh = new ArrayMesh(); mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays, null, null, format); return mesh; } + + /// Writes the skin's surface, one triangle corner after another, into the two streams (no allocation). + private static void Pack(PuppetSkin skin, int[] corners, byte[] vertexStream, byte[] attributeStream) + { + var vertex = MemoryMarshal.Cast(vertexStream); + var attribute = MemoryMarshal.Cast(attributeStream); + for (int t = 0; t < corners.Length / 3; t++) + { + var facet = skin.Facet[t]; + for (int k = 0; k < 3; k++) + { + int slot = 3 * t + k, c = corners[slot]; + var p = skin.Skinned[c]; + vertex[3 * slot] = p.x; vertex[3 * slot + 1] = p.y; vertex[3 * slot + 2] = p.z; + int o = AttributeBytes / 4 * slot; + attribute[o] = k == 0 ? skin.Altitude[3 * t] : 0; attribute[o + 1] = k == 1 ? skin.Altitude[3 * t + 1] : 0; attribute[o + 2] = k == 2 ? skin.Altitude[3 * t + 2] : 0; + attribute[o + 3] = skin.SmallestAltitude[t]; + attribute[o + 4] = skin.Crease[3 * t]; attribute[o + 5] = skin.Crease[3 * t + 1]; attribute[o + 6] = skin.Crease[3 * t + 2]; + attribute[o + 7] = facet.x; attribute[o + 8] = facet.y; attribute[o + 9] = facet.z; + var n = skin.VertexNormal[c]; + attribute[o + 10] = n.x; attribute[o + 11] = n.y; attribute[o + 12] = n.z; + } + } + } } diff --git a/client/PuppetField.cs b/client/PuppetField.cs index 0c25f42..e917954 100644 --- a/client/PuppetField.cs +++ b/client/PuppetField.cs @@ -73,9 +73,6 @@ public sealed class PuppetShape /// public required int[] Across { get; init; } - /// How far a skinned vertex can lie from its bone's origin. - public required float Reach { get; init; } - /// The mesher's own account of its untangle: how many vertices it pulled back toward their net position, and the worst distance (m) of one of them from the isosurface. public required int Pulled { get; init; } public required float OffSurface { get; init; } @@ -160,12 +157,10 @@ public static class PuppetField { 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; @@ -208,8 +203,6 @@ public static class PuppetField } var across = Across(corners); - 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]; @@ -218,7 +211,7 @@ public static class PuppetField { Ids = ids, SpreadBind = t, Joints = js, Vertices = vertices.ToArray(), BoneA = ba.ToArray(), BoneB = bb.ToArray(), WeightA = wa.ToArray(), Corners = corners, Across = across, - Reach = 2 * reach + 2 * maxBall + smin, Pulled = pulled, OffSurface = offSurface, + Pulled = pulled, OffSurface = offSurface, }; } diff --git a/client/PuppetModel.cs b/client/PuppetModel.cs index 928f0d7..457bd9d 100644 --- a/client/PuppetModel.cs +++ b/client/PuppetModel.cs @@ -16,7 +16,7 @@ public readonly record struct PuppetJointLane(Box3DSoaJointKind Kind, ulong A, u /// public sealed class PuppetModel { - /// The skin's bone count: the shader's array size. + /// The most shape bodies the puppet draws; past it nothing is drawn. public const int MaxBones = 32; private readonly float _smin, _ballScale, _boxRound; diff --git a/client/PuppetSkin.cs b/client/PuppetSkin.cs new file mode 100644 index 0000000..e31c911 --- /dev/null +++ b/client/PuppetSkin.cs @@ -0,0 +1,123 @@ +using System; +using CultMath; + +namespace BadDay.Client; + +/// +/// The puppet's drawn surface, engine-free, owned for every frame: skins the welded vertices of a +/// by the bodies' transforms and derives from the skinned corners the facet normals, the creases (half the turn between neighbouring +/// facets, once per edge and the same on both sides), the area-weighted vertex normals and the altitudes that give the bevel its distances. +/// A crease is a property of the deformed surface, so none of it is kept from the bind. Every array is allocated once, here, and refilled. +/// +public sealed class PuppetSkin +{ + private readonly PuppetShape _shape; + private readonly float[] _bones; + + public PuppetSkin(PuppetShape shape) + { + _shape = shape; + _bones = new float[12 * shape.Ids.Length]; + int slots = shape.Corners.Length, triangles = slots / 3; + Skinned = new float3[shape.Vertices.Length]; + VertexNormal = new float3[shape.Vertices.Length]; + Facet = new float3[triangles]; + Crease = new float[slots]; + Altitude = new float[slots]; + SmallestAltitude = new float[triangles]; + } + + /// Every vertex skinned, in the space the bodies' transforms take the spread bind to. + public float3[] Skinned { get; } + + /// Per triangle: the unit normal seen from outside. + public float3[] Facet { get; } + + /// + /// Per corner slot (3t+k is edge k of triangle t, the edge opposite corner k): half the turn from this facet's normal to the + /// neighbour's across that edge, in radians, positive where the edge is convex. Both sides of an edge carry the same value. An edge + /// without exactly one neighbour has 0, and so has a fold (the two sides disagree on which way it turns). + /// + public float[] Crease { get; } + + /// Per vertex: the unit sum of its triangles' normals weighted by their areas. + public float3[] VertexNormal { get; } + + /// Per corner slot: the distance (m) from corner k to the line of edge k, 2 * area / |edge k|. + public float[] Altitude { get; } + + /// Per triangle: the smallest of its three altitudes. + public float[] SmallestAltitude { get; } + + /// The corners of the box around the skinned vertices. + public float3 Lo { get; private set; } + public float3 Hi { get; private set; } + + /// take each body from the spread bind to where it is now, one per body of the shape. + public void Update(ReadOnlySpan bones) + { + var s = _shape; + for (int i = 0; i < bones.Length; i++) + { + var r = bones[i].R; var t = bones[i].T; int o = 12 * i; + _bones[o] = r._m00; _bones[o + 1] = r._m01; _bones[o + 2] = r._m02; + _bones[o + 3] = r._m10; _bones[o + 4] = r._m11; _bones[o + 5] = r._m12; + _bones[o + 6] = r._m20; _bones[o + 7] = r._m21; _bones[o + 8] = r._m22; + _bones[o + 9] = t.x; _bones[o + 10] = t.y; _bones[o + 11] = t.z; + } + + float3 lo = new(float.MaxValue, float.MaxValue, float.MaxValue), hi = new(float.MinValue, float.MinValue, float.MinValue); + for (int v = 0; v < Skinned.Length; v++) + { + var p = s.Vertices[v]; float w = s.WeightA[v]; + int a = 12 * s.BoneA[v], b = 12 * s.BoneB[v]; + var q = new float3( + w * (_bones[a] * p.x + _bones[a + 1] * p.y + _bones[a + 2] * p.z + _bones[a + 9]) + (1 - w) * (_bones[b] * p.x + _bones[b + 1] * p.y + _bones[b + 2] * p.z + _bones[b + 9]), + w * (_bones[a + 3] * p.x + _bones[a + 4] * p.y + _bones[a + 5] * p.z + _bones[a + 10]) + (1 - w) * (_bones[b + 3] * p.x + _bones[b + 4] * p.y + _bones[b + 5] * p.z + _bones[b + 10]), + w * (_bones[a + 6] * p.x + _bones[a + 7] * p.y + _bones[a + 8] * p.z + _bones[a + 11]) + (1 - w) * (_bones[b + 6] * p.x + _bones[b + 7] * p.y + _bones[b + 8] * p.z + _bones[b + 11])); + Skinned[v] = q; VertexNormal[v] = new float3(0, 0, 0); + lo = math.min(lo, q); hi = math.max(hi, q); + } + Lo = lo; Hi = hi; + + var corners = s.Corners; + for (int t = 0; t < Facet.Length; t++) + { + int c0 = corners[3 * t], c1 = corners[3 * t + 1], c2 = corners[3 * t + 2]; + var a = Skinned[c0]; var b = Skinned[c1]; var c = Skinned[c2]; + // The winding is clockwise from outside, so the counter-clockwise cross points in and its negation is the outward, area-weighted normal. + var outward = -math.cross(b - a, c - a); + float twiceArea = math.length(outward); + Facet[t] = twiceArea > 1e-24f ? outward / twiceArea : new float3(0, 1, 0); + VertexNormal[c0] += outward; VertexNormal[c1] += outward; VertexNormal[c2] += outward; + float h0 = Altitude3(twiceArea, b, c), h1 = Altitude3(twiceArea, c, a), h2 = Altitude3(twiceArea, a, b); + Altitude[3 * t] = h0; Altitude[3 * t + 1] = h1; Altitude[3 * t + 2] = h2; + SmallestAltitude[t] = MathF.Min(h0, MathF.Min(h1, h2)); + } + for (int v = 0; v < VertexNormal.Length; v++) + { + float l = math.length(VertexNormal[v]); + VertexNormal[v] = l > 1e-24f ? VertexNormal[v] / l : new float3(0, 1, 0); + } + + for (int slot = 0; slot < Crease.Length; slot++) + { + int other = s.Across[slot]; + if (other < 0) { Crease[slot] = 0; continue; } + if (other < slot) continue; // its pair, lower in the array, set both + var fn = Facet[slot / 3]; var fm = Facet[other / 3]; + // Convex from a side: the neighbour's far corner (the corner opposite the shared edge) lies behind this facet's plane. + bool convexHere = math.dot(fn, Skinned[corners[other]] - Skinned[corners[3 * (slot / 3) + (slot % 3 + 1) % 3]]) < 0; + bool convexThere = math.dot(fm, Skinned[corners[slot]] - Skinned[corners[3 * (other / 3) + (other % 3 + 1) % 3]]) < 0; + if (convexHere != convexThere) { Crease[slot] = Crease[other] = 0; continue; } + float half = 0.5f * MathF.Atan2(math.length(math.cross(fn, fm)), math.dot(fn, fm)); + Crease[slot] = Crease[other] = convexHere ? half : -half; + } + } + + private static float Altitude3(float twiceArea, float3 p, float3 q) + { + float length = math.length(p - q); + return length > 1e-12f ? twiceArea / length : 0; + } +} diff --git a/client/puppet.gdshader b/client/puppet.gdshader index a5aef46..657d776 100644 --- a/client/puppet.gdshader +++ b/client/puppet.gdshader @@ -1,36 +1,39 @@ 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, turned by the skin blend. +// The puppet is one mesh that the CPU skins and shapes every frame (PuppetSkin), so the shader draws what it is given and moves +// nothing: VERTEX is already where the body is, and the colour, depth and shadow passes all draw those positions. // -// The soft bevel is the facet normal tilted toward each edge's bisector, within bevel_width of the edge. Two more attributes -// carry what it needs from the mesh, the same at the three corners of a triangle where noted: -// CUSTOM0: vertex k holds its own altitude h_k in component k and 0 in the others (so the interpolated component k is the -// distance, in bind metres, to edge k, the edge opposite vertex k); w is the triangle's smallest altitude. -// CUSTOM2: the triangle's three creases, crease[k] for edge k: half the turn from this facet's normal to the neighbour's, -// positive where the edge is convex (PuppetShape.Crease). -// The in-plane direction to each edge comes from screen derivatives of the distances, so the shader never evaluates the SDF. -// At an edge the tilt is exactly the bisector from both sides, so the normal is continuous across it. -const int MAX_BONES = 32; -uniform mat4 bones[MAX_BONES]; +// The soft bevel is the facet normal tilted toward each edge's bisector, within a width of the edge, and blended to the smooth +// vertex normal where edges meet. Each corner of a triangle carries: +// CUSTOM0: corner k holds its own altitude h_k in component k and 0 in the others (so the interpolated component k is the +// distance, in metres, to edge k, the edge opposite corner k); w is the triangle's smallest altitude. +// CUSTOM1: the triangle's three creases, crease[k] for edge k: half the turn from this facet to the neighbour's across that edge, +// positive where the edge is convex, the same on both sides of the edge. +// CUSTOM2: the facet normal (NORMAL in vertex()). +// CUSTOM3: this corner's vertex normal, the area-weighted mean of the facets that meet there; interpolated, it is the same on both +// sides of an edge. +// All of it is in model space and derived from the pose being drawn, never from the bind. The in-plane direction to each edge comes from +// screen derivatives of the distances, so the shader never evaluates the SDF. At an edge the tilt is exactly the bisector from both +// sides, so the normal is continuous across it. +// +// The width is on the screen: bevel_screen is a fraction of the viewport's height and the distance across one pixel (metres per pixel, +// from the derivatives of the distance to the edge) turns it into metres; bevel_min floors it, and half the triangle's smallest altitude +// caps it so the bands of one triangle never meet. A world width is bevel_screen 0 and bevel_min the width. uniform vec3 albedo : source_color = vec3(0.9, 0.9, 0.88); -uniform float bevel_width = 0.0; +uniform float bevel_screen = 0.0; +uniform float bevel_min = 0.0; uniform bool show_normals = false; // RenderCheck's view of the shading normal: the normal in view space as emission, rgb = n * 0.5 + 0.5. varying vec4 edge; varying vec3 crease; +varying vec3 vertex_normal; 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); + NORMAL = CUSTOM2.xyz; edge = CUSTOM0; - crease = CUSTOM2.xyz; + crease = CUSTOM1.xyz; + vertex_normal = (MODELVIEW_MATRIX * vec4(CUSTOM3.xyz, 0.0)).xyz; } void fragment() { @@ -38,24 +41,40 @@ void fragment() { // Derivatives are undefined in non-uniform control flow: take them all here, branch afterwards. vec3 dx = dFdx(VERTEX); vec3 dy = dFdy(VERTEX); + vec3 fx = dFdx(edge.xyz); + vec3 fy = dFdy(edge.xyz); vec3 r1 = cross(dy, n); vec3 r2 = cross(n, dx); float det = dot(dx, r1); - vec3 fx = dFdx(edge.xyz); - vec3 fy = dFdy(edge.xyz); - float width = min(bevel_width, 0.5 * edge.w); - if (width > 0.0 && abs(det) > 1e-20) { + if (abs(det) > 1e-20) { + vec3 g[3]; + float width[3]; vec3 tilt = vec3(0.0); for (int k = 0; k < 3; k++) { // The in-plane gradient of the distance to edge k points into the facet; the normal tips the other way. vec3 grad = (fx[k] * r1 + fy[k] * r2) / det; float len = length(grad); - if (crease[k] != 0.0 && len > 1e-12) { - float s = 1.0 - smoothstep(0.0, width, edge[k]); - tilt += s * tan(clamp(crease[k], -1.4, 1.4)) * grad / len; + g[k] = len > 1e-12 ? grad / len : vec3(0.0); + float metres_per_pixel = length(vec2(fx[k], fy[k])); + width[k] = min(max(bevel_screen * VIEWPORT_SIZE.y * metres_per_pixel, bevel_min), 0.5 * edge.w); + if (crease[k] != 0.0 && width[k] > 0.0) { + float s = 1.0 - smoothstep(0.0, width[k], edge[k]); + tilt += s * tan(clamp(crease[k], -1.4, 1.4)) * g[k]; } } - n = normalize(n - tilt); + // Near a corner two edges' bands overlap and their tilts add up to a notch; there the normal goes to the smooth vertex normal instead. + // Corner k is where edges i and j meet, and its exact distance from the pixel follows from the two edge distances and the angle between them. + float corner = 0.0; + for (int k = 0; k < 3; k++) { + int i = (k + 1) % 3; + int j = (k + 2) % 3; + float c = dot(g[i], g[j]); + float r_squared = (edge[i] * edge[i] + edge[j] * edge[j] - 2.0 * edge[i] * edge[j] * c) / max(1.0 - c * c, 1e-6); + float reach = 1.5 * max(width[i], width[j]); + if (reach > 0.0) corner = max(corner, 1.0 - smoothstep(0.0, reach, sqrt(max(r_squared, 0.0)))); + } + n = normalize(n - (1.0 - corner) * tilt); + n = normalize(mix(n, normalize(vertex_normal), corner)); } NORMAL = n; ALBEDO = show_normals ? vec3(0.0) : albedo; diff --git a/client/tests/PuppetChecks.cs b/client/tests/PuppetChecks.cs index ae2639c..550277d 100644 --- a/client/tests/PuppetChecks.cs +++ b/client/tests/PuppetChecks.cs @@ -124,6 +124,7 @@ public static class PuppetChecks Mesher(puppet, Check); AcrossIsPositionWeld(puppet, Check); + SkinnedSurface(puppet, Check); } /// The corner slot's vertex, in the spread bind. @@ -229,6 +230,78 @@ public static class PuppetChecks check(wrong == 0, $"{wrong} corner slots' Across differs from the edge match a weld by position makes"); } + /// + /// against the geometry it should describe, measured from its own skinned corners and the bones alone, at + /// bends of 0, 45 and 90 degrees (seeds 0 to 19): every vertex where the bones put it; per edge the same crease on both sides, half + /// the angle between the skinned facets with the sign of the edge's convexity there, or 0 on a skinned fold and on an edge with + /// no neighbour (a bind-time crease fails this at the bends: Soul counted 1368 sign flips at 90); the altitudes as 2 * area over the + /// edge's length; the facet and area-weighted vertex normals. + /// + private static void SkinnedSurface(PuppetShape shape, Action check) + { + var skin = new PuppetSkin(shape); + int moved = 0, shared = 0, creased = 0, folds = 0, badFold = 0, asymmetric = 0, notHalf = 0, badSign = 0, badLoose = 0, badAltitude = 0, badFacet = 0, badVertexNormal = 0; + foreach (float degrees in new[] { 0f, 45f, 90f }) + for (int seed = 0; seed < 20; seed++) + { + var bones = Bend(shape, seed, degrees * MathF.PI / 180f); + skin.Update(bones); + var at = new float3[shape.Vertices.Length]; + for (int v = 0; v < at.Length; v++) + { + float w = shape.WeightA[v]; + at[v] = bones[shape.BoneA[v]].Apply(shape.Vertices[v]) * w + bones[shape.BoneB[v]].Apply(shape.Vertices[v]) * (1 - w); + if (math.length(skin.Skinned[v] - at[v]) > 1e-5f) moved++; + } + float3 P(int slot) => at[shape.Corners[slot]]; + float3 Outward(int t) => -math.cross(P(3 * t + 1) - P(3 * t), P(3 * t + 2) - P(3 * t)); + var normal = new float3[shape.Triangles]; + var vertexSum = new float3[at.Length]; + for (int t = 0; t < normal.Length; t++) + { + var outward = Outward(t); + normal[t] = outward / math.length(outward); + if (math.length(skin.Facet[t] - normal[t]) > 1e-4f) badFacet++; + for (int k = 0; k < 3; k++) vertexSum[shape.Corners[3 * t + k]] += outward; + for (int k = 0; k < 3; k++) + { + float h = math.length(outward) / math.length(P(3 * t + (k + 1) % 3) - P(3 * t + (k + 2) % 3)); + if (MathF.Abs(skin.Altitude[3 * t + k] - h) > 1e-6f) badAltitude++; + } + float smallest = MathF.Min(skin.Altitude[3 * t], MathF.Min(skin.Altitude[3 * t + 1], skin.Altitude[3 * t + 2])); + if (skin.SmallestAltitude[t] != smallest) badAltitude++; + } + for (int v = 0; v < at.Length; v++) if (math.length(skin.VertexNormal[v] - vertexSum[v] / math.length(vertexSum[v])) > 1e-4f) badVertexNormal++; + for (int s = 0; s < shape.Across.Length; s++) + { + int o = shape.Across[s]; + if (o < 0) { if (skin.Crease[s] != 0) badLoose++; continue; } + if (o < s) continue; + shared++; + if (MathF.Abs(skin.Crease[s] - skin.Crease[o]) > 1e-5f) asymmetric++; + float3 na = normal[s / 3], nb = normal[o / 3]; + float angle = MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)); + if (angle < 1e-2f) continue; // a flat edge has no convexity to speak of, and its crease is below the float noise of the sign + bool convexA = math.dot(na, P(o) - P(3 * (s / 3) + (s % 3 + 1) % 3)) < 0; + bool convexB = math.dot(nb, P(s) - P(3 * (o / 3) + (o % 3 + 1) % 3)) < 0; + if (convexA != convexB) { folds++; if (skin.Crease[s] != 0 || skin.Crease[o] != 0) badFold++; continue; } + creased++; + if (MathF.Abs(MathF.Abs(skin.Crease[s]) - 0.5f * angle) > 1e-4f) notHalf++; + if ((skin.Crease[s] > 0) != convexA || (skin.Crease[o] > 0) != convexB) badSign++; + } + } + check(shared > 60 * 1000 && creased > 60 * 100, $"the skin check is vacuous: {shared} shared edges, {creased} turning more than a hundredth of a radian, over 60 poses"); + check(moved == 0, $"{moved} skinned vertices are not where the bones put them"); + check(badFacet == 0, $"{badFacet} facet normals differ from the skinned corners'"); + check(badVertexNormal == 0, $"{badVertexNormal} vertex normals differ from the area-weighted sum of their skinned facets"); + check(badAltitude == 0, $"{badAltitude} altitudes differ from 2 * area / edge length of the skinned triangle"); + check(asymmetric == 0, $"{asymmetric} of {shared} shared edges carry different creases on their two sides"); + check(notHalf == 0, $"{notHalf} of {creased} turning edges have a crease that is not half the angle between the skinned facets"); + check(badSign == 0, $"{badSign} of {creased} turning edges have a crease whose sign does not match the skinned convexity"); + check(badFold == 0, $"{badFold} of {folds} skinned folds carry a crease"); + check(badLoose == 0, $"{badLoose} edges without exactly one neighbour carry a crease"); + } + /// The mesh's connected pieces. public static int Pieces(PuppetShape shape) {