diff --git a/Assets/Scripts/Fauna Display/SpringRig.cs b/Assets/Scripts/Fauna Display/SpringRig.cs new file mode 100644 index 000000000..ee3855ee7 --- /dev/null +++ b/Assets/Scripts/Fauna Display/SpringRig.cs @@ -0,0 +1,164 @@ +/* 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 Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; +using UnityEngine; + +namespace Aetheria.FaunaDisplay +{ + public enum SpringLod { Full, Frozen, Hidden } + + // One whale's skeleton, presentation only (rulings whale-rig-spring-bone-tendrils, presenter-phase-from-zone-time, + // fauna-in-sim-ruled): it owns every bone pose and skin matrix, body and tendril, of the frame it draws. The caller + // hands in the drawn time (DrawAhead.Time) and the whale's root pose; nothing else enters, and only the skin buffer + // and the renderer's bounds leave. No GameObject per joint and no Unity skinning or animation components: a shader reads the + // skin matrices (SpringSkin.cginc) from the mesh's BLENDINDICES and BLENDWEIGHTS. + public sealed class SpringRig : MonoBehaviour + { + // The solver's fixed substep, in drawn seconds, and the most substeps one frame runs (a hitch drops the rest). + public const int SubstepRate = 120; + public const int MaxSubsteps = 4; + + public MeshRenderer Renderer; + public SwimSettings Swim = SwimSettings.Default; + [Tooltip("Projected height of the whale as a fraction of the viewport at or above which the tendrils are solved.")] + public float FullAbove = 0.06f; + [Tooltip("Below FullAbove and at or above this the tendrils hold their rest pose on the swimming body; below it the caller hides them.")] + public float FrozenAbove = 0.015f; + public Camera LodCamera; + + public SpringRigData Data { get; private set; } + public SpringLod Level { get; private set; } + public GraphicsBuffer SkinBuffer { get; private set; } + public NativeArray.ReadOnly Skin => _skin.AsReadOnly(); + public long SubstepsRun { get; private set; } + public int SolveJobsScheduled { get; private set; } + public int Resets { get; private set; } + public float3 BonePosition(int bone) => _bonePos[bone]; + public quaternion BoneRotation(int bone) => _boneRot[bone]; + + NativeArray _order, _parent, _spine, _chainStart, _chainLen, _chainBone, _chainColStart, _chainColLen, _chainCol; + NativeArray _restPos, _bonePos, _simPos, _simPrev; + NativeArray _restRot, _boneRot; + NativeArray _bind, _skin; + NativeArray _param; + NativeArray _colliders; + bool _started, _wasFull; + long _lastIndex; + float3 _lastPosition; + + readonly System.Collections.Generic.List _owned = new System.Collections.Generic.List(); + + NativeArray Own(T[] source) where T : unmanaged { var a = new NativeArray(source, Allocator.Persistent); _owned.Add(a); return a; } + NativeArray Own(int length) where T : unmanaged { var a = new NativeArray(length, Allocator.Persistent); _owned.Add(a); return a; } + + public void Initialize(SpringRigData data, Bounds meshBounds) + { + Release(); + Data = data; + _order = Own(data._order); + _parent = Own(data._parent); + _spine = Own(data._spine); + _chainStart = Own(data._chainStart); + _chainLen = Own(data._chainLen); + _chainBone = Own(data._chainBone); + _chainColStart = Own(data._chainColStart); + _chainColLen = Own(data._chainColLen); + _chainCol = Own(data._chainCol); + _restPos = Own(data._restPos); + _restRot = Own(data._restRot); + _bind = Own(data._bind); + _param = Own(data._chainParam); + _colliders = Own(data._colliders); + int n = data.BoneCount; + _bonePos = Own(n); + _simPos = Own(n); + _simPrev = Own(n); + _boneRot = Own(n); + _skin = Own(n); + SkinBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, n, 64); + var block = new MaterialPropertyBlock(); + block.SetBuffer("_SpringBones", SkinBuffer); + Renderer.SetPropertyBlock(block); + // Tendrils swing beyond the rest mesh by at most their length. + meshBounds.Expand(data.MaxChainLength * 2f); + Renderer.localBounds = meshBounds; + _started = false; + } + + // The one entry: swim pose, solver substeps, skin write, upload, bounds. drawnTime is DrawAhead.Time. + public SpringLod Present(double drawnTime, Vector3 position, Quaternion rotation, float scale) + { + if (Data == null) throw new InvalidOperationException("SpringRig.Present before Initialize."); + Level = Classify(position, scale); + bool full = Level == SpringLod.Full; + + // Substeps owed: the fixed 1/120 s boundaries crossed since the last frame, by absolute drawn time so the + // count over any span is the same at any frame rate. Not full: keep the index current so an unfreeze owes nothing. + long index = (long)math.floor(drawnTime * SubstepRate); + int steps = _started && full ? (int)math.clamp(index - _lastIndex, 0, MaxSubsteps) : 0; + _lastIndex = index; + + bool reset = !_started || (full && !_wasFull) || math.distance(_lastPosition, position) > Data.MaxChainLength * scale; + _started = true; + _wasFull = full; + _lastPosition = position; + if (reset && full) Resets++; + + var pos = (float3)position; + var rot = (quaternion)rotation; + var pose = new PoseJob + { + 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) + { + SolveJobsScheduled++; + SubstepsRun += steps; + pose = new SpringSolveJob + { + 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, reset = reset, + }.Schedule(Data.ChainCount, 4, pose); + } + 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(); + SkinBuffer.SetData(_skin); + + var t = Renderer.transform; + t.SetPositionAndRotation(position, rotation); + t.localScale = new Vector3(scale, scale, scale); + return Level; + } + + // Projected height of the whale's bounds as a fraction of the viewport. + SpringLod Classify(Vector3 position, float scale) + { + var cam = LodCamera; + if (cam == null) return SpringLod.Full; + float diameter = Renderer.localBounds.extents.magnitude * 2f * scale; + float visible = cam.orthographic ? cam.orthographicSize * 2f : 2f * Vector3.Distance(cam.transform.position, position) * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad); + float height = diameter / Mathf.Max(visible, 1e-6f); + return height >= FullAbove ? SpringLod.Full : height >= FrozenAbove ? SpringLod.Frozen : SpringLod.Hidden; + } + + void Release() + { + foreach (var a in _owned) a.Dispose(); + _owned.Clear(); + SkinBuffer?.Release(); + SkinBuffer = null; + } + + void OnDestroy() => Release(); + } +} diff --git a/Assets/Scripts/Fauna Display/SpringRig.cs.meta b/Assets/Scripts/Fauna Display/SpringRig.cs.meta new file mode 100644 index 000000000..af877a6bb --- /dev/null +++ b/Assets/Scripts/Fauna Display/SpringRig.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 02a69b7a8aa84824cbd397cbe3c02d4b \ No newline at end of file diff --git a/Assets/Scripts/Fauna Display/SpringSolver.cs b/Assets/Scripts/Fauna Display/SpringSolver.cs new file mode 100644 index 000000000..f9ea48ab2 --- /dev/null +++ b/Assets/Scripts/Fauna Display/SpringSolver.cs @@ -0,0 +1,154 @@ +/* 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 Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; + +namespace Aetheria.FaunaDisplay +{ + // The three jobs one whale runs each frame, in order: PoseJob (every bone at its swimming-body pose, springs at rest), + // SpringSolveJob (the VRM SpringBone step over chains, overwriting the spring bones; skipped when frozen) and SkinJob + // (skin = rootInverse x boneWorld x bindPose for every bone). Bone worlds are position + rotation with a uniform scale; + // the solver works in world space so a swimming root drags the tendrils. + + [BurstCompile(CompileSynchronously = true, DisableSafetyChecks = true)] + public struct PoseJob : IJob + { + [ReadOnly] public NativeArray order, parent, spine; + [ReadOnly] public NativeArray restPos; + [ReadOnly] public NativeArray restRot; + public SwimSettings swim; + public double time; + public float3 rootPos; + public quaternion rootRot; + public float scale; + public NativeArray bonePos; + public NativeArray boneRot; + + public void Execute() + { + for (int n = 0; n < order.Length; n++) + { + int i = order[n], p = parent[i]; + quaternion local = spine[i] >= 0 ? math.mul(restRot[i], SwimPose.Rotation(time, spine[i], swim)) : restRot[i]; + quaternion pr = p < 0 ? rootRot : boneRot[p]; + float3 pp = p < 0 ? rootPos : bonePos[p]; + bonePos[i] = pp + math.mul(pr, restPos[i] * scale); + boneRot[i] = math.mul(pr, local); + } + } + } + + [BurstCompile(CompileSynchronously = true, DisableSafetyChecks = true)] + public struct SpringSolveJob : IJobParallelFor + { + [ReadOnly] public NativeArray chainStart, chainLen, chainBone, chainColStart, chainColLen, chainCol; + [ReadOnly] public NativeArray restPos; + [ReadOnly] public NativeArray restRot; + [ReadOnly] public NativeArray param; + [ReadOnly] public NativeArray colliders; + // Bone-indexed. A chain writes only its own bones; colliders read body bones only. + [NativeDisableParallelForRestriction] public NativeArray bonePos, simPos, simPrev; + [NativeDisableParallelForRestriction] public NativeArray boneRot; + public int substeps; + public float step, scale; + public bool reset; + + public void Execute(int c) + { + int start = chainStart[c], len = chainLen[c]; + if (reset) + for (int k = 0; k < len; k++) + { + int bone = chainBone[start + k]; + simPos[bone] = simPrev[bone] = bonePos[bone]; + } + int root = chainBone[start]; + float3 headPos0 = bonePos[root]; + quaternion headRest0 = boneRot[root]; + + // With no substeps due the loop still runs once without integrating, to publish the held state. + int passes = math.max(substeps, 1); + for (int pass = 0; pass < passes; pass++) + { + bool integrate = pass < substeps; + float3 headPos = headPos0; + quaternion headRest = headRest0; + for (int k = 1; k < len; k++) + { + int bone = chainBone[start + k]; + float3 p = simPos[bone]; + float seg = math.length(restPos[bone]) * scale; + float3 axis = math.normalizesafe(restPos[bone], new float3(0, -1, 0)); + float3 np = p; + if (integrate) + { + var jp = param[start + k - 1]; + float3 target = headPos + math.mul(headRest, restPos[bone] * scale); + np = p + (p - simPrev[bone]) * (1f - jp.DragForce) // inertia + + (target - p) * math.saturate(jp.Stiffness * step) // pull to the rest direction from the parent's current rotation + + jp.GravityDir * (jp.GravityPower * step * scale); // gravity + np = Reproject(headPos, np, seg, math.mul(headRest, axis)); + float hit = jp.HitRadius * scale; + int cs = chainColStart[c], cn = chainColLen[c]; + for (int q = 0; q < cn; q++) np = PushOut(np, colliders[chainCol[cs + q]], hit); + np = Reproject(headPos, np, seg, math.mul(headRest, axis)); + simPrev[bone] = p; + simPos[bone] = np; + } + quaternion aimed = math.mul(FromTo(math.mul(headRest, axis), math.normalizesafe(np - headPos, math.mul(headRest, axis))), headRest); + boneRot[chainBone[start + k - 1]] = aimed; + bonePos[bone] = np; + headPos = np; + headRest = math.mul(aimed, restRot[bone]); + } + boneRot[chainBone[start + len - 1]] = headRest; + } + } + + static float3 Reproject(float3 head, float3 p, float length, float3 fallback) => head + math.normalizesafe(p - head, fallback) * length; + + float3 PushOut(float3 p, SpringCollider col, float hit) + { + float3 origin = bonePos[col.Bone], center = origin + math.mul(boneRot[col.Bone], col.Offset * scale); + float3 nearest = center; + if (col.Capsule) + { + float3 tail = origin + math.mul(boneRot[col.Bone], col.Tail * scale), axis = tail - center; + nearest = center + axis * math.saturate(math.dot(p - center, axis) / math.max(math.lengthsq(axis), 1e-12f)); + } + float3 d = p - nearest; + float r = col.Radius * scale + hit, l = math.length(d); + return l < r ? nearest + (l > 1e-9f ? d / l : new float3(0, 1, 0)) * r : p; + } + + static quaternion FromTo(float3 a, float3 b) + { + float d = math.dot(a, b); + if (d < -0.99999f) + { + float3 axis = math.normalize(math.cross(a, math.abs(a.x) < 0.9f ? new float3(1, 0, 0) : new float3(0, 1, 0))); + return new quaternion(axis.x, axis.y, axis.z, 0); + } + float3 c = math.cross(a, b); + return math.normalize(new quaternion(c.x, c.y, c.z, 1f + d)); + } + } + + [BurstCompile(CompileSynchronously = true, DisableSafetyChecks = true)] + public struct SkinJob : IJobParallelFor + { + [ReadOnly] public NativeArray bonePos; + [ReadOnly] public NativeArray boneRot; + [ReadOnly] public NativeArray bind; + public float4x4 rootInverse; + public float scale; + [WriteOnly] public NativeArray skin; + + public void Execute(int i) => + skin[i] = math.mul(rootInverse, math.mul(float4x4.TRS(bonePos[i], boneRot[i], new float3(scale)), bind[i])); + } +} diff --git a/Assets/Scripts/Fauna Display/SpringSolver.cs.meta b/Assets/Scripts/Fauna Display/SpringSolver.cs.meta new file mode 100644 index 000000000..c8a5ee0ac --- /dev/null +++ b/Assets/Scripts/Fauna Display/SpringSolver.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 93b873d12ec4f68459ca547f239f3b15 \ No newline at end of file diff --git a/Assets/Scripts/Fauna Display/SwimPose.cs b/Assets/Scripts/Fauna Display/SwimPose.cs new file mode 100644 index 000000000..9d5cca7e6 --- /dev/null +++ b/Assets/Scripts/Fauna Display/SwimPose.cs @@ -0,0 +1,34 @@ +/* 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 Unity.Mathematics; + +namespace Aetheria.FaunaDisplay +{ + // Body swim as a closed form of drawn time (ruling presenter-phase-from-zone-time): a wave travelling down the spine + // chain, one phase step per spine bone. Pure: no state, no clock; the same drawn time gives the same pose however it + // was reached, and a paused zone holds it. + [Serializable] + public struct SwimSettings + { + public float AmplitudeDegrees; // peak bend of each spine bone + public float PeriodSeconds; // one full wave cycle + public float PhasePerBone; // cycles of lag per spine bone (0.1 = ten bones per wavelength) + public float3 Axis; // bend axis in the bone's local frame (X: pitch for a body along Z) + + public static SwimSettings Default => new SwimSettings { AmplitudeDegrees = 6f, PeriodSeconds = 4f, PhasePerBone = 0.08f, Axis = new float3(1, 0, 0) }; + } + + public static class SwimPose + { + // Extra local rotation (applied after the rest rotation) of the spine bone at spineIndex at drawn time t. + public static quaternion Rotation(double t, int spineIndex, in SwimSettings s) + { + double cycles = t / math.max(s.PeriodSeconds, 1e-4f) - spineIndex * (double)s.PhasePerBone; + float phase = (float)(cycles - math.floor(cycles)); + return quaternion.AxisAngle(math.normalizesafe(s.Axis, new float3(1, 0, 0)), math.radians(s.AmplitudeDegrees) * math.sin(phase * (2f * math.PI))); + } + } +} diff --git a/Assets/Scripts/Fauna Display/SwimPose.cs.meta b/Assets/Scripts/Fauna Display/SwimPose.cs.meta new file mode 100644 index 000000000..4a313f072 --- /dev/null +++ b/Assets/Scripts/Fauna Display/SwimPose.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 2e41e6c57dffede48a9926cd59432848 \ No newline at end of file diff --git a/Assets/Shaders/FaunaSkinned.shader b/Assets/Shaders/FaunaSkinned.shader new file mode 100644 index 000000000..034feca21 --- /dev/null +++ b/Assets/Shaders/FaunaSkinned.shader @@ -0,0 +1,67 @@ +// Minimal lit built-in-pipeline shader for a SpringRig mesh: base colour texture, one directional light and ambient. +// The leviathan's look shader is later work (follow-up whale-rig-leviathan-asset); it includes SpringSkin.cginc the same way. +Shader "Aetheria/FaunaSkinned" +{ + Properties + { + _MainTex ("Base colour", 2D) = "white" {} + _Color ("Tint", Color) = (1, 1, 1, 1) + [Enum(UnityEngine.Rendering.CullMode)] _Cull ("Cull", Float) = 2 + } + SubShader + { + Tags { "RenderType" = "Opaque" } + Pass + { + Tags { "LightMode" = "ForwardBase" } + Cull [_Cull] + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 4.5 + #include "UnityCG.cginc" + #include "UnityLightingCommon.cginc" + #include "SpringSkin.cginc" + + sampler2D _MainTex; + float4 _MainTex_ST; + fixed4 _Color; + + struct appdata + { + float4 vertex : POSITION; + float3 normal : NORMAL; + float2 uv : TEXCOORD0; + uint4 bones : BLENDINDICES; + float4 weights : BLENDWEIGHTS; + }; + + struct v2f + { + float4 pos : SV_POSITION; + float2 uv : TEXCOORD0; + float3 normal : TEXCOORD1; + }; + + v2f vert(appdata v) + { + float3 position = v.vertex.xyz, normal = v.normal; + SpringSkin(position, normal, v.bones, v.weights); + v2f o; + o.pos = UnityObjectToClipPos(float4(position, 1)); + o.uv = TRANSFORM_TEX(v.uv, _MainTex); + o.normal = UnityObjectToWorldNormal(normal); + return o; + } + + fixed4 frag(v2f i) : SV_Target + { + fixed4 albedo = tex2D(_MainTex, i.uv) * _Color; + float3 n = normalize(i.normal); + float3 light = _LightColor0.rgb * max(0, dot(n, _WorldSpaceLightPos0.xyz)) + ShadeSH9(float4(n, 1)); + return fixed4(albedo.rgb * light, 1); + } + ENDCG + } + } +} diff --git a/Assets/Shaders/FaunaSkinned.shader.meta b/Assets/Shaders/FaunaSkinned.shader.meta new file mode 100644 index 000000000..75261c9ce --- /dev/null +++ b/Assets/Shaders/FaunaSkinned.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 3b700be39bc236146bb1a60e94fe2948 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Shaders/SpringSkin.cginc b/Assets/Shaders/SpringSkin.cginc new file mode 100644 index 000000000..b974648fe --- /dev/null +++ b/Assets/Shaders/SpringSkin.cginc @@ -0,0 +1,22 @@ +// Skinning for meshes driven by SpringRig: bone matrices (skin = rootInverse x boneWorld x bindPose, object space) in a +// structured buffer, indices and weights from the mesh's BLENDINDICES and BLENDWEIGHTS. Include it in any look shader. +#ifndef SPRING_SKIN_INCLUDED +#define SPRING_SKIN_INCLUDED + +StructuredBuffer _SpringBones; + +// Object-space position and normal after up to four weighted bones. Uniform bone scale only (normals are not re-inverted). +void SpringSkin(inout float3 position, inout float3 normal, uint4 indices, float4 weights) +{ + float3 p = 0, n = 0; + [unroll] for (int k = 0; k < 4; k++) + { + float4x4 m = _SpringBones[indices[k]]; + p += weights[k] * mul(m, float4(position, 1)).xyz; + n += weights[k] * mul((float3x3)m, normal); + } + position = p; + normal = normalize(n); +} + +#endif diff --git a/Assets/Shaders/SpringSkin.cginc.meta b/Assets/Shaders/SpringSkin.cginc.meta new file mode 100644 index 000000000..e416b4aa0 --- /dev/null +++ b/Assets/Shaders/SpringSkin.cginc.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 982ed83513ac5db4fb28f70a35095baf +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: