Soul s1 fixes: the base colour is decoded on the CPU; the shadow, normals, root jump, ease default and colour space are pinned

import-needs-gpu: SpringRigImporter.Albedo no longer blits through a RenderTexture: decode, area-average downscale, mip chain and BC7 are
CPU work, so the texture is the same with or without a device (raw SHA-256 E204A8B6B6CD1F93185B6AACCD2D1B95A61508B498F8ABA302C57E34049498AE
with Direct3D11 and with -nographics). The importer version is 2 and the importer depends on its own script, so an edit reimports.
SpringRigVerify.ImportNoGfx (run with -nographics) reimports the committed asset and checks the hash; importer-builds checks the same hash
and that the texture is sRGB.

shadow-skin-unpinned: shadow-is-skinned renders a ShadowsOnly leviathan under a downward light and compares the floor shadow with the
projection of its skinned triangles: IoU 0.877 shipped, 0.330 with SHADOWCASTER dropped from the shader guard; bound 0.538.

edges-unpinned: root-jump-resets (a joint 1.79 from rest if a jump during the ease seeds from the drawn pose, 8e-8 shipped; bound 3.9e-4),
normals-are-skinned (light seen from a bent whale 41253 shipped, 13667 with the normals unskinned; bound 23700), the BlendSeconds default in
0.5 to 1 (kills 0.25), sRGB (kills a linear texture). Each mutant fails Run; the final Run passes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nibu-hands 2026-12-01 12:43:26 +01:00 • committed by soul
commit c206a6ea51
2 changed files with 257 additions and 12 deletions

View file

@ -27,7 +27,9 @@ namespace Aetheria.EditorTools
/// MeshFilter, MeshRenderer and SpringRig. SpringRigData.FromGlb decides whether the rig is acceptable and adds no rule here; glTFast
/// supplies the mesh in the same handedness as the rig (SpringRigData's mirror) and is used here and in VerifyGlb only.
/// </summary>
[ScriptedImporter(1, "springrig")]
// The version is bumped whenever the importer's product changes (a Library keeps what an older importer made); the dependency on this
// script's own file reimports on any edit of it, so a forgotten bump cannot leave a stale asset behind.
[ScriptedImporter(2, "springrig")]
public sealed class SpringRigImporter : ScriptedImporter
{
public SwimSettings Swim = new SwimSettings { AmplitudeDegrees = 9f, PeriodSeconds = 3.2f, PhasePerBone = 0.1f, Axis = new float3(1, 0, 0) };
@ -45,6 +47,7 @@ namespace Aetheria.EditorTools
if (mesh == null) { ctx.LogImportError($"{ctx.assetPath}: {refusal}"); return; }
mesh.name = "mesh";
ctx.DependsOnSourceAsset("Assets/Scripts/Editor/SpringRigImporter.cs");
ctx.DependsOnSourceAsset("Assets/Shaders/FaunaSkinned.shader"); // the material needs the shader imported first, and reimports with it
var material = new Material(Shader.Find("Aetheria/FaunaSkinned")) { name = "material" };
var materialIndex = json["meshes"]?[0]?["primitives"]?[0]?["material"];
@ -158,27 +161,47 @@ namespace Aetheria.EditorTools
return bytes;
}
// sRGB, mips, BC7. Scaled down first when larger than max.
// sRGB, mips, BC7. Scaled down first when larger than max. Every step is CPU work on the image's pixels (decode, area average,
// mip chain, BC7), so the product is the same with or without a graphics device (-nographics batch imports, CI, cache producers).
static Texture2D Albedo(byte[] image, int max)
{
var decoded = new Texture2D(2, 2, TextureFormat.RGBA32, false, false);
if (!decoded.LoadImage(image, false)) { UnityEngine.Object.DestroyImmediate(decoded); return null; }
int w = decoded.width, h = decoded.height, side = Math.Max(w, h);
if (side > max) { w = Math.Max(1, w * max / side); h = Math.Max(1, h * max / side); }
var rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
var previous = RenderTexture.active;
Graphics.Blit(decoded, rt);
var texture = new Texture2D(w, h, TextureFormat.RGBA32, true, false);
RenderTexture.active = rt;
texture.ReadPixels(new Rect(0, 0, w, h), 0, 0);
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(rt);
var pixels = decoded.GetPixels32();
UnityEngine.Object.DestroyImmediate(decoded);
if (side > max)
{
int tw = Math.Max(1, w * max / side), th = Math.Max(1, h * max / side);
pixels = AreaAverage(pixels, w, h, tw, th);
w = tw; h = th;
}
var texture = new Texture2D(w, h, TextureFormat.RGBA32, true, false);
texture.SetPixels32(pixels);
texture.Apply(true);
EditorUtility.CompressTexture(texture, TextureFormat.BC7, TextureCompressionQuality.Normal);
return texture;
}
// Each target pixel is the mean of the source pixels it covers (box filter by source index ranges).
static Color32[] AreaAverage(Color32[] src, int w, int h, int tw, int th)
{
var dst = new Color32[tw * th];
for (int y = 0; y < th; y++)
{
int y0 = y * h / th, y1 = Math.Max(y0 + 1, (y + 1) * h / th);
for (int x = 0; x < tw; x++)
{
int x0 = x * w / tw, x1 = Math.Max(x0 + 1, (x + 1) * w / tw);
int r = 0, g = 0, bl = 0, a = 0, n = 0;
for (int sy = y0; sy < y1; sy++)
for (int sx = x0; sx < x1; sx++) { var p = src[sy * w + sx]; r += p.r; g += p.g; bl += p.b; a += p.a; n++; }
dst[y * tw + x] = new Color32((byte)((r + n / 2) / n), (byte)((g + n / 2) / n), (byte)((bl + n / 2) / n), (byte)((a + n / 2) / n));
}
}
return dst;
}
// The JSON chunk and the offset of the BIN chunk's data (the container SpringRigData.FromGlb reads).
static (JObject json, int binAt) Chunks(byte[] glb)
{

View file

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Aetheria.FaunaDisplay;
using Newtonsoft.Json.Linq;
using Unity.Mathematics;
@ -62,7 +63,8 @@ namespace Aetheria.EditorTools
("lengths-hold-at-any-rate", LengthsHoldAtAnyRate), ("steady-motion-is-smooth", SteadyMotionIsSmooth), ("skin-matches-fk", SkinMatchesFk),
("capsule-is-finite", CapsuleIsFinite), ("gravity-sags", GravitySags), ("reset-honours-scale", ResetHonoursScale),
("bounds-follow-the-swim", BoundsFollowTheSwim), ("lod-hysteresis", LodHysteresis), ("inertia-carries", InertiaCarries),
("reentry-is-continuous", ReentryIsContinuous),
("reentry-is-continuous", ReentryIsContinuous), ("root-jump-resets", RootJumpResets), ("shadow-is-skinned", ShadowIsSkinned),
("normals-are-skinned", NormalsAreSkinned),
};
int failed = 0;
foreach (var (name, body) in checks)
@ -675,6 +677,11 @@ namespace Aetheria.EditorTools
static string ReentryIsContinuous()
{
// The ease default reads as settling, not as a flare (finding ease-moves-fast: 0.5 to 1 s).
var defaults = new GameObject("easeDefault");
Scrap.Add(defaults);
float blend = defaults.AddComponent<SpringRig>().BlendSeconds;
if (blend < 0.5f || blend > 1f) return $"BlendSeconds defaults to {blend}, not in 0.5 to 1";
var shortOut = ReentryCase(3);
var longOut = ReentryCase(8); // both run, so both readings are logged
return shortOut ?? longOut;
@ -710,6 +717,184 @@ namespace Aetheria.EditorTools
return moved <= ReentryBound ? null : $"returning after {framesOut} frames out moved a tip {moved:P0} of its chain in one frame (a reset to rest, not a continuation)";
}
// A root jump while the ease is part way still resets to rest: the returning frame's tips lie on the body's rest pose, not on the
// stale drawn pose far away. Readings (largest distance of a spring joint from its rest place, in units; the chain is 1.2 long):
// shipped 8.4e-8, a solver seeded from the stale drawn pose 1.79; bound sqrt(8.4e-8 x 1.79) = 3.9e-4..
const double JumpBound = 3.9e-4;
static string RootJumpResets()
{
var cam = new GameObject("lodCam").AddComponent<Camera>();
Scrap.Add(cam.gameObject);
cam.fieldOfView = 60;
var w = Whale(new Synth { Gravity = 0, Stiffness = 4 }, out var data);
w.LodCamera = cam;
w.Swim.AmplitudeDegrees = 0;
double t = 0;
Vector3 at = Vector3.zero;
void Frame(float back) { cam.transform.position = at + new Vector3(0, 0, -back); w.Present(t, at, Quaternion.identity, 1); t += Dt; }
for (; t < 3;) { at = new Vector3(Mathf.Sin((float)t * 5) * 3.2f, 0, 0); Frame(50); }
for (int i = 0; i < 3; i++) Frame(300);
at = new Vector3(500, 0, 0);
Frame(50);
double off = Displacement(w, data, t - Dt, at, quaternion.identity);
Debug.Log($"{Tag} root jump during the ease: a spring joint {off:F4} u from rest on the returning frame (bound {JumpBound})");
return off <= JumpBound ? null : $"after a root jump a spring joint is {off} from rest: the solver was seeded from the stale pose";
}
// The shadow caster skins like the body: a ShadowsOnly leviathan swimming at 40 degrees under a light pointing straight down casts, on
// a floor seen from above, the silhouette of its skinned triangles, not of its rest triangles. Intersection over union against the CPU
// projection of the skinned triangles. Readings: shipped 0.877; a caster that compiles the empty stub 0.330 (and 0.879 to the rest
// triangles). The bound is lodur:ruling:deterministic-bound-margin's geometric mean sqrt(0.877 x 0.330) = 0.538, separation 1.63 each side.
const double ShadowBound = 0.538;
static string ShadowIsSkinned()
{
var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath);
if (prefab == null) return $"{AssetPath} imported no main object";
var (shadows, distance, resolution) = (QualitySettings.shadows, QualitySettings.shadowDistance, QualitySettings.shadowResolution);
var (ambientMode, ambient) = (RenderSettings.ambientMode, RenderSettings.ambientLight);
try
{
var go = UnityEngine.Object.Instantiate(prefab);
Scrap.Add(go);
var rig = go.GetComponent<SpringRig>();
rig.Initialize();
rig.Swim.AmplitudeDegrees = 40;
go.GetComponent<MeshRenderer>().shadowCastingMode = ShadowCastingMode.ShadowsOnly;
QualitySettings.shadows = ShadowQuality.All; QualitySettings.shadowDistance = 20; QualitySettings.shadowResolution = UnityEngine.ShadowResolution.VeryHigh;
var light = new GameObject("sun").AddComponent<Light>();
Scrap.Add(light.gameObject);
light.type = LightType.Directional; light.intensity = 1.2f; light.shadows = LightShadows.Hard; light.shadowBias = 0.005f; light.shadowNormalBias = 0f;
light.transform.rotation = Quaternion.Euler(90, 0, 0);
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = new Color(0.1f, 0.1f, 0.1f);
double t = 0;
for (int f = 0; f < 150; f++, t += Dt) rig.Present(t, new Vector3(0, 0.5f, 0), Quaternion.identity, 1);
var floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
Scrap.Add(floor);
floor.transform.position = new Vector3(0, -0.6f, 0); floor.transform.localScale = new Vector3(0.3f, 1, 0.3f);
floor.GetComponent<Renderer>().sharedMaterial = new Material(Shader.Find("Standard")) { color = Color.white };
var cam = new GameObject("shadowCam").AddComponent<Camera>();
Scrap.Add(cam.gameObject);
cam.orthographic = true; cam.orthographicSize = 0.6f; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = Color.black;
cam.transform.position = new Vector3(0, 3, 0); cam.transform.rotation = Quaternion.Euler(90, 0, 0);
cam.nearClipPlane = 0.1f; cam.farClipPlane = 10;
const int size = 512;
var rt = new RenderTexture(size, size, 24, RenderTextureFormat.ARGB32);
cam.targetTexture = rt;
cam.Render();
var read = new Texture2D(size, size, TextureFormat.RGBA32, false);
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, size, size), 0, 0);
RenderTexture.active = null;
var px = read.GetPixels32();
int lo = 255, hi = 0;
foreach (var p in px) { lo = Math.Min(lo, p.r); hi = Math.Max(hi, p.r); }
if (hi - lo < 40) return $"no shadow on the floor (floor values {lo} to {hi})";
int threshold = (lo + hi) / 2;
var gpu = px.Select(p => p.r < threshold).ToArray();
var mesh = go.GetComponent<MeshFilter>().sharedMesh;
var verts = mesh.vertices; var weights = mesh.boneWeights;
var l2w = go.transform.localToWorldMatrix;
var skinned = new Vector2[verts.Length];
for (int v = 0; v < verts.Length; v++)
{
var p4 = new float4(verts[v], 1); var w = weights[v];
float3 s = w.weight0 * math.mul(rig.Skin[w.boneIndex0], p4).xyz + w.weight1 * math.mul(rig.Skin[w.boneIndex1], p4).xyz
+ w.weight2 * math.mul(rig.Skin[w.boneIndex2], p4).xyz + w.weight3 * math.mul(rig.Skin[w.boneIndex3], p4).xyz;
skinned[v] = (Vector2)cam.WorldToScreenPoint(l2w.MultiplyPoint3x4(s));
}
double iou = Iou(gpu, Raster(skinned, mesh.triangles, size));
UnityEngine.Object.DestroyImmediate(rt);
Debug.Log($"{Tag} shadow: intersection over union with the skinned triangles' projection {iou:F3} (bound {ShadowBound})");
return iou >= ShadowBound ? null : $"the shadow matches the skinned silhouette only {iou:F3} (bound {ShadowBound}): the shadow caster is not skinning";
}
finally { QualitySettings.shadows = shadows; QualitySettings.shadowDistance = distance; QualitySettings.shadowResolution = resolution; RenderSettings.ambientMode = ambientMode; RenderSettings.ambientLight = ambient; }
}
static bool[] Raster(Vector2[] v, int[] tris, int size)
{
var m = new bool[size * size];
for (int i = 0; i < tris.Length; i += 3)
{
var a = v[tris[i]]; var b = v[tris[i + 1]]; var c = v[tris[i + 2]];
int x0 = Mathf.Max(0, Mathf.FloorToInt(Mathf.Min(a.x, Mathf.Min(b.x, c.x)))), x1 = Mathf.Min(size - 1, Mathf.CeilToInt(Mathf.Max(a.x, Mathf.Max(b.x, c.x))));
int y0 = Mathf.Max(0, Mathf.FloorToInt(Mathf.Min(a.y, Mathf.Min(b.y, c.y)))), y1 = Mathf.Min(size - 1, Mathf.CeilToInt(Mathf.Max(a.y, Mathf.Max(b.y, c.y))));
for (int y = y0; y <= y1; y++)
for (int x = x0; x <= x1; 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)) m[y * size + x] = true;
}
}
return m;
}
static double Iou(bool[] a, bool[] b)
{
int both = 0, either = 0;
for (int k = 0; k < a.Length; k++) { if (a[k] && b[k]) both++; if (a[k] || b[k]) either++; }
return either == 0 ? 0 : (double)both / either;
}
// The normals are skinned with the positions: a whale lit by one directional light pointing straight down (black ambient) whose body is
// bent about Z turns its triangles' normals (X at rest, so lit by nothing) up toward the light, and reflects light; a shader that skins
// positions only keeps the normals at X and reflects none. The light the camera sees from the bent whale. Readings: shipped 41253, normals not skinned 13667 (rest 12545); the bound is
// lodur:ruling:deterministic-bound-margin's geometric mean sqrt(41253 x 13667) = 23744, a separation of 1.74 on each side.
const double NormalsBound = 23700;
static string NormalsAreSkinned()
{
var (ambientMode, ambient) = (RenderSettings.ambientMode, RenderSettings.ambientLight);
try
{
var light = new GameObject("normalsSun").AddComponent<Light>();
Scrap.Add(light.gameObject);
light.type = LightType.Directional; light.intensity = 1; light.shadows = LightShadows.None;
light.transform.rotation = Quaternion.Euler(90, 0, 0);
RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = Color.black;
double Seen(float amplitude)
{
var s = new Synth { Spine = 2, Chains = 1, Joints = 2, Gravity = 0, Stiffness = 4 };
var go = new GameObject("normalsTest");
Scrap.Add(go);
var rig = go.AddComponent<SpringRig>();
var data = SpringRigData.FromGlbJson(s.Build(out var bin), bin);
var (verts, tris) = BoneTriangles(data);
var mesh = MakeMesh(verts, tris);
go.AddComponent<MeshFilter>().sharedMesh = mesh;
var mr = go.AddComponent<MeshRenderer>();
mr.sharedMaterial = SkinMaterial(0);
rig.Renderer = mr;
rig.Swim = new SwimSettings { AmplitudeDegrees = amplitude, PeriodSeconds = 4, PhasePerBone = 0, Axis = new float3(0, 0, 1) };
rig.Initialize(data, mesh.bounds);
rig.Present(1.0, Vector3.zero, Quaternion.identity, 1); // a quarter period: the swim at its peak
var cam = new GameObject("normalsCam").AddComponent<Camera>();
Scrap.Add(cam.gameObject);
cam.orthographic = true; cam.orthographicSize = 1.5f;
cam.transform.SetPositionAndRotation(new Vector3(10, 0, 0.5f), Quaternion.LookRotation(Vector3.left));
cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = Color.black;
cam.nearClipPlane = 0.1f; cam.farClipPlane = 50;
var rt = new RenderTexture(128, 128, 24, RenderTextureFormat.ARGB32);
cam.targetTexture = rt;
cam.Render();
var read = new Texture2D(128, 128, TextureFormat.RGBA32, false);
RenderTexture.active = rt;
read.ReadPixels(new Rect(0, 0, 128, 128), 0, 0);
RenderTexture.active = null;
UnityEngine.Object.DestroyImmediate(rt);
double total = 0;
foreach (var p in read.GetPixels32()) total += p.r + p.g + p.b;
return total;
}
double rest = Seen(0), bent = Seen(40);
Debug.Log($"{Tag} normals: light seen at rest {rest}, bent 40 degrees {bent} (bound {NormalsBound})");
return bent >= NormalsBound ? null : $"a whale bent 40 degrees reflects {bent} (at rest {rest}): its normals did not turn with it";
}
finally { RenderSettings.ambientMode = ambientMode; RenderSettings.ambientLight = ambient; }
}
// Hovering at the Full threshold must not flip the level every frame.
static string LodHysteresis()
{
@ -878,6 +1063,9 @@ namespace Aetheria.EditorTools
|| mesh.GetVertexAttributeFormat(VertexAttribute.BlendIndices) != VertexAttributeFormat.UInt32 || mesh.GetVertexAttributeDimension(VertexAttribute.BlendIndices) != 4)
{ done("the mesh does not carry BlendWeight Float32x4 and BlendIndices UInt32x4"); return; }
var texture = main.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_MainTex") as Texture2D;
if (texture != null && !texture.isDataSRGB) { done("the base colour is linear, not sRGB"); return; }
var hash = AlbedoHash();
if (hash != null) { done(hash); return; }
if (texture == null || texture.format != TextureFormat.BC7 || texture.mipmapCount < 2) { done($"the base colour is {(texture == null ? "missing" : texture.format + " with " + texture.mipmapCount + " mips")}, not BC7 with mips"); return; }
var entry = UnityEditor.AddressableAssets.AddressableAssetSettingsDefaultObject.Settings.FindAssetEntry(AssetDatabase.AssetPathToGUID(AssetPath), true);
if (entry == null) { done("Addressables has no entry for the asset (Assets/Content is the folder entry)"); return; }
@ -892,6 +1080,40 @@ namespace Aetheria.EditorTools
});
}
// The imported base colour is a function of the file's bytes alone: the SHA-256 of its raw BC7 data with mips is the same in a session
// with a graphics device and in a -nographics one (SpringRigVerify.ImportNoGfx forces a reimport there and runs the same check).
const string AlbedoRawSha = "E204A8B6B6CD1F93185B6AACCD2D1B95A61508B498F8ABA302C57E34049498AE";
static string AlbedoHash()
{
var main = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath);
var texture = main == null ? null : main.GetComponent<MeshRenderer>().sharedMaterial.GetTexture("_MainTex") as Texture2D;
if (texture == null) return "the asset has no base colour";
using var sha = SHA256.Create();
string got = BitConverter.ToString(sha.ComputeHash(texture.GetRawTextureData<byte>().ToArray())).Replace("-", "");
Debug.Log($"{Tag} albedo raw SHA-256 {got} ({SystemInfo.graphicsDeviceType})");
return got == AlbedoRawSha ? null : $"the base colour's raw SHA-256 is {got}, not {AlbedoRawSha}";
}
// Batch method for a -nographics session: reimport the committed asset with no device and check what comes out.
public static void ImportNoGfx()
{
string verdict;
try
{
if (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Null) verdict = "this session has a graphics device; run it with -nographics";
else
{
AssetDatabase.ImportAsset(AssetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
verdict = AssetDatabase.LoadAssetAtPath<GameObject>(AssetPath) == null ? "the reimport made no main object" : AlbedoHash();
}
}
catch (Exception e) { verdict = "exception: " + e; }
if (verdict == null) Debug.Log($"{Tag} PASS import without a device");
else Debug.LogError($"{Tag} FAIL import without a device: {verdict}");
EditorApplication.Exit(verdict == null ? 0 : 1);
}
// The head is at +Z: the spine's root bone sits, at rest, past the centre of the imported mesh's bounds along Z, which is where SpringRig's
// heading (its rotation) points the whale. A recipe whose head lands at -Z fails here.
static string HeadForward(string path)