diff --git a/Assets/Scripts/Editor/SpringRigVerify.cs b/Assets/Scripts/Editor/SpringRigVerify.cs index b1c8da995..7c682ca18 100644 --- a/Assets/Scripts/Editor/SpringRigVerify.cs +++ b/Assets/Scripts/Editor/SpringRigVerify.cs @@ -30,10 +30,11 @@ namespace Aetheria.EditorTools 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, drawn-pose collision rounds - // included, other agents' load on the machine. Shipped worst 1.79 (runs 1.61, 1.66, 1.79), least mutant 7.05 (Burst off; - // runs 7.05 to 10.96), separation 3.9; bound sqrt(1.79 x 7.05) = 3.55. Before the interpolated pose: shipped 0.78 to 0.87. - const double CostBoundMs = 3.55; + // spring joints, Starfire (Ryzen 3 3100, GTX 1070), editor batchmode, 2 substeps a frame, drawn-pose collision rounds and the + // Burst bounds job included, other agents' load on the machine. Paired interleaved rounds of 60 frames, shipped against Burst + // off: shipped worst 0.728, least mutant 10.28 (Burst off), separation 14; bound sqrt(0.728 x 10.28) = 2.73. The managed + // bounds loop it replaced cost about 0.9 ms of the 1.5 ms this read before (Soul). + const double CostBoundMs = 2.73; static readonly List Scrap = new List(); static readonly SwimSettings NoSwim = new SwimSettings { PeriodSeconds = 1, Axis = new float3(1, 0, 0) }; @@ -53,7 +54,7 @@ namespace Aetheria.EditorTools ("freeze-and-reset", FreezeAndReset), ("skin-matches-cpu", SkinMatchesCpu), ("cost-bound", CostBound), ("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), + ("bounds-follow-the-swim", BoundsFollowTheSwim), ("lod-hysteresis", LodHysteresis), ("inertia-carries", InertiaCarries), }; int failed = 0; foreach (var (name, body) in checks) @@ -86,7 +87,7 @@ namespace Aetheria.EditorTools {""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]}], + {""name"":""t2"",""translation"":[0,-0.25,0]},{""name"":""loose""}], ""skins"": [{""joints"":[0,1,2,3,4]}], ""extensions"": {""VRMC_springBone"": {""specVersion"":""1.0"", ""colliders"": [ @@ -95,7 +96,7 @@ namespace Aetheria.EditorTools ""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"":3,""hitRadius"":0.06,""stiffness"":3,""gravityPower"":0.25,""gravityDir"":[0.6,-0.8,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}"; @@ -103,7 +104,7 @@ namespace Aetheria.EditorTools 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"; + if (j1.HitRadius != 0.06f || j1.Stiffness != 3f || j1.GravityPower != 0.25f || j1.DragForce != 0.2f || !j1.GravityDir.Equals(new float3(-0.6f, -0.8f, 0))) return "joint 1 parameters (gravity direction is mirrored in x like every glTF vector)"; 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"; @@ -119,7 +120,7 @@ namespace Aetheria.EditorTools return Refused(f => f.Replace("\"sphere\"", "\"cone\""), "unknown shape 'cone'") ?? Refused(f => f.Replace("{\"name\":\"fin\",\"translation\":[1,0,0]}", "{\"name\":\"fin\",\"matrix\":[1,0,0,0,0,1,0,0,0,0,1,0,1,0,0,1]}"), "uses a matrix") ?? Refused(f => f.Replace("{\"name\":\"fin\",\"translation\":[1,0,0]}", "{\"name\":\"fin\",\"scale\":[2,1,1]}"), "non-unit scale") - ?? Refused(f => f.Replace("{\"node\":1,\"shape\"", "{\"node\":9,\"shape\""), "Collider 1 sits on node 9, which is not a skin joint") + ?? Refused(f => f.Replace("{\"node\":1,\"shape\"", "{\"node\":5,\"shape\""), "Collider 1 sits on node 5, which is not a skin joint") ?? Refused(f => f.Replace("{\"node\":4,\"hitRadius\":0.07}", "{\"node\":3,\"hitRadius\":0.07}"), "named twice") ?? Refused(f => f.Replace("{\"node\":0,\"shape\"", "{\"node\":3,\"shape\""), "a spring joint; colliders ride body bones") ?? Refused(f => f.Replace("{\"name\":\"t1\",\"translation\":[0,-0.5,0]", "{\"name\":\"t1\",\"translation\":[0,0,0]"), "sits on its predecessor") @@ -127,9 +128,12 @@ namespace Aetheria.EditorTools ?? 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() + // Stiffness is a rate, so the rest pull settles at any value; a fixed-size nudge along the axis (VRM's) limit-cycles at 60. + static string RestHolds() => RestCase(20) ?? RestCase(60); + + static string RestCase(float stiffness) { - var s = new Synth { Gravity = 0, Stiffness = 20 }; + var s = new Synth { Gravity = 0, Stiffness = stiffness }; var w = Whale(s, out var data); w.Swim.AmplitudeDegrees = 0; double t = 0, moved = 0; @@ -141,7 +145,7 @@ namespace Aetheria.EditorTools 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"; + return worst <= 1e-4 ? null : $"stiffness {stiffness}: after 600 frames the worst spring joint is {worst} chain lengths from rest"; } static string LengthHolds() @@ -171,12 +175,13 @@ namespace Aetheria.EditorTools // radius at every stiffness from 2 to 60 and 0.18% under a scaled, rotated root (run7; the solver step alone left 0.8% at 2 // up to 3.9% at 60, Soul). Bound per lodur:ruling:deterministic-bound-margin: shipped worst 0.18%, least claimed mutant // (push-out removed) 100%, bound sqrt(0.0018 x 1.0) = 4%, separation 22 and 25. Mutants that ignore the whale's scale or - // its bone's rotation read 47% and 100%. + // its bone's rotation read 47% and 100%. Stiffness 60 claims the VRM nudge (a fixed-size pull along the rest axis, which a rate + // pull is not): it reads 4.6% there against shipped 0.13%, so that case's bound is sqrt(0.0013 x 0.046) = 0.9%, separation 5 and 7. static string ColliderPushesOut() => ColliderCase(8, 0.04, 1, Quaternion.identity, Vector3.zero) ?? ColliderCase(2, 0.04, 1, Quaternion.identity, Vector3.zero) ?? ColliderCase(20, 0.04, 1, Quaternion.identity, Vector3.zero) - ?? ColliderCase(60, 0.04, 1, Quaternion.identity, Vector3.zero) + ?? ColliderCase(60, 0.009, 1, Quaternion.identity, Vector3.zero) // A scaled, rotated whale: a collider that ignores the whale's scale or its bone's rotation is far from the tendril. ?? ColliderCase(8, 0.04, 2.2f, Quaternion.Euler(25, 70, 15), new Vector3(4, -3, 9)); @@ -283,8 +288,18 @@ namespace Aetheria.EditorTools 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; + // Leaving Full the tendrils ease to rest instead of snapping: the first frozen frame moves a tip, relative to its chain root, a + // small part of the chain (a snap is about half of it). + var chain = data.ChainBones(0); + float3 Rel() => w.BonePosition(chain[chain.Count - 1]) - w.BonePosition(chain[0]); + var relBefore = Rel(); cam.transform.position = new Vector3(0, 0, -300); + w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1); + double snap = math.distance(Rel(), relBefore) / ((s.Joints - 1) * math.length(s.Seg)); + if (snap > 0.15) return $"the first frozen frame moved a tip {snap:P0} of its chain (a snap, not an ease)"; + t += Dt; + w.Swim.AmplitudeDegrees = 15; + for (int i = 0; i < 30; i++, t += Dt) w.Present(t, new Vector3(Mathf.Sin((float)t * 5), 0, 0), Quaternion.identity, 1); // the ease ends at BlendSeconds int jobs = w.SolveJobsScheduled; double rest = 0; for (int i = 0; i < 10; i++, t += Dt) @@ -402,26 +417,31 @@ namespace Aetheria.EditorTools 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() + // Paired interleaved readings: rounds of 60 frames (10 warm-up), Burst on then off, five rounds; shipped worst and least mutant. + double Block(int round) { var ms = new List(); - for (int f = 0; f < 330; f++) + for (int f = 0; f < 70; f++) { - double t = f * Dt; + double t = (round * 70 + 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); + if (f >= 10) ms.Add((Stopwatch.GetTimestamp() - start) * 1000.0 / Stopwatch.Frequency); } ms.Sort(); return ms[ms.Count / 2]; } - double shipped, mutant; + double shipped = 0, mutant = double.MaxValue; try { - shipped = Measure(); - Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = false; - mutant = Measure(); + for (int round = 0; round < 5; round++) + { + Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = true; + shipped = math.max(shipped, Block(round * 2)); + Unity.Burst.BurstCompiler.Options.EnableBurstCompilation = false; + mutant = math.min(mutant, Block(round * 2 + 1)); + } } finally { @@ -439,7 +459,7 @@ namespace Aetheria.EditorTools } 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"); + Debug.Log($"{Tag} cost-bound: 3 whales x 770 joints, median ms per frame, paired rounds: shipped worst {shipped:F3}, Burst-off least {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; @@ -504,6 +524,30 @@ namespace Aetheria.EditorTools return hi - lo <= BeatBound ? null : $"the tip's lag behind a steadily moving body beats by {hi - lo} u (bound {BeatBound})"; } + // Inertia: a tendril dragged behind a body that stops swings forward past rest (velocity carried, light drag); a pull alone only + // creeps back. Without the velocity term the overshoot is nil. + static string InertiaCarries() + { + var s = new Synth { Chains = 2, Gravity = 0, Stiffness = 1.5f, Drag = 0.05f, Colliders = new JArray() }; + var w = Whale(s, out var data); + w.Swim.AmplitudeDegrees = 0; + var chain = data.ChainBones(0); + int tip = chain[chain.Count - 1]; + double t = 0, overshoot = double.MinValue; + for (int i = 0; i < 60; i++, t += Dt) w.Present(t, new Vector3(0, 0, i * 4f / 60), Quaternion.identity, 1); + var stop = new Vector3(0, 0, 59 * 4f / 60); + Fk(data, 0, NoSwim, stop, quaternion.identity, 1, out var rest, out _); + for (int i = 0; i < 180; i++, t += Dt) + { + w.Present(t, stop, Quaternion.identity, 1); + overshoot = math.max(overshoot, w.BonePosition(tip).z - rest[tip].z); + } + Debug.Log($"{Tag} inertia: tip overshoot past rest along the motion {overshoot:F5} u"); + return overshoot >= InertiaBound ? null : $"after the body stops the tip overshoots rest by {overshoot} u, expected at least {InertiaBound}"; + } + // Shipped overshoot 1.15 u, no-inertia mutant -0.03 u (it only creeps back): the bound sits between, at 0.5. + const double InertiaBound = 0.5; + // The skin matrices are the product they claim to be, checked against forward kinematics that shares no code with the jobs, // on a rig with rotated rest bones, exact inverse bind matrices, a swimming body and a scaled, rotated root. static string SkinMatchesFk() diff --git a/Assets/Scripts/Fauna Display/SpringRig.cs b/Assets/Scripts/Fauna Display/SpringRig.cs index 7eee663d6..7d3b12d3b 100644 --- a/Assets/Scripts/Fauna Display/SpringRig.cs +++ b/Assets/Scripts/Fauna Display/SpringRig.cs @@ -34,6 +34,8 @@ namespace Aetheria.FaunaDisplay public float FrozenAbove = 0.015f; [Tooltip("A level is left only once the projected height is this fraction below the threshold that entered it.")] [Range(0f, 0.5f)] public float Hysteresis = 0.15f; + [Tooltip("Drawn seconds over which the tendrils ease to rest when the level leaves Full.")] + public float BlendSeconds = 0.25f; public Camera LodCamera; public SpringRigData Data { get; private set; } @@ -56,7 +58,10 @@ namespace Aetheria.FaunaDisplay long _lastIndex; float3 _lastPosition; float _pad; - float _lodDiameter; + float _lodDiameter, _restWeight = 1f, _lastFrac; + double _lastTime; + bool _everFull; + NativeArray _minMax; readonly System.Collections.Generic.List _owned = new System.Collections.Generic.List(); @@ -87,6 +92,7 @@ namespace Aetheria.FaunaDisplay _simPrev = Own(n); _boneRot = Own(n); _skin = Own(n); + _minMax = Own(2); SkinBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, n, 64); var block = new MaterialPropertyBlock(); block.SetBuffer("_SpringBones", SkinBuffer); @@ -106,6 +112,8 @@ namespace Aetheria.FaunaDisplay // One radius all round (the mesh turns with its bones): the rest mesh's largest margin past its bones, per axis, as a length. _pad = math.length(math.max(math.max(lo - (float3)meshBounds.min, (float3)meshBounds.max - hi), 0f)); _started = false; + _everFull = false; + _restWeight = 1f; } // The one entry: swim pose, solver substeps, skin write, upload, bounds. drawnTime is DrawAhead.Time. @@ -122,6 +130,13 @@ namespace Aetheria.FaunaDisplay _lastIndex = index; float frac = (float)(drawnTime * SubstepRate - index); + // Leaving Full the tendrils ease to rest over BlendSeconds of drawn time (no snap); the solver still draws, with no steps. + double dt = _started ? math.max(drawnTime - _lastTime, 0) : 0; + _lastTime = drawnTime; + if (full) { _restWeight = 0f; _everFull = true; _lastFrac = frac; } + else if (_everFull) _restWeight = (float)math.min(1.0, _restWeight + dt / math.max(BlendSeconds, 1e-4f)); + bool easing = !full && _everFull && _restWeight < 1f; + bool reset = !_started || (full && !_wasFull) || math.distance(_lastPosition, position) > Data.MaxChainLength * scale; _started = true; _wasFull = full; @@ -135,7 +150,7 @@ namespace Aetheria.FaunaDisplay order = _order, parent = _parent, spine = _spine, restPos = _restPos, restRot = _restRot, swim = Swim, time = drawnTime, rootPos = pos, rootRot = rot, scale = scale, bonePos = _bonePos, boneRot = _boneRot, }.Schedule(); - if (full) + if (full || easing) { SolveJobsScheduled++; SubstepsRun += steps; @@ -144,13 +159,14 @@ namespace Aetheria.FaunaDisplay chainStart = _chainStart, chainLen = _chainLen, chainBone = _chainBone, chainColStart = _chainColStart, chainColLen = _chainColLen, chainCol = _chainCol, restPos = _restPos, restRot = _restRot, param = _param, colliders = _colliders, bonePos = _bonePos, boneRot = _boneRot, simPos = _simPos, simPrev = _simPrev, - substeps = steps, step = 1f / SubstepRate, scale = scale, frac = frac, reset = reset, + substeps = steps, step = 1f / SubstepRate, scale = scale, frac = full ? frac : _lastFrac, blend = full ? 0f : _restWeight, reset = reset, }.Schedule(Data.ChainCount, 4, pose); } - new SkinJob + var skinned = new SkinJob { bonePos = _bonePos, boneRot = _boneRot, bind = _bind, rootInverse = math.inverse(float4x4.TRS(pos, rot, new float3(scale))), scale = scale, skin = _skin, - }.Schedule(Data.BoneCount, 64, pose).Complete(); + }.Schedule(Data.BoneCount, 64, pose); + new BoundsJob { bonePos = _bonePos, rootPos = pos, rootRot = rot, scale = scale, minMax = _minMax }.Schedule(skinned).Complete(); SkinBuffer.SetData(_skin); var t = Renderer.transform; @@ -158,14 +174,7 @@ namespace Aetheria.FaunaDisplay t.localScale = new Vector3(scale, scale, scale); // Bounds follow the pose: every bone in object space, plus the rest mesh's margin around the bones. - var inverse = math.inverse(rot); - float3 min = new float3(float.MaxValue), max = new float3(float.MinValue); - for (int i = 0; i < _bonePos.Length; i++) - { - float3 local = math.mul(inverse, _bonePos[i] - pos) / scale; - min = math.min(min, local); max = math.max(max, local); - } - min -= _pad; max += _pad; + float3 min = _minMax[0] - _pad, max = _minMax[1] + _pad; Renderer.localBounds = new Bounds((min + max) * 0.5f, max - min); return Level; } diff --git a/Assets/Scripts/Fauna Display/SpringSolver.cs b/Assets/Scripts/Fauna Display/SpringSolver.cs index cf9eb1ab1..79dd2e0d1 100644 --- a/Assets/Scripts/Fauna Display/SpringSolver.cs +++ b/Assets/Scripts/Fauna Display/SpringSolver.cs @@ -54,7 +54,7 @@ namespace Aetheria.FaunaDisplay [NativeDisableParallelForRestriction] public NativeArray bonePos, simPos, simPrev; [NativeDisableParallelForRestriction] public NativeArray boneRot; public int substeps; - public float step, scale, frac; + public float step, scale, frac, blend; public bool reset; public void Execute(int c) @@ -109,7 +109,7 @@ namespace Aetheria.FaunaDisplay float3 axis = math.normalizesafe(restPos[bone], new float3(0, -1, 0)); var jp = param[start + k - 1]; float3 fall = math.mul(rest, axis); - float3 p = Reproject(head, math.lerp(simPrev[bone], simPos[bone], frac), seg, fall); + float3 p = Reproject(head, math.lerp(math.lerp(simPrev[bone], simPos[bone], frac), bonePos[bone], blend), seg, fall); // blend: weight toward rest (bonePos still holds it) int cs = chainColStart[c], cn = chainColLen[c]; // A blend of two pushed-out points can dip into a collider; two rounds of push-out and length settle it. for (int round = 0; round < 2 && cn > 0; round++) @@ -162,6 +162,29 @@ namespace Aetheria.FaunaDisplay } } + // The renderer's bounds: every bone's place in the whale's object space, min and max. + [BurstCompile(CompileSynchronously = true, DisableSafetyChecks = true)] + public struct BoundsJob : IJob + { + [ReadOnly] public NativeArray bonePos; + public float3 rootPos; + public quaternion rootRot; + public float scale; + public NativeArray minMax; + + public void Execute() + { + quaternion inverse = math.inverse(rootRot); + float3 min = new float3(float.MaxValue), max = new float3(float.MinValue); + for (int i = 0; i < bonePos.Length; i++) + { + float3 local = math.mul(inverse, bonePos[i] - rootPos) / scale; + min = math.min(min, local); max = math.max(max, local); + } + minMax[0] = min; minMax[1] = max; + } + } + [BurstCompile(CompileSynchronously = true, DisableSafetyChecks = true)] public struct SkinJob : IJobParallelFor {