BDS client: the SDF puppet, porcelain studio and their checks are deleted; every body draws as its own primitive
Deletes Puppet, PuppetField, PuppetModel, PuppetSkin, puppet.gdshader, studio.gdshaderinc, PuppetChecks, the 978-line RenderCheck, Look's porcelain and studio, Smoke's puppet checks, the GameCult.Geometry reference (and with it BDS's own CultLib pin props and revision check, which only guarded that reference; Ymir keeps its own), and msaa_3d. BodyRenderer draws every body (static and dynamic) as its Ymir primitive under a carrier per stable id; the carrier logic is Puppet.Sync's. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
b6c77737a9
commit
350e137066
17 changed files with 103 additions and 2672 deletions
|
|
@ -3,12 +3,5 @@
|
|||
<!-- Sibling Lodur checkout (main, from the nervous-layers merge on): the nervous model BDS consumes. Set LODUR_ROOT to override. -->
|
||||
<LodurRoot Condition="'$(LodurRoot)' == '' and '$(LODUR_ROOT)' != ''">$(LODUR_ROOT)</LodurRoot>
|
||||
<LodurRoot Condition="'$(LodurRoot)' == ''">$(MSBuildThisFileDirectory)..\Lodur</LodurRoot>
|
||||
<!-- Sibling CultLib checkout at the one revision Ymir admits (its Directory.Build.props owns the pin): GameCult.Geometry for the client's puppet mesh. Set CULTLIB_ROOT to override. -->
|
||||
<CultLibRoot Condition="'$(CultLibRoot)' == '' and '$(CULTLIB_ROOT)' != ''">$(CULTLIB_ROOT)</CultLibRoot>
|
||||
<CultLibRoot Condition="'$(CultLibRoot)' == ''">$(MSBuildThisFileDirectory)..\CultLib</CultLibRoot>
|
||||
<!-- CultLib 2.0.0: tag cultlib-unity-v2.0.0. Keep equal to Ymir's CultLibRevision. -->
|
||||
<CultLibRevision>42dce3611a81adc5c5fac54cadbaa5637d6022d3</CultLibRevision>
|
||||
<GitExecutable Condition="'$(GitExecutable)' == '' and Exists('C:\Program Files\Git\cmd\git.exe')">C:\Program Files\Git\cmd\git.exe</GitExecutable>
|
||||
<GitExecutable Condition="'$(GitExecutable)' == ''">git</GitExecutable>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,30 +0,0 @@
|
|||
<Project>
|
||||
<!-- The same check as Ymir's Directory.Build.targets, for the client's CultLib reference. Builds consume CultLib at one admitted revision. Point CultLibRoot (or CULTLIB_ROOT) at a clean
|
||||
worktree of that revision: git worktree add <path> cultlib-unity-v2.0.0 (detached) (in CultLib). -->
|
||||
<Target Name="VerifyCultLibRevision"
|
||||
BeforeTargets="ResolveProjectReferences"
|
||||
Condition="'$(SkipCultLibRevisionCheck)' != 'true'">
|
||||
<ItemGroup>
|
||||
<_CultLibReference Include="@(ProjectReference)"
|
||||
Condition="$([System.String]::Copy('%(Filename)').StartsWith('GameCult.')) or '%(Filename)' == 'CultMath'" />
|
||||
</ItemGroup>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and !Exists('$(CultLibRoot)\src\GameCult.Caching\GameCult.Caching.csproj')"
|
||||
Text="CultLibRoot '$(CultLibRoot)' is not a CultLib checkout." />
|
||||
<Exec Condition="'@(_CultLibReference)' != ''"
|
||||
Command=""$(GitExecutable)" -C "$(CultLibRoot)" rev-parse HEAD"
|
||||
ConsoleToMSBuild="true"
|
||||
StandardOutputImportance="Low">
|
||||
<Output TaskParameter="ConsoleOutput" PropertyName="ActualCultLibRevision" />
|
||||
</Exec>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and '$([System.String]::Copy($(ActualCultLibRevision)).Trim())' != '$(CultLibRevision)'"
|
||||
Text="CultLib must be revision $(CultLibRevision) (cultlib-unity-v2.0.0); found $([System.String]::Copy($(ActualCultLibRevision)).Trim()). Set CultLibRoot to a clean worktree of that tag." />
|
||||
<Exec Condition="'@(_CultLibReference)' != ''"
|
||||
Command=""$(GitExecutable)" -C "$(CultLibRoot)" status --porcelain --untracked-files=normal"
|
||||
ConsoleToMSBuild="true"
|
||||
StandardOutputImportance="Low">
|
||||
<Output TaskParameter="ConsoleOutput" PropertyName="CultLibStatus" />
|
||||
</Exec>
|
||||
<Error Condition="'@(_CultLibReference)' != '' and '$([System.String]::Copy($(CultLibStatus)).Trim())' != ''"
|
||||
Text="CultLibRoot '$(CultLibRoot)' must be clean before this repo consumes it." />
|
||||
</Target>
|
||||
</Project>
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
<Project Sdk="Godot.NET.Sdk/4.7.2">
|
||||
<!-- The Godot client: presentation and input over BodyPainBoxSession. Building it builds CultLib (Geometry, for the puppet mesh), Lodur, Ymir (cmake and a C compiler) and BDS into .godot/mono/temp/bin/Debug. -->
|
||||
<!-- The Godot client: presentation and input over BodyPainBoxSession. Building it builds Lodur, Ymir (cmake and a C compiler) and BDS into .godot/mono/temp/bin/Debug. -->
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<EnableDynamicLoading>true</EnableDynamicLoading>
|
||||
|
|
@ -9,6 +9,5 @@
|
|||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\src\BadDay.Ymir\BadDay.Ymir.csproj" />
|
||||
<ProjectReference Include="$(CultLibRoot)\src\GameCult.Geometry\GameCult.Geometry.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
|
@ -5,61 +6,104 @@ using Ymir.Box3D;
|
|||
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"/>, which draws them as one skinned SDF mesh.
|
||||
/// 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
|
||||
/// of the lane's size). The anchor has no shape and draws nothing.
|
||||
/// </summary>
|
||||
public partial class BodyRenderer : Node3D
|
||||
{
|
||||
private readonly Puppet _puppet = new() { Name = "Puppet" };
|
||||
private readonly Dictionary<ulong, MeshInstance3D> _scenery = new();
|
||||
private readonly StandardMaterial3D _material = Look.Matte(Look.Scenery);
|
||||
private readonly record struct Carrier(Node3D Node, MeshInstance3D? Mesh, bool Dynamic);
|
||||
|
||||
private readonly Dictionary<ulong, Carrier> _carriers = new();
|
||||
private readonly HashSet<ulong> _seen = new();
|
||||
private readonly StandardMaterial3D _figure = Look.Matte(Look.Figure);
|
||||
private readonly StandardMaterial3D _scenery = Look.Matte(Look.Scenery);
|
||||
|
||||
/// <summary>Bodies drawn, static and dynamic.</summary>
|
||||
public int BodyCount => _puppet.BodyCount + _scenery.Count;
|
||||
public int BodyCount => _carriers.Count;
|
||||
|
||||
/// <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;
|
||||
/// <summary>How many MeshInstance3D this renderer has made: a Reset with the same bodies makes none.</summary>
|
||||
public int MeshBuilds { get; private set; }
|
||||
|
||||
/// <summary>The world centre of the puppet's drawn bounds, or null before the first draw: where the camera orbits.</summary>
|
||||
public Vector3? PuppetCentre => _puppet.Centre;
|
||||
public BaseMaterial3D SceneryMaterial => _scenery;
|
||||
|
||||
/// <summary>How many times the puppet's Godot mesh has been built.</summary>
|
||||
public int PuppetMeshBuilds => _puppet.MeshBuilds;
|
||||
|
||||
public BaseMaterial3D SceneryMaterial => _material;
|
||||
|
||||
/// <summary>Where body <paramref name="stableId"/> is drawn now, or null if it is not drawn.</summary>
|
||||
public Transform3D? PoseOf(ulong stableId) => _puppet.PoseOf(stableId) ?? (_scenery.TryGetValue(stableId, out var n) ? n.Transform : null);
|
||||
|
||||
/// <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) => _puppet.InterpolatedPoseOf(stableId) ?? PoseOf(stableId);
|
||||
|
||||
public override void _Ready() => AddChild(_puppet);
|
||||
|
||||
public void Sync(in Box3DSoaView view, bool teleport = false)
|
||||
/// <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>
|
||||
public Vector3? PuppetCentre
|
||||
{
|
||||
_puppet.Sync(view, teleport);
|
||||
var ids = view.StableId;
|
||||
var kind = view.Kind;
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
get
|
||||
{
|
||||
if ((Box3DSoaKind)kind[i] != Box3DSoaKind.StaticBox) continue;
|
||||
if (!_scenery.TryGetValue(ids[i], out var node))
|
||||
Aabb? union = null;
|
||||
foreach (var c in _carriers.Values)
|
||||
{
|
||||
node = new MeshInstance3D
|
||||
{
|
||||
Name = $"Static{ids[i]}",
|
||||
Mesh = new BoxMesh { Size = new Vector3(2f * view.Size0[i], 2f * view.Size1[i], 2f * view.Size2[i]) },
|
||||
MaterialOverride = _material,
|
||||
};
|
||||
AddChild(node);
|
||||
_scenery[ids[i]] = node;
|
||||
if (!c.Dynamic || c.Mesh is null) continue;
|
||||
var box = c.Node.GetGlobalTransformInterpolated() * c.Mesh.GetAabb();
|
||||
union = union is { } u ? u.Merge(box) : box;
|
||||
}
|
||||
node.Transform = new Transform3D(
|
||||
new Basis(new Quaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i])),
|
||||
new Vector3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]));
|
||||
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>
|
||||
public Transform3D? PoseOf(ulong stableId) => _carriers.TryGetValue(stableId, out var c) ? c.Node.Transform : null;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <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)
|
||||
{
|
||||
var ids = view.StableId;
|
||||
if (ids.Length != _carriers.Count || !AllPresent(ids))
|
||||
{
|
||||
_seen.Clear();
|
||||
for (int i = 0; i < ids.Length; i++) _seen.Add(ids[i]);
|
||||
foreach (var id in new List<ulong>(_carriers.Keys))
|
||||
{
|
||||
if (_seen.Contains(id)) continue;
|
||||
_carriers[id].Node.QueueFree();
|
||||
_carriers.Remove(id);
|
||||
}
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
if (_carriers.ContainsKey(ids[i])) continue;
|
||||
var node = new Node3D { Name = $"Body{ids[i]}" };
|
||||
var kind = (Box3DSoaKind)view.Kind[i];
|
||||
MeshInstance3D? mesh = null;
|
||||
if (PrimitiveOf(kind, view.Size0[i], view.Size1[i], view.Size2[i]) is { } primitive)
|
||||
{
|
||||
var dynamic = kind != Box3DSoaKind.StaticBox;
|
||||
mesh = new MeshInstance3D { Name = "Mesh", Mesh = primitive, MaterialOverride = dynamic ? _figure : _scenery };
|
||||
node.AddChild(mesh);
|
||||
MeshBuilds++;
|
||||
}
|
||||
AddChild(node);
|
||||
_carriers[ids[i]] = new Carrier(node, mesh, kind != Box3DSoaKind.StaticBox);
|
||||
teleport = true;
|
||||
}
|
||||
}
|
||||
|
||||
var px = view.PositionX; var py = view.PositionY; var pz = view.PositionZ;
|
||||
var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW;
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
var node = _carriers[ids[i]].Node;
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
private bool AllPresent(ReadOnlySpan<ulong> ids)
|
||||
{
|
||||
for (int i = 0; i < ids.Length; i++) if (!_carriers.ContainsKey(ids[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The body's own primitive, or null for a body with no shape. A capsule's lane is its radius and half-length along Y; a box's its half extents.</summary>
|
||||
private static Mesh? PrimitiveOf(Box3DSoaKind kind, float size0, float size1, float size2) => kind switch
|
||||
{
|
||||
Box3DSoaKind.Capsule => new CapsuleMesh { Radius = size0, Height = 2f * (size1 + size0), RadialSegments = 6, Rings = 1 },
|
||||
Box3DSoaKind.Box or Box3DSoaKind.StaticBox => new BoxMesh { Size = new Vector3(2f * size0, 2f * size1, 2f * size2) },
|
||||
Box3DSoaKind.Sphere => new SphereMesh { Radius = size0, Height = 2f * size0, RadialSegments = 6, Rings = 4 },
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
116
client/Look.cs
116
client/Look.cs
|
|
@ -2,12 +2,7 @@ using Godot;
|
|||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// The scene's stylised look: white glazed porcelain on dark grey, lit by a studio the camera carries. The bisque is lit by three
|
||||
/// directional lights (a shadowing key and two rims) and the glaze reflects the same studio analytically (studio.gdshaderinc), both from
|
||||
/// the constants here, so the lights and the reflections cannot drift. The clip bound RenderCheck sets is the bisque's; the glaze's
|
||||
/// highlights are meant to clip, within the bound it sets for them.
|
||||
/// </summary>
|
||||
/// <summary>The scene's colours and its colour environment: dark grey, a colour ambient, linear tone mapping, no sky and no glow.</summary>
|
||||
public static class Look
|
||||
{
|
||||
public static readonly Color Background = new(0.10f, 0.10f, 0.11f);
|
||||
|
|
@ -15,112 +10,25 @@ 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 chamber light at full glow. At 3 it washed the whole dummy out to white (56% of its pixels clipped at near full glow); at 0.1 under 1% clip. RenderCheck bounds the clipped share and the facet contrast.</summary>
|
||||
/// <summary>The chamber light at full glow. At 3 it washed the whole dummy out to white (56% of its pixels clipped at near full glow); at 0.1 under 1% clip.</summary>
|
||||
public const float GlowLightEnergy = 0.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;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="BevelMin"/> as the width is a world width; an answer changes these two
|
||||
/// constants and nothing else.
|
||||
/// </summary>
|
||||
public const float BevelScreen = 2f / 720f;
|
||||
|
||||
/// <summary>The narrowest bevel (m) however near the camera is: 3 mm, so a puppet filling the screen still has soft edges.</summary>
|
||||
public const float BevelMin = 0.003f;
|
||||
|
||||
/// <summary>The bisque: how rough the unglazed porcelain is, its dielectric specular, and the warm light that passes through it at grazing angles.</summary>
|
||||
public const float Roughness = 0.45f, Specular = 0.5f;
|
||||
|
||||
public static readonly Vector3 Backlight = 0.03f * new Vector3(1f, 0.8f, 0.65f);
|
||||
|
||||
/// <summary>How far the albedo pools darker and cooler in a concave crease, and warmer over a convex bevel (0 to 1).</summary>
|
||||
public const float GlazePool = 0.8f;
|
||||
|
||||
/// <summary>The glaze's strength: 0 is the bisque alone, 1 the glaze as the studio gives it.</summary>
|
||||
public const float GlazeStrength = 1f;
|
||||
|
||||
/// <summary>
|
||||
/// The studio's directions, the directions its lights come from, in the camera's space (+Y up, +Z toward the viewer): the key is a soft
|
||||
/// box up and left behind the viewer, the rims strips behind the figure on either side.
|
||||
/// </summary>
|
||||
public static readonly Vector3 KeyDirection = new Vector3(-0.45f, 0.55f, 0.70f).Normalized();
|
||||
public static readonly Vector3 RimDirectionA = new Vector3(0.85f, 0.25f, -0.45f).Normalized();
|
||||
public static readonly Vector3 RimDirectionB = new Vector3(-0.85f, 0.35f, -0.40f).Normalized();
|
||||
|
||||
/// <summary>What the glaze reflects: the radiance of the key soft box (its half width on the plane at unit distance) and of the rim strips, the dark room and the dim floor.</summary>
|
||||
public const float KeyRadiance = 20f, RimRadiance = 12f, KeySize = 0.45f, FloorRadiance = 0.03f;
|
||||
|
||||
public static readonly Vector2 RimSize = new(0.10f, 0.9f);
|
||||
public static readonly Color RimTint = new(0.85f, 0.92f, 1f);
|
||||
public static readonly Vector3 Room = new(0.02f, 0.02f, 0.022f);
|
||||
|
||||
/// <summary>The punctual lights' energies, tuned with the bisque so it stays under white where the key and a rim overlap; the second rim is dimmer.</summary>
|
||||
public const float KeyEnergy = 0.22f, RimEnergyA = 0.3f, RimEnergyB = 0.21f;
|
||||
|
||||
public const float AmbientEnergy = 0.06f;
|
||||
public static readonly Color AmbientColor = new(0.9f, 0.93f, 1f);
|
||||
|
||||
/// <summary>The scene's environment (a colour background, a colour ambient, linear, no glow) and the studio's lights, carried by <paramref name="camera"/>: a shadowing key and two rims, its children.</summary>
|
||||
public static WorldEnvironment Studio(Camera3D camera)
|
||||
/// <summary>The scene's environment: a colour background, a colour ambient, linear, no glow.</summary>
|
||||
public static WorldEnvironment World() => new()
|
||||
{
|
||||
// The studio turns with the camera, as a photographer's lights do (lodur:ruling:porcelain-studio-follows-camera): form and glints on every
|
||||
// side as the player orbits, at the cost of the key's floor shadow swinging with the camera.
|
||||
camera.AddChild(Light("StudioKey", KeyDirection, KeyEnergy, true, new Color(1f, 0.98f, 0.95f)));
|
||||
camera.AddChild(Light("StudioRimA", RimDirectionA, RimEnergyA, false, RimTint));
|
||||
camera.AddChild(Light("StudioRimB", RimDirectionB, RimEnergyB, false, RimTint));
|
||||
return new WorldEnvironment
|
||||
Environment = new Godot.Environment
|
||||
{
|
||||
Environment = new Godot.Environment
|
||||
{
|
||||
BackgroundMode = Godot.Environment.BGMode.Color,
|
||||
BackgroundColor = Background,
|
||||
AmbientLightSource = Godot.Environment.AmbientSource.Color,
|
||||
AmbientLightColor = AmbientColor,
|
||||
AmbientLightEnergy = AmbientEnergy,
|
||||
TonemapMode = Godot.Environment.ToneMapper.Linear,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private static DirectionalLight3D Light(string name, Vector3 from, float energy, bool shadow, Color color) => new()
|
||||
{
|
||||
Name = name,
|
||||
Transform = Transform3D.Identity.LookingAt(-from, Vector3.Up), // shines along -from: the light comes from `from`
|
||||
LightEnergy = energy,
|
||||
LightColor = color,
|
||||
ShadowEnabled = shadow,
|
||||
BackgroundMode = Godot.Environment.BGMode.Color,
|
||||
BackgroundColor = Background,
|
||||
AmbientLightSource = Godot.Environment.AmbientSource.Color,
|
||||
AmbientLightColor = AmbientColor,
|
||||
AmbientLightEnergy = AmbientEnergy,
|
||||
TonemapMode = Godot.Environment.ToneMapper.Linear,
|
||||
},
|
||||
};
|
||||
|
||||
/// <summary>Sets the puppet shader's bisque and studio uniforms.</summary>
|
||||
public static void Glaze(ShaderMaterial material)
|
||||
{
|
||||
material.SetShaderParameter("roughness", Roughness);
|
||||
material.SetShaderParameter("specular", Specular);
|
||||
material.SetShaderParameter("backlight", Backlight);
|
||||
material.SetShaderParameter("glaze", GlazeStrength);
|
||||
material.SetShaderParameter("glaze_pool", GlazePool);
|
||||
material.SetShaderParameter("studio_room", Room);
|
||||
material.SetShaderParameter("studio_key_dir", KeyDirection);
|
||||
material.SetShaderParameter("studio_key_size", KeySize);
|
||||
material.SetShaderParameter("studio_key_radiance", KeyRadiance);
|
||||
material.SetShaderParameter("studio_rim_a", RimDirectionA);
|
||||
material.SetShaderParameter("studio_rim_b", RimDirectionB);
|
||||
material.SetShaderParameter("studio_rim_size", RimSize);
|
||||
material.SetShaderParameter("studio_rim_tint", new Vector3(RimTint.R, RimTint.G, RimTint.B));
|
||||
material.SetShaderParameter("studio_rim_radiance", RimRadiance);
|
||||
material.SetShaderParameter("studio_floor", FloorRadiance);
|
||||
}
|
||||
|
||||
public static StandardMaterial3D Matte(Color color) => new() { AlbedoColor = color, Roughness = 1f, MetallicSpecular = 0f };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,7 +56,7 @@ public partial class Main : Node3D
|
|||
AddChild(_chamber);
|
||||
_camera = new OrbitCamera { Name = "Camera", Pivot = () => _bodies.PuppetCentre };
|
||||
AddChild(_camera);
|
||||
AddChild(Look.Studio(_camera));
|
||||
AddChild(Look.World());
|
||||
_hud = new Hud(this) { Name = "Hud" };
|
||||
AddChild(_hud);
|
||||
Reset(Seed);
|
||||
|
|
|
|||
214
client/Puppet.cs
214
client/Puppet.cs
|
|
@ -1,214 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using CultMath;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// The puppet: its drawn surface is one SDF isosurface mesh (<see cref="PuppetField"/>) 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 <see cref="PuppetSkin"/> 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.
|
||||
/// </summary>
|
||||
public partial class Puppet : Node3D
|
||||
{
|
||||
/// <summary>Bytes per triangle corner in the vertex stream (VERTEX, float3) and in the attribute stream (CUSTOM0 float4, CUSTOM1..3 float3 each).</summary>
|
||||
private const int VertexBytes = 12, AttributeBytes = 52;
|
||||
|
||||
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 PuppetModel _model = new(Look.SminRadius, Look.JointBallScale, Look.BoxRound);
|
||||
private ArrayMesh? _mesh;
|
||||
private Node3D[] _boneNodes = Array.Empty<Node3D>();
|
||||
private Transform3D[] _inverseBind = Array.Empty<Transform3D>();
|
||||
private Rigid[] _bones = Array.Empty<Rigid>();
|
||||
private PuppetSkin? _surface;
|
||||
private byte[] _vertexStream = Array.Empty<byte>(), _attributeStream = Array.Empty<byte>();
|
||||
|
||||
public Puppet()
|
||||
{
|
||||
_material.SetShaderParameter("albedo", Look.Figure);
|
||||
_material.SetShaderParameter("bevel_screen", Look.BevelScreen);
|
||||
_material.SetShaderParameter("bevel_min", Look.BevelMin);
|
||||
Look.Glaze(_material);
|
||||
_skin.MaterialOverride = _material;
|
||||
}
|
||||
|
||||
public int BodyCount => _nodes.Count;
|
||||
|
||||
/// <summary>How many times the Godot mesh has been made from a shape: the one build counter, which the smoke asserts.</summary>
|
||||
public int MeshBuilds { get; private set; }
|
||||
|
||||
/// <summary>The colour the puppet is drawn in: the shader's albedo.</summary>
|
||||
public Color Color => _material.GetShaderParameter("albedo").AsColor();
|
||||
|
||||
/// <summary>The glaze on (Look's strength) or off, the bisque alone: RenderCheck's bounds on the lit facets are the bisque's.</summary>
|
||||
public bool Glazed { set => _material.SetShaderParameter("glaze", value ? Look.GlazeStrength : 0f); }
|
||||
|
||||
/// <summary>Draws the shading normal (in view space, as n * 0.5 + 0.5) instead of the lit puppet: RenderCheck's view of what the bevel did.</summary>
|
||||
public bool ShowNormals { set => _material.SetShaderParameter("show_normals", value); }
|
||||
|
||||
/// <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 => _model.Shape;
|
||||
|
||||
/// <summary>The world centre of the puppet's drawn bounds (the mesh's <c>CustomAabb</c>, in the skin's space), or null before the first draw.</summary>
|
||||
public Vector3? Centre => _mesh is { CustomAabb: { } box } && box.HasSurface() ? _skin.GlobalTransform * (box.Position + box.Size / 2) : null;
|
||||
|
||||
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;
|
||||
|
||||
/// <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>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>The <see cref="Rigid"/> of a Godot transform (rotation only; no scale).</summary>
|
||||
public static Rigid ToRigid(Transform3D t) => new(
|
||||
new CultMath.float3x3(new CultMath.float3(t.Basis.Row0.X, t.Basis.Row0.Y, t.Basis.Row0.Z), new CultMath.float3(t.Basis.Row1.X, t.Basis.Row1.Y, t.Basis.Row1.Z), new CultMath.float3(t.Basis.Row2.X, t.Basis.Row2.Y, t.Basis.Row2.Z)),
|
||||
new CultMath.float3(t.Origin.X, t.Origin.Y, t.Origin.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;
|
||||
var kind = view.Kind;
|
||||
if (CountDynamic(kind) != _nodes.Count || !AllPresent(ids, kind))
|
||||
{
|
||||
_seen.Clear();
|
||||
for (int i = 0; i < ids.Length; i++) if (IsPuppet(kind[i])) _seen.Add(ids[i]);
|
||||
foreach (var id in new List<ulong>(_nodes.Keys))
|
||||
{
|
||||
if (_seen.Contains(id)) continue;
|
||||
_nodes[id].QueueFree();
|
||||
_nodes.Remove(id);
|
||||
}
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
if (!IsPuppet(kind[i]) || _nodes.ContainsKey(ids[i])) continue;
|
||||
var node = new Node3D { Name = $"Body{ids[i]}" };
|
||||
AddChild(node);
|
||||
_nodes[ids[i]] = node;
|
||||
teleport = true;
|
||||
}
|
||||
}
|
||||
|
||||
var px = view.PositionX; var py = view.PositionY; var pz = view.PositionZ;
|
||||
var rx = view.RotationX; var ry = view.RotationY; var rz = view.RotationZ; var rw = view.RotationW;
|
||||
for (int i = 0; i < ids.Length; i++)
|
||||
{
|
||||
if (!IsPuppet(kind[i])) continue;
|
||||
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();
|
||||
}
|
||||
|
||||
if (_model.Update(view)) Rebuild();
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
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();
|
||||
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;
|
||||
|
||||
private static int CountDynamic(ReadOnlySpan<uint> kind)
|
||||
{
|
||||
int n = 0;
|
||||
foreach (var k in kind) if (IsPuppet(k)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
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>Takes up the model's new shape: the carriers that are its bones, their inverse bind, the skin's buffers and the mesh layout.</summary>
|
||||
private void Rebuild()
|
||||
{
|
||||
var shape = _model.Shape!;
|
||||
_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()); }
|
||||
_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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A surface of <paramref name="corners"/> 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.
|
||||
/// </summary>
|
||||
private static ArrayMesh LayoutOf(int corners)
|
||||
{
|
||||
var arrays = new Godot.Collections.Array();
|
||||
arrays.Resize((int)Mesh.ArrayType.Max);
|
||||
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.FormatCustom3Shift));
|
||||
var mesh = new ArrayMesh();
|
||||
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays, null, null, format);
|
||||
return mesh;
|
||||
}
|
||||
|
||||
/// <summary>Writes the skin's surface, one triangle corner after another, into the two streams (no allocation).</summary>
|
||||
private static void Pack(PuppetSkin skin, int[] corners, byte[] vertexStream, byte[] attributeStream)
|
||||
{
|
||||
var vertex = MemoryMarshal.Cast<byte, float>(vertexStream);
|
||||
var attribute = MemoryMarshal.Cast<byte, float>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,433 +0,0 @@
|
|||
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 welded:
|
||||
/// each vertex once, in the spread bind, with its two bones and the first one's weight, and the triangles as indices into the vertices.
|
||||
/// </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; }
|
||||
|
||||
/// <summary>The vertices in the spread bind.</summary>
|
||||
public required float3[] Vertices { get; init; }
|
||||
public required int[] BoneA { get; init; }
|
||||
public required int[] BoneB { get; init; }
|
||||
public required float[] WeightA { get; init; }
|
||||
|
||||
/// <summary>The triangles, three vertex indices each, wound clockwise seen from outside (Godot's front face).</summary>
|
||||
public required int[] Corners { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// One entry per corner slot: for slot 3t+k, which is edge k of triangle t (the edge opposite corner k), the slot of the neighbour's corner
|
||||
/// opposite that same edge, or -1 unless exactly two triangles share the edge. Whoever pairs the two sides of an edge reads it here.
|
||||
/// </summary>
|
||||
public required int[] Across { get; init; }
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public required int Pulled { get; init; }
|
||||
public required float OffSurface { get; init; }
|
||||
|
||||
public int Triangles => Corners.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 (m): the coarsest at which the thinnest limb, radius 40 mm, still spans two cells across (PuppetChecks measures this against the coarser cells).</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>A body's radius, or for a box its smallest half extent: the thickness of the limb it draws.</summary>
|
||||
public static float Thickness(Box3DSoaKind kind, float3 size) => kind == Box3DSoaKind.Box ? math.min(size.x, math.min(size.y, size.z)) : size.x;
|
||||
|
||||
/// <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);
|
||||
|
||||
/// <summary>Builds the shape on a grid of <paramref name="cell"/> metres (the shipped <see cref="Cell"/>; the resolution check sweeps it).</summary>
|
||||
public static PuppetShape Build(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJoint> joints, float smin, float ballScale, float boxRound, float cell = Cell)
|
||||
{
|
||||
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, cell);
|
||||
}
|
||||
|
||||
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, float cell)
|
||||
{
|
||||
int n = bodies.Count;
|
||||
var lo = new float3(float.MaxValue, float.MaxValue, float.MaxValue); var hi = new float3(float.MinValue, float.MinValue, float.MinValue);
|
||||
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);
|
||||
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; the untangle then pulls back the few it threw into a fold.
|
||||
var net = new float3[nets.VertexCount]; var projected = new float3[net.Length];
|
||||
for (int i = 0; i < net.Length; i++)
|
||||
{
|
||||
net[i] = new float3(nets.Positions[3 * i], nets.Positions[3 * i + 1], nets.Positions[3 * i + 2]);
|
||||
var p = net[i];
|
||||
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); }
|
||||
projected[i] = p;
|
||||
}
|
||||
var (v, tris, pulled, offSurface) = Untangle(f, nets.Quads, net, projected);
|
||||
|
||||
// The nets wind every quad counter-clockwise seen from the field's outside; Godot's front face is clockwise, so each triangle is emitted reversed.
|
||||
// Only the vertices some triangle uses are kept, in the order they are first used.
|
||||
var welded = new int[v.Length]; Array.Fill(welded, -1);
|
||||
var vertices = new List<float3>(); var ba = new List<int>(); var bb = new List<int>(); var wa = new List<float>();
|
||||
var corners = new int[tris.Length];
|
||||
for (int k = 0; k < tris.Length; k += 3)
|
||||
for (int c = 0; c < 3; c++)
|
||||
{
|
||||
int i = tris[k + (3 - c) % 3]; // reversed: 0, 2, 1
|
||||
if (welded[i] < 0)
|
||||
{
|
||||
welded[i] = vertices.Count;
|
||||
f.Eval(v[i], out int bone, out int other, out float w);
|
||||
vertices.Add(v[i]); ba.Add(bone); bb.Add(other); wa.Add(w);
|
||||
}
|
||||
corners[k + c] = welded[i];
|
||||
}
|
||||
var across = Across(corners);
|
||||
|
||||
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,
|
||||
Vertices = vertices.ToArray(), BoneA = ba.ToArray(), BoneB = bb.ToArray(), WeightA = wa.ToArray(), Corners = corners, Across = across,
|
||||
Pulled = pulled, OffSurface = offSurface,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>The untangle's pull-back rounds: each halves the Newton displacement of the vertices it marks, so twelve leave them at the net.</summary>
|
||||
private const int UntangleRounds = 12;
|
||||
|
||||
/// <summary>
|
||||
/// The nets' triangles (quads split on the flatter diagonal, wound as the nets wind them) over the vertices <paramref name="projected"/>
|
||||
/// onto the isosurface, with every vertex of a bad triangle pulled back toward its net position, half as far each round, until none
|
||||
/// is bad or <see cref="UntangleRounds"/> rounds are done. A triangle is bad when it faces against the field's gradient at its centroid,
|
||||
/// is inverted or collapsed against its net triangle (its cross has a component along the net's of at most 5% of the net's squared
|
||||
/// length), or has an edge that is a fold (its two triangles disagree on convexity). Returns the vertices, the triangles (three
|
||||
/// indices each), how many vertices were pulled back and the worst distance of one from the isosurface (m).
|
||||
/// </summary>
|
||||
private static (float3[] V, int[] Tris, int Pulled, float OffSurface) Untangle(Field f, uint[] quads, float3[] net, float3[] projected)
|
||||
{
|
||||
var v = (float3[])projected.Clone();
|
||||
var pull = new float[v.Length]; Array.Fill(pull, 1f);
|
||||
int[] tris;
|
||||
for (int round = 0; ; round++)
|
||||
{
|
||||
tris = Triangulate(quads, v);
|
||||
var bad = new HashSet<int>();
|
||||
var sides = new Dictionary<(int, int), List<int>>();
|
||||
for (int k = 0; k < tris.Length; k += 3)
|
||||
{
|
||||
int a = tris[k], b = tris[k + 1], c = tris[k + 2];
|
||||
var cross = math.cross(v[b] - v[a], v[c] - v[a]);
|
||||
var netCross = math.cross(net[b] - net[a], net[c] - net[a]);
|
||||
var g = f.Eval((v[a] + v[b] + v[c]) / 3f, out _, out _, out _);
|
||||
// The nets wind every quad counter-clockwise seen from the field's outside, so a triangle's cross points along the gradient.
|
||||
bool against = math.dot(cross, new float3(g.x, g.y, g.z)) <= 0;
|
||||
bool inverted = math.dot(cross, netCross) <= 0.05f * math.lengthsq(netCross);
|
||||
if (against || inverted) { bad.Add(a); bad.Add(b); bad.Add(c); }
|
||||
for (int e = 0; e < 3; e++)
|
||||
{
|
||||
int p = tris[k + (e + 1) % 3], q = tris[k + (e + 2) % 3];
|
||||
var key = p < q ? (p, q) : (q, p);
|
||||
if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List<int>(2);
|
||||
list.Add(k + e);
|
||||
}
|
||||
}
|
||||
foreach (var list in sides.Values)
|
||||
{
|
||||
if (list.Count != 2) continue;
|
||||
if (Convex(tris, v, list[0], list[1]) != Convex(tris, v, list[1], list[0]) && Turns(tris, v, list[0], list[1]))
|
||||
foreach (int s in list) { bad.Add(tris[s]); bad.Add(tris[s - s % 3 + (s % 3 + 1) % 3]); bad.Add(tris[s - s % 3 + (s % 3 + 2) % 3]); }
|
||||
}
|
||||
if (bad.Count == 0 || round == UntangleRounds) break;
|
||||
foreach (int i in bad) { pull[i] *= 0.5f; v[i] = net[i] + (projected[i] - net[i]) * pull[i]; }
|
||||
}
|
||||
int pulled = 0; float off = 0;
|
||||
for (int i = 0; i < v.Length; i++)
|
||||
if (pull[i] < 1) { pulled++; off = MathF.Max(off, MathF.Abs(f.Eval(v[i], out _, out _, out _).w)); }
|
||||
return (v, tris, pulled, off);
|
||||
}
|
||||
|
||||
/// <summary>The quads as triangles, each split on its flatter diagonal, in the quad's winding.</summary>
|
||||
private static int[] Triangulate(uint[] quads, float3[] v)
|
||||
{
|
||||
var tris = new int[quads.Length / 4 * 6];
|
||||
for (int i = 0, o = 0; i < quads.Length; i += 4, o += 6)
|
||||
{
|
||||
int ia = (int)quads[i], ib = (int)quads[i + 1], ic = (int)quads[i + 2], id = (int)quads[i + 3];
|
||||
var a = v[ia]; var b = v[ib]; var c = v[ic]; var d = v[id];
|
||||
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)));
|
||||
var t = ac ? new[] { ia, ib, ic, ia, ic, id } : new[] { ia, ib, id, ib, ic, id };
|
||||
t.CopyTo(tris, o);
|
||||
}
|
||||
return tris;
|
||||
}
|
||||
|
||||
/// <summary>Whether, from the triangle of slot <paramref name="s"/>, the triangle of slot <paramref name="other"/> lies behind its plane: the edge between them is convex there.</summary>
|
||||
private static bool Convex(int[] tris, float3[] v, int s, int other)
|
||||
{
|
||||
int k = s - s % 3, e = s % 3;
|
||||
var n = math.cross(v[tris[k + 1]] - v[tris[k]], v[tris[k + 2]] - v[tris[k]]);
|
||||
return math.dot(n, v[tris[other]] - v[tris[k + (e + 1) % 3]]) < 0;
|
||||
}
|
||||
|
||||
/// <summary>Whether the two triangles' normals differ by more than a hundredth of a radian: a flatter edge has no convexity to speak of.</summary>
|
||||
private static bool Turns(int[] tris, float3[] v, int s, int t)
|
||||
{
|
||||
int a = s - s % 3, b = t - t % 3;
|
||||
var na = Unit(math.cross(v[tris[a + 1]] - v[tris[a]], v[tris[a + 2]] - v[tris[a]]));
|
||||
var nb = Unit(math.cross(v[tris[b + 1]] - v[tris[b]], v[tris[b + 2]] - v[tris[b]]));
|
||||
return MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)) >= 1e-2f;
|
||||
}
|
||||
|
||||
/// <summary>Each triangle edge is matched to its neighbour by the two vertex indices it joins; <see cref="PuppetShape.Across"/>.</summary>
|
||||
private static int[] Across(int[] corners)
|
||||
{
|
||||
var sides = new Dictionary<(int, int), List<int>>();
|
||||
for (int s = 0; s < corners.Length; s++)
|
||||
{
|
||||
int t = s / 3, k = s % 3;
|
||||
int p = corners[3 * t + (k + 1) % 3], q = corners[3 * t + (k + 2) % 3];
|
||||
var key = p < q ? (p, q) : (q, p);
|
||||
if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List<int>(2);
|
||||
list.Add(s);
|
||||
}
|
||||
var across = new int[corners.Length];
|
||||
Array.Fill(across, -1);
|
||||
foreach (var list in sides.Values)
|
||||
if (list.Count == 2) { across[list[0]] = list[1]; across[list[1]] = list[0]; }
|
||||
return across;
|
||||
}
|
||||
|
||||
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) => PuppetField.Thickness(_kind[i], _size[i]);
|
||||
|
||||
/// <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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,104 +0,0 @@
|
|||
using System.Collections.Generic;
|
||||
using CultMath;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>A qualifying joint as the lanes name it: the bodies by StableId, the joint origin in the world now.</summary>
|
||||
public readonly record struct PuppetJointLane(Box3DSoaJointKind Kind, ulong A, ulong B, float3 Origin);
|
||||
|
||||
/// <summary>
|
||||
/// Owns the puppet's shape and the one rule for when it is rebuilt, engine-free so the rule can be tested without a scene:
|
||||
/// the mesh is built from the first update and again only when the topology signature changes, which is the ordered
|
||||
/// (StableId, Kind, Size0..2) of the shape bodies and the ordered (JointKind, StableId A, StableId B) of the qualifying joints.
|
||||
/// A body's bind is its pose the first time it is seen (the creation pose); a joint's origin is kept in body A's frame from then.
|
||||
/// Poses and joint origins alone never rebuild.
|
||||
/// </summary>
|
||||
public sealed class PuppetModel
|
||||
{
|
||||
private readonly float _smin, _ballScale, _boxRound;
|
||||
private readonly Dictionary<ulong, Rigid> _bind = new();
|
||||
private readonly Dictionary<(Box3DSoaJointKind, ulong, ulong), float3> _originLocal = new();
|
||||
private readonly List<BodySignature> _bodies = new();
|
||||
private readonly List<JointSignature> _joints = new();
|
||||
private readonly List<PuppetBody> _laneBodies = new();
|
||||
private readonly List<PuppetJointLane> _laneJoints = new();
|
||||
private bool _signed;
|
||||
|
||||
private readonly record struct BodySignature(ulong Id, Box3DSoaKind Kind, float S0, float S1, float S2);
|
||||
private readonly record struct JointSignature(Box3DSoaJointKind Kind, ulong A, ulong B);
|
||||
|
||||
public PuppetModel(float smin, float ballScale, float boxRound) { _smin = smin; _ballScale = ballScale; _boxRound = boxRound; }
|
||||
|
||||
/// <summary>The shape built from the current signature, or null before the first update.</summary>
|
||||
public PuppetShape? Shape { get; private set; }
|
||||
|
||||
/// <summary>Reads the shape bodies and qualifying joints of the lanes and updates.</summary>
|
||||
public bool Update(in Box3DSoaView view)
|
||||
{
|
||||
Lanes(view, _laneBodies, _laneJoints);
|
||||
return Update(_laneBodies, _laneJoints);
|
||||
}
|
||||
|
||||
/// <summary>The shape bodies (with their pose now) and the qualifying joints of the lanes: a Revolute, Spherical or Weld between two shapes.</summary>
|
||||
public static void Lanes(in Box3DSoaView view, List<PuppetBody> bodies, List<PuppetJointLane> joints)
|
||||
{
|
||||
bodies.Clear(); joints.Clear();
|
||||
var kind = view.Kind;
|
||||
for (int i = 0; i < kind.Length; i++)
|
||||
{
|
||||
if (!PuppetField.HasShape((Box3DSoaKind)kind[i])) continue;
|
||||
bodies.Add(new PuppetBody(view.StableId[i], (Box3DSoaKind)kind[i], new float3(view.Size0[i], view.Size1[i], view.Size2[i]),
|
||||
Rigid.FromQuaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i], new float3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]))));
|
||||
}
|
||||
for (int j = 0; j < view.JointCount; j++)
|
||||
{
|
||||
int a = view.JointBodyA[j], b = view.JointBodyB[j];
|
||||
if (a < 0 || b < 0 || !PuppetField.Qualifies((Box3DSoaJointKind)view.JointKind[j], (Box3DSoaKind)kind[a], (Box3DSoaKind)kind[b])) continue;
|
||||
joints.Add(new PuppetJointLane((Box3DSoaJointKind)view.JointKind[j], view.StableId[a], view.StableId[b], new float3(view.JointOriginX[j], view.JointOriginY[j], view.JointOriginZ[j])));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <paramref name="bodies"/> carry their pose now in <see cref="PuppetBody.Bind"/>; the model keeps the first one it saw.
|
||||
/// Returns whether the signature changed, which is whether the shape was rebuilt.
|
||||
/// </summary>
|
||||
public bool Update(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJointLane> joints)
|
||||
{
|
||||
foreach (var b in bodies) _bind.TryAdd(b.Id, b.Bind);
|
||||
if (_signed && SignatureHolds(bodies, joints)) return false;
|
||||
|
||||
_bodies.Clear(); _joints.Clear();
|
||||
var index = new Dictionary<ulong, int>();
|
||||
var bound = new List<PuppetBody>();
|
||||
foreach (var b in bodies)
|
||||
{
|
||||
index[b.Id] = bound.Count;
|
||||
_bodies.Add(new BodySignature(b.Id, b.Kind, b.Size.x, b.Size.y, b.Size.z));
|
||||
bound.Add(b with { Bind = _bind[b.Id] });
|
||||
}
|
||||
var built = new List<PuppetJoint>();
|
||||
foreach (var j in joints)
|
||||
{
|
||||
var key = (j.Kind, j.A, j.B);
|
||||
_joints.Add(new JointSignature(j.Kind, j.A, j.B));
|
||||
// The origin is body A's, kept in A's frame so it follows A; the first sight is the creation pose.
|
||||
if (!_originLocal.TryGetValue(key, out var local)) _originLocal[key] = local = _bind[j.A].Inverse().Apply(j.Origin);
|
||||
built.Add(new PuppetJoint(j.Kind, index[j.A], index[j.B], local));
|
||||
}
|
||||
_signed = true;
|
||||
|
||||
Shape = PuppetField.Build(bound, built, _smin, _ballScale, _boxRound);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool SignatureHolds(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJointLane> joints)
|
||||
{
|
||||
if (bodies.Count != _bodies.Count || joints.Count != _joints.Count) return false;
|
||||
for (int i = 0; i < bodies.Count; i++)
|
||||
if (_bodies[i] != new BodySignature(bodies[i].Id, bodies[i].Kind, bodies[i].Size.x, bodies[i].Size.y, bodies[i].Size.z)) return false;
|
||||
for (int i = 0; i < joints.Count; i++)
|
||||
if (_joints[i] != new JointSignature(joints[i].Kind, joints[i].A, joints[i].B)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,123 +0,0 @@
|
|||
using System;
|
||||
using CultMath;
|
||||
|
||||
namespace BadDay.Client;
|
||||
|
||||
/// <summary>
|
||||
/// The puppet's drawn surface, engine-free, owned for every frame: <see cref="Update"/> skins the welded vertices of a <see cref="PuppetShape"/>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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];
|
||||
}
|
||||
|
||||
/// <summary>Every vertex skinned, in the space the bodies' transforms take the spread bind to.</summary>
|
||||
public float3[] Skinned { get; }
|
||||
|
||||
/// <summary>Per triangle: the unit normal seen from outside.</summary>
|
||||
public float3[] Facet { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public float[] Crease { get; }
|
||||
|
||||
/// <summary>Per vertex: the unit sum of its triangles' normals weighted by their areas.</summary>
|
||||
public float3[] VertexNormal { get; }
|
||||
|
||||
/// <summary>Per corner slot: the distance (m) from corner k to the line of edge k, 2 * area / |edge k|.</summary>
|
||||
public float[] Altitude { get; }
|
||||
|
||||
/// <summary>Per triangle: the smallest of its three altitudes.</summary>
|
||||
public float[] SmallestAltitude { get; }
|
||||
|
||||
/// <summary>The corners of the box around the skinned vertices.</summary>
|
||||
public float3 Lo { get; private set; }
|
||||
public float3 Hi { get; private set; }
|
||||
|
||||
/// <summary><paramref name="bones"/> take each body from the spread bind to where it is now, one per body of the shape.</summary>
|
||||
public void Update(ReadOnlySpan<Rigid> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -31,4 +31,3 @@ common/physics_interpolation=true
|
|||
|
||||
renderer/rendering_method="gl_compatibility"
|
||||
renderer/rendering_method.mobile="gl_compatibility"
|
||||
anti_aliasing/quality/msaa_3d=2
|
||||
|
|
|
|||
|
|
@ -1,127 +0,0 @@
|
|||
shader_type spatial;
|
||||
render_mode cull_back;
|
||||
#include "res://studio.gdshaderinc"
|
||||
|
||||
// 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 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.
|
||||
//
|
||||
// The puppet is glazed porcelain. The bisque is the PBR surface (roughness, specular, backlight) lit by Look's studio lights. The glaze
|
||||
// is analytic: Fresnel times the studio (studio.gdshaderinc) in the direction the shading normal reflects the view, added as emission, so
|
||||
// it needs no radiance map and draws the same under gl_compatibility, whose clearcoat sees punctual lights only. The bevel's tilted
|
||||
// normal feeds it, so the chamfers glint. Where two facets meet in a concave crease the glaze pools: the albedo goes darker and cooler,
|
||||
// and warmer over a convex bevel. Every number comes from Look.Glaze.
|
||||
//
|
||||
// The highlights are prefiltered where they are decided (geometric specular antialiasing): the shading normal changes across a pixel
|
||||
// along the bevel's chamfers and at facet edges, so a point sample of the studio in the reflected direction flickers as the camera moves.
|
||||
// The spread of the normal over the pixel, from its screen derivatives, widens the studio the glaze reads, so each pixel reflects the
|
||||
// studio's average over the directions it covers. (The bisque's roughness is left as it is: widening it by the same spread changed no pixel
|
||||
// at any framing, the bisque's specular being dim.) MSAA (project.godot) antialiases the silhouette and the
|
||||
// triangle edges, which this does not touch.
|
||||
uniform vec3 albedo : source_color = vec3(0.9, 0.9, 0.88);
|
||||
uniform float bevel_screen = 0.0;
|
||||
uniform float bevel_min = 0.0;
|
||||
uniform float roughness = 1.0;
|
||||
uniform float specular = 0.0;
|
||||
uniform vec3 backlight = vec3(0.0);
|
||||
uniform float glaze = 0.0; // 0 is the bisque alone
|
||||
uniform float glaze_pool = 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() {
|
||||
NORMAL = CUSTOM2.xyz;
|
||||
edge = CUSTOM0;
|
||||
crease = CUSTOM1.xyz;
|
||||
vertex_normal = (MODELVIEW_MATRIX * vec4(CUSTOM3.xyz, 0.0)).xyz;
|
||||
}
|
||||
|
||||
void fragment() {
|
||||
vec3 n = normalize(NORMAL);
|
||||
// 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);
|
||||
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);
|
||||
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];
|
||||
}
|
||||
}
|
||||
// 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;
|
||||
// The pixel's normal spread as GGX alpha^2 (Tokuyoshi and Kaplanyan 2021, JCGT 10(2) 31-58, Listing 5) with the pixel filter's variance
|
||||
// 1/24 and the clamp of Kaplanyan et al. 2016 (HPG) at 0.18. 1/24 is half of a box one pixel wide's own variance (1/12) and an eighth of the
|
||||
// paper's 1/(2 pi); RenderCheck's flicker check holds it from both sides: with 1/24 the highlights stop crawling, and at 1/12 or more they
|
||||
// are blurred below the supersampled reference's brightness. Derivatives are taken here, after every branch has joined, in uniform control flow.
|
||||
const float PIXEL_VARIANCE = 1.0 / 24.0;
|
||||
const float MAX_SPREAD = 0.18;
|
||||
float kernel = min(2.0 * PIXEL_VARIANCE * (dot(dFdx(n), dFdx(n)) + dot(dFdy(n), dFdy(n))), MAX_SPREAD);
|
||||
// The creases within 6 mm of an edge: concave tints the albedo cooler and darker, convex warmer.
|
||||
float convex = 0.0, concave = 0.0;
|
||||
for (int k = 0; k < 3; k++) {
|
||||
float near = 1.0 - smoothstep(0.0, 0.006, edge[k]);
|
||||
convex = max(convex, near * clamp(crease[k] * 2.0, 0.0, 1.0));
|
||||
concave = max(concave, near * clamp(-crease[k] * 2.0, 0.0, 1.0));
|
||||
}
|
||||
vec3 a = albedo;
|
||||
a = mix(a, a * vec3(0.80, 0.82, 0.86), glaze_pool * concave);
|
||||
a = mix(a, a * vec3(1.02, 0.99, 0.94), glaze_pool * convex);
|
||||
ALBEDO = show_normals ? vec3(0.0) : a;
|
||||
// RenderCheck's normal view is the emission alone: no light, however shiny the bisque, may add to it.
|
||||
ROUGHNESS = show_normals ? 1.0 : roughness;
|
||||
SPECULAR = show_normals ? 0.0 : specular;
|
||||
BACKLIGHT = show_normals ? vec3(0.0) : backlight;
|
||||
EMISSION = show_normals ? n * 0.5 + 0.5 : vec3(0.0);
|
||||
if (!show_normals && glaze > 0.0) {
|
||||
vec3 r = reflect(-VIEW, n);
|
||||
float f = 0.04 + 0.96 * pow(1.0 - clamp(dot(n, VIEW), 0.0, 1.0), 5.0);
|
||||
EMISSION += glaze * f * studio(r, kernel);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
// The studio the glaze reflects: a dark room, one large soft box (key), two tall strip lights (rims) and a dim floor. Look owns the
|
||||
// numbers and feeds the same ones to the punctual lights, so the lights and the reflections are one studio. The directions are the
|
||||
// directions the light comes from, in view space (the studio turns with the camera, as a photographer's lights do). Radiances are in the render's linear units and are meant to clip where the glaze catches them.
|
||||
// The studio is prefiltered: it takes the spread of the pixel's normal and returns the average over the directions the pixel reflects, so a highlight does not flicker as the camera moves.
|
||||
uniform vec3 studio_room = vec3(0.0);
|
||||
uniform vec3 studio_key_dir = vec3(0.0, 1.0, 0.0);
|
||||
uniform float studio_key_size = 0.0;
|
||||
uniform float studio_key_radiance = 0.0;
|
||||
uniform vec3 studio_rim_a = vec3(0.0, 1.0, 0.0);
|
||||
uniform vec3 studio_rim_b = vec3(0.0, 1.0, 0.0);
|
||||
uniform vec2 studio_rim_size = vec2(0.0);
|
||||
uniform vec3 studio_rim_tint = vec3(1.0);
|
||||
uniform float studio_rim_radiance = 0.0;
|
||||
uniform float studio_floor = 0.0;
|
||||
|
||||
// A rectangular emitter seen from the origin along c, w by h on the plane at unit distance, prefiltered by the pixel's normal spread a2
|
||||
// (GGX alpha^2; the shader's kernel). A reflected direction that spreads by variance 2 a2 per axis spreads (1 + |q|^2) times wider on the
|
||||
// plane at unit distance, so each axis of the box (half width 0.9 h) is averaged over a box kernel of half width w (variance w^2 / 3: the
|
||||
// lobe's 2 a2 times that stretch squared, plus the authored edge's own (0.1 h)^2). The result is a trapezoid: a linear ramp from 0.8 h to h
|
||||
// at a2 = 0 (the authored edge was a smoothstep over the same span, so the two differ by under a tenth of the box's level), widening as a2
|
||||
// grows. The box's integral over the reflected directions is kept to about 6% up to a2 = 0.05; at the 0.18 clamp about a third of it remains,
|
||||
// where the filter has stopped following the lobe and the highlight dims rather than brightens.
|
||||
float studio_box(vec3 d, vec3 c, vec2 half_size, float a2) {
|
||||
vec3 up = abs(c.y) > 0.9 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);
|
||||
vec3 u = normalize(cross(up, c));
|
||||
vec3 v = cross(c, u);
|
||||
float f = dot(d, c);
|
||||
if (f <= 0.0) return 0.0;
|
||||
vec2 q = abs(vec2(dot(d, u), dot(d, v)) / f);
|
||||
float stretch = 1.0 + dot(q, q);
|
||||
vec2 edge = 0.9 * half_size;
|
||||
vec2 w = max(sqrt(0.01 * half_size * half_size + 6.0 * a2 * stretch * stretch), vec2(1e-6));
|
||||
vec2 e = max(min(q + w, edge) - max(q - w, -edge), 0.0) / (2.0 * w);
|
||||
return e.x * e.y;
|
||||
}
|
||||
|
||||
vec3 studio(vec3 d, float a2) {
|
||||
vec3 c = studio_room;
|
||||
c += studio_key_radiance * studio_box(d, normalize(studio_key_dir), vec2(studio_key_size, studio_key_size * 0.7), a2) * vec3(1.0, 0.98, 0.95);
|
||||
c += studio_rim_radiance * studio_box(d, normalize(studio_rim_a), studio_rim_size, a2) * studio_rim_tint;
|
||||
c += studio_rim_radiance * studio_box(d, normalize(studio_rim_b), studio_rim_size, a2) * studio_rim_tint;
|
||||
c += studio_floor * smoothstep(0.0, -0.3, d.y) * vec3(1.0);
|
||||
return c;
|
||||
}
|
||||
|
|
@ -1,422 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CultMath;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The puppet's rules that need no scene, run by the smoke before its scenario: when the model rebuilds the shape.
|
||||
/// Each check reports what broke through <c>fail</c>.
|
||||
/// </summary>
|
||||
public static class PuppetChecks
|
||||
{
|
||||
/// <summary>No skinned edge may be longer than this many times its bind length.</summary>
|
||||
public const float StretchLimit = 4f;
|
||||
|
||||
private static PuppetBody Body(ulong id, Box3DSoaKind kind, float s0, float s1, float y) =>
|
||||
new(id, kind, new float3(s0, s1, 0), Rigid.FromQuaternion(0, 0, 0, 1, new float3(0, y, 0)));
|
||||
|
||||
private static (List<PuppetBody> Bodies, List<PuppetJointLane> Joints) Chain() => (
|
||||
new List<PuppetBody>
|
||||
{
|
||||
Body(10, Box3DSoaKind.Capsule, 0.06f, 0.15f, 0.3f),
|
||||
Body(11, Box3DSoaKind.Capsule, 0.05f, 0.12f, 0.7f),
|
||||
Body(12, Box3DSoaKind.Sphere, 0.09f, 0f, 1.0f),
|
||||
},
|
||||
new List<PuppetJointLane>
|
||||
{
|
||||
new(Box3DSoaJointKind.Spherical, 10, 11, new float3(0, 0.5f, 0)),
|
||||
new(Box3DSoaJointKind.Revolute, 11, 12, new float3(0, 0.85f, 0)),
|
||||
});
|
||||
|
||||
public static void Run(Action<string> fail, in Box3DSoaView creationView)
|
||||
{
|
||||
void Check(bool ok, string what) { if (!ok) fail(what); }
|
||||
PuppetModel Fresh() => new(Look.SminRadius, Look.JointBallScale, Look.BoxRound);
|
||||
|
||||
// The first update builds; the same signature again, even from new lists, never does.
|
||||
var m = Fresh();
|
||||
var (bodies, joints) = Chain();
|
||||
Check(m.Update(bodies, joints) && m.Shape is not null, "the first update did not build the puppet");
|
||||
var first = m.Shape;
|
||||
var (again, againJoints) = Chain();
|
||||
Check(!m.Update(again, againJoints) && ReferenceEquals(m.Shape, first), "an unchanged signature rebuilt the puppet");
|
||||
|
||||
// Poses and joint origins alone are not topology: the bind is the first sight.
|
||||
var moved = Chain();
|
||||
for (int i = 0; i < moved.Bodies.Count; i++) moved.Bodies[i] = moved.Bodies[i] with { Bind = Rigid.FromQuaternion(0, 0, 0, 1, new float3(0.5f, 2f + i, 0)) };
|
||||
moved.Joints[0] = moved.Joints[0] with { Origin = new float3(9, 9, 9) };
|
||||
Check(!m.Update(moved.Bodies, moved.Joints) && ReferenceEquals(m.Shape, first), "bodies that only moved rebuilt the puppet");
|
||||
|
||||
// Each change of topology rebuilds exactly once, and then holds.
|
||||
void Changes(string what, Action<List<PuppetBody>, List<PuppetJointLane>> edit)
|
||||
{
|
||||
var model = Fresh();
|
||||
var (b, j) = Chain();
|
||||
model.Update(b, j);
|
||||
var built = model.Shape;
|
||||
edit(b, j);
|
||||
Check(model.Update(b, j) && !ReferenceEquals(model.Shape, built), $"{what}: the signature changed and the puppet was not rebuilt");
|
||||
var rebuilt = model.Shape;
|
||||
Check(!model.Update(b, j) && ReferenceEquals(model.Shape, rebuilt), $"{what}: the new signature rebuilt again");
|
||||
}
|
||||
Changes("a joint removed", (b, j) => j.RemoveAt(1));
|
||||
Changes("a body added", (b, j) => b.Add(Body(13, Box3DSoaKind.Sphere, 0.05f, 0f, 1.3f)));
|
||||
Changes("a body removed", (b, j) => { b.RemoveAt(2); j.RemoveAt(1); });
|
||||
Changes("a size changed", (b, j) => b[0] = b[0] with { Size = new float3(0.07f, 0.15f, 0f) });
|
||||
Changes("a shape kind changed", (b, j) => b[2] = b[2] with { Kind = Box3DSoaKind.Capsule, Size = new float3(0.09f, 0.05f, 0f) });
|
||||
Changes("a joint's kind changed", (b, j) => j[0] = j[0] with { Kind = Box3DSoaJointKind.Weld });
|
||||
Changes("a body's identity changed", (b, j) => { b[1] = b[1] with { Id = 21 }; j[0] = j[0] with { B = 21 }; j[1] = j[1] with { A = 21 }; });
|
||||
|
||||
// Any number of bodies is drawn: a crowd of 40 (no cap, however many the skin has to carry) builds a shape whose every body owns a
|
||||
// vertex, and skins to a surface with a facet for every triangle.
|
||||
var many = Fresh();
|
||||
var crowd = Enumerable.Range(0, 40).Select(i => Body((ulong)(100 + i), Box3DSoaKind.Sphere, 0.05f, 0f, i * 0.2f)).ToList();
|
||||
Check(many.Update(crowd, new List<PuppetJointLane>()) && many.Shape is { Corners.Length: > 0 }, "a puppet of 40 bodies was not built");
|
||||
var crowdShape = many.Shape!;
|
||||
Check(crowdShape.Ids.Length == 40, $"the crowd's shape carries {crowdShape.Ids.Length} bodies, not 40");
|
||||
Check(!many.Update(crowd, new List<PuppetJointLane>()), "a crowd reported a change with none");
|
||||
var crowdSkin = new PuppetSkin(crowdShape);
|
||||
crowdSkin.Update(Enumerable.Repeat(Identity, crowdShape.Ids.Length).ToArray());
|
||||
Check(crowdSkin.Facet.Length * 3 == crowdShape.Corners.Length && crowdSkin.Facet.All(f => math.length(f) > 0.99f), "the crowd's skin has no unit facet for every triangle");
|
||||
|
||||
// The real puppet at its creation pose: the grid cell is the coarsest that resolves its limbs, and bent every which way
|
||||
// no skinned edge is a web.
|
||||
var real = new List<PuppetBody>(); var realLanes = new List<PuppetJointLane>();
|
||||
PuppetModel.Lanes(creationView, real, realLanes);
|
||||
var index = real.Select((b, k) => (b.Id, k)).ToDictionary(x => x.Id, x => x.k);
|
||||
var inputs = realLanes.Select(j => new PuppetJoint(j.Kind, index[j.A], index[j.B], real[index[j.A]].Bind.Inverse().Apply(j.Origin))).ToList();
|
||||
PuppetShape Build(float cell) => PuppetField.Build(real, inputs, Look.SminRadius, Look.JointBallScale, Look.BoxRound, cell);
|
||||
|
||||
// Resolved: the cell is at most the thinnest limb's radius (Nyquist: the thinnest limb spans at least two cells across, so the
|
||||
// grid can represent it), the mesh is one piece, and every body owns some of the surface (is the most influential bone of at
|
||||
// least one triangle corner). The first condition decides which cell is the coarsest; the other two catch a mesh that
|
||||
// lost a limb, and say nothing about how fine a cell must be.
|
||||
float thinnest = real.Min(b => PuppetField.Thickness(b.Kind, b.Size));
|
||||
bool Resolved(float cell)
|
||||
{
|
||||
var shape = Build(cell);
|
||||
var owned = new int[real.Count];
|
||||
for (int v = 0; v < shape.Vertices.Length; v++) owned[shape.WeightA[v] >= 0.5f ? shape.BoneA[v] : shape.BoneB[v]]++;
|
||||
return cell <= thinnest + 1e-6f && Pieces(shape) == 1 && owned.Min() > 0;
|
||||
}
|
||||
// The look constants may be changed by the operator's joint-look question, within what the mesh can hold: a blend wider than
|
||||
// the thinnest limb swallows it, and a negative ball or rounding is no shape.
|
||||
Check(Look.SminRadius > 0 && Look.SminRadius <= thinnest, $"Look.SminRadius {Look.SminRadius} m is not within (0, the thinnest limb's radius {thinnest} m]");
|
||||
Check(Look.JointBallScale >= 0 && Look.BoxRound >= 0, "Look.JointBallScale or Look.BoxRound is negative");
|
||||
Check(Resolved(PuppetField.Cell), $"the shipped {PuppetField.Cell * 1000:F0} mm cell does not resolve the limbs");
|
||||
foreach (float coarser in new[] { thinnest * 1.05f, 0.05f, 0.06f, 0.08f, 0.10f })
|
||||
Check(coarser <= PuppetField.Cell || !Resolved(coarser), $"a {coarser * 1000:F0} mm cell resolves the limbs, so {PuppetField.Cell * 1000:F0} mm is not the coarsest");
|
||||
|
||||
// Bent at random, every joint at once, no skinned edge is a web. The bounds are what the shipped look measures with a
|
||||
// margin (200 poses each: 3.24x and 0.140 m at 45 degrees, 5.0x and 0.205 m at 90); a bind edge is about a cell
|
||||
// (0.04 m), so 0.17 m is four cells and 0.25 m is six. At 90 degrees only the length is bounded, since the ratio
|
||||
// overstates when a bind edge is tiny.
|
||||
var puppet = Build(PuppetField.Cell);
|
||||
float worstRatio = 0, worstLength = 0, worstLength90 = 0;
|
||||
for (int seed = 0; seed < 200; seed++)
|
||||
{
|
||||
var (ratio, length) = Stretch(puppet, Bend(puppet, seed, 45f * MathF.PI / 180f));
|
||||
worstRatio = MathF.Max(worstRatio, ratio); worstLength = MathF.Max(worstLength, length);
|
||||
worstLength90 = MathF.Max(worstLength90, Stretch(puppet, Bend(puppet, seed, 90f * MathF.PI / 180f)).Length);
|
||||
}
|
||||
Check(worstRatio <= StretchLimit, $"every joint bent up to 45 degrees stretches an edge {worstRatio:F2}x its bind length, over {StretchLimit}x");
|
||||
Check(worstLength <= 0.17f, $"every joint bent up to 45 degrees makes a skinned edge {worstLength:F3} m long, over 0.17 m");
|
||||
Check(worstLength90 <= 0.25f, $"every joint bent up to 90 degrees makes a skinned edge {worstLength90:F3} m long, over 0.25 m");
|
||||
|
||||
Mesher(puppet, Check);
|
||||
AcrossIsPositionWeld(puppet, Check);
|
||||
SkinnedSurface(puppet, Check);
|
||||
FoldHasNoCrease(Check);
|
||||
}
|
||||
|
||||
/// <summary>The corner slot's vertex, in the spread bind.</summary>
|
||||
private static float3 At(PuppetShape shape, int slot) => shape.Vertices[shape.Corners[slot]];
|
||||
|
||||
/// <summary>The unit normal of a triangle seen from outside (the winding is clockwise from outside), from its corners.</summary>
|
||||
private static float3 Facet(PuppetShape shape, int triangle)
|
||||
{
|
||||
var cross = math.cross(At(shape, 3 * triangle + 1) - At(shape, 3 * triangle), At(shape, 3 * triangle + 2) - At(shape, 3 * triangle));
|
||||
return -cross / math.length(cross);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mesher's untangle on the shipped cell: no edge folds (its two triangles disagree on convexity), no triangle faces into the body
|
||||
/// (seen from a point a millimetre off its face along its normal, the surface is crossed an odd number of times in two directions),
|
||||
/// none is tiny, and the vertices the untangle pulled back are few and stay near the isosurface. The coarser cells of the resolution
|
||||
/// sweep are judged by Resolved alone: the untangle leaves some marked there.
|
||||
/// </summary>
|
||||
private static void Mesher(PuppetShape shape, Action<bool, string> check)
|
||||
{
|
||||
int count = shape.Triangles;
|
||||
int folds = 0, edges = 0;
|
||||
for (int s = 0; s < shape.Across.Length; s++)
|
||||
{
|
||||
int o = shape.Across[s];
|
||||
if (o < s) continue;
|
||||
edges++;
|
||||
float3 na = Facet(shape, s / 3), nb = Facet(shape, o / 3);
|
||||
if (MathF.Atan2(math.length(math.cross(na, nb)), math.dot(na, nb)) < 1e-2f) continue; // a flatter edge has no convexity to speak of
|
||||
// Convex from a side: the neighbour's far corner (the corner opposite the shared edge) lies behind this facet's plane.
|
||||
bool convexA = math.dot(na, At(shape, o) - At(shape, 3 * (s / 3) + (s % 3 + 1) % 3)) < 0;
|
||||
bool convexB = math.dot(nb, At(shape, s) - At(shape, 3 * (o / 3) + (o % 3 + 1) % 3)) < 0;
|
||||
if (convexA != convexB) folds++;
|
||||
}
|
||||
check(edges > 1000, $"the mesher check is vacuous: {edges} shared edges");
|
||||
check(folds == 0, $"{folds} of {edges} shared edges are folds: their two triangles disagree on convexity");
|
||||
|
||||
// Facing into the body: an odd crossing count from just outside the face means the face looks inward.
|
||||
var directions = new[] { math.normalize(new float3(0.5773f, 0.3011f, 0.7571f)), math.normalize(new float3(-0.2113f, 0.8317f, -0.5129f)) };
|
||||
int inward = 0; float smallest = float.MaxValue;
|
||||
for (int t = 0; t < count; t++)
|
||||
{
|
||||
var a = At(shape, 3 * t); var b = At(shape, 3 * t + 1); var c = At(shape, 3 * t + 2);
|
||||
smallest = MathF.Min(smallest, 0.5f * math.length(math.cross(b - a, c - a)));
|
||||
var origin = (a + b + c) / 3f + Facet(shape, t) * 1e-3f;
|
||||
bool both = true;
|
||||
foreach (var d in directions)
|
||||
{
|
||||
int crossings = 0;
|
||||
for (int u = 0; u < count; u++) if (Crosses(origin, d, At(shape, 3 * u), At(shape, 3 * u + 1), At(shape, 3 * u + 2))) crossings++;
|
||||
both &= crossings % 2 == 1;
|
||||
}
|
||||
if (both) inward++;
|
||||
}
|
||||
check(inward == 0, $"{inward} of {count} triangles face into the body");
|
||||
check(smallest >= 1e-6f, $"the smallest triangle is {smallest * 1e6:F2} mm2, under 1 mm2");
|
||||
check(shape.Pulled <= 16, $"the untangle pulled back {shape.Pulled} vertices, over 16");
|
||||
check(shape.OffSurface <= 0.015f, $"a pulled-back vertex is {shape.OffSurface * 1000:F1} mm off the isosurface, over 15 mm");
|
||||
}
|
||||
|
||||
/// <summary>Whether the ray from <paramref name="o"/> along <paramref name="d"/> crosses the triangle (Moller-Trumbore).</summary>
|
||||
private static bool Crosses(float3 o, float3 d, float3 a, float3 b, float3 c)
|
||||
{
|
||||
var e1 = b - a; var e2 = c - a; var pv = math.cross(d, e2);
|
||||
float det = math.dot(e1, pv);
|
||||
if (MathF.Abs(det) < 1e-12f) return false;
|
||||
var tv = o - a; float u = math.dot(tv, pv) / det;
|
||||
if (u < 0 || u > 1) return false;
|
||||
var qv = math.cross(tv, e1); float w = math.dot(d, qv) / det;
|
||||
return w >= 0 && u + w <= 1 && math.dot(e2, qv) / det > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="PuppetShape.Across"/> is the edge match a weld by position makes: vertices at the same place are one, and an edge joins
|
||||
/// the corners opposite it in the two triangles that have it, or nothing where it has other than two.
|
||||
/// </summary>
|
||||
private static void AcrossIsPositionWeld(PuppetShape shape, Action<bool, string> check)
|
||||
{
|
||||
var id = new Dictionary<(long, long, long), int>();
|
||||
var weld = new int[shape.Corners.Length];
|
||||
for (int s = 0; s < weld.Length; s++)
|
||||
{
|
||||
var p = At(shape, s);
|
||||
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 weld[s])) id[key] = weld[s] = id.Count;
|
||||
}
|
||||
var sides = new Dictionary<(int, int), List<int>>();
|
||||
for (int s = 0; s < weld.Length; s++)
|
||||
{
|
||||
int t = s / 3, k = s % 3, p = weld[3 * t + (k + 1) % 3], q = weld[3 * t + (k + 2) % 3];
|
||||
var key = p < q ? (p, q) : (q, p);
|
||||
if (!sides.TryGetValue(key, out var list)) sides[key] = list = new List<int>();
|
||||
list.Add(s);
|
||||
}
|
||||
int wrong = 0, shared = 0, loose = 0;
|
||||
foreach (var list in sides.Values)
|
||||
{
|
||||
if (list.Count == 2) { shared++; if (shape.Across[list[0]] != list[1] || shape.Across[list[1]] != list[0]) wrong++; }
|
||||
else { loose++; foreach (int s in list) if (shape.Across[s] != -1) wrong++; }
|
||||
}
|
||||
check(shape.Across.Length == shape.Corners.Length, $"the puppet has {shape.Across.Length} Across entries for {shape.Corners.Length} corner slots");
|
||||
check(shared > 1000, $"the Across check is vacuous: {shared} shared edges and {loose} not");
|
||||
check(wrong == 0, $"{wrong} corner slots' Across differs from the edge match a weld by position makes");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="PuppetSkin"/> 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.
|
||||
/// </summary>
|
||||
private static void SkinnedSurface(PuppetShape shape, Action<bool, string> 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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A skinned fold, two triangles lying over each other so that their sides disagree on which way their shared edge turns, has no edge to
|
||||
/// bevel: both sides carry crease 0. No pose of the real puppet reaches one but a single joint swung 180 degrees, so the rule is held to
|
||||
/// two small shapes of four vertices, both with one bone and no joint: the same four points wound so that the second triangle is
|
||||
/// inconsistent with the first (a fold), and wound consistently with a right angle between the two (a turn, which keeps its crease).
|
||||
/// </summary>
|
||||
private static void FoldHasNoCrease(Action<bool, string> check)
|
||||
{
|
||||
PuppetShape Pair(float3[] vertices, int[] corners, int slotA, int slotB)
|
||||
{
|
||||
var across = Enumerable.Repeat(-1, corners.Length).ToArray();
|
||||
across[slotA] = slotB; across[slotB] = slotA;
|
||||
return new PuppetShape
|
||||
{
|
||||
Ids = new ulong[] { 1 }, SpreadBind = new[] { Identity }, Joints = Array.Empty<(Box3DSoaJointKind, int, int, float3)>(),
|
||||
Vertices = vertices, BoneA = new int[vertices.Length], BoneB = new int[vertices.Length], WeightA = Enumerable.Repeat(1f, vertices.Length).ToArray(),
|
||||
Corners = corners, Across = across, Pulled = 0, OffSurface = 0,
|
||||
};
|
||||
}
|
||||
// Triangle A is (0, 1, 2); its edge 1-2 is opposite its corner 0 (slot 0).
|
||||
var fold = Pair(new[] { new float3(0, 0, 0), new float3(1, 0, 0), new float3(0, 1, 0), new float3(1, 1, 0.1f) }, new[] { 0, 1, 2, 1, 2, 3 }, 0, 5);
|
||||
var turn = Pair(new[] { new float3(0, 0, 0), new float3(1, 0, 0), new float3(0, 1, 0), new float3(0.5f, 0.5f, 0.7f) }, new[] { 0, 1, 2, 1, 3, 2 }, 0, 4);
|
||||
foreach (var (name, shape, folds) in new[] { ("fold", fold, true), ("turn", turn, false) })
|
||||
{
|
||||
var skin = new PuppetSkin(shape);
|
||||
skin.Update(new[] { Identity });
|
||||
float3 P(int slot) => shape.Vertices[shape.Corners[slot]];
|
||||
float3 na = skin.Facet[0], nb = skin.Facet[1];
|
||||
bool convexA = math.dot(na, P(shape.Across[0]) - P(1)) < 0, convexB = math.dot(nb, P(0) - P(1)) < 0;
|
||||
check((convexA != convexB) == folds, $"the {name} fixture is {(folds ? "not" : "")} a fold: the two sides {(convexA == convexB ? "agree" : "disagree")} on convexity");
|
||||
int other = shape.Across[0];
|
||||
check(skin.Crease[0] == skin.Crease[other], $"the {name} fixture's two sides carry different creases, {skin.Crease[0]} and {skin.Crease[other]}");
|
||||
check(folds ? skin.Crease[0] == 0 : MathF.Abs(skin.Crease[0]) > 0.1f, $"the {name} fixture's crease is {skin.Crease[0]}: a fold has none, a turn keeps its own");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The mesh's connected pieces.</summary>
|
||||
public static int Pieces(PuppetShape shape)
|
||||
{
|
||||
var parent = Enumerable.Range(0, shape.Vertices.Length).ToArray();
|
||||
int Find(int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; }
|
||||
for (int t = 0; t < shape.Corners.Length; t += 3) { parent[Find(shape.Corners[t + 1])] = Find(shape.Corners[t]); parent[Find(shape.Corners[t + 2])] = Find(shape.Corners[t]); }
|
||||
return shape.Corners.Select(Find).Distinct().Count();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The worst a skinned triangle edge gets under <paramref name="bones"/> (per body, applied to the spread bind): its length over
|
||||
/// its bind length, and its length in metres. The ratio overstates when the bind edge is tiny; the length does not.
|
||||
/// </summary>
|
||||
public static (float Ratio, float Length) Stretch(PuppetShape shape, Rigid[] bones)
|
||||
{
|
||||
float3 Skin(int v) { float w = shape.WeightA[v]; var p = shape.Vertices[v]; return bones[shape.BoneA[v]].Apply(p) * w + bones[shape.BoneB[v]].Apply(p) * (1 - w); }
|
||||
float ratio = 0, length = 0;
|
||||
for (int t = 0; t < shape.Corners.Length; t += 3)
|
||||
for (int e = 0; e < 3; e++)
|
||||
{
|
||||
int a = shape.Corners[t + e], b = shape.Corners[t + (e + 1) % 3];
|
||||
float bind = math.length(shape.Vertices[a] - shape.Vertices[b]);
|
||||
float now = math.length(Skin(a) - Skin(b));
|
||||
length = MathF.Max(length, now);
|
||||
if (bind > 1e-5f) ratio = MathF.Max(ratio, now / bind);
|
||||
}
|
||||
return (ratio, length);
|
||||
}
|
||||
|
||||
private static int[] Parents(PuppetShape shape)
|
||||
{
|
||||
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;
|
||||
return up;
|
||||
}
|
||||
|
||||
/// <summary>Whether body <paramref name="i"/> is <paramref name="root"/> or hangs under it through the joints' first-parent tree.</summary>
|
||||
public static bool Under(PuppetShape shape, int i, int root)
|
||||
{
|
||||
var up = Parents(shape);
|
||||
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 Rigid Identity => Rigid.FromQuaternion(0, 0, 0, 1, new float3(0, 0, 0));
|
||||
|
||||
/// <summary>The bones of a pose with joint <paramref name="joint"/>'s child subtree turned by <paramref name="radians"/> about <paramref name="axis"/> through the joint origin.</summary>
|
||||
public static Rigid[] Swing(PuppetShape shape, int joint, float3 axis, float radians)
|
||||
{
|
||||
var turn = Rigid.About(shape.Joints[joint].Origin, axis, radians);
|
||||
return Enumerable.Range(0, shape.Ids.Length).Select(i => Under(shape, i, shape.Joints[joint].B) ? turn : Identity).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The bones of a pose with every joint bent by a random angle up to <paramref name="maxRadians"/> about a random axis, parents first.</summary>
|
||||
public static Rigid[] Bend(PuppetShape shape, int seed, float maxRadians)
|
||||
{
|
||||
var rng = new System.Random(seed);
|
||||
var bones = Enumerable.Range(0, shape.Ids.Length).Select(_ => Identity).ToArray();
|
||||
var up = Parents(shape);
|
||||
int Depth(int i) { int d = 0; while (up[i] >= 0 && d <= up.Length) { i = up[i]; d++; } return d; }
|
||||
foreach (int j in Enumerable.Range(0, shape.Joints.Length).OrderBy(j => Depth(shape.Joints[j].B)))
|
||||
{
|
||||
var joint = shape.Joints[j];
|
||||
if (up[joint.B] != joint.A) continue; // only the joint that decides the body's blend
|
||||
var axis = new float3((float)rng.NextDouble() * 2 - 1, (float)rng.NextDouble() * 2 - 1, (float)rng.NextDouble() * 2 - 1);
|
||||
axis = math.length(axis) < 1e-3f ? new float3(1, 0, 0) : math.normalize(axis);
|
||||
var turn = Rigid.About(bones[joint.A].Apply(joint.Origin), axis, ((float)rng.NextDouble() * 2 - 1) * maxRadians);
|
||||
for (int i = 0; i < bones.Length; i++) if (Under(shape, i, joint.B)) bones[i] = turn.After(bones[i]);
|
||||
}
|
||||
return bones;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,978 +0,0 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The puppet as the GPU draws it. The headless smoke has no renderer, so nothing there runs the shader, the attribute packing or the
|
||||
/// per-frame skin upload; this check does, in a window (Godot's gl_compatibility renderer, the client's own).
|
||||
/// It poses the carriers in a bent pose (every joint turned at random) under a moved and turned BodyRenderer, renders one frame of the
|
||||
/// puppet alone on black, and compares the rendered silhouette with the silhouette of the same mesh skinned on the CPU from the
|
||||
/// carriers and the spread bind (not from anything Puppet computed) and projected through the camera. Intersection over union must be
|
||||
/// at least <see cref="MinIou"/>. It also looks at the light, with the chamber near full glow: the bisque's faces (the glaze off) must not clip to white and must differ from each other, and the chamber's light must lift the puppet over the same frame with that light off (so the glow is bounded from below as well).
|
||||
/// It then turns the glaze on at the close view, from the front and from behind (see <see cref="GlazeCheck"/>): it must show, and the studio the camera carries must light the puppet from both sides.
|
||||
/// It also reads the shading normal the shader draws (ShowNormals: the view-space normal as emission) on the torso in the <see cref="Views"/> (close, far,
|
||||
/// bent 90 degrees, and at 1920x1080 mid and far) and compares it pixel by pixel with a CPU reference of the whole formula (see <see cref="NormalCheck"/>), on all the interior pixels
|
||||
/// and on the pixels of the corner blend and of sharp creases alone, and the drawn normals of adjacent pixels across triangle boundaries.
|
||||
/// Last it checks that the glaze does not flicker (see <see cref="FlickerCheck"/>): the puppet in the pose the player sees, drawn with the project's MSAA from 16 sub-pixel camera shifts in the play and close views, against the same shifts drawn 8 times the window's size.
|
||||
/// The frames above are drawn with MSAA off, since they check the shader's own pixels.
|
||||
/// <c>godot --path client res://tests/RenderCheck.tscn [-- --png=path] [-- --glaze-png=path] [-- --glaze-behind-png=path] [-- --normals-png=path] [-- --normals-far-png=path] [-- --normals-bend90-png=path] [-- --normals-mid-png=path] [-- --normals-far1080-png=path]</c>; exit code 0 passes, 1 fails. It needs a window, so it is
|
||||
/// not part of the headless smoke.
|
||||
/// </summary>
|
||||
public partial class RenderCheck : Node
|
||||
{
|
||||
/// <summary>
|
||||
/// A correct render measures 1.0000 in this pose, on every run so far, so the floor sits at the measurement's noise. Soul's
|
||||
/// gross skinning mutants (a flipped weight, no inverse bind, the creation pose as the bind, an inverted CUSTOM1 weight, an
|
||||
/// ignored parent) measure 0.10 to 0.61; the localized ones (a forearm bone 10 degrees off 0.982, a bone 2 cm off 0.973, hard
|
||||
/// weights 0.998) were under a floor of 0.95 and only fail at this one. Gap that remains: the culling box (a box of half the skinned bounds around their centre passes; a 1 cm box culls the close view and fails).
|
||||
/// </summary>
|
||||
private const float MinIou = 0.999f;
|
||||
|
||||
/// <summary>The bisque's lit faces (the glaze off): at most this share of its pixels may be at 250 or more of 255.</summary>
|
||||
private const float MaxClipped = 0.02f;
|
||||
|
||||
/// <summary>
|
||||
/// The glaze must show: with it on, at least this share of the puppet's pixels differ from the bisque's by <see cref="GlazeDifference"/> levels or more (it runs under
|
||||
/// gl_compatibility, whose clearcoat sees punctual lights only), and at most <see cref="MaxGlazedClipped"/> of them are clipped: the glaze's highlights are meant to
|
||||
/// clip, a puppet white from head to foot is not. Measured at the close view from the front and from behind.
|
||||
/// </summary>
|
||||
private const float MinGlazeShare = 0.03f, MaxGlazedClipped = 0.12f;
|
||||
|
||||
/// <summary>From behind the torso's back is one broad face that mirrors the key, so the glaze clips 20.4% there (measured): the bound has margin over that and fails a white-out.</summary>
|
||||
private const float MaxGlazedClippedBehind = 0.24f;
|
||||
|
||||
/// <summary>
|
||||
/// The glaze and the lights are one studio: the pixels the glaze lights most (<see cref="HighlightLevels"/> or more above the bisque) must reflect a direction that Look's studio
|
||||
/// emits light from. At each such pixel the drawn normal (the normal view, in view space) and the ray through the pixel give the reflected direction, which must fall within
|
||||
/// <see cref="EmitterSlack"/> times the footprint of the key's soft box or of a rim strip, at least <see cref="MinHighlightAgreement"/> of the pixels, of at least
|
||||
/// <see cref="MinHighlights"/>. A glaze that reflects a mirrored, world-fixed or otherwise different studio puts its highlights elsewhere.
|
||||
/// </summary>
|
||||
private const float HighlightLevels = 40f, EmitterSlack = 1.3f, MinHighlightAgreement = 0.97f;
|
||||
|
||||
private const int MinHighlights = 1000;
|
||||
|
||||
/// <summary>The crease pooling must show: with it off, at least this share of the bisque's pixels differ by <see cref="PoolDifference"/> levels or more at the close view from the front.</summary>
|
||||
private const float MinPoolShare = 0.03f, PoolDifference = 3f;
|
||||
|
||||
private const float GlazeDifference = 8f;
|
||||
|
||||
/// <summary>The puppet's facets must differ: its 10th to 90th percentile brightness spans at least this many of 255 levels.</summary>
|
||||
private const float MinSpread = 30f;
|
||||
|
||||
/// <summary>The chamber's glow must light the puppet: with the light on, the mean level of the puppet's pixels must exceed the same frame with the light off by at least this many of 255 levels (the shipped light lifts it 9.8). A glow of 0 fails.</summary>
|
||||
private const float MinGlowLift = 5f;
|
||||
|
||||
/// <summary>The 90th percentile angular error (degrees) of the drawn normal against the CPU reference, over the interior pixels.</summary>
|
||||
private const float MaxNormalP90 = 2f;
|
||||
|
||||
/// <summary>The median angular error (degrees) over the bevel band: pixels within 0.6 of the bevel width of an edge that turns by more than 0.1 radian.</summary>
|
||||
private const float MaxBandMedian = 0.6f;
|
||||
|
||||
/// <summary>The median angular error (degrees) over the pixels of triangles whose bevel width the smallest altitude caps.</summary>
|
||||
private const float MaxClampedMedian = 1.5f;
|
||||
|
||||
/// <summary>
|
||||
/// Vacuity: the band's reference normal must lie this many degrees (median) from the facet's, or a bevel that is off would pass; each
|
||||
/// <see cref="Views"/> entry also says how many interior, band, width-capped, corner-blend and sharp-crease pixels it must reach.
|
||||
/// </summary>
|
||||
private const float MinBandTilt = 4f;
|
||||
|
||||
/// <summary>
|
||||
/// The corner blend, the part that takes the bevel to the smooth vertex normal where edges meet, is held on its own pixels (those it moves
|
||||
/// past <see cref="CornerBlendFloor"/>), in a space and a radius the percentiles over all interior pixels do not see: the median angular error
|
||||
/// there is at most <see cref="MaxCornerMedian"/>, and the blend must move the normal by at least <see cref="MinCornerEffect"/> degrees (median) or
|
||||
/// the check cannot tell a blend that is off. The crease clamp is held the same way on the band pixels of edges whose half turn is
|
||||
/// between <see cref="SharpCrease"/> and <see cref="SharpCreaseTop"/> radians (115 to 137 degrees of turn: a clamp under 1 rad bites there, and
|
||||
/// the reference is still well conditioned, while at the clamp itself, 1.4 rad, the tilt is tan(c) = 5.8 and a pixel of drift in the
|
||||
/// distance moves the normal by tens of degrees), at most <see cref="MaxClampedMedian"/>.
|
||||
/// </summary>
|
||||
private const float CornerBlendFloor = 0.05f, MaxCornerMedian = 0.7f, MinCornerEffect = 0.8f, SharpCrease = 1.0f, SharpCreaseTop = 1.2f;
|
||||
|
||||
/// <summary>Across triangle boundaries: the pairs of adjacent pixels the check must reach (the shares and percentiles each view allows are in <see cref="Views"/>).</summary>
|
||||
private const int MinPairs = 20000;
|
||||
|
||||
/// <summary>The flicker check's reference is this many times the window on a side; each view must reach at least this many interior and highlight pixels (see <see cref="FlickerCheck"/>) or it proves nothing.</summary>
|
||||
private const int FlickerSupersample = 8, MinFlickerPixels = 15000, MinFlickerHighlights = 200;
|
||||
|
||||
private const float HighlightLuma = 245f;
|
||||
|
||||
/// <summary>
|
||||
/// The bounds on the flicker views, fitted to every pose and framing it draws (the session pose in seven framings, the puppet bent 30 and 60 degrees in three each) and not to one: the shipped shader reads
|
||||
/// 1.34 at the shipped framing and 1.19 at another. The p99 flicker ratio: shipped 1.19 to 1.35 play and 1.16 to 1.22 close; kernel 0 1.56 to 2.19 play and 1.30 to 1.49 close (the bent 60 close view reads 1.30, so
|
||||
/// it is the other views that fail it there), the bounds between (1.45, 1.33). The highlight shift in levels of 255: shipped at most 0.97; the paper's pixel variance 1/(2 pi) reads 1.52 to 4.31 in the five session
|
||||
/// play framings and 1.28 at most bent, and 1/12, double the shipped, 2.30 and 1.64 in two session framings and nothing bent, so 1.5; both overblurs are therefore caught only in the session pose. The silhouette
|
||||
/// ring, where MSAA works and the interior pixels do not look: the ring's mean |shown - reference| in levels of luma, shipped 16.7 to 18.9, widened or overblurred shaders up to 20.4, no MSAA 25.4 to 29.4, so 22
|
||||
/// (the ring's std against the reference's overlapped between shipped and no MSAA once the pose moved, so it is not the metric). The orbit's crawl, the halo's mean error second difference: shipped 5.6, kernel 0 10.5,
|
||||
/// no MSAA 6.1, the widened smoothstep 7.0, so 8.
|
||||
/// </summary>
|
||||
private const float MaxFlickerRatioPlay = 1.45f, MaxFlickerRatioClose = 1.33f, MaxHighlightShift = 1.5f, MaxSilhouetteError = 22f, MaxOrbitCrawl = 8f;
|
||||
|
||||
private const int OrbitFrames = 30, MinOrbitSamples = 1000;
|
||||
|
||||
private static readonly float OrbitStep = Mathf.DegToRad(0.15f);
|
||||
|
||||
private static readonly int[] FlickerBends = { 30, 60 };
|
||||
|
||||
/// <summary>The views (indices into <see cref="FlickerViews"/>) the bent poses are drawn in: the shipped play framing, the head-and-torso play framing and the close one on the hold point.</summary>
|
||||
private static readonly int[] FlickerBentViews = { 0, 3, 6 };
|
||||
|
||||
private const int BendSeed = 7;
|
||||
private const float BendDegrees = 60f;
|
||||
|
||||
public override void _Ready() => _ = RunAsync();
|
||||
|
||||
private async Task RunAsync()
|
||||
{
|
||||
bool ok = true;
|
||||
try
|
||||
{
|
||||
ok = await Check();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
GD.PrintErr("RENDER FAIL: " + e);
|
||||
ok = false;
|
||||
}
|
||||
GD.Print(ok ? "RENDER PASS" : "RENDER FAILED");
|
||||
GetTree().Quit(ok ? 0 : 1);
|
||||
}
|
||||
|
||||
private async Task<bool> Check()
|
||||
{
|
||||
var main = GD.Load<PackedScene>("res://Main.tscn").Instantiate<Main>();
|
||||
AddChild(main);
|
||||
if (main.Failure is { } failure) { GD.PrintErr("RENDER FAIL: Main could not start a session: " + failure); return false; }
|
||||
if (main.Bodies.PuppetShape is not { } shape) { GD.PrintErr("RENDER FAIL: the puppet has no mesh"); return false; }
|
||||
|
||||
// The puppet alone, on black, with a parent that is neither at the origin nor unturned.
|
||||
main.SetPhysicsProcess(false);
|
||||
GetViewport().Msaa3D = Viewport.Msaa.Disabled; // the oracle frames below check the shader's own pixels; the flicker check restores the project's setting
|
||||
main.Hud.Visible = false;
|
||||
// The chamber's volume is not the puppet, but its glow lights the puppet: run the box near full glow and keep the light.
|
||||
foreach (var volume in main.Chamber.GetChildren().OfType<MeshInstance3D>()) volume.Visible = false;
|
||||
main.SetIntensity(1.5);
|
||||
for (int i = 0; i < 1200; i++) main.Session.Step();
|
||||
main.Chamber.Sync(main.Session);
|
||||
if (main.Chamber.Glow < 0.9f) { GD.PrintErr($"RENDER FAIL: the chamber glows {main.Chamber.Glow}, not near full; the light probe proves nothing"); return false; }
|
||||
foreach (var scenery in main.Bodies.GetChildren().OfType<MeshInstance3D>()) scenery.Visible = false;
|
||||
main.GetChildren().OfType<WorldEnvironment>().Single().Environment.BackgroundColor = Colors.Black;
|
||||
main.Bodies.Transform = new Transform3D(new Basis(Vector3.Up, 0.45f), new Vector3(0.15f, 0f, 0.1f));
|
||||
|
||||
// The puppet is drawn once as it was created before it is bent: a surface that kept anything from its first pose, creases above all,
|
||||
// is wrong in the next, and nothing here would see it if the bent pose were the first.
|
||||
for (int i = 0; i < 3; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
|
||||
var carriers = shape.Ids.Select(id => main.Bodies.GetNode<Node3D>($"Puppet/Body{id}")).ToArray();
|
||||
var puppet = main.Bodies.GetNode<Puppet>("Puppet");
|
||||
puppet.Glazed = false; // the bounds on the lit facets are the bisque's; the glaze has its own check
|
||||
var world = await Pose(shape, carriers, BendDegrees);
|
||||
var frame = Capture(shape, world, "--png=");
|
||||
var (w, h, puppetPixels, levels) = (frame.Width, frame.Height, frame.Pixels, frame.Levels);
|
||||
int clipped = levels.Count(l => l >= 250f);
|
||||
float iou = frame.Iou;
|
||||
|
||||
float meanOn = levels.Count == 0 ? 0 : levels.Average();
|
||||
levels = levels.OrderBy(l => l).ToList();
|
||||
float lit = levels.Count;
|
||||
float spread = lit == 0 ? 0 : levels[(int)(lit * 0.9f)] - levels[(int)(lit * 0.1f)];
|
||||
float share = lit == 0 ? 1 : clipped / lit;
|
||||
|
||||
// The control: the same frame with the chamber's light off, over the same pixels.
|
||||
var glowLight = main.Chamber.GetChildren().OfType<OmniLight3D>().Single();
|
||||
float energy = glowLight.LightEnergy;
|
||||
glowLight.LightEnergy = 0f;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var dark = GetViewport().GetTexture().GetImage();
|
||||
dark.Convert(Image.Format.Rgba8);
|
||||
glowLight.LightEnergy = energy;
|
||||
float meanOff = puppetPixels.Count == 0 ? 0 : puppetPixels.Average(i => { var px = dark.GetPixel(i % w, i / w); return Mathf.Max(px.R, Mathf.Max(px.G, px.B)) * 255f; });
|
||||
float lift = meanOn - meanOff;
|
||||
|
||||
GD.Print($"RENDER glow lift {lift:F2} levels (mean {meanOn:F1} lit, {meanOff:F1} with the chamber light off)");
|
||||
GD.Print($"RENDER iou {iou:F4} (covered {frame.Covered}, drawn {frame.Drawn}), clipped {share:P1} of {lit} puppet pixels, 10th to 90th percentile level spread {spread:F0} of 255");
|
||||
bool ok = true;
|
||||
if (iou < MinIou) { GD.PrintErr($"RENDER FAIL: the drawn silhouette matches the CPU-skinned mesh with IoU {iou:F3}, under {MinIou}"); ok = false; }
|
||||
if (share > MaxClipped) { GD.PrintErr($"RENDER FAIL: {share:P1} of the bisque's pixels are clipped to white, over {MaxClipped:P0}; the facets cannot read"); ok = false; }
|
||||
if (spread < MinSpread) { GD.PrintErr($"RENDER FAIL: the puppet's pixels span only {spread:F0} levels between the 10th and 90th percentile, under {MinSpread}; the facets do not differ"); ok = false; }
|
||||
if (lift < MinGlowLift) { GD.PrintErr($"RENDER FAIL: the chamber's light lifts the puppet by {lift:F2} levels, under {MinGlowLift}; the box's glow does not light the body"); ok = false; }
|
||||
ok &= await GlazeCheck(main, shape, carriers, world);
|
||||
ok &= await NormalCheck(main, shape, carriers, world);
|
||||
ok &= await FlickerCheck(main, shape, carriers);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The glaze at the close view from the front and from behind (the camera is main's own, so the studio rig it carries turns with it): the bisque alone must still clip
|
||||
/// at most <see cref="MaxClipped"/> and spread at least <see cref="MinSpread"/> from both sides, and the glaze must change at least <see cref="MinGlazeShare"/> of the puppet's
|
||||
/// pixels and clip at most <see cref="MaxGlazedClipped"/> of them from the front, <see cref="MaxGlazedClippedBehind"/> from behind. It also checks that the glaze is one studio with the lights and that the crease pooling shows.
|
||||
/// </summary>
|
||||
private async Task<bool> GlazeCheck(Main main, PuppetShape shape, Node3D[] carriers, Transform3D[] world)
|
||||
{
|
||||
int torso = Array.IndexOf(shape.Ids, 101UL);
|
||||
var puppet = main.Bodies.GetNode<Puppet>("Puppet");
|
||||
var camera = main.GetNode<Camera3D>("Camera");
|
||||
camera.Fov = 30f;
|
||||
var target = carriers[torso].GlobalPosition;
|
||||
bool ok = true;
|
||||
var skin = (ShaderMaterial)puppet.GetNode<MeshInstance3D>("Skin").MaterialOverride;
|
||||
foreach (var (label, yaw, pngArg, maxClipped) in new[] { ("front", 0f, "--glaze-png=", MaxGlazedClipped), ("behind", Mathf.Pi, "--glaze-behind-png=", MaxGlazedClippedBehind) })
|
||||
{
|
||||
camera.GlobalPosition = target + new Basis(Vector3.Up, yaw) * new Vector3(0.35f, 0.2f, 0.55f);
|
||||
camera.LookAt(target, Vector3.Up);
|
||||
puppet.Glazed = false;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var bisque = Capture(shape, world, "--bisque-" + pngArg["--".Length..]);
|
||||
puppet.Glazed = true;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var glazed = Capture(shape, world, pngArg);
|
||||
|
||||
if (yaw == 0f)
|
||||
{
|
||||
// The pooling: the same bisque frame with the albedo's crease pooling off.
|
||||
var pool = skin.GetShaderParameter("glaze_pool");
|
||||
puppet.Glazed = false;
|
||||
skin.SetShaderParameter("glaze_pool", 0f);
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var flat = Capture(shape, world, "--bisque-nopool-png=");
|
||||
skin.SetShaderParameter("glaze_pool", pool);
|
||||
puppet.Glazed = true;
|
||||
float pooled = (float)bisque.Pixels.Count(i => Math.Abs(Level(flat.Image, i) - Level(bisque.Image, i)) >= PoolDifference) / Math.Max(1, bisque.Pixels.Count);
|
||||
GD.Print($"RENDER glaze pooling: {pooled:P2} of the bisque's pixels differ with it off");
|
||||
if (pooled < MinPoolShare) { GD.PrintErr($"RENDER FAIL: the crease pooling changes {pooled:P2} of the bisque's pixels, under {MinPoolShare:P0}; there is no pooling"); ok = false; }
|
||||
}
|
||||
|
||||
// The agreement: the normal view of the same frame gives the reflected direction at each pixel the glaze lights most.
|
||||
puppet.ShowNormals = true;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var normals = GetViewport().GetTexture().GetImage();
|
||||
normals.Convert(Image.Format.Rgba8);
|
||||
puppet.ShowNormals = false;
|
||||
int highlights = 0, agree = 0;
|
||||
var screen = GetViewport().GetVisibleRect().Size;
|
||||
foreach (int i in glazed.Pixels)
|
||||
{
|
||||
if (Level(glazed.Image, i) - Level(bisque.Image, i) < HighlightLevels) continue;
|
||||
int x = i % glazed.Width, y = i / glazed.Width;
|
||||
var c = normals.GetPixel(x, y);
|
||||
var n = new Vector3(c.R * 2f - 1f, c.G * 2f - 1f, c.B * 2f - 1f).Normalized();
|
||||
var toEye = -camera.ProjectLocalRayNormal(new Vector2(x + 0.5f, y + 0.5f) * screen / new Vector2(glazed.Width, glazed.Height));
|
||||
var r = 2f * n.Dot(toEye) * n - toEye;
|
||||
highlights++;
|
||||
if (InEmitter(r, Look.KeyDirection, new Vector2(Look.KeySize, Look.KeySize * 0.7f)) || InEmitter(r, Look.RimDirectionA, Look.RimSize) || InEmitter(r, Look.RimDirectionB, Look.RimSize)) agree++;
|
||||
}
|
||||
float agreement = highlights == 0 ? 0 : (float)agree / highlights;
|
||||
GD.Print($"RENDER glaze studio ({label}): {agreement:P1} of {highlights} highlight pixels reflect where Look's studio shines");
|
||||
if (highlights < MinHighlights) { GD.PrintErr($"RENDER FAIL: only {highlights} highlight pixels from {label}, under {MinHighlights}; the glaze's studio cannot be located"); ok = false; }
|
||||
else if (agreement < MinHighlightAgreement) { GD.PrintErr($"RENDER FAIL: {agreement:P1} of the glaze's highlights from {label} reflect a direction Look's studio does not light from, under {MinHighlightAgreement:P0}; the glaze and the lights are not one studio"); ok = false; }
|
||||
|
||||
var sorted = bisque.Levels.OrderBy(l => l).ToList();
|
||||
float bisqueClipped = (float)bisque.Levels.Count(l => l >= 250f) / Math.Max(1, sorted.Count);
|
||||
float bisqueSpread = sorted.Count == 0 ? 0 : sorted[(int)(sorted.Count * 0.9f)] - sorted[(int)(sorted.Count * 0.1f)];
|
||||
int changed = glazed.Pixels.Count(i => Math.Abs(Level(glazed.Image, i) - Level(bisque.Image, i)) >= GlazeDifference);
|
||||
float changedShare = (float)changed / Math.Max(1, glazed.Pixels.Count);
|
||||
float glazedClipped = (float)glazed.Levels.Count(l => l >= 250f) / Math.Max(1, glazed.Levels.Count);
|
||||
GD.Print($"RENDER glaze ({label}): bisque clipped {bisqueClipped:P1}, spread {bisqueSpread:F0}; glaze changes {changedShare:P1} of {glazed.Pixels.Count} puppet pixels, clips {glazedClipped:P1}");
|
||||
if (glazed.Pixels.Count < 20000) { GD.PrintErr($"RENDER FAIL: the glaze view ({label}) has only {glazed.Pixels.Count} puppet pixels; it proves nothing"); ok = false; }
|
||||
if (bisqueClipped > MaxClipped) { GD.PrintErr($"RENDER FAIL: {bisqueClipped:P1} of the bisque's pixels are clipped from {label}, over {MaxClipped:P0}"); ok = false; }
|
||||
if (bisqueSpread < MinSpread) { GD.PrintErr($"RENDER FAIL: the bisque's pixels span only {bisqueSpread:F0} levels from {label}, under {MinSpread}; the studio does not light that side"); ok = false; }
|
||||
if (changedShare < MinGlazeShare) { GD.PrintErr($"RENDER FAIL: the glaze changes {changedShare:P1} of the puppet's pixels from {label}, under {MinGlazeShare:P0}; there is no glaze"); ok = false; }
|
||||
if (glazedClipped > maxClipped) { GD.PrintErr($"RENDER FAIL: {glazedClipped:P1} of the glazed puppet's pixels are clipped from {label}, over {maxClipped:P0}; the porcelain is white-out"); ok = false; }
|
||||
}
|
||||
return ok; // the glaze stays on, as shipped: the normal views that follow must not see it
|
||||
}
|
||||
|
||||
/// <summary>Whether direction d (view space) falls in the footprint of a rectangular emitter along c, by the half sizes on the plane at unit distance (the shader's studio_box), with <see cref="EmitterSlack"/>.</summary>
|
||||
private static bool InEmitter(Vector3 d, Vector3 c, Vector2 half)
|
||||
{
|
||||
float f = d.Dot(c);
|
||||
if (f <= 0f) return false;
|
||||
var up = Mathf.Abs(c.Y) > 0.9f ? Vector3.Right : Vector3.Up;
|
||||
var u = up.Cross(c).Normalized();
|
||||
var v = c.Cross(u);
|
||||
var q = new Vector2(d.Dot(u), d.Dot(v)) / f;
|
||||
return Mathf.Abs(q.X) <= half.X * EmitterSlack && Mathf.Abs(q.Y) <= half.Y * EmitterSlack;
|
||||
}
|
||||
|
||||
private static float Level(Image image, int pixel)
|
||||
{
|
||||
var c = image.GetPixel(pixel % image.GetWidth(), pixel / image.GetWidth());
|
||||
return Mathf.Max(c.R, Mathf.Max(c.G, c.B)) * 255f;
|
||||
}
|
||||
|
||||
/// <summary>One drawn frame of the puppet: the pixels where the GPU drew it and the CPU-skinned mesh covers it, and their levels (the brightest channel, of 255).</summary>
|
||||
private sealed record Frame(int Width, int Height, List<int> Pixels, List<float> Levels, float Iou, int Covered, int Drawn, Image Image);
|
||||
|
||||
/// <summary>
|
||||
/// The viewport's frame against the same mesh skinned on the CPU from the carriers' world poses (nothing from Puppet), seen from the
|
||||
/// current camera. The frame is saved to the file a <paramref name="pngArg"/> user argument names, if one is given.
|
||||
/// </summary>
|
||||
private Frame Capture(PuppetShape shape, Transform3D[] world, string pngArg)
|
||||
{
|
||||
var image = GetViewport().GetTexture().GetImage();
|
||||
image.Convert(Image.Format.Rgba8);
|
||||
foreach (var arg in OS.GetCmdlineUserArgs())
|
||||
if (arg.StartsWith(pngArg)) image.SavePng(arg[pngArg.Length..]);
|
||||
|
||||
// What the GPU drew.
|
||||
int w = image.GetWidth(), h = image.GetHeight();
|
||||
var drawn = new bool[w * h];
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
var c = image.GetPixel(x, y);
|
||||
drawn[y * w + x] = Mathf.Max(c.R, Mathf.Max(c.G, c.B)) > 0.12f;
|
||||
}
|
||||
|
||||
// What the same mesh covers skinned on the CPU: bones from the carriers' world poses and the spread bind, nothing from Puppet.
|
||||
var camera = GetViewport().GetCamera3D();
|
||||
var scale = new Vector2(w, h) / GetViewport().GetVisibleRect().Size;
|
||||
var skinned = new Vector3[shape.Vertices.Length];
|
||||
for (int v = 0; v < skinned.Length; v++)
|
||||
{
|
||||
var p = new Vector3(shape.Vertices[v].x, shape.Vertices[v].y, shape.Vertices[v].z);
|
||||
skinned[v] = world[shape.BoneA[v]] * p * shape.WeightA[v] + world[shape.BoneB[v]] * p * (1f - shape.WeightA[v]);
|
||||
}
|
||||
var covered = new bool[w * h];
|
||||
for (int t = 0; t < shape.Corners.Length; t += 3)
|
||||
{
|
||||
var a = camera.UnprojectPosition(skinned[shape.Corners[t]]) * scale; var b = camera.UnprojectPosition(skinned[shape.Corners[t + 1]]) * scale; var c = camera.UnprojectPosition(skinned[shape.Corners[t + 2]]) * scale;
|
||||
Fill(covered, w, h, a, b, c);
|
||||
}
|
||||
|
||||
int both = 0, either = 0;
|
||||
var pixels = new List<int>();
|
||||
var levels = new List<float>();
|
||||
for (int i = 0; i < covered.Length; i++)
|
||||
{
|
||||
if (covered[i] || drawn[i]) either++;
|
||||
if (!covered[i] || !drawn[i]) continue;
|
||||
both++;
|
||||
pixels.Add(i);
|
||||
var px = image.GetPixel(i % w, i / w);
|
||||
levels.Add(Mathf.Max(px.R, Mathf.Max(px.G, px.B)) * 255f);
|
||||
}
|
||||
return new Frame(w, h, pixels, levels, either == 0 ? 0 : (float)both / either, covered.Count(x => x), drawn.Count(x => x), image);
|
||||
}
|
||||
|
||||
/// <summary>The reference surface in the world: the carriers' skin of the shape, welded by position, with its own facets, altitudes, vertex normals and creases.</summary>
|
||||
private sealed record Surface(Vector3[] P, int[] Weld, Vector3[] Facet, float[] Altitude, float[] Smallest, Vector3[] VertexNormal, float[] Crease);
|
||||
|
||||
/// <summary>
|
||||
/// One look at the drawn normal: where from (the offset from the torso and the field of view), in which pose and at which window size, and
|
||||
/// what it must reach to prove anything (interior, bevel-band, width-capped, corner-blend and sharply creased pixels) and, if it
|
||||
/// reads the continuity across triangles, the bar for it in that pose.
|
||||
/// </summary>
|
||||
private readonly record struct NormalViewSpec(string Label, Vector3 Offset, float Fov, int Bend, Vector2I Size, string PngArg, bool Continuity, float MaxAcross30, float MaxAcrossP90,
|
||||
int MinKept, int MinBand, int MinClamped, int MinCorner, int MinSharp);
|
||||
|
||||
private static readonly Vector2I Hd = new(1280, 720), FullHd = new(1920, 1080);
|
||||
|
||||
/// <summary>
|
||||
/// The views. Close (0.35, 0.2, 0.55 m off body 101, FOV 30) is at the 3 mm floor of the bevel; far (about 3.7 m) is where the screen width
|
||||
/// decides, and the same far view at 1080 lines is where a width fixed at 720 lines is wrong; mid (2.2 m) is in between, where the floor and
|
||||
/// the screen width are within a tenth of each other and the width changes across the frame. Bend 90 is a pose of sharp creases: the
|
||||
/// crease clamp is reached there, and the continuity across triangles has its own bar, since some edges fold past 120 degrees and 2 px
|
||||
/// cannot soften them.
|
||||
/// </summary>
|
||||
private static readonly NormalViewSpec[] Views =
|
||||
{
|
||||
new("close", new Vector3(0.35f, 0.2f, 0.55f), 30f, 60, Hd, "--normals-png=", true, 0.005f, 6f, 200000, 20000, 200, 5000, 1000),
|
||||
new("far", new Vector3(1.9f, 1.1f, 3.0f), 30f, 60, Hd, "--normals-far-png=", false, 0f, 0f, 10000, 100, 150, 400, 0),
|
||||
new("bend 90 close", new Vector3(0.35f, 0.2f, 0.55f), 30f, 90, Hd, "--normals-bend90-png=", true, 0.03f, 7f, 200000, 20000, 200, 5000, 100),
|
||||
new("mid 1080", new Vector3(1.13f, 0.645f, 1.77f), 30f, 60, FullHd, "--normals-mid-png=", false, 0f, 0f, 30000, 100, 100, 3000, 40),
|
||||
new("far 1080", new Vector3(1.9f, 1.1f, 3.0f), 30f, 60, FullHd, "--normals-far1080-png=", false, 0f, 0f, 20000, 1000, 150, 3000, 20),
|
||||
};
|
||||
|
||||
private async Task<Transform3D[]> Pose(PuppetShape shape, Node3D[] carriers, float degrees)
|
||||
{
|
||||
var bones = PuppetChecks.Bend(shape, BendSeed, degrees * Mathf.Pi / 180f);
|
||||
for (int i = 0; i < carriers.Length; i++)
|
||||
{
|
||||
carriers[i].Transform = Puppet.ToTransform(bones[i].After(shape.SpreadBind[i]));
|
||||
carriers[i].ResetPhysicsInterpolation();
|
||||
}
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
return carriers.Select((c, i) => c.GlobalTransform * Puppet.ToTransform(shape.SpreadBind[i].Inverse())).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drawn shading normal against the shader's formula evaluated on the CPU, from this check's own skinning of the shape's vertices
|
||||
/// by the carriers (nothing the puppet computed): its own weld of the corners by position, its own edge match, facets, creases,
|
||||
/// area-weighted vertex normals, altitudes, the screen width and the corner blend. The puppet is seen in the bent pose from the
|
||||
/// torso's front-top in each of the <see cref="Views"/>; the view-space normal is read raw from the frame (n * 0.5 + 0.5, not
|
||||
/// sRGB-decoded) and turned to world by the camera's basis.
|
||||
/// </summary>
|
||||
private async Task<bool> NormalCheck(Main main, PuppetShape shape, Node3D[] carriers, Transform3D[] world)
|
||||
{
|
||||
int torso = Array.IndexOf(shape.Ids, 101UL);
|
||||
if (torso < 0) { GD.PrintErr("RENDER FAIL: the puppet has no body 101 to look at"); return false; }
|
||||
var puppet = main.Bodies.GetNode<Puppet>("Puppet");
|
||||
var window = GetWindow(); var home = window.Size;
|
||||
int bend = (int)BendDegrees;
|
||||
var surface = BuildSurface(shape, world);
|
||||
|
||||
bool ok = true;
|
||||
foreach (var spec in Views)
|
||||
{
|
||||
if (spec.Bend != bend)
|
||||
{
|
||||
bend = spec.Bend;
|
||||
surface = BuildSurface(shape, await Pose(shape, carriers, bend));
|
||||
}
|
||||
if (window.Size != spec.Size)
|
||||
{
|
||||
window.Size = spec.Size;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
}
|
||||
var camera = new Camera3D { Fov = spec.Fov, Current = true };
|
||||
AddChild(camera);
|
||||
var target = carriers[torso].GlobalPosition;
|
||||
camera.GlobalPosition = target + spec.Offset;
|
||||
camera.LookAt(target, Vector3.Up);
|
||||
puppet.ShowNormals = true;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var image = GetViewport().GetTexture().GetImage();
|
||||
image.Convert(Image.Format.Rgba8);
|
||||
puppet.ShowNormals = false;
|
||||
foreach (var arg in OS.GetCmdlineUserArgs())
|
||||
if (arg.StartsWith(spec.PngArg)) image.SavePng(arg[spec.PngArg.Length..]);
|
||||
if (image.GetSize() != spec.Size) { GD.PrintErr($"RENDER FAIL: the {spec.Label} view was drawn at {image.GetSize()}, not the {spec.Size} it is for"); ok = false; }
|
||||
else ok &= NormalView(spec, image, camera, surface);
|
||||
camera.QueueFree();
|
||||
}
|
||||
window.Size = home;
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>One framing of the flicker check: what the camera aims at, from which side, how high, how far (FOV 55 throughout, OrbitCamera's).</summary>
|
||||
private readonly record struct FlickerView(string Label, FlickerAim Aim, float Yaw, float Pitch, float Distance);
|
||||
|
||||
private enum FlickerAim { Hold, Head, Torso }
|
||||
|
||||
/// <summary>
|
||||
/// The framings. The first is where OrbitCamera starts (the hold point, yaw 0.35, pitch 0.2, 2.4 m); the rest move the aim, the side, the height and the distance, because the highlights
|
||||
/// that flicker are where the facets happen to face the studio, and a bound fitted to one framing fails the shipped shader in another (the shipped framing reads 1.34, the head-and-torso
|
||||
/// framing at yaw 0.5 reads 1.19). The last two look at the head and shoulders from 0.7 m.
|
||||
/// </summary>
|
||||
private static readonly FlickerView[] FlickerViews =
|
||||
{
|
||||
new("play", FlickerAim.Hold, 0.35f, 0.2f, 2.4f),
|
||||
new("play side", FlickerAim.Hold, -0.5f, 0.2f, 2.4f),
|
||||
new("play level", FlickerAim.Hold, 0.35f, 0f, 2.4f),
|
||||
new("play head", FlickerAim.Head, 0.5f, 0.15f, 2.4f),
|
||||
new("play torso", FlickerAim.Torso, 0.35f, 0.2f, 2.4f),
|
||||
new("close", FlickerAim.Head, 0.5f, 0.15f, 0.7f),
|
||||
new("close hold", FlickerAim.Hold, 0.35f, 0.2f, 0.7f),
|
||||
};
|
||||
|
||||
/// <summary>The camera, the supersampled twin that sees what it sees, and the points the views aim at.</summary>
|
||||
private sealed record FlickerRig(Camera3D Camera, Camera3D ReferenceCamera, SubViewport Reference, Viewport Viewport, int W, int H, Vector3 Hold, Vector3 Head, Vector3 Torso)
|
||||
{
|
||||
public void Place(FlickerView view, float yaw, Vector2 shift)
|
||||
{
|
||||
var target = view.Aim switch { FlickerAim.Hold => Hold, FlickerAim.Head => Head * 0.45f + Torso * 0.55f, _ => Torso };
|
||||
Camera.Fov = 55f;
|
||||
var direction = new Vector3(Mathf.Sin(yaw) * Mathf.Cos(view.Pitch), Mathf.Sin(view.Pitch), Mathf.Cos(yaw) * Mathf.Cos(view.Pitch));
|
||||
Camera.GlobalPosition = target + direction * view.Distance;
|
||||
Camera.LookAt(target, Vector3.Up);
|
||||
float pixel = 2f * view.Distance * Mathf.Tan(Mathf.DegToRad(55f) / 2f) / H;
|
||||
Camera.GlobalPosition += Camera.GlobalBasis.X * shift.X * pixel + Camera.GlobalBasis.Y * shift.Y * pixel;
|
||||
ReferenceCamera.Fov = Camera.Fov;
|
||||
ReferenceCamera.GlobalTransform = Camera.GlobalTransform;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The glaze must not flicker: a highlight whose pixel value jumps as the camera moves by a fraction of a pixel crawls on screen. The puppet in the pose the player sees (the shipped shader and the
|
||||
/// project's MSAA) is drawn in each of the <see cref="FlickerViews"/> from 16 camera positions on a sub-pixel grid, and by a viewport <see cref="FlickerSupersample"/> times the window's size, MSAA off, box-filtered
|
||||
/// down in linear light, which is what a pixel would show if it averaged the scene over its own area. On the pixels the puppet covers fully in every reference frame (eroded by one pixel), the 99th percentile of the
|
||||
/// per-pixel standard deviation of luma over the shifts must be at most <see cref="MaxFlickerRatioPlay"/> (<see cref="MaxFlickerRatioClose"/> from 0.7 m) times the reference's, and the mean luma over the pixels the reference
|
||||
/// lights to <see cref="HighlightLuma"/> or more within <see cref="MaxHighlightShift"/> levels of the reference's. On the silhouette's ring, which MSAA owns, the mean |shown - reference| is at most
|
||||
/// <see cref="MaxSilhouetteError"/> levels. The same views are drawn with the puppet bent 30 and 60 degrees (<see cref="FlickerBends"/>), and <see cref="FlickerOrbit"/> turns the camera slowly at the shipped framing.
|
||||
/// </summary>
|
||||
private async Task<bool> FlickerCheck(Main main, PuppetShape shape, Node3D[] bodies)
|
||||
{
|
||||
var window = GetWindow();
|
||||
var home = window.Size;
|
||||
window.Size = Hd;
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var puppet = main.Bodies.GetNode<Puppet>("Puppet");
|
||||
var camera = main.GetNode<Camera3D>("Camera");
|
||||
camera.Current = true;
|
||||
puppet.ShowNormals = false;
|
||||
// The pose the player sees: the session's own, under an unmoved body renderer, not the bent pose of the oracle frames.
|
||||
main.Bodies.Transform = Transform3D.Identity;
|
||||
main.Bodies.Sync(main.Session.View, teleport: true);
|
||||
for (int i = 0; i < 4; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var viewport = GetViewport();
|
||||
viewport.Msaa3D = (Viewport.Msaa)(int)ProjectSettings.GetSetting("rendering/anti_aliasing/quality/msaa_3d");
|
||||
int w = viewport.GetTexture().GetWidth(), h = viewport.GetTexture().GetHeight();
|
||||
|
||||
var carriers = puppet.GetChildren().OfType<Node3D>().Where(c => c.Name.ToString().StartsWith("Body")).ToArray();
|
||||
var reference = new SubViewport { Size = new Vector2I(w * FlickerSupersample, h * FlickerSupersample), RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled, Msaa3D = Viewport.Msaa.Disabled };
|
||||
var referenceCamera = new Camera3D { Current = true, Fov = 55f };
|
||||
reference.AddChild(referenceCamera);
|
||||
AddChild(reference);
|
||||
var rig = new FlickerRig(camera, referenceCamera, reference, viewport, w, h,
|
||||
new Vector3(BodyPainBox.HoldPoint.X, BodyPainBox.HoldPoint.Y, BodyPainBox.HoldPoint.Z),
|
||||
carriers.OrderByDescending(c => c.GlobalPosition.Y).First().GlobalPosition, puppet.GetNode<Node3D>("Body101").GlobalPosition);
|
||||
|
||||
bool ok = true;
|
||||
puppet.Glazed = true;
|
||||
foreach (var view in FlickerViews) ok &= await FlickerShifts(rig, view, view.Label);
|
||||
ok &= await FlickerOrbit(rig, FlickerViews[0]);
|
||||
// The same puppet bent, under a moved parent, as the oracle frames pose it: its highlights fall elsewhere, and a bound fitted to the session pose alone fails the shipped shader here.
|
||||
main.Bodies.Transform = new Transform3D(new Basis(Vector3.Up, 0.45f), new Vector3(0.15f, 0f, 0.1f));
|
||||
foreach (int degrees in FlickerBends)
|
||||
{
|
||||
await Pose(shape, bodies, degrees);
|
||||
for (int i = 0; i < 8; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw); // let the skin follow the carriers before the first reference frame
|
||||
var bent = rig with { Head = bodies.OrderByDescending(c => c.GlobalPosition.Y).First().GlobalPosition, Torso = bodies[Array.IndexOf(shape.Ids, 101UL)].GlobalPosition };
|
||||
foreach (int v in FlickerBentViews) ok &= await FlickerShifts(bent, FlickerViews[v], $"bent {degrees} {FlickerViews[v].Label}");
|
||||
}
|
||||
reference.QueueFree();
|
||||
window.Size = home;
|
||||
return ok;
|
||||
}
|
||||
|
||||
private async Task<bool> FlickerShifts(FlickerRig rig, FlickerView view, string label)
|
||||
{
|
||||
int w = rig.W, h = rig.H;
|
||||
var shifts = new List<Vector2>();
|
||||
for (int j = 0; j < 4; j++) for (int i = 0; i < 4; i++) shifts.Add(new Vector2((i + 0.5f) / 4f - 0.5f, (j + 0.5f) / 4f - 0.5f));
|
||||
var supersampled = new List<float[]>();
|
||||
var coverage = new List<float[]>();
|
||||
foreach (var shift in shifts)
|
||||
{
|
||||
rig.Place(view, view.Yaw, shift);
|
||||
var (luma, cover) = await Supersample(rig.Reference, w, h);
|
||||
supersampled.Add(luma);
|
||||
coverage.Add(cover);
|
||||
}
|
||||
var drawn = new List<float[]>();
|
||||
foreach (var shift in shifts)
|
||||
{
|
||||
rig.Place(view, view.Yaw, shift);
|
||||
drawn.Add(await Draw(rig));
|
||||
}
|
||||
|
||||
var eroded = Interior(w, h, coverage);
|
||||
var ring = new bool[w * h];
|
||||
for (int i = 0; i < ring.Length; i++) ring[i] = !eroded[i] && coverage.Any(c => c[i] > 0.001f) && !coverage.All(c => c[i] >= 0.999f);
|
||||
var highlight = new bool[w * h];
|
||||
for (int i = 0; i < highlight.Length; i++) highlight[i] = eroded[i] && supersampled.Any(l => l[i] >= HighlightLuma);
|
||||
|
||||
int pixels = eroded.Count(b => b), highlights = highlight.Count(b => b);
|
||||
float shownP99 = P99(Deviation(drawn, eroded)), referenceP99 = P99(Deviation(supersampled, eroded));
|
||||
float ratio = shownP99 / Mathf.Max(referenceP99, 1e-3f);
|
||||
float ringError = RingError(drawn, supersampled, ring);
|
||||
float highlightShift = highlights == 0 ? 0 : Mathf.Abs(Mean(drawn, highlight) - Mean(supersampled, highlight));
|
||||
float maxRatio = view.Distance < 1f ? MaxFlickerRatioClose : MaxFlickerRatioPlay;
|
||||
GD.Print($"RENDER flicker ({label}): {pixels} interior pixels, {highlights} highlight; p99 luma std {shownP99:F1} against the {FlickerSupersample}x reference's {referenceP99:F1} (ratio {ratio:F2}); highlight mean shift {highlightShift:F2}; silhouette ring mean error {ringError:F2}");
|
||||
bool ok = true;
|
||||
if (pixels < MinFlickerPixels || highlights < MinFlickerHighlights) { GD.PrintErr($"RENDER FAIL: the {label} flicker view reaches {pixels} interior and {highlights} highlight pixels, under {MinFlickerPixels} and {MinFlickerHighlights}; it proves nothing"); ok = false; }
|
||||
if (ratio > maxRatio) { GD.PrintErr($"RENDER FAIL: the highlights flicker in the {label} view: p99 luma std {shownP99:F1} is {ratio:F2} times the supersampled reference's {referenceP99:F1}, over {maxRatio}"); ok = false; }
|
||||
if (highlightShift > MaxHighlightShift) { GD.PrintErr($"RENDER FAIL: the {label} view's highlights are {highlightShift:F2} levels from the reference's, over {MaxHighlightShift}; the glaze is blurred away or brighter than the studio"); ok = false; }
|
||||
if (ringError > MaxSilhouetteError) { GD.PrintErr($"RENDER FAIL: the {label} view's silhouette is {ringError:F2} levels from the supersampled reference's on average, over {MaxSilhouetteError}; the 3D is not antialiased"); ok = false; }
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A slow continuous orbit at the shipped framing (<see cref="OrbitFrames"/> frames of 0.15 degrees, no sub-pixel grid): the crawl the player sees. At each pixel the error against the supersampled
|
||||
/// reference, shown minus reference, is differenced twice in time, |e(t) - (e(t-1) + e(t+1)) / 2|; the true motion cancels, and what is left is the pixel's own shimmer. It is read on the halo of the
|
||||
/// highlights (pixels the reference leaves under <see cref="HighlightLuma"/> with a 4-neighbour at or over it, fully covered in the three frames), where a point-sampled highlight's edge steps from pixel to pixel;
|
||||
/// a mask on the reference's lit pixels would rather rank blur (a filtered highlight is dimmer there, an unfiltered one saturates and is quiet). The mean must be at most <see cref="MaxOrbitCrawl"/> levels.
|
||||
/// </summary>
|
||||
private async Task<bool> FlickerOrbit(FlickerRig rig, FlickerView view)
|
||||
{
|
||||
int w = rig.W, h = rig.H;
|
||||
var supersampled = new List<float[]>();
|
||||
var coverage = new List<float[]>();
|
||||
var drawn = new List<float[]>();
|
||||
for (int f = 0; f < OrbitFrames; f++)
|
||||
{
|
||||
rig.Place(view, view.Yaw + OrbitStep * f, Vector2.Zero);
|
||||
var (luma, cover) = await Supersample(rig.Reference, w, h);
|
||||
supersampled.Add(luma);
|
||||
coverage.Add(cover);
|
||||
drawn.Add(await Draw(rig));
|
||||
}
|
||||
double sum = 0;
|
||||
long count = 0;
|
||||
for (int f = 1; f < OrbitFrames - 1; f++)
|
||||
{
|
||||
var interior = Interior(w, h, new[] { coverage[f - 1], coverage[f], coverage[f + 1] });
|
||||
var lit = supersampled[f];
|
||||
for (int i = w + 1; i < interior.Length - w - 1; i++)
|
||||
{
|
||||
if (!interior[i] || lit[i] >= HighlightLuma) continue;
|
||||
if (lit[i - 1] < HighlightLuma && lit[i + 1] < HighlightLuma && lit[i - w] < HighlightLuma && lit[i + w] < HighlightLuma) continue;
|
||||
float e0 = drawn[f - 1][i] - supersampled[f - 1][i], e1 = drawn[f][i] - lit[i], e2 = drawn[f + 1][i] - supersampled[f + 1][i];
|
||||
sum += Mathf.Abs(e1 - 0.5f * (e0 + e2));
|
||||
count++;
|
||||
}
|
||||
}
|
||||
float crawl = count == 0 ? 0 : (float)(sum / count);
|
||||
GD.Print($"RENDER flicker (orbit, {OrbitFrames} frames of 0.15 degrees): {count} halo samples; mean error second difference {crawl:F2} levels");
|
||||
bool ok = true;
|
||||
if (count < MinOrbitSamples) { GD.PrintErr($"RENDER FAIL: the orbit reaches {count} halo samples, under {MinOrbitSamples}; it proves nothing"); ok = false; }
|
||||
if (crawl > MaxOrbitCrawl) { GD.PrintErr($"RENDER FAIL: the highlights crawl under a slow orbit: the halo's error second difference averages {crawl:F2} levels, over {MaxOrbitCrawl}"); ok = false; }
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>The mean over the frames and the ring's pixels of |shown - reference|, in levels of luma: the silhouette's own antialiasing, which MSAA does and the shader does not.</summary>
|
||||
private static float RingError(List<float[]> shown, List<float[]> reference, bool[] ring)
|
||||
{
|
||||
double sum = 0;
|
||||
long count = 0;
|
||||
for (int k = 0; k < shown.Count; k++)
|
||||
for (int i = 0; i < ring.Length; i++)
|
||||
if (ring[i]) { sum += Mathf.Abs(shown[k][i] - reference[k][i]); count++; }
|
||||
return count == 0 ? 0 : (float)(sum / count);
|
||||
}
|
||||
|
||||
private async Task<float[]> Draw(FlickerRig rig)
|
||||
{
|
||||
for (int i = 0; i < 3; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var image = rig.Viewport.GetTexture().GetImage();
|
||||
image.Convert(Image.Format.Rgba8);
|
||||
return Luma(image.GetData(), rig.W * rig.H);
|
||||
}
|
||||
|
||||
/// <summary>The pixels the puppet covers fully in every one of the coverage maps, eroded by one pixel.</summary>
|
||||
private static bool[] Interior(int w, int h, IEnumerable<float[]> covers)
|
||||
{
|
||||
var full = new bool[w * h];
|
||||
Array.Fill(full, true);
|
||||
foreach (var cover in covers) for (int i = 0; i < full.Length; i++) full[i] &= cover[i] >= 0.999f;
|
||||
var eroded = new bool[w * h];
|
||||
for (int y = 1; y < h - 1; y++)
|
||||
for (int x = 1; x < w - 1; x++)
|
||||
{
|
||||
int i = y * w + x;
|
||||
eroded[i] = full[i] && full[i - 1] && full[i + 1] && full[i - w] && full[i + w];
|
||||
}
|
||||
return eroded;
|
||||
}
|
||||
|
||||
/// <summary>The reference frame of the current camera: the supersampled viewport box-filtered to the window's size in linear light, as luma (Rec. 709 weights on the encoded levels, 0 to 255) and the share of its samples the puppet covers (any channel over 31 of 255, on black).</summary>
|
||||
private async Task<(float[] Luma, float[] Cover)> Supersample(SubViewport reference, int w, int h)
|
||||
{
|
||||
reference.RenderTargetUpdateMode = SubViewport.UpdateMode.Once;
|
||||
for (int i = 0; i < 2; i++) await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||||
var big = reference.GetTexture().GetImage();
|
||||
big.Convert(Image.Format.Rgba8);
|
||||
var data = big.GetData();
|
||||
big.Dispose();
|
||||
int factor = FlickerSupersample, row = w * factor;
|
||||
var luma = new float[w * h];
|
||||
var cover = new float[w * h];
|
||||
float inverse = 1f / (factor * factor);
|
||||
Parallel.For(0, h, y =>
|
||||
{
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
float r = 0, g = 0, b = 0, covered = 0;
|
||||
for (int sy = 0; sy < factor; sy++)
|
||||
for (int sx = 0; sx < factor; sx++)
|
||||
{
|
||||
int o = ((y * factor + sy) * row + x * factor + sx) * 4;
|
||||
r += SrgbToLinear[data[o]]; g += SrgbToLinear[data[o + 1]]; b += SrgbToLinear[data[o + 2]];
|
||||
if (Math.Max(data[o], Math.Max(data[o + 1], data[o + 2])) > 31) covered++;
|
||||
}
|
||||
luma[y * w + x] = 0.2126f * LinearToSrgb(r * inverse) + 0.7152f * LinearToSrgb(g * inverse) + 0.0722f * LinearToSrgb(b * inverse);
|
||||
cover[y * w + x] = covered * inverse;
|
||||
}
|
||||
});
|
||||
return (luma, cover);
|
||||
}
|
||||
|
||||
private static readonly float[] SrgbToLinear = Enumerable.Range(0, 256).Select(i => { float c = i / 255f; return c <= 0.04045f ? c / 12.92f : Mathf.Pow((c + 0.055f) / 1.055f, 2.4f); }).ToArray();
|
||||
|
||||
private static float LinearToSrgb(float c) => 255f * (c <= 0.0031308f ? c * 12.92f : 1.055f * Mathf.Pow(c, 1f / 2.4f) - 0.055f);
|
||||
|
||||
private static float[] Luma(byte[] rgba, int count)
|
||||
{
|
||||
var luma = new float[count];
|
||||
for (int i = 0; i < count; i++) luma[i] = 0.2126f * rgba[4 * i] + 0.7152f * rgba[4 * i + 1] + 0.0722f * rgba[4 * i + 2];
|
||||
return luma;
|
||||
}
|
||||
|
||||
/// <summary>The standard deviation over the frames of each masked pixel.</summary>
|
||||
private static List<float> Deviation(List<float[]> frames, bool[] mask)
|
||||
{
|
||||
var result = new List<float>();
|
||||
for (int i = 0; i < mask.Length; i++)
|
||||
{
|
||||
if (!mask[i]) continue;
|
||||
float mean = 0;
|
||||
foreach (var f in frames) mean += f[i];
|
||||
mean /= frames.Count;
|
||||
float sum = 0;
|
||||
foreach (var f in frames) sum += (f[i] - mean) * (f[i] - mean);
|
||||
result.Add(Mathf.Sqrt(sum / frames.Count));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static float P99(List<float> values)
|
||||
{
|
||||
if (values.Count == 0) return 0;
|
||||
values.Sort();
|
||||
return values[(int)(values.Count * 0.99f)];
|
||||
}
|
||||
|
||||
private static float Mean(List<float[]> frames, bool[] mask)
|
||||
{
|
||||
double sum = 0;
|
||||
long count = 0;
|
||||
foreach (var f in frames) for (int i = 0; i < mask.Length; i++) if (mask[i]) { sum += f[i]; count++; }
|
||||
return count == 0 ? 0 : (float)(sum / count);
|
||||
}
|
||||
|
||||
private static Surface BuildSurface(PuppetShape shape, Transform3D[] world)
|
||||
{
|
||||
int n = shape.Corners.Length, triangles = n / 3;
|
||||
var skinned = new Vector3[shape.Vertices.Length];
|
||||
for (int v = 0; v < skinned.Length; v++)
|
||||
{
|
||||
var p = new Vector3(shape.Vertices[v].x, shape.Vertices[v].y, shape.Vertices[v].z);
|
||||
skinned[v] = world[shape.BoneA[v]] * p * shape.WeightA[v] + world[shape.BoneB[v]] * p * (1f - shape.WeightA[v]);
|
||||
}
|
||||
var P = new Vector3[n];
|
||||
for (int s = 0; s < n; s++) P[s] = skinned[shape.Corners[s]];
|
||||
var welds = new System.Collections.Generic.Dictionary<(long, long, long), int>();
|
||||
var weld = new int[n];
|
||||
for (int s = 0; s < n; s++)
|
||||
{
|
||||
var key = ((long)Math.Round(P[s].X * 1e5), (long)Math.Round(P[s].Y * 1e5), (long)Math.Round(P[s].Z * 1e5));
|
||||
if (!welds.TryGetValue(key, out weld[s])) welds[key] = weld[s] = welds.Count;
|
||||
}
|
||||
var facet = new Vector3[triangles]; var altitude = new float[n]; var smallest = new float[triangles];
|
||||
var vertexNormal = new Vector3[welds.Count];
|
||||
for (int t = 0; t < triangles; t++)
|
||||
{
|
||||
var outward = -(P[3 * t + 1] - P[3 * t]).Cross(P[3 * t + 2] - P[3 * t]);
|
||||
float twiceArea = outward.Length();
|
||||
facet[t] = outward / twiceArea;
|
||||
smallest[t] = float.MaxValue;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
vertexNormal[weld[3 * t + k]] += outward;
|
||||
altitude[3 * t + k] = twiceArea / (P[3 * t + (k + 1) % 3] - P[3 * t + (k + 2) % 3]).Length();
|
||||
smallest[t] = Math.Min(smallest[t], altitude[3 * t + k]);
|
||||
}
|
||||
}
|
||||
for (int v = 0; v < vertexNormal.Length; v++) vertexNormal[v] = vertexNormal[v].Normalized();
|
||||
var sides = new System.Collections.Generic.Dictionary<(int, int), System.Collections.Generic.List<int>>();
|
||||
for (int s = 0; s < n; s++)
|
||||
{
|
||||
int t = s / 3, k = s % 3, p = weld[3 * t + (k + 1) % 3], q = weld[3 * t + (k + 2) % 3];
|
||||
var key = p < q ? (p, q) : (q, p);
|
||||
if (!sides.TryGetValue(key, out var list)) sides[key] = list = new System.Collections.Generic.List<int>();
|
||||
list.Add(s);
|
||||
}
|
||||
// An edge two triangles share turns by half the angle between their facets, positive where it is convex (the neighbour's far corner
|
||||
// lies behind this facet's plane); a fold, whose sides disagree on that, and an edge with other than two sides turn by nothing.
|
||||
var crease = new float[n];
|
||||
foreach (var list in sides.Values)
|
||||
{
|
||||
if (list.Count != 2) continue;
|
||||
int a = list[0], b = list[1];
|
||||
bool convexA = facet[a / 3].Dot(P[b] - P[3 * (a / 3) + (a % 3 + 1) % 3]) < 0, convexB = facet[b / 3].Dot(P[a] - P[3 * (b / 3) + (b % 3 + 1) % 3]) < 0;
|
||||
if (convexA != convexB) continue;
|
||||
float half = 0.5f * facet[a / 3].AngleTo(facet[b / 3]);
|
||||
crease[a] = crease[b] = convexA ? half : -half;
|
||||
}
|
||||
return new Surface(P, weld, facet, altitude, smallest, vertexNormal, crease);
|
||||
}
|
||||
|
||||
private bool NormalView(NormalViewSpec spec, Image image, Camera3D camera, Surface surface)
|
||||
{
|
||||
string label = spec.Label;
|
||||
var (P, weld, facet, altitude, smallest, vertexNormal, crease) = surface;
|
||||
int w = image.GetWidth(), h = image.GetHeight(), triangles = P.Length / 3;
|
||||
|
||||
// Depth raster: the nearest triangle under each pixel centre, with its barycentrics.
|
||||
var origin = camera.GlobalPosition; var basis = camera.GlobalBasis;
|
||||
float tanHalf = Mathf.Tan(Mathf.DegToRad(camera.Fov) / 2f), aspect = (float)w / h;
|
||||
Vector3 Ray(int x, int y) => (basis * new Vector3((2f * (x + 0.5f) / w - 1f) * tanHalf * aspect, -(2f * (y + 0.5f) / h - 1f) * tanHalf, -1f)).Normalized();
|
||||
var depth = new float[w * h]; var tri = new int[w * h]; var bary = new Vector3[w * h];
|
||||
Array.Fill(depth, float.MaxValue); Array.Fill(tri, -1);
|
||||
var scale = new Vector2(w, h) / GetViewport().GetVisibleRect().Size;
|
||||
for (int t = 0; t < triangles; t++)
|
||||
{
|
||||
Vector3 a = P[3 * t], b = P[3 * t + 1], c = P[3 * t + 2];
|
||||
if (camera.IsPositionBehind(a) || camera.IsPositionBehind(b) || camera.IsPositionBehind(c)) continue;
|
||||
var pa = camera.UnprojectPosition(a) * scale; var pb = camera.UnprojectPosition(b) * scale; var pc = camera.UnprojectPosition(c) * scale;
|
||||
int x0 = Math.Max(0, (int)Math.Floor(Math.Min(pa.X, Math.Min(pb.X, pc.X))) - 1), x1 = Math.Min(w - 1, (int)Math.Ceiling(Math.Max(pa.X, Math.Max(pb.X, pc.X))) + 1);
|
||||
int y0 = Math.Max(0, (int)Math.Floor(Math.Min(pa.Y, Math.Min(pb.Y, pc.Y))) - 1), y1 = Math.Min(h - 1, (int)Math.Ceiling(Math.Max(pa.Y, Math.Max(pb.Y, pc.Y))) + 1);
|
||||
Vector3 e1 = b - a, e2 = c - a;
|
||||
for (int y = y0; y <= y1; y++)
|
||||
for (int x = x0; x <= x1; x++)
|
||||
{
|
||||
var d = Ray(x, y);
|
||||
var pv = d.Cross(e2);
|
||||
float det = e1.Dot(pv);
|
||||
if (Mathf.Abs(det) < 1e-12f) continue;
|
||||
var tv = origin - a;
|
||||
float u = tv.Dot(pv) / det;
|
||||
var qv = tv.Cross(e1);
|
||||
float vv = d.Dot(qv) / det;
|
||||
if (u < 0 || vv < 0 || u + vv > 1) continue;
|
||||
float dist = e2.Dot(qv) / det;
|
||||
if (dist <= 0 || dist >= depth[y * w + x]) continue;
|
||||
depth[y * w + x] = dist; tri[y * w + x] = t; bary[y * w + x] = new Vector3(1 - u - vv, u, vv);
|
||||
}
|
||||
}
|
||||
|
||||
// The barycentrics of a point on triangle t's plane, and where a ray meets that plane.
|
||||
Vector3 Bary(int t, Vector3 p)
|
||||
{
|
||||
Vector3 a = P[3 * t], v0 = P[3 * t + 1] - a, v1 = P[3 * t + 2] - a, v2 = p - a;
|
||||
float d00 = v0.Dot(v0), d01 = v0.Dot(v1), d11 = v1.Dot(v1), d20 = v2.Dot(v0), d21 = v2.Dot(v1), denom = d00 * d11 - d01 * d01;
|
||||
float vb = (d11 * d20 - d01 * d21) / denom, wb = (d00 * d21 - d01 * d20) / denom;
|
||||
return new Vector3(1 - vb - wb, vb, wb);
|
||||
}
|
||||
Vector3 OnPlane(int t, Vector3 d) => origin + d * ((P[3 * t] - origin).Dot(facet[t]) / d.Dot(facet[t]));
|
||||
|
||||
float screenHeight = h;
|
||||
var errors = new System.Collections.Generic.List<float>(); var band = new System.Collections.Generic.List<float>(); var bandTilt = new System.Collections.Generic.List<float>();
|
||||
var clamped = new System.Collections.Generic.List<float>();
|
||||
var cornerErr = new System.Collections.Generic.List<float>(); var cornerEffect = new System.Collections.Generic.List<float>(); var sharp = new System.Collections.Generic.List<float>();
|
||||
var drawnNormal = new Vector3[w * h];
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++)
|
||||
{
|
||||
if (tri[y * w + x] < 0) continue;
|
||||
var px = image.GetPixel(x, y);
|
||||
drawnNormal[y * w + x] = (basis * new Vector3(px.R * 2f - 1f, px.G * 2f - 1f, px.B * 2f - 1f)).Normalized();
|
||||
}
|
||||
for (int y = 1; y < h - 1; y++)
|
||||
for (int x = 1; x < w - 1; x++)
|
||||
{
|
||||
int t = tri[y * w + x];
|
||||
if (t < 0) continue;
|
||||
bool interior = true;
|
||||
for (int dy = -1; dy <= 1 && interior; dy++) for (int dx = -1; dx <= 1; dx++) if (tri[(y + dy) * w + x + dx] != t) { interior = false; break; }
|
||||
if (!interior) continue;
|
||||
var bc = bary[y * w + x];
|
||||
// The distance to each edge here and one pixel over in x and in y on the same plane: metres per pixel across the edge.
|
||||
var bx = Bary(t, OnPlane(t, Ray(x + 1, y))); var by = Bary(t, OnPlane(t, Ray(x, y + 1)));
|
||||
var tilt = Vector3.Zero; bool inBand = false, wasClamped = false, inSharp = false;
|
||||
var g = new Vector3[3]; var width = new float[3]; var distance = new float[3];
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
var corner = P[3 * t + k]; var edgeStart = P[3 * t + (k + 1) % 3]; var edge = P[3 * t + (k + 2) % 3] - edgeStart;
|
||||
g[k] = facet[t].Cross(edge).Normalized();
|
||||
if (g[k].Dot(corner - edgeStart) < 0) g[k] = -g[k];
|
||||
float alt = altitude[3 * t + k];
|
||||
distance[k] = bc[k] * alt;
|
||||
float mpp = Mathf.Sqrt(Mathf.Pow(bx[k] * alt - distance[k], 2) + Mathf.Pow(by[k] * alt - distance[k], 2));
|
||||
float wanted = Mathf.Max(Look.BevelScreen * screenHeight * mpp, Look.BevelMin), cap = 0.5f * smallest[t];
|
||||
width[k] = Mathf.Min(wanted, cap);
|
||||
float c = crease[3 * t + k];
|
||||
if (c == 0f) continue;
|
||||
if (cap < wanted) wasClamped = true;
|
||||
tilt += (1f - Mathf.SmoothStep(0f, width[k], distance[k])) * Mathf.Tan(Mathf.Clamp(c, -1.4f, 1.4f)) * g[k];
|
||||
if (distance[k] < 0.6f * width[k] && Mathf.Abs(c) > 0.1f) inBand = true;
|
||||
if (distance[k] < 0.6f * width[k] && Mathf.Abs(c) > SharpCrease && Mathf.Abs(c) < SharpCreaseTop) inSharp = true;
|
||||
}
|
||||
// Near a corner the bevel gives way to the smooth vertex normal: corner k is where edges i and j meet, at the distance
|
||||
// sqrt((d_i^2 + d_j^2 - 2 d_i d_j cos) / sin^2) from the pixel.
|
||||
float cornerBlend = 0f;
|
||||
for (int k = 0; k < 3; k++)
|
||||
{
|
||||
int i = (k + 1) % 3, j = (k + 2) % 3;
|
||||
float cosine = g[i].Dot(g[j]);
|
||||
float r = Mathf.Sqrt(Mathf.Max((distance[i] * distance[i] + distance[j] * distance[j] - 2f * distance[i] * distance[j] * cosine) / Mathf.Max(1f - cosine * cosine, 1e-6f), 0f));
|
||||
float reach = 1.5f * Mathf.Max(width[i], width[j]);
|
||||
if (reach > 0f) cornerBlend = Mathf.Max(cornerBlend, 1f - Mathf.SmoothStep(0f, reach, r));
|
||||
}
|
||||
var smooth = (vertexNormal[weld[3 * t]] * bc.X + vertexNormal[weld[3 * t + 1]] * bc.Y + vertexNormal[weld[3 * t + 2]] * bc.Z).Normalized();
|
||||
var reference = (facet[t] - (1f - cornerBlend) * tilt).Normalized().Lerp(smooth, cornerBlend).Normalized();
|
||||
float err = Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(drawnNormal[y * w + x].Dot(reference), -1f, 1f)));
|
||||
errors.Add(err);
|
||||
if (cornerBlend > CornerBlendFloor) { cornerErr.Add(err); cornerEffect.Add(Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(reference.Dot((facet[t] - (1f - cornerBlend) * tilt).Normalized()), -1f, 1f)))); }
|
||||
if (inSharp) sharp.Add(err);
|
||||
if (inBand) { band.Add(err); bandTilt.Add(Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(reference.Dot(facet[t]), -1f, 1f)))); }
|
||||
if (wasClamped) clamped.Add(err);
|
||||
}
|
||||
errors.Sort(); band.Sort(); bandTilt.Sort(); clamped.Sort(); cornerErr.Sort(); cornerEffect.Sort(); sharp.Sort();
|
||||
float p90 = errors.Count == 0 ? float.MaxValue : errors[(int)(errors.Count * 0.9f)];
|
||||
float bandMedian = band.Count == 0 ? float.MaxValue : band[band.Count / 2];
|
||||
float tiltMedian = bandTilt.Count == 0 ? 0 : bandTilt[bandTilt.Count / 2];
|
||||
float clampedMedian = clamped.Count == 0 ? float.MaxValue : clamped[clamped.Count / 2];
|
||||
GD.Print($"RENDER normals {label}: p90 error {p90:F2} deg over {errors.Count} interior pixels; band median error {bandMedian:F2} deg over {band.Count} pixels, reference tilt from the facet {tiltMedian:F1} deg; width-clamped triangles' median error {clampedMedian:F2} deg over {clamped.Count} pixels");
|
||||
float cornerMedian = cornerErr.Count == 0 ? float.MaxValue : cornerErr[cornerErr.Count / 2];
|
||||
float cornerP90 = cornerErr.Count == 0 ? float.MaxValue : cornerErr[(int)(cornerErr.Count * 0.9f)];
|
||||
float effectMedian = cornerEffect.Count == 0 ? 0 : cornerEffect[cornerEffect.Count / 2];
|
||||
float sharpMedian = sharp.Count == 0 ? float.MaxValue : sharp[sharp.Count / 2];
|
||||
GD.Print($"RENDER corners {label}: median error {cornerMedian:F2} deg and p90 {cornerP90:F2} over {cornerErr.Count} pixels the corner blend reaches, which it moves by {effectMedian:F1} deg (median); sharp creases ({SharpCrease} to {SharpCreaseTop} rad): median error {sharpMedian:F2} deg over {sharp.Count} band pixels");
|
||||
bool ok = true;
|
||||
var floors = (Kept: spec.MinKept, Band: spec.MinBand, Clamped: spec.MinClamped);
|
||||
if (errors.Count < floors.Kept || band.Count < floors.Band || clamped.Count < floors.Clamped) { GD.PrintErr($"RENDER FAIL: the {label} normal check reached {errors.Count} interior, {band.Count} band and {clamped.Count} clamped pixels, under {floors.Kept}, {floors.Band} and {floors.Clamped}; it proves nothing"); ok = false; }
|
||||
if (tiltMedian < MinBandTilt) { GD.PrintErr($"RENDER FAIL: the {label} bevel band's reference normal is {tiltMedian:F1} degrees from the facet's, under {MinBandTilt}; the check cannot see a bevel"); ok = false; }
|
||||
if (p90 > MaxNormalP90) { GD.PrintErr($"RENDER FAIL: the {label} drawn shading normal is {p90:F2} degrees from the CPU reference at the 90th percentile, over {MaxNormalP90}"); ok = false; }
|
||||
if (bandMedian > MaxBandMedian) { GD.PrintErr($"RENDER FAIL: across the {label} bevel band the drawn normal is {bandMedian:F2} degrees from the CPU reference (median), over {MaxBandMedian}; the bevel is not where or as large as the creases say"); ok = false; }
|
||||
if (clampedMedian > MaxClampedMedian) { GD.PrintErr($"RENDER FAIL: on the {label} triangles whose width the smallest altitude caps the drawn normal is {clampedMedian:F2} degrees from the CPU reference (median), over {MaxClampedMedian}; the cap is not where the shader puts it"); ok = false; }
|
||||
if (cornerErr.Count < spec.MinCorner || sharp.Count < spec.MinSharp) { GD.PrintErr($"RENDER FAIL: the {label} normal check reached {cornerErr.Count} corner-blend and {sharp.Count} sharp-crease pixels, under {spec.MinCorner} and {spec.MinSharp}; it proves nothing about them"); ok = false; }
|
||||
if (spec.MinCorner > 0 && effectMedian < MinCornerEffect) { GD.PrintErr($"RENDER FAIL: the {label} corner blend moves the reference normal by {effectMedian:F1} degrees (median), under {MinCornerEffect}; the check cannot see a corner blend that is off"); ok = false; }
|
||||
if (spec.MinCorner > 0 && cornerMedian > MaxCornerMedian) { GD.PrintErr($"RENDER FAIL: where the {label} corner blend reaches, the drawn normal is {cornerMedian:F2} degrees from the CPU reference (median), over {MaxCornerMedian}; the vertex normal is in the wrong space or the blend has the wrong radius"); ok = false; }
|
||||
if (spec.MinSharp > 0 && sharpMedian > MaxClampedMedian) { GD.PrintErr($"RENDER FAIL: across the {label} band of edges turning by {SharpCrease} to {SharpCreaseTop} rad (half) the drawn normal is {sharpMedian:F2} degrees from the CPU reference (median), over {MaxClampedMedian}; the crease clamp is not where the creases say"); ok = false; }
|
||||
if (spec.Continuity) ok &= Continuity(spec, tri, depth, drawnNormal, weld, w, h);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The drawn normal across triangle boundaries: horizontally or vertically adjacent pixels on different triangles that share a vertex,
|
||||
/// at depths within 4 mm, must hardly differ, however the bevel falls on the two sides. Compares drawn pixels with drawn pixels.
|
||||
/// </summary>
|
||||
private static bool Continuity(NormalViewSpec spec, int[] tri, float[] depth, Vector3[] drawnNormal, int[] weld, int w, int h)
|
||||
{
|
||||
bool Shares(int t, int u) { for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) if (weld[3 * t + i] == weld[3 * u + j]) return true; return false; }
|
||||
var angles = new System.Collections.Generic.List<float>();
|
||||
for (int y = 0; y < h - 1; y++)
|
||||
for (int x = 0; x < w - 1; x++)
|
||||
{
|
||||
int i = y * w + x, t = tri[i];
|
||||
if (t < 0) continue;
|
||||
foreach (int j in new[] { i + 1, i + w })
|
||||
{
|
||||
int u = tri[j];
|
||||
if (u < 0 || u == t || Math.Abs(depth[i] - depth[j]) > 0.004f || !Shares(t, u)) continue;
|
||||
angles.Add(Mathf.RadToDeg(Mathf.Acos(Mathf.Clamp(drawnNormal[i].Dot(drawnNormal[j]), -1f, 1f))));
|
||||
}
|
||||
}
|
||||
string label = spec.Label;
|
||||
angles.Sort();
|
||||
float over = angles.Count == 0 ? 1f : angles.Count(a => a > 30f) / (float)angles.Count;
|
||||
float p90 = angles.Count == 0 ? float.MaxValue : angles[(int)(angles.Count * 0.9f)];
|
||||
GD.Print($"RENDER continuity {label}: {angles.Count} pairs across triangle boundaries, {over:P2} over 30 deg, p90 {p90:F2} deg");
|
||||
bool ok = true;
|
||||
if (angles.Count < MinPairs) { GD.PrintErr($"RENDER FAIL: the {label} continuity check reached {angles.Count} pairs, under {MinPairs}; it proves nothing"); ok = false; }
|
||||
if (over > spec.MaxAcross30) { GD.PrintErr($"RENDER FAIL: {over:P2} of the {label} pixel pairs across triangle boundaries differ by more than 30 degrees, over {spec.MaxAcross30:P1}"); ok = false; }
|
||||
if (p90 > spec.MaxAcrossP90) { GD.PrintErr($"RENDER FAIL: the {label} pixel pairs across triangle boundaries differ by {p90:F2} degrees at the 90th percentile, over {spec.MaxAcrossP90}"); ok = false; }
|
||||
return ok;
|
||||
}
|
||||
|
||||
/// <summary>Marks the pixels whose centres lie inside the triangle.</summary>
|
||||
private static void Fill(bool[] mask, int w, int h, Vector2 a, Vector2 b, Vector2 c)
|
||||
{
|
||||
int x0 = Math.Max(0, (int)Math.Floor(Math.Min(a.X, Math.Min(b.X, c.X)))), x1 = Math.Min(w - 1, (int)Math.Ceiling(Math.Max(a.X, Math.Max(b.X, c.X))));
|
||||
int y0 = Math.Max(0, (int)Math.Floor(Math.Min(a.Y, Math.Min(b.Y, c.Y)))), y1 = Math.Min(h - 1, (int)Math.Ceiling(Math.Max(a.Y, Math.Max(b.Y, c.Y))));
|
||||
float Edge(Vector2 p, Vector2 q, float x, float y) => (q.X - p.X) * (y - p.Y) - (q.Y - p.Y) * (x - p.X);
|
||||
for (int y = y0; y <= y1; y++)
|
||||
for (int x = x0; x <= x1; x++)
|
||||
{
|
||||
float px = x + 0.5f, py = y + 0.5f;
|
||||
float e0 = Edge(a, b, px, py), e1 = Edge(b, c, px, py), e2 = Edge(c, a, px, py);
|
||||
if ((e0 >= 0 && e1 >= 0 && e2 >= 0) || (e0 <= 0 && e1 <= 0 && e2 <= 0)) mask[y * w + x] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
[gd_scene load_steps=2 format=3]
|
||||
|
||||
[ext_resource type="Script" path="res://tests/RenderCheck.cs" id="1"]
|
||||
|
||||
[node name="RenderCheck" type="Node"]
|
||||
script = ExtResource("1")
|
||||
|
|
@ -5,6 +5,7 @@ using System.Threading.Tasks;
|
|||
using BadDay.Core;
|
||||
using BadDay.Ymir;
|
||||
using Godot;
|
||||
using Ymir.Box3D;
|
||||
|
||||
namespace BadDay.Client.Tests;
|
||||
|
||||
|
|
@ -57,7 +58,6 @@ public partial class Smoke : Node
|
|||
private async Task Scenario()
|
||||
{
|
||||
CheckEngineAndScene();
|
||||
PuppetChecks.Run(failure => Check(false, "puppet: " + failure), Session.View);
|
||||
if (_failures.Count > 0) return;
|
||||
|
||||
// Slow motion, by wall clock: a quarter of the session steps per real second, the same run.
|
||||
|
|
@ -72,10 +72,10 @@ public partial class Smoke : Node
|
|||
// The rest runs the physics clock fast; the session still steps 1/120 s per frame.
|
||||
Engine.PhysicsTicksPerSecond = 1200;
|
||||
|
||||
// A Reset is not a topology change: the mesh stays the one built at startup. Checked after three resets so a rebuild per
|
||||
// A Reset is not a new set of bodies: the carriers and meshes made at startup stay. Checked after three resets so a rebuild per
|
||||
// Reset fails here, not after hundreds.
|
||||
for (ulong seed = 1; seed <= 3; seed++) { PressReset(seed); await Frame(); }
|
||||
Check(_main.Bodies.PuppetMeshBuilds == 1, $"the puppet mesh was built {_main.Bodies.PuppetMeshBuilds} times by the third Reset; the signature never changed, so once");
|
||||
CheckMeshBuilds("by the third Reset");
|
||||
CameraChecks.Run(failure => Check(false, "camera: " + failure), _main);
|
||||
// The camera writes its transform on input only: one written between frames stays through them.
|
||||
var orbit = _main.GetNode<OrbitCamera>("Camera");
|
||||
|
|
@ -105,7 +105,6 @@ 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.
|
||||
|
|
@ -139,7 +138,7 @@ public partial class Smoke : Node
|
|||
await Frame();
|
||||
}
|
||||
Check(_main.Seed == 1399, $"after 400 resets the seed is {_main.Seed}");
|
||||
Check(_main.Bodies.PuppetMeshBuilds == 1, $"the puppet mesh was built {_main.Bodies.PuppetMeshBuilds} times; the signature never changed, so once");
|
||||
CheckMeshBuilds("after 400 Resets");
|
||||
|
||||
// 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);
|
||||
|
|
@ -175,52 +174,22 @@ public partial class Smoke : Node
|
|||
Check(_main.IsPhysicsInterpolatedAndEnabled() && (bool)ProjectSettings.GetSetting("physics/common/physics_interpolation"), "physics interpolation is off");
|
||||
Check(_main.Seed == Seed, "Main did not start from the smoke's seed");
|
||||
|
||||
// The look: white on dark grey, flat.
|
||||
var puppet = _main.Bodies.PuppetColor;
|
||||
Check(puppet.Luminance > 0.7f && puppet.S < 0.1f, $"the puppet is {puppet}, not white");
|
||||
// The look: dark grey.
|
||||
Check(_main.Bodies.SceneryMaterial.AlbedoColor.Luminance < 0.3f, "the floor is not dark");
|
||||
var glow = _main.Chamber.Material.AlbedoColor;
|
||||
Check(glow.V > 0.7f && glow.S < 0.3f, $"the chamber is {glow}, not light");
|
||||
var environment = _main.GetChildren().OfType<WorldEnvironment>().Single().Environment;
|
||||
Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey");
|
||||
// The studio: a shadowing key and two rims. Where the camera turns the key's light turns with it, and it keeps coming from the studio's direction in the camera's space.
|
||||
var rig = _main.FindChildren("*", "DirectionalLight3D", true, false).Cast<DirectionalLight3D>().ToArray();
|
||||
Check(rig.Length == 3 && rig.Count(l => l.ShadowEnabled) == 1, $"the scene has {rig.Length} directional lights, {rig.Count(l => l.ShadowEnabled)} with a shadow, not a key and two rims");
|
||||
var camera = _main.GetNode<Camera3D>("Camera");
|
||||
var home = camera.GlobalTransform;
|
||||
foreach (float turn in new[] { 0f, 2.1f })
|
||||
{
|
||||
camera.GlobalTransform = new Transform3D(home.Basis.Rotated(Vector3.Up, turn), home.Origin);
|
||||
foreach (var key in rig.Where(l => l.ShadowEnabled))
|
||||
{
|
||||
var shinesAlong = camera.GlobalBasis.Inverse() * -key.GlobalBasis.Z; // the key's direction of travel in the camera's space
|
||||
Check((shinesAlong + Look.KeyDirection).Length() < 1e-3f, $"the key shines along {shinesAlong} in the camera's space after the camera turned {turn} rad; the studio does not follow the camera");
|
||||
}
|
||||
}
|
||||
camera.GlobalTransform = home;
|
||||
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>The puppet's one mesh as it is drawn: 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)
|
||||
/// <summary>Every body with a shape is drawn by one mesh, made once: the anchor has none.</summary>
|
||||
private void CheckMeshBuilds(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 = PuppetChecks.Pieces(shape);
|
||||
Check(pieces == 1, $"{when}: the puppet mesh is {pieces} pieces, not one");
|
||||
|
||||
var posed = new Rigid[shape.Ids.Length];
|
||||
for (int i = 0; i < posed.Length; i++)
|
||||
posed[i] = Puppet.ToRigid((_main.Bodies.PoseOf(shape.Ids[i]) ?? Transform3D.Identity) * Puppet.ToTransform(shape.SpreadBind[i].Inverse()));
|
||||
float stretch = PuppetChecks.Stretch(shape, posed).Ratio;
|
||||
Check(stretch <= PuppetChecks.StretchLimit, $"{when}: a skinned edge is {stretch:F1}x its bind length, over {PuppetChecks.StretchLimit}x");
|
||||
|
||||
for (int j = 0; j < shape.Joints.Length; j++)
|
||||
{
|
||||
if (shape.Joints[j].Kind != global::Ymir.Box3D.Box3DSoaJointKind.Spherical) continue;
|
||||
stretch = PuppetChecks.Stretch(shape, PuppetChecks.Swing(shape, j, new CultMath.float3(1, 0, 0), MathF.PI / 2)).Ratio;
|
||||
Check(stretch <= PuppetChecks.StretchLimit, $"{when}: with body {shape.Ids[shape.Joints[j].B]} swung 90 degrees a skinned edge is {stretch:F1}x its bind length, over {PuppetChecks.StretchLimit}x");
|
||||
}
|
||||
var view = Session.View;
|
||||
int shaped = 0;
|
||||
for (int i = 0; i < view.Count; i++) if ((Box3DSoaKind)view.Kind[i] != Box3DSoaKind.Anchor) shaped++;
|
||||
Check(_main.Bodies.MeshBuilds == shaped, $"{when}: {_main.Bodies.MeshBuilds} body meshes were made for {shaped} bodies with a shape; a Reset makes none");
|
||||
}
|
||||
|
||||
private void CheckPoses(string when)
|
||||
|
|
|
|||
Loading…
Reference in a new issue