diff --git a/packages/cultmath/docs/design.md b/packages/cultmath/docs/design.md index d9f06b5f..d0bb6245 100644 --- a/packages/cultmath/docs/design.md +++ b/packages/cultmath/docs/design.md @@ -519,6 +519,12 @@ helpers that HLSL lacks (`float2x2.Rotate`, `float3x3.Euler`, `quaternion`, `snoise`) enter only when a consumer needs them, with their semantics stated in code. +`quaternion` now carries rotation algebra for GameCult.Animation (ruling +`aetheria-release:ruling:solver-in-gamecult-animation`) in `math.Quaternion.cs`: +Hamilton product, xyzw, radians, `mul(a, b)` applies `b` first, and +`q == mul(swing, twist)`. HLSL's vector `mul(v, v)` (the inner product) is defined so that +`mul(float4, float4)` cannot bind to the quaternion product. + Known C# friction: under `using static CultMath.math;` the constructor functions (`float3(...)`, `float3x3(...)`) hide the type names in member access, so static members need a qualified type (`CultMath.float3x3.Euler(...)`). diff --git a/packages/cultmath/src/CultMath/math.Quaternion.cs b/packages/cultmath/src/CultMath/math.Quaternion.cs new file mode 100644 index 00000000..ae75efbc --- /dev/null +++ b/packages/cultmath/src/CultMath/math.Quaternion.cs @@ -0,0 +1,139 @@ +namespace CultMath; + +public static partial class math +{ + // Rotation algebra on quaternion (design.md, "Where HLSL is silent"). Conventions: Hamilton product, + // components stored xyzw, angles in radians, rotations right-handed about their axis, and + // mul(a, b) applies b first. Rotation functions assume unit quaternions and unit axes; like the + // rest of math these preconditions are documented, not checked. + + private static float3 vec(quaternion q) => new(q.x, q.y, q.z); + + /// + /// The Hamilton product. rotate(mul(a, b), v) == rotate(a, rotate(b, v)): b is applied first. + /// + public static quaternion mul(quaternion a, quaternion b) + { + var va = vec(a); + var vb = vec(b); + var v = a.w * vb + b.w * va + cross(va, vb); + return new quaternion(v.x, v.y, v.z, a.w * b.w - dot(va, vb)); + } + + /// Rotates by the unit quaternion . + public static float3 rotate(quaternion q, float3 v) + { + var u = vec(q); + var t = 2.0f * cross(u, v); + return v + q.w * t + cross(u, t); + } + + /// (-x, -y, -z, w). For a unit quaternion this is its inverse. + public static quaternion conjugate(quaternion q) => new(-q.x, -q.y, -q.z, q.w); + + /// + /// conjugate(q) / dot(q, q). Not guarded: a zero quaternion yields non-finite components, + /// as HLSL division does. + /// + public static quaternion inverse(quaternion q) + { + var n = 1.0f / (q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); + return new quaternion(-q.x * n, -q.y * n, -q.z * n, q.w * n); + } + + /// + /// Spherical interpolation along the shortest arc (b is negated when dot(a, b) < 0). + /// Nearly parallel inputs (|dot| above 0.9995) use a normalised lerp, which is stable where + /// sin(theta) vanishes. t is not clamped. a and b must be unit. + /// + public static quaternion slerp(quaternion a, quaternion b, float t) + { + float4 fa = a; + float4 fb = b; + var d = dot(fa, fb); + if (d < 0.0f) + { + fb = -fb; + d = -d; + } + + if (d > 0.9995f) + { + return normalize(new quaternion( + lerp(fa.x, fb.x, t), lerp(fa.y, fb.y, t), lerp(fa.z, fb.z, t), lerp(fa.w, fb.w, t))); + } + + var theta = acos(d); + var s = sin(theta); + var r = fa * (sin((1.0f - t) * theta) / s) + fb * (sin(t * theta) / s); + return new quaternion(r.x, r.y, r.z, r.w); + } + + /// + /// Splits unit into a twist about (q's projection + /// onto the axis, normalised) and the remaining swing, so that q == mul(swing, twist): the twist + /// is applied first and the swing's axis is perpendicular to the twist axis. When the projection + /// vanishes (length below 1e-6: a half-turn swing) the twist is identity and swing is q. + /// + public static void swing_twist(quaternion q, float3 unitTwistAxis, out quaternion swing, out quaternion twist) + { + var p = unitTwistAxis * dot(vec(q), unitTwistAxis); + var len = sqrt(dot(p, p) + q.w * q.w); + if (len < 1e-6f) + { + twist = quaternion.identity; + } + else + { + var inv = 1.0f / len; + twist = new quaternion(p.x * inv, p.y * inv, p.z * inv, q.w * inv); + } + + swing = mul(q, conjugate(twist)); + } + + /// + /// Limits a twist (a rotation about , as from swing_twist) to + /// [, ] radians, min <= max. The angle is + /// 2 atan2(dot(twist.xyz, axis), twist.w) wrapped to (-pi, pi]. Inside the limit the input is + /// returned unchanged; outside, AxisAngle(axis, clamp(angle, min, max)). + /// + public static quaternion clamp_twist(quaternion twist, float3 unitAxis, float min, float max) + { + var angle = 2.0f * atan2(dot(vec(twist), unitAxis), twist.w); + const float pi = MathF.PI; + if (angle > pi) angle -= 2.0f * pi; + else if (angle <= -pi) angle += 2.0f * pi; + + if (angle >= min && angle <= max) return twist; + return quaternion.AxisAngle(unitAxis, clamp(angle, min, max)); + } + + /// + /// A hinge about : clamp_twist of q's twist about the axis, with + /// the swing discarded. min <= max. + /// + public static quaternion clamp_hinge(quaternion q, float3 unitAxis, float min, float max) + { + swing_twist(q, unitAxis, out _, out var twist); + return clamp_twist(twist, unitAxis, min, max); + } + + /// + /// Limits a swing to a cone of half-angle about . + /// The angle is that between rotate(swing, axis) and the axis. Inside the cone the input is + /// returned unchanged; outside, the rotation by maxAngle about normalize(cross(axis, + /// rotate(swing, axis))), or about the swing's own axis at a half turn, where that cross + /// product vanishes (length below 1e-6). + /// + public static quaternion clamp_cone(quaternion swing, float3 unitAxis, float maxAngle) + { + var d = rotate(swing, unitAxis); + var angle = acos(clamp(dot(unitAxis, d), -1.0f, 1.0f)); + if (angle <= maxAngle) return swing; + + var c = cross(unitAxis, d); + var axis = dot(c, c) < 1e-12f ? normalize(vec(swing)) : normalize(c); + return quaternion.AxisAngle(axis, maxAngle); + } +} diff --git a/packages/cultmath/src/CultMath/math.Quaternion.cs.meta b/packages/cultmath/src/CultMath/math.Quaternion.cs.meta new file mode 100644 index 00000000..8d169536 --- /dev/null +++ b/packages/cultmath/src/CultMath/math.Quaternion.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f4d9effad14457cf75699ff2dcc7cb96 diff --git a/packages/cultmath/src/CultMath/quaternion.cs b/packages/cultmath/src/CultMath/quaternion.cs index e8c4a48c..b2e69d9a 100644 --- a/packages/cultmath/src/CultMath/quaternion.cs +++ b/packages/cultmath/src/CultMath/quaternion.cs @@ -82,6 +82,17 @@ public struct quaternion : IEquatable } } + /// + /// Rotation of about , right-handed: + /// (axis sin(r/2), cos(r/2)). The axis must be unit; it is not normalised here. + /// + public static quaternion AxisAngle(float3 unitAxis, float radians) + { + var half = 0.5f * radians; + var s = math.sin(half); + return new quaternion(unitAxis.x * s, unitAxis.y * s, unitAxis.z * s, math.cos(half)); + } + public static implicit operator quaternion(float4 value) => new(value.x, value.y, value.z, value.w); public static implicit operator float4(quaternion value) => new(value.x, value.y, value.z, value.w); diff --git a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs index c57c7900..050be34d 100644 --- a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs @@ -24,4 +24,239 @@ public sealed class QuaternionTests Assert.Equal(11.0f, mul(new float2(1.0f, 2.0f), new float2(3.0f, 4.0f))); Assert.Equal(32.0f, mul(new float3(1.0f, 2.0f, 3.0f), new float3(4.0f, 5.0f, 6.0f))); } + + private const float Eps = 2e-5f; + + private static float Uniform(System.Random r, float lo, float hi) => lo + (hi - lo) * r.NextSingle(); + + private static float3 RandomUnit3(System.Random r) + { + while (true) + { + var v = new float3(Uniform(r, -1, 1), Uniform(r, -1, 1), Uniform(r, -1, 1)); + var l = length(v); + if (l > 0.1f && l <= 1.0f) return v / l; + } + } + + private static quaternion RandomRotation(System.Random r) => + quaternion.AxisAngle(RandomUnit3(r), Uniform(r, -MathF.PI, MathF.PI)); + + private static void AssertVec(float3 expected, float3 actual, float eps = Eps) + { + Assert.True(length(expected - actual) <= eps, $"expected {expected}, got {actual}"); + } + + private static void AssertSameRotation(quaternion a, quaternion b, float eps = Eps) + { + var d = abs(dot((float4)a, (float4)b)); + Assert.True(d >= 1.0f - eps, $"|dot| = {d} for {a} vs {b}"); + } + + private static float AngleBetween(float3 a, float3 b) => + acos(clamp(dot(a, b) / (length(a) * length(b)), -1.0f, 1.0f)); + + [Fact] + public void CompositionAppliesTheRightOperandFirst() + { + var r = new System.Random(11); + for (var i = 0; i < 200; i++) + { + var a = RandomRotation(r); + var b = RandomRotation(r); + var v = new float3(Uniform(r, -3, 3), Uniform(r, -3, 3), Uniform(r, -3, 3)); + AssertVec(rotate(a, rotate(b, v)), rotate(mul(a, b), v), 1e-4f); + } + } + + [Fact] + public void MulByInverseIsIdentity() + { + var r = new System.Random(12); + for (var i = 0; i < 100; i++) + { + var q = RandomRotation(r); + AssertSameRotation(mul(q, inverse(q)), quaternion.identity); + AssertSameRotation(mul(inverse(q), q), quaternion.identity); + } + // Not a unit quaternion: inverse divides by dot(q, q). + var s = new quaternion(0.0f, 0.0f, 2.0f, 0.0f); + var p = mul(s, inverse(s)); + Assert.True(abs(p.w - 1.0f) <= 1e-6f && abs(p.x) <= 1e-6f && abs(p.y) <= 1e-6f && abs(p.z) <= 1e-6f); + } + + [Fact] + public void InverseOfZeroIsNonFinite() + { + var q = inverse(new quaternion(0.0f, 0.0f, 0.0f, 0.0f)); + Assert.False(float.IsFinite(q.w)); + } + + [Fact] + public void ConjugateNegatesTheVectorPartAndEqualsInverseForUnit() + { + var q = new quaternion(1.0f, -2.0f, 3.0f, 4.0f); + Assert.Equal(new quaternion(-1.0f, 2.0f, -3.0f, 4.0f), conjugate(q)); + var r = new System.Random(13); + for (var i = 0; i < 50; i++) + { + var u = RandomRotation(r); + var c = conjugate(u); + var n = inverse(u); + Assert.True(abs(c.x - n.x) <= 1e-6f && abs(c.y - n.y) <= 1e-6f && abs(c.z - n.z) <= 1e-6f && abs(c.w - n.w) <= 1e-6f); + } + } + + [Fact] + public void AxisAngleIsRightHanded() + { + var q = quaternion.AxisAngle(new float3(0, 0, 1), MathF.PI / 2); + AssertVec(new float3(0, 1, 0), rotate(q, new float3(1, 0, 0))); + AssertVec(new float3(-1, 0, 0), rotate(q, new float3(0, 1, 0))); + AssertVec(new float3(0, 0, 1), rotate(q, new float3(0, 0, 1))); + var h = quaternion.AxisAngle(new float3(0, 0, 1), 0.8f); + Assert.Equal(sin(0.4f) , h.z); + Assert.Equal(cos(0.4f), h.w); + } + + [Fact] + public void SlerpEndpointsAndMidpoint() + { + var r = new System.Random(14); + for (var i = 0; i < 50; i++) + { + var a = RandomRotation(r); + var b = RandomRotation(r); + AssertSameRotation(slerp(a, b, 0.0f), a); + AssertSameRotation(slerp(a, b, 1.0f), b); + } + var mid = slerp(quaternion.identity, quaternion.AxisAngle(new float3(0, 0, 1), 1.0f), 0.5f); + AssertSameRotation(mid, quaternion.AxisAngle(new float3(0, 0, 1), 0.5f)); + } + + [Fact] + public void SlerpTakesTheShortestArc() + { + var z = new float3(0, 0, 1); + var a = quaternion.identity; + var b = quaternion.AxisAngle(z, 1.0f); + // -b is the same rotation with dot(a, -b) < 0; the long way would pass through 1 - pi. + var nb = new quaternion(-b.x, -b.y, -b.z, -b.w); + Assert.True(dot((float4)a, (float4)nb) < 0.0f); + AssertSameRotation(slerp(a, nb, 0.5f), quaternion.AxisAngle(z, 0.5f)); + AssertSameRotation(slerp(a, nb, 0.25f), quaternion.AxisAngle(z, 0.25f)); + } + + [Fact] + public void SlerpOfNearlyParallelQuaternionsIsFiniteAndUnit() + { + var a = quaternion.AxisAngle(new float3(0, 1, 0), 0.3f); + foreach (var b in new[] { a, quaternion.AxisAngle(new float3(0, 1, 0), 0.3f + 1e-6f), normalize(new quaternion(a.x + 1e-7f, a.y, a.z, a.w)) }) + { + var s = slerp(a, b, 0.37f); + var l = length((float4)s); + Assert.True(float.IsFinite(l) && abs(l - 1.0f) <= 1e-5f, $"{s}"); + AssertSameRotation(s, a, 1e-5f); + } + } + + [Fact] + public void SwingTwistRecomposesAndSplitsAboutTheAxis() + { + var r = new System.Random(15); + for (var i = 0; i < 200; i++) + { + var q = RandomRotation(r); + var axis = RandomUnit3(r); + swing_twist(q, axis, out var swing, out var twist); + AssertSameRotation(mul(swing, twist), q, 1e-4f); + Assert.True(length(cross(new float3(twist.x, twist.y, twist.z), axis)) <= 1e-5f, "twist axis parallel"); + Assert.True(abs(dot(new float3(swing.x, swing.y, swing.z), axis)) <= 1e-5f, "swing axis perpendicular"); + } + } + + [Fact] + public void SwingTwistOfAHalfTurnSwingHasIdentityTwist() + { + var q = quaternion.AxisAngle(new float3(1, 0, 0), MathF.PI); + swing_twist(q, new float3(0, 0, 1), out var swing, out var twist); + AssertSameRotation(twist, quaternion.identity); + AssertSameRotation(swing, q); + } + + [Fact] + public void ClampTwistReturnsTheInputBitIdenticalInsideTheLimit() + { + var z = new float3(0, 0, 1); + var r = new System.Random(16); + for (var i = 0; i < 50; i++) + { + var twist = quaternion.AxisAngle(z, Uniform(r, -0.9f, 0.9f)); + Assert.True(twist == clamp_twist(twist, z, -1.0f, 1.0f)); + } + } + + [Fact] + public void ClampTwistReturnsTheBoundaryAngleOutside() + { + var z = new float3(0, 0, 1); + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 2.0f), z, -1.0f, 0.5f), quaternion.AxisAngle(z, 0.5f)); + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, -2.0f), z, -1.0f, 0.5f), quaternion.AxisAngle(z, -1.0f)); + // Wrapped: 3 pi / 2 about z is -pi / 2, below the lower limit. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 3.0f * MathF.PI / 2.0f), z, -1.0f, 1.0f), quaternion.AxisAngle(z, -1.0f)); + } + + [Fact] + public void ClampHingeDiscardsTheSwing() + { + var z = new float3(0, 0, 1); + var r = new System.Random(17); + for (var i = 0; i < 50; i++) + { + var q = RandomRotation(r); + var h = clamp_hinge(q, z, -0.7f, 0.7f); + // A hinge result is a pure rotation about the axis within the limits. + Assert.True(abs(h.x) <= 1e-6f && abs(h.y) <= 1e-6f); + var angle = 2.0f * atan2(h.z, h.w); + Assert.True(angle >= -0.7f - 1e-5f && angle <= 0.7f + 1e-5f); + } + // Inside the limit about the axis, the twist survives and the swing does not. + var swing = quaternion.AxisAngle(new float3(1, 0, 0), 0.6f); + var twist = quaternion.AxisAngle(z, 0.4f); + AssertSameRotation(clamp_hinge(mul(swing, twist), z, -1.0f, 1.0f), twist, 1e-4f); + } + + [Fact] + public void ClampConeReturnsTheInputBitIdenticalInsideTheCone() + { + var z = new float3(0, 0, 1); + var r = new System.Random(18); + for (var i = 0; i < 50; i++) + { + var swing = quaternion.AxisAngle(RandomUnit3(r), Uniform(r, 0.0f, 0.5f)); + var inside = AngleBetween(rotate(swing, z), z); + Assert.True(inside < 0.5f); + Assert.True(swing == clamp_cone(swing, z, 0.6f)); + } + } + + [Fact] + public void ClampConeReturnsTheBoundaryAngleOutside() + { + var z = new float3(0, 0, 1); + var r = new System.Random(19); + for (var i = 0; i < 50; i++) + { + var swing = quaternion.AxisAngle(RandomUnit3(r), Uniform(r, 1.0f, 3.0f)); + if (AngleBetween(rotate(swing, z), z) <= 0.4f) continue; + var c = clamp_cone(swing, z, 0.4f); + Assert.True(abs(AngleBetween(rotate(c, z), z) - 0.4f) <= 1e-4f); + // Clamped toward the original direction: same plane, so the clamped and original axes agree. + Assert.True(dot(cross(z, rotate(c, z)), cross(z, rotate(swing, z))) > 0.0f); + } + // Half turn: the cross product vanishes; the clamp still lands on the boundary. + var half = quaternion.AxisAngle(new float3(1, 0, 0), MathF.PI); + var ch = clamp_cone(half, z, 0.4f); + Assert.True(abs(AngleBetween(rotate(ch, z), z) - 0.4f) <= 1e-4f); + } }