fauna: SpringRigVerify, batchmode checks and capture for the whale rig (whale-rig-s1)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
soul 2026-12-01 02:08:57 +01:00
commit 7a982d2a0d
2 changed files with 704 additions and 0 deletions

View file

@ -0,0 +1,702 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Aetheria.FaunaDisplay;
using Newtonsoft.Json.Linq;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using Debug = UnityEngine.Debug;
namespace Aetheria.EditorTools
{
/// <summary>
/// Batchmode verify for the whale rig (campaign aetheria-fauna, cut whale-rig-s1): a synthetic rig built in code as a glTF
/// skin plus VRMC_springBone, run through SpringRig.Present, checked against CPU re-derivations. Opens no scene.
/// Needs a graphics device (the skin check renders): run WITHOUT -nographics, and without -quit (Run exits itself, 0 or 1).
/// Unity -batchmode -projectPath &lt;repo&gt; -executeMethod Aetheria.EditorTools.SpringRigVerify.Run -logFile &lt;path&gt;
/// Capture renders a short swim to PNG frames in SPRINGRIG_CAPTURE_OUT (same flags, method Capture).
/// </summary>
public static class SpringRigVerify
{
const string Tag = "[SpringRigVerify]";
const double Dt = 1.0 / 60;
// Cost bound (lodur:ruling:deterministic-bound-margin): median ms per frame of three Present calls, three whales of 770
// spring joints, Starfire (Ryzen 3 3100, GTX 1070), editor batchmode, 2 substeps a frame. Shipped worst 0.868 (runs: 0.802,
// 0.868), least mutant 7.048 (Burst off; runs: 7.048, 9.321), separation 8.1; bound sqrt(0.868 x 7.048) = 2.47.
const double CostBoundMs = 2.47;
static readonly List<GameObject> Scrap = new List<GameObject>();
public static void Run()
{
if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null)
{
Debug.LogError($"{Tag} FAIL: no graphics device in this session; rerun batchmode without -nographics.");
EditorApplication.Exit(1);
return;
}
var checks = new (string name, Func<string> body)[]
{
("vrmc-parse", VrmcParse), ("rest-holds", RestHolds), ("length-holds", LengthHolds), ("collider-pushes-out", ColliderPushesOut),
("fixed-substeps", FixedSubsteps), ("pause-freezes", PauseFreezes), ("swim-closed-form", SwimClosedForm),
("freeze-and-reset", FreezeAndReset), ("skin-matches-cpu", SkinMatchesCpu), ("cost-bound", CostBound),
};
int failed = 0;
foreach (var (name, body) in checks)
{
string verdict;
try { verdict = body(); }
catch (Exception e) { verdict = "exception: " + e; }
finally { foreach (var go in Scrap) if (go != null) UnityEngine.Object.DestroyImmediate(go); Scrap.Clear(); }
if (verdict == null) Debug.Log($"{Tag} PASS {name}");
else { Debug.LogError($"{Tag} FAIL {name}: {verdict}"); failed++; }
}
Debug.Log(failed == 0 ? $"{Tag} PASS all" : $"{Tag} FAIL {failed} check(s)");
EditorApplication.Exit(failed == 0 ? 0 : 1);
}
// ---------------------------------------------------------------- the checks (null is a pass)
static string VrmcParse()
{
const string fixture = @"{
""nodes"": [
{""name"":""body"",""translation"":[0,0,0],""children"":[1,2]},
{""name"":""fin"",""translation"":[1,0,0]},
{""name"":""t0"",""translation"":[0,-1,0],""children"":[3]},
{""name"":""t1"",""translation"":[0,-0.5,0],""children"":[4]},
{""name"":""t2"",""translation"":[0,-0.25,0]}],
""skins"": [{""joints"":[0,1,2,3,4]}],
""extensions"": {""VRMC_springBone"": {""specVersion"":""1.0"",
""colliders"": [
{""node"":0,""shape"":{""sphere"":{""offset"":[0,0,0.1],""radius"":0.4}}},
{""node"":1,""shape"":{""capsule"":{""offset"":[0,0,0],""radius"":0.1,""tail"":[0.5,0,0]}}}],
""colliderGroups"": [{""name"":""body"",""colliders"":[0,1]}],
""springs"": [{""name"":""tendril"",""colliderGroups"":[0],""joints"":[
{""node"":2,""hitRadius"":0.05,""stiffness"":2,""gravityPower"":0.5,""gravityDir"":[0,-1,0],""dragForce"":0.3},
{""node"":3,""hitRadius"":0.06,""stiffness"":3,""gravityPower"":0.25,""gravityDir"":[0,-1,0],""dragForce"":0.2},
{""node"":4,""hitRadius"":0.07}]}]}}}";
var d = SpringRigData.FromGlbJson(JObject.Parse(fixture), null);
if (d.BoneCount != 5 || d.BodyCount != 2 || d.ChainCount != 1 || d.SpringJointCount != 3) return $"counts {d.BoneCount}/{d.BodyCount}/{d.ChainCount}/{d.SpringJointCount}";
if (!d.Parent.SequenceEqual(new[] { -1, 0, 0, 2, 3 })) return "parents " + string.Join(",", d.Parent);
if (!d.IsBody.SequenceEqual(new[] { true, true, false, false, false })) return "body flags";
if (!d.ChainBones(0).SequenceEqual(new[] { 2, 3, 4 }) || d.ChainName(0) != "tendril") return "chain bones";
var j1 = d.ChainJoint(0, 1);
if (j1.HitRadius != 0.06f || j1.Stiffness != 3f || j1.GravityPower != 0.25f || j1.DragForce != 0.2f || !j1.GravityDir.Equals(new float3(0, -1, 0))) return "joint 1 parameters";
var j2 = d.ChainJoint(0, 2);
if (j2.Stiffness != 1f || j2.DragForce != 0.5f || j2.GravityPower != 0f) return "joint 2 defaults";
if (d.Colliders.Count != 2 || d.Colliders[0].Capsule || d.Colliders[0].Bone != 0 || d.Colliders[0].Radius != 0.4f || !d.Colliders[0].Offset.Equals(new float3(0, 0, 0.1f))) return "sphere collider";
if (!d.Colliders[1].Capsule || d.Colliders[1].Bone != 1 || !d.Colliders[1].Tail.Equals(new float3(0.5f, 0, 0))) return "capsule collider";
if (!d.ChainColliders(0).SequenceEqual(new[] { 0, 1 })) return "collider group";
if (!d.RestPosition[3].Equals(new float3(0, -0.5f, 0)) || d.SpineIndex[0] != 0 || d.SpineIndex[1] != 1 || d.SpineIndex[2] != -1) return "rest or spine";
string Refused(Func<string, string> mutate, string expect)
{
try { SpringRigData.FromGlbJson(JObject.Parse(mutate(fixture)), null); return $"'{expect}' mutant parsed"; }
catch (InvalidDataException e) { return e.Message.Contains(expect) ? null : $"'{expect}' mutant refused with: {e.Message}"; }
}
return Refused(f => f.Replace("\"sphere\"", "\"cone\""), "unknown shape 'cone'")
?? Refused(f => f.Replace("{\"node\":3,\"hitRadius\":0.06", "{\"node\":4,\"hitRadius\":0.06").Replace("{\"node\":4,\"hitRadius\":0.07}", "{\"node\":3,\"hitRadius\":0.07}"), "not its predecessor")
?? Refused(f => f.Replace("\"children\":[1,2]", "\"children\":[1]").Replace("\"children\":[3]", "\"children\":[3]").Replace("\"children\":[4]", "\"children\":[4,2]"), "Cycle in the node tree");
}
static string RestHolds()
{
var s = new Synth { Gravity = 0, Stiffness = 20 };
var w = Whale(s, out var data);
w.Swim.AmplitudeDegrees = 0;
double t = 0, moved = 0;
for (; t < 2; t += Dt) // jostle the tendrils
{
w.Present(t, new Vector3(Mathf.Sin((float)t * 6) * 0.8f, 0, 0), Quaternion.identity, 1);
moved = math.max(moved, Displacement(w, data, t, default, quaternion.identity));
}
if (moved < 0.05) return $"the jostle moved the tendrils only {moved} (vacuous)";
for (int i = 0; i < 600; i++, t += Dt) w.Present(t, Vector3.zero, Quaternion.identity, 1);
double worst = Displacement(w, data, t - Dt, default, quaternion.identity) / (s.Joints - 1) / math.length(s.Seg);
return worst <= 1e-4 ? null : $"after 600 frames the worst spring joint is {worst} chain lengths from rest";
}
static string LengthHolds()
{
var s = new Synth { Gravity = 0.3f, Stiffness = 3 };
var w = Whale(s, out var data);
w.Swim.AmplitudeDegrees = 20;
double worst = 0;
for (int i = 0; i < 600; i++)
{
double t = i * Dt;
w.Present(t, new Vector3(Mathf.Sin((float)t * 3) * 2, 0, (float)t * 8), Quaternion.Euler(0, Mathf.Sin((float)t * 2) * 30, 0), 1.5f);
for (int c = 0; c < data.ChainCount; c++)
{
var bones = data.ChainBones(c);
for (int k = 1; k < bones.Count; k++)
{
double rest = math.length(data.RestPosition[bones[k]]) * 1.5, len = math.distance(w.BonePosition(bones[k]), w.BonePosition(bones[k - 1]));
worst = math.max(worst, math.abs(len - rest) / rest);
}
}
}
return worst <= 1e-3 ? null : $"worst relative segment error {worst}";
}
static string ColliderPushesOut()
{
var s = new Synth { Gravity = 0, Stiffness = 8 };
var hostA = s.Host(0); var hostB = s.Host(1);
s.Colliders = new JArray
{
Collider(hostA, "sphere", s.JointRest(0, 3), null, 0.12f),
Collider(hostB, "capsule", s.JointRest(1, 3) + new float3(-0.2f, 0, 0), s.JointRest(1, 3) + new float3(0.2f, 0, 0), 0.12f),
};
var w = Whale(s, out var data);
w.Swim.AmplitudeDegrees = 0;
w.Present(0, Vector3.zero, Quaternion.identity, 1);
double worst = 0; // deepest penetration as a fraction of radius + hit radius
for (int i = 1; i < 240; i++)
{
w.Present(i * Dt, Vector3.zero, Quaternion.identity, 1);
foreach (var col in data.Colliders)
for (int c = 0; c < data.ChainCount; c++)
{
var bones = data.ChainBones(c);
for (int k = 1; k < bones.Count; k++)
{
float3 origin = w.BonePosition(col.Bone), a = origin + math.mul(w.BoneRotation(col.Bone), col.Offset), b = origin + math.mul(w.BoneRotation(col.Bone), col.Tail);
float3 seg = b - a, p = w.BonePosition(bones[k]);
float3 near = col.Capsule ? a + seg * math.saturate(math.dot(p - a, seg) / math.max(math.lengthsq(seg), 1e-12f)) : a;
float reach = col.Radius + data.ChainJoint(c, k - 1).HitRadius;
worst = math.max(worst, (reach - math.distance(p, near)) / reach);
}
}
}
// Push-out then length again cannot hold a joint exactly on the surface when the length constraint pulls it back in (the
// rest pull fights the push each substep); the residual measured here is 1% of the reach. Without push-out it is 100%.
return worst <= 0.02 ? null : $"a joint ends a frame {worst:P1} of its reach inside a collider";
}
static string FixedSubsteps()
{
long Run(int fps, int seconds)
{
var w = Whale(new Synth(), out _);
for (int i = 0; i <= fps * seconds; i++) w.Present(i / (double)fps, Vector3.zero, Quaternion.identity, 1);
return w.SubstepsRun;
}
long a = Run(30, 3), b = Run(144, 3);
if (a != 360 || b != 360) return $"3 s ran {a} substeps at 30 fps and {b} at 144 fps; floor(3 x 120) = 360";
var hitch = Whale(new Synth(), out _);
hitch.Present(0, Vector3.zero, Quaternion.identity, 1);
hitch.Present(0.5, Vector3.zero, Quaternion.identity, 1);
return hitch.SubstepsRun == 4 ? null : $"a half-second hitch ran {hitch.SubstepsRun} substeps, not 4";
}
static string PauseFreezes()
{
var w = Whale(new Synth { Gravity = 0.3f }, out _);
double t = 0;
for (int i = 0; i < 90; i++, t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 4), 0, (float)t * 5), Quaternion.Euler(0, (float)t * 20, 0), 1);
t -= Dt;
var pose = new Vector3(Mathf.Sin((float)t * 4), 0, (float)t * 5);
w.Present(t, pose, Quaternion.Euler(0, (float)t * 20, 0), 1);
var first = w.Skin.ToArray();
for (int i = 0; i < 10; i++)
{
w.Present(t, pose, Quaternion.Euler(0, (float)t * 20, 0), 1);
var now = w.Skin.ToArray();
for (int j = 0; j < now.Length; j++)
if (!BitEqual(first[j], now[j])) return $"bone {j} changed on held frame {i + 1}";
}
return null;
}
static string SwimClosedForm()
{
var one = Whale(new Synth(), out var data);
var many = Whale(new Synth(), out _);
one.Present(5.0, Vector3.zero, Quaternion.identity, 1);
for (int i = 0; i <= 100; i++) many.Present(5.0 * i / 100, Vector3.zero, Quaternion.identity, 1);
var a = one.Skin.ToArray(); var b = many.Skin.ToArray();
bool moves = false;
for (int i = 0; i < data.BoneCount; i++)
{
if (!data.IsBody[i]) continue;
if (!BitEqual(a[i], b[i])) return $"body bone {i} differs between 1 and 100 frames";
moves |= !BitEqual(a[i], float4x4.identity);
}
return moves ? null : "the swim moved nothing (vacuous)";
}
static string FreezeAndReset()
{
var cam = new GameObject("lodCam").AddComponent<Camera>();
Scrap.Add(cam.gameObject);
cam.fieldOfView = 60;
var s = new Synth { Gravity = 0, Stiffness = 4 };
var w = Whale(s, out var data);
w.LodCamera = cam;
w.Swim.AmplitudeDegrees = 0;
cam.transform.position = new Vector3(0, 0, -50);
double t = 0;
for (; t < 3; t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1);
if (w.Level != SpringLod.Full) return "near whale is not Full";
// Far: frozen. Tendrils at rest on the swimming body, no solver job.
w.Swim.AmplitudeDegrees = 15;
cam.transform.position = new Vector3(0, 0, -300);
int jobs = w.SolveJobsScheduled;
double rest = 0;
for (int i = 0; i < 10; i++, t += Dt)
{
var pos = new Vector3(Mathf.Sin((float)t * 5), 0, 0);
if (w.Present(t, pos, Quaternion.identity, 1) != SpringLod.Frozen) return "far whale is not Frozen";
Fk(data, t, w.Swim, pos, quaternion.identity, 1, out var fp, out _);
for (int b = 0; b < data.BoneCount; b++) rest = math.max(rest, math.distance(fp[b], w.BonePosition(b)));
}
if (w.SolveJobsScheduled != jobs) return "a solver job ran while frozen";
if (rest > 1e-4) return $"frozen tendrils are {rest} from rest on the swimming body";
// Unfreeze with the body still: the stale perturbed state must not show.
w.Swim.AmplitudeDegrees = 0;
var held = new Vector3(Mathf.Sin((float)(t - Dt) * 5), 0, 0);
w.Present(t, held, Quaternion.identity, 1); // still frozen, at the amplitude-0 pose
var before = Positions(w, data);
cam.transform.position = new Vector3(0, 0, -50);
t += Dt;
if (w.Present(t, held, Quaternion.identity, 1) != SpringLod.Full) return "near whale did not return to Full";
double joint = Max(before, Positions(w, data), data, springs: true);
if (joint > 1e-4) return $"unfreeze: first frame moved a spring joint {joint}, body moved 0";
// A root jump longer than the longest chain, in one frame.
for (int i = 0; i < 60; i++) { t += Dt; w.Present(t, held + new Vector3(Mathf.Sin(i * 0.5f) * 0.5f, 0, 0), Quaternion.identity, 1); }
before = Positions(w, data);
int resets = w.Resets;
t += Dt;
var jumped = held + new Vector3(0, 0, 50);
w.Present(t, jumped, Quaternion.identity, 1);
if (w.Resets != resets + 1) return "a root jump did not reset";
var after = Positions(w, data);
// The joints come to rest on the jumped body (so they moved no more than the body plus the pre-jump lag), not stretched behind it.
double lag = Displacement(w, data, t, jumped, quaternion.identity);
return lag <= 1e-3 ? null : $"root jump: a spring joint is {lag} from rest on the body in the first frame";
}
static string SkinMatchesCpu()
{
var s = new Synth { Spine = 3, Chains = 2, Joints = 3, Gravity = 0.2f, Stiffness = 4 };
var go = new GameObject("skinTest");
Scrap.Add(go);
var rig = go.AddComponent<SpringRig>();
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
Fk(data, 0, SwimSettings.Default, default, quaternion.identity, 1, out var restPos, out _);
var verts = new List<Vertex>();
var tris = new List<int>();
for (int i = 0; i < data.BoneCount; i++)
{
int other = data.Parent[i] >= 0 ? data.Parent[i] : i;
foreach (var o in new[] { new float3(0, 0.12f, 0), new float3(0, -0.12f, 0), new float3(0, 0, 0.3f) })
{
tris.Add(verts.Count);
verts.Add(new Vertex { p = restPos[i] + o, n = Vector3.right, uv = new Vector2(0.5f, 0.5f), w = new Vector4(0.6f, 0.4f, 0, 0), b0 = (uint)i, b1 = (uint)other });
}
}
var mesh = MakeMesh(verts, tris);
Scrap.Add(go);
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var mr = go.AddComponent<MeshRenderer>();
mr.sharedMaterial = SkinMaterial(0);
rig.Renderer = mr;
rig.Swim.AmplitudeDegrees = 25;
rig.Initialize(data, mesh.bounds);
double t = 0;
for (int i = 0; i < 90; i++, t += Dt) rig.Present(t, new Vector3(0, 0, (float)t * 2), Quaternion.Euler(0, 20, 0), 1.3f);
var localToWorld = go.transform.localToWorldMatrix;
var world = new Vector3[verts.Count];
var skin = rig.Skin;
for (int v = 0; v < verts.Count; v++)
{
float3 p = 0;
var vert = verts[v];
p += vert.w.x * math.mul(skin[(int)vert.b0], new float4(vert.p, 1)).xyz + vert.w.y * math.mul(skin[(int)vert.b1], new float4(vert.p, 1)).xyz;
world[v] = localToWorld.MultiplyPoint3x4(p);
}
const int size = 256;
var bounds = new Bounds(world[0], Vector3.zero);
foreach (var p in world) bounds.Encapsulate(p);
var cam = new GameObject("skinCam").AddComponent<Camera>();
Scrap.Add(cam.gameObject);
cam.orthographic = true;
cam.orthographicSize = Mathf.Max(bounds.extents.y, bounds.extents.z) * 1.15f;
cam.transform.SetPositionAndRotation(bounds.center + new Vector3(10, 0, 0), Quaternion.LookRotation(Vector3.left));
cam.clearFlags = CameraClearFlags.SolidColor;
cam.backgroundColor = Color.black;
cam.nearClipPlane = 0.1f; cam.farClipPlane = 50;
var rt = new RenderTexture(size, size, 24, RenderTextureFormat.ARGB32);
cam.targetTexture = rt;
RenderSettings.ambientMode = AmbientMode.Flat;
RenderSettings.ambientLight = Color.white;
cam.Render();
var read = new Texture2D(size, size, TextureFormat.RGBA32, false);
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, size, size), 0, 0);
read.Apply();
RenderTexture.active = null;
var gpu = read.GetPixels32().Select(c => c.r > 8 || c.g > 8 || c.b > 8).ToArray();
var cpu = new bool[size * size];
for (int i = 0; i < tris.Count; i += 3)
{
var a = (Vector2)cam.WorldToScreenPoint(world[tris[i]]); var b = (Vector2)cam.WorldToScreenPoint(world[tris[i + 1]]); var c = (Vector2)cam.WorldToScreenPoint(world[tris[i + 2]]);
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
{
var p = new Vector2(x + 0.5f, y + 0.5f);
float d1 = Edge(p, a, b), d2 = Edge(p, b, c), d3 = Edge(p, c, a);
if ((d1 >= 0 && d2 >= 0 && d3 >= 0) || (d1 <= 0 && d2 <= 0 && d3 <= 0)) cpu[y * size + x] = true;
}
}
UnityEngine.Object.DestroyImmediate(rt);
int lit = cpu.Count(x => x);
if (lit < 400) return $"only {lit} px covered (vacuous)";
int stray = 0;
for (int y = 0; y < size; y++)
for (int x = 0; x < size; x++)
{
if (gpu[y * size + x] && !Near(cpu, x, y, size)) stray++;
if (cpu[y * size + x] && !Near(gpu, x, y, size)) stray++;
}
return stray == 0 ? null : $"{stray} px differ by more than 1 px between the shader and the CPU skin ({lit} px covered)";
}
static string CostBound()
{
var s = new Synth { Spine = 12, Chains = 110, Joints = 7 };
var whales = Enumerable.Range(0, 3).Select(i => Whale(s, out var unused)).ToArray();
var debugger = Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled;
Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled = false;
double Measure()
{
var ms = new List<double>();
for (int f = 0; f < 330; f++)
{
double t = f * Dt;
long start = Stopwatch.GetTimestamp();
for (int i = 0; i < whales.Length; i++)
whales[i].Present(t, new Vector3(i * 30 + Mathf.Sin((float)t * 3), 0, (float)t * 6), Quaternion.Euler(0, (float)t * 10, 0), 4);
if (f >= 30) ms.Add((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency);
}
ms.Sort();
return ms[ms.Count / 2];
}
double shipped, mutant;
try
{
shipped = Measure();
Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = false;
mutant = Measure();
}
finally
{
Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = true;
Unity.Jobs.LowLevel.Unsafe.JobsUtility.JobDebuggerEnabled = debugger;
}
// The write-back alone: one GraphicsBuffer.SetData of a whale's skin matrices.
var upload = new Unity.Collections.NativeArray<float4x4>(whales[0].Data.BoneCount, Unity.Collections.Allocator.Temp);
var uploads = new List<double>();
for (int i = 0; i < 300; i++)
{
long start = Stopwatch.GetTimestamp();
whales[0].SkinBuffer.SetData(upload);
uploads.Add((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency);
}
upload.Dispose();
uploads.Sort();
Debug.Log($"{Tag} cost-bound: 3 whales x 770 joints, median ms per frame: shipped {shipped:F3}, Burst off {mutant:F3}, ratio {mutant / shipped:F2}; bound {CostBoundMs}; skin upload alone {uploads[uploads.Count / 2]:F4} ms per whale");
if (shipped * 1.2 > CostBoundMs) return $"shipped {shipped:F3} ms is not 1.2x under the bound {CostBoundMs}";
if (mutant < CostBoundMs * 1.2) return $"the Burst-off mutant {mutant:F3} ms is not 1.2x over the bound {CostBoundMs}";
return null;
}
// ---------------------------------------------------------------- capture
public static void Capture()
{
var dir = Environment.GetEnvironmentVariable("SPRINGRIG_CAPTURE_OUT") ?? throw new InvalidOperationException("Set SPRINGRIG_CAPTURE_OUT.");
Directory.CreateDirectory(dir);
try
{
var s = new Synth { Spine = 8, Chains = 28, Joints = 8, Stiffness = 2.5f, Drag = 0.3f, Gravity = 0f, Ring = 0.45f, Seg = new Vector3(0, -0.12f, -0.34f) };
var go = new GameObject("whale");
var rig = go.AddComponent<SpringRig>();
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
var mesh = TubeMesh(data, s);
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var mr = go.AddComponent<MeshRenderer>();
mr.sharedMaterial = SkinMaterial(0);
rig.Renderer = mr;
rig.Swim = new SwimSettings { AmplitudeDegrees = 7, PeriodSeconds = 3.2f, PhasePerBone = 0.1f, Axis = new float3(1, 0, 0) };
rig.Initialize(data, mesh.bounds);
var light = new GameObject("sun").AddComponent<Light>();
light.type = LightType.Directional; light.intensity = 1.1f;
light.transform.rotation = Quaternion.Euler(45, -35, 0);
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.25f, 0.28f, 0.34f);
var cam = new GameObject("cam").AddComponent<Camera>();
cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = new Color(0.03f, 0.04f, 0.09f);
cam.fieldOfView = 40; cam.nearClipPlane = 0.1f; cam.farClipPlane = 200;
var rt = new RenderTexture(960, 540, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
cam.targetTexture = rt;
var read = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
for (int f = 0; f < 300; f++)
{
double t = f * Dt;
// Swim forward along +z, wandering in a slow S so the body yaws and the tendrils trail across it.
var pos = new Vector3(Mathf.Sin((float)t * 0.9f) * 1.6f, Mathf.Sin((float)t * 0.5f) * 0.4f, (float)t * 3.2f);
var yaw = Mathf.Cos((float)t * 0.9f) * 14f;
rig.Present(t, pos, Quaternion.Euler(0, yaw, 0), 1);
var centre = pos + new Vector3(0, -0.2f, 3);
cam.transform.position = centre + new Vector3(9.5f, 2.0f, -3.5f);
cam.transform.LookAt(centre);
cam.Render();
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
RenderTexture.active = null;
File.WriteAllBytes(Path.Combine(dir, $"frame_{f:D4}.png"), read.EncodeToPNG());
}
Debug.Log($"{Tag} captured 300 frames to {dir}");
EditorApplication.Exit(0);
}
catch (Exception e)
{
Debug.LogError($"{Tag} capture FAIL: {e}");
EditorApplication.Exit(1);
}
}
// ---------------------------------------------------------------- the synthetic rig
// A glTF skin built in code: a spine along +z (body bones) and Chains tendrils of Joints joints hanging from it
// in a ring, one VRMC_springBone spring each. All rest rotations are identity, so rest world = summed translations.
sealed class Synth
{
public int Spine = 4, Chains = 8, Joints = 5;
public float Stiffness = 8, Drag = 0.4f, Gravity = 0, Hit = 0.02f, Ring = 0.4f;
public Vector3 Seg = new Vector3(0, -0.1f, -0.3f);
public JArray Colliders; // null: a sphere on every spine bone but the root
public int Host(int chain) => 1 + chain % Math.Max(1, Spine - 1);
float Theta(int chain) => ((chain * 0.618f) % 1f - 0.5f) * 2.4f;
public float3 JointRest(int chain, int k) => new float3(Ring * Mathf.Sin(Theta(chain)), -Ring * Mathf.Cos(Theta(chain)), 0) + (float3)Seg * k;
public JObject Build(out byte[] bin)
{
int n = Spine + Chains * Joints;
var nodes = new JArray(); var world = new List<float3>();
for (int i = 0; i < Spine; i++)
{
nodes.Add(new JObject { ["name"] = "spine" + i, ["translation"] = Arr(i == 0 ? default : new float3(0, 0, 1)), ["children"] = new JArray() });
world.Add(new float3(0, 0, i));
}
var springs = new JArray();
for (int c = 0; c < Chains; c++)
{
var joints = new JArray();
for (int k = 0; k < Joints; k++)
{
int node = Spine + c * Joints + k;
var local = k == 0 ? JointRest(c, 0) : (float3)Seg;
nodes.Add(new JObject { ["name"] = $"t{c}_{k}", ["translation"] = Arr(local), ["children"] = new JArray() });
var parent = k == 0 ? Host(c) : node - 1;
((JArray)nodes[parent]["children"]).Add(node);
world.Add(world[parent] + local);
joints.Add(new JObject { ["node"] = node, ["hitRadius"] = Hit, ["stiffness"] = Stiffness, ["gravityPower"] = Gravity, ["gravityDir"] = Arr(new float3(0, -1, 0)), ["dragForce"] = Drag });
}
springs.Add(new JObject { ["name"] = "tendril" + c, ["joints"] = joints, ["colliderGroups"] = new JArray(0) });
}
for (int i = 1; i < Spine; i++) ((JArray)nodes[i - 1]["children"]).Add(i);
var colliders = Colliders ?? new JArray(Enumerable.Range(1, Spine - 1).Select(i => Collider(i, "sphere", default, null, Ring * 0.8f)));
var bytes = new byte[n * 64];
for (int i = 0; i < n; i++)
{
var m = new[] { 1f, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -world[i].x, -world[i].y, -world[i].z, 1 };
Buffer.BlockCopy(m, 0, bytes, i * 64, 64);
}
bin = bytes;
return new JObject
{
["nodes"] = nodes,
["skins"] = new JArray(new JObject { ["joints"] = new JArray(Enumerable.Range(0, n)), ["inverseBindMatrices"] = 0 }),
["accessors"] = new JArray(new JObject { ["bufferView"] = 0, ["componentType"] = 5126, ["count"] = n, ["type"] = "MAT4" }),
["bufferViews"] = new JArray(new JObject { ["buffer"] = 0, ["byteOffset"] = 0, ["byteLength"] = n * 64 }),
["extensions"] = new JObject
{
["VRMC_springBone"] = new JObject
{
["specVersion"] = "1.0", ["colliders"] = colliders, ["springs"] = springs,
["colliderGroups"] = new JArray(new JObject { ["name"] = "body", ["colliders"] = new JArray(Enumerable.Range(0, colliders.Count)) }),
},
},
};
}
}
static JArray Arr(float3 v) => new JArray(v.x, v.y, v.z);
static JObject Collider(int node, string shape, float3 offset, float3? tail, float radius)
{
var body = new JObject { ["offset"] = Arr(offset), ["radius"] = radius };
if (tail.HasValue) body["tail"] = Arr(tail.Value);
return new JObject { ["node"] = node, ["shape"] = new JObject { [shape] = body } };
}
static SpringRig Whale(Synth s, out SpringRigData data)
{
var go = new GameObject("whale");
Scrap.Add(go);
var rig = go.AddComponent<SpringRig>();
rig.Renderer = go.AddComponent<MeshRenderer>();
data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
rig.Initialize(data, new Bounds(Vector3.zero, new Vector3(2, 2, 8)));
return rig;
}
// ---------------------------------------------------------------- CPU references and helpers
// Forward kinematics of the swimming body with every spring joint at rest, independent of the jobs.
static void Fk(SpringRigData d, double t, SwimSettings swim, float3 rootPos, quaternion rootRot, float scale, out float3[] pos, out quaternion[] rot)
{
pos = new float3[d.BoneCount]; rot = new quaternion[d.BoneCount];
for (int i = 0; i < d.BoneCount; i++)
{
int p = d.Parent[i];
var local = d.SpineIndex[i] >= 0 ? math.mul(d.RestRotation[i], SwimPose.Rotation(t, d.SpineIndex[i], swim)) : d.RestRotation[i];
pos[i] = (p < 0 ? rootPos : pos[p]) + math.mul(p < 0 ? rootRot : rot[p], d.RestPosition[i] * scale);
rot[i] = math.mul(p < 0 ? rootRot : rot[p], local);
}
}
// Largest distance of a spring joint from its rest place on the body at the whale's pose.
static double Displacement(SpringRig w, SpringRigData d, double t, float3 rootPos, quaternion rootRot)
{
Fk(d, t, w.Swim, rootPos, rootRot, 1, out var rest, out _);
double worst = 0;
for (int i = 0; i < d.BoneCount; i++) if (!d.IsBody[i]) worst = math.max(worst, math.distance(rest[i], w.BonePosition(i)));
return worst;
}
static float3[] Positions(SpringRig w, SpringRigData d) => Enumerable.Range(0, d.BoneCount).Select(i => w.BonePosition(i)).ToArray();
static double Max(float3[] a, float3[] b, SpringRigData d, bool springs)
{
double worst = 0;
for (int i = 0; i < a.Length; i++) if (d.IsBody[i] != springs) worst = math.max(worst, math.distance(a[i], b[i]));
return worst;
}
static bool BitEqual(float4x4 a, float4x4 b) =>
a.c0.Equals(b.c0) && a.c1.Equals(b.c1) && a.c2.Equals(b.c2) && a.c3.Equals(b.c3);
static float Edge(Vector2 p, Vector2 a, Vector2 b) => (p.x - a.x) * (b.y - a.y) - (p.y - a.y) * (b.x - a.x);
static bool Near(bool[] mask, int x, int y, int size)
{
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
int px = x + dx, py = y + dy;
if (px >= 0 && py >= 0 && px < size && py < size && mask[py * size + px]) return true;
}
return false;
}
// ---------------------------------------------------------------- meshes and materials
struct PosNormal { public Vector3 p, n; }
struct Blend { public Vector4 w; public uint b0, b1, b2, b3; }
struct Vertex { public Vector3 p, n; public Vector2 uv; public Vector4 w; public uint b0, b1, b2, b3; }
static Mesh MakeMesh(List<Vertex> verts, List<int> tris)
{
var mesh = new Mesh();
mesh.SetVertexBufferParams(verts.Count,
new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3, 0),
new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3, 0),
new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2, 1),
new VertexAttributeDescriptor(VertexAttribute.BlendWeight, VertexAttributeFormat.Float32, 4, 2),
new VertexAttributeDescriptor(VertexAttribute.BlendIndices, VertexAttributeFormat.UInt32, 4, 2));
// A skinned mesh keeps position and normal, texcoords, and the blend pair in streams 0, 1, 2.
mesh.SetVertexBufferData(verts.Select(v => new PosNormal { p = v.p, n = v.n }).ToArray(), 0, 0, verts.Count, 0);
mesh.SetVertexBufferData(verts.Select(v => v.uv).ToArray(), 0, 0, verts.Count, 1);
mesh.SetVertexBufferData(verts.Select(v => new Blend { w = v.w, b0 = v.b0, b1 = v.b1, b2 = v.b2, b3 = v.b3 }).ToArray(), 0, 0, verts.Count, 2);
mesh.SetIndexBufferParams(tris.Count, IndexFormat.UInt32);
mesh.SetIndexBufferData(tris, 0, 0, tris.Count);
mesh.subMeshCount = 1;
mesh.SetSubMesh(0, new SubMeshDescriptor(0, tris.Count));
mesh.RecalculateBounds();
return mesh;
}
static Material SkinMaterial(float cull)
{
var tex = new Texture2D(2, 1, TextureFormat.RGBA32, false) { filterMode = FilterMode.Point };
tex.SetPixels(new[] { new Color(0.45f, 0.62f, 0.82f), new Color(0.95f, 0.72f, 0.45f) });
tex.Apply();
var m = new Material(Shader.Find("Aetheria/FaunaSkinned"));
m.SetTexture("_MainTex", tex);
m.SetFloat("_Cull", cull);
return m;
}
// A closed-ish whale: rings of body skinned to the spine, a thin tube along every tendril skinned joint by joint.
static Mesh TubeMesh(SpringRigData d, Synth s)
{
var verts = new List<Vertex>(); var tris = new List<int>();
void Ring(Func<int, (Vector3 p, Vector3 n)> shape, int sides, Vector4 w, uint b0, uint b1, Vector2 uv)
{
for (int i = 0; i < sides; i++) { var (p, n) = shape(i); verts.Add(new Vertex { p = p, n = n, uv = uv, w = w, b0 = b0, b1 = b1 }); }
}
void Join(int ringA, int ringB, int sides)
{
for (int i = 0; i < sides; i++)
{
int j = (i + 1) % sides;
tris.AddRange(new[] { ringA + i, ringB + i, ringA + j, ringA + j, ringB + i, ringB + j });
}
}
const int bodySides = 14, stations = 40;
float length = s.Spine - 1 + 0.9f;
int firstBody = verts.Count;
for (int k = 0; k < stations; k++)
{
float z = -0.45f + length * k / (stations - 1), u = (z + 0.45f) / length;
float r = 0.12f + 0.62f * Mathf.Pow(Mathf.Sin(Mathf.PI * Mathf.Clamp01(u * 0.95f + 0.02f)), 0.7f);
int lo = Mathf.Clamp(Mathf.FloorToInt(z), 0, s.Spine - 1), hi = Mathf.Min(lo + 1, s.Spine - 1);
float f = Mathf.Clamp01(z - lo);
Ring(i => { float a = i * 2 * Mathf.PI / bodySides; var nrm = new Vector3(Mathf.Cos(a), Mathf.Sin(a), 0); return (new Vector3(nrm.x * r, nrm.y * r * 0.85f, z), nrm); },
bodySides, new Vector4(1 - f, f, 0, 0), (uint)lo, (uint)hi, new Vector2(0.25f, 0.5f));
if (k > 0) Join(firstBody + (k - 1) * bodySides, firstBody + k * bodySides, bodySides);
}
Fk(d, 0, SwimSettings.Default, default, quaternion.identity, 1, out var rest, out _);
const int tubeSides = 5;
for (int c = 0; c < d.ChainCount; c++)
{
var bones = d.ChainBones(c);
int first = verts.Count;
for (int k = 0; k < bones.Count; k++)
{
float r = 0.045f * (1 - 0.7f * k / (bones.Count - 1));
var centre = (Vector3)rest[bones[k]];
Ring(i => { float a = i * 2 * Mathf.PI / tubeSides; var nrm = new Vector3(Mathf.Cos(a), Mathf.Sin(a), 0); return (centre + nrm * r, nrm); },
tubeSides, new Vector4(1, 0, 0, 0), (uint)bones[k], (uint)bones[k], new Vector2(0.75f, 0.5f));
if (k > 0) Join(first + (k - 1) * tubeSides, first + k * tubeSides, tubeSides);
}
}
return MakeMesh(verts, tris);
}
}
}

View file

@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f27873c0b90b6049a96315bf294d8c0