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..dac1aec5 --- /dev/null +++ b/packages/cultmath/src/CultMath/math.Quaternion.cs @@ -0,0 +1,153 @@ +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), computed on q divided by its largest component so that + /// dot(q, q) cannot underflow or overflow: every nonzero finite q gives its true inverse, except + /// where the result itself exceeds the float range. A zero quaternion yields non-finite + /// components, as HLSL division does. + /// + public static quaternion inverse(quaternion q) + { + var m = max(max(abs(q.x), abs(q.y)), max(abs(q.z), abs(q.w))); + var s = new float4(q.x, q.y, q.z, q.w) / m; + var n = 1.0f / dot(s, s); + return new quaternion(-s.x * n / m, -s.y * n / m, -s.z * n / m, s.w * n / m); + } + + /// + /// 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. Angles are taken modulo a + /// turn: the twist's angle 2 atan2(dot(twist.xyz, axis), twist.w) is wrapped into the turn + /// centred on the window, (centre - pi, centre + pi], so limits may lie anywhere (beyond pi, or + /// spanning more than half a turn) and a window of a full turn or more admits every twist. Inside the + /// window the input is returned unchanged; outside, AxisAngle(axis, clamp(angle, min, max)), + /// whose boundary is the one nearer by arc. A window of a full turn or more, including infinite + /// limits, admits every twist and returns it unchanged. A NaN twist or limit gives a NaN quaternion, + /// as clamp_cone does. + /// + 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 (max - min >= 2.0f * pi) return twist; + var centre = 0.5f * (min + max); + var a = angle - centre; + angle = a - 2.0f * pi * ceil((a - pi) / (2.0f * pi)) + centre; + if (float.IsNaN(angle)) return new quaternion(float.NaN, float.NaN, float.NaN, float.NaN); + + 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 (at least 0) about + /// . The angle is that between rotate(swing, axis) and the axis, + /// atan2(|cross|, dot), accurate at every size including tiny limits. 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 with the rotated axis pointing away). + /// + public static quaternion clamp_cone(quaternion swing, float3 unitAxis, float maxAngle) + { + var d = rotate(swing, unitAxis); + var c = cross(unitAxis, d); + var cosine = dot(unitAxis, d); + var angle = atan2(length(c), cosine); + if (angle <= maxAngle) return swing; + + var axis = cosine < 0.0f && 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/math.cs b/packages/cultmath/src/CultMath/math.cs index a7c41f48..5b87df43 100644 --- a/packages/cultmath/src/CultMath/math.cs +++ b/packages/cultmath/src/CultMath/math.cs @@ -222,16 +222,19 @@ public static partial class math public static float2 normalize(float2 value) => value * (1.0f / MathF.Sqrt(dot(value, value))); public static float3 normalize(float3 value) => value * (1.0f / MathF.Sqrt(dot(value, value))); public static float4 normalize(float4 value) => value * (1.0f / MathF.Sqrt(dot(value, value))); + // Scaled by the largest component, as inverse(quaternion) is, so neither the squared sum underflows nor + // overflows: any nonzero finite quaternion keeps its direction. Zero returns identity. public static quaternion normalize(quaternion value) { - var length = MathF.Sqrt(value.x * value.x + value.y * value.y + value.z * value.z + value.w * value.w); - if (length <= 1.0e-20f) + var m = max(max(abs(value.x), abs(value.y)), max(abs(value.z), abs(value.w))); + if (m <= 0.0f) { return quaternion.identity; } - var invLength = 1.0f / length; - return new quaternion(value.x * invLength, value.y * invLength, value.z * invLength, value.w * invLength); + var s = new float4(value.x, value.y, value.z, value.w) / m; + var invLength = 1.0f / MathF.Sqrt(dot(s, s)); + return new quaternion(s.x * invLength, s.y * invLength, s.z * invLength, s.w * invLength); } public static float2 reflect(float2 incident, float2 normal) => incident - 2.0f * dot(normal, incident) * normal; @@ -515,6 +518,12 @@ public static partial class math // HLSL mul: mul(m, v) treats v as a column vector, mul(v, m) as a row vector. public static float mul(float left, float right) => left * right; + // mul(v, v) is the inner product, as in HLSL. It also keeps mul(float4, float4) from binding to the + // quaternion product through float4's implicit conversion to quaternion. + public static float mul(float2 left, float2 right) => dot(left, right); + public static float mul(float3 left, float3 right) => dot(left, right); + public static float mul(float4 left, float4 right) => dot(left, right); + public static float2 mul(float2x2 m, float2 v) => new(m._m00 * v.x + m._m01 * v.y, m._m10 * v.x + m._m11 * v.y); 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 new file mode 100644 index 00000000..22fec3de --- /dev/null +++ b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs @@ -0,0 +1,463 @@ +using CultMath; +using Xunit; +using static CultMath.math; + +namespace CultMath.Tests; + +/// +/// The rotation algebra of math.Quaternion.cs. Conventions: Hamilton, xyzw, radians, right-handed, +/// mul(a, b) applies b first. Rotations are compared by what they do to vectors or by |dot| near 1, +/// never by component equality (q and -q are one rotation), except where a test says bit-identical. +/// +public sealed class QuaternionTests +{ + [Fact] + public void MulOfTwoFloat4IsTheInnerProduct() + { + // quaternion converts implicitly from float4; without the vector overloads this call would bind + // to the quaternion product and return a float4. + var a = new float4(1.0f, 2.0f, 3.0f, 4.0f); + var b = new float4(5.0f, 6.0f, 7.0f, 8.0f); + float r = mul(a, b); + Assert.Equal(70.0f, r); + Assert.Equal(dot(a, b), r); + 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}"); + } + + // atan2 form: acos resolves nothing below about 5e-4 rad. + private static float AngleBetween(float3 a, float3 b) => atan2(length(cross(a, b)), dot(a, b)); + + [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); + } + + private static float TwistAngle(quaternion q, float3 axis) => 2.0f * atan2(dot(new float3(q.x, q.y, q.z), axis), q.w); + + [Fact] + public void InverseIsTheTrueInverseAcrossTheFloatRange() + { + // dot(q, q) underflows (5e-21 each, 1e-30) or overflows (5e19 each) in float; the inverse is still + // conjugate(q) / |q|^2. Expected values are computed in double. + foreach (var (x, w) in new[] { (5e-21f, 5e-21f), (1e-30f, 1e-30f), (5e19f, 5e19f), (3e-25f, -4e-25f) }) + { + var q = new quaternion(x, x, x, w); + var n = (double)x * x * 3 + (double)w * w; + var r = inverse(q); + Assert.True(RelativelyEqual(-x / n, r.x) && RelativelyEqual(-x / n, r.y) && RelativelyEqual(-x / n, r.z) && RelativelyEqual(w / n, r.w), $"{q} -> {r}"); + } + // The result itself beyond the float range is infinite, not a wrong finite number. + Assert.True(float.IsInfinity(inverse(new quaternion(1e-40f, 0.0f, 0.0f, 1e-40f)).w)); + } + + private static bool RelativelyEqual(double expected, float actual) => + float.IsFinite(actual) && Math.Abs(expected - actual) <= 1e-5 * Math.Abs(expected); + + [Fact] + public void SwingTwistOfAnExactHalfTurnHasIdentityTwist() + { + // Exactly zero projection onto the axis (and zero w): the twist must be identity, not NaN. + foreach (var q in new[] { new quaternion(1.0f, 0.0f, 0.0f, 0.0f), new quaternion(0.0f, 1.0f, 0.0f, 0.0f) }) + { + swing_twist(q, new float3(0, 0, 1), out var swing, out var twist); + Assert.Equal(quaternion.identity, twist); + AssertSameRotation(swing, q, 1e-6f); + } + } + + [Fact] + public void ClampTwistTakesTheNearerBoundaryAcrossTheWrap() + { + var z = new float3(0, 0, 1); + // 3.1 against [-3.0, -2.5]: -3.0 is 0.18 rad away across the wrap, -2.5 is 5.6 rad away. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 3.1f), z, -3.0f, -2.5f), quaternion.AxisAngle(z, -3.0f)); + // And the mirror image. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, -3.1f), z, 2.5f, 3.0f), quaternion.AxisAngle(z, 3.0f)); + // A window centred on pi: an angle just past -pi is inside it and unchanged. + var inside = quaternion.AxisAngle(z, -3.0f); + Assert.True(inside == clamp_twist(inside, z, 3.2f, 4.0f)); + Assert.True(inside == clamp_twist(inside, z, 2.5f, 3.4f)); + // Outside a window beyond pi: -2.0 (= 4.28) is nearer 4.0 than 3.2. + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, -2.0f), z, 3.2f, 4.0f), quaternion.AxisAngle(z, 4.0f)); + // A window of more than half a turn admits what it contains and clamps what it does not. + var a = quaternion.AxisAngle(z, 3.5f); + Assert.True(a == clamp_twist(a, z, -1.0f, 4.0f)); + AssertSameRotation(clamp_twist(quaternion.AxisAngle(z, 2.0f), z, -1.0f, 1.0f), quaternion.AxisAngle(z, 1.0f)); + // A full turn or more admits everything. + var any = quaternion.AxisAngle(z, 2.9f); + Assert.True(any == clamp_twist(any, z, -3.5f, 3.5f)); + } + + [Fact] + public void ClampHingeUsesTheGivenAxis() + { + var r = new System.Random(20); + for (var i = 0; i < 100; i++) + { + var axis = RandomUnit3(r); + var q = RandomRotation(r); + var h = clamp_hinge(q, axis, -0.7f, 0.7f); + Assert.True(length(cross(new float3(h.x, h.y, h.z), axis)) <= 1e-5f, "pure rotation about the given axis"); + var angle = TwistAngle(h, axis); + Assert.True(angle >= -0.7f - 1e-5f && angle <= 0.7f + 1e-5f); + + // Inside the limit the twist about that axis survives and the swing does not. + var perp = normalize(cross(axis, abs(axis.x) < 0.9f ? new float3(1, 0, 0) : new float3(0, 1, 0))); + var twist = quaternion.AxisAngle(axis, 0.4f); + AssertSameRotation(clamp_hinge(mul(quaternion.AxisAngle(perp, 0.6f), twist), axis, -1.0f, 1.0f), twist, 1e-4f); + } + } + + [Fact] + public void ClampConeEnforcesTinyLimits() + { + var z = new float3(0, 0, 1); + foreach (var angle in new[] { 1e-4f, 3e-5f, 1e-5f * 1.5f }) + { + var swing = quaternion.AxisAngle(new float3(1, 0, 0), angle); + var c = clamp_cone(swing, z, 1e-5f); + Assert.False(swing == c, $"swing of {angle} rad against 1e-5 was returned unchanged"); + Assert.True(abs(AngleBetween(rotate(c, z), z) - 1e-5f) <= 2e-6f, $"{c}"); + } + // Inside a tiny limit stays bit-identical. + var inside = quaternion.AxisAngle(new float3(1, 0, 0), 5e-6f); + Assert.True(inside == clamp_cone(inside, z, 1e-5f)); + } + + [Fact] + public void ClampConeOfAnExactHalfTurnLandsOnTheBoundary() + { + // rotate((1,0,0,0), z) is exactly -z, so cross(axis, rotated) is exactly zero: the swing's own axis + // is used and the result is finite and on the boundary. + var z = new float3(0, 0, 1); + var c = clamp_cone(new quaternion(1.0f, 0.0f, 0.0f, 0.0f), z, 0.4f); + Assert.True(float.IsFinite(c.x) && float.IsFinite(c.w), $"{c}"); + Assert.True(abs(AngleBetween(rotate(c, z), z) - 0.4f) <= 1e-4f); + } + + [Fact] + public void ClampConeUsesTheGivenAxis() + { + var r = new System.Random(21); + for (var i = 0; i < 100; i++) + { + var axis = RandomUnit3(r); + var swing = quaternion.AxisAngle(RandomUnit3(r), Uniform(r, 1.0f, 3.0f)); + if (AngleBetween(rotate(swing, axis), axis) <= 0.4f) continue; + var c = clamp_cone(swing, axis, 0.4f); + Assert.True(abs(AngleBetween(rotate(c, axis), axis) - 0.4f) <= 1e-4f); + } + } + + [Fact] + public void ClampTwistWithInfiniteLimitsReturnsTheInputUnchanged() + { + var z = new float3(0, 0, 1); + var inf = float.PositiveInfinity; + var r = new System.Random(22); + for (var i = 0; i < 50; i++) + { + var twist = quaternion.AxisAngle(z, Uniform(r, -3.1f, 3.1f)); + Assert.True(twist == clamp_twist(twist, z, -inf, inf)); + Assert.True(twist == clamp_twist(twist, z, -1.0f, inf)); + Assert.True(twist == clamp_twist(twist, z, -inf, 1.0f)); + Assert.True(twist == clamp_hinge(twist, z, -inf, inf) || length((float4)clamp_hinge(twist, z, -inf, inf) - (float4)twist) <= 1e-6f); + } + var q = quaternion.AxisAngle(new float3(1, 0, 0), 0.7f); + var h = clamp_hinge(q, z, -inf, inf); + Assert.True(float.IsFinite(h.w) && float.IsFinite(h.z)); + } + + [Fact] + public void BothClampsPropagateNaN() + { + var z = new float3(0, 0, 1); + var nan = float.NaN; + var good = quaternion.AxisAngle(z, 0.3f); + var bad = new quaternion(nan, nan, nan, nan); + foreach (var c in new[] + { + clamp_twist(bad, z, -1.0f, 1.0f), + clamp_twist(good, z, nan, 1.0f), + clamp_twist(good, z, -1.0f, nan), + clamp_twist(good, z, nan, nan), + clamp_hinge(bad, z, -1.0f, 1.0f), + clamp_cone(bad, z, 0.5f), + clamp_cone(quaternion.AxisAngle(new float3(1, 0, 0), 1.0f), z, nan), + }) + { + // Any NaN component poisons the rotation: it is never a plausible unit quaternion. + Assert.True(float.IsNaN(c.x) && float.IsNaN(c.y) && float.IsNaN(c.z), $"{c}"); + } + } + + [Fact] + public void NormalizeAndInverseAgreeAcrossTheFloatRange() + { + foreach (var scale in new[] { 1e-30f, 1e-20f, 1e-12f, 1.0f, 1e19f, 1e30f }) + { + var q = new quaternion(1.0f * scale, -2.0f * scale, 0.5f * scale, 3.0f * scale); + var n = normalize(q); + var expected = normalize(new quaternion(1.0f, -2.0f, 0.5f, 3.0f)); + Assert.True(length((float4)n - (float4)expected) <= 1e-6f, $"{scale}: {n}"); + AssertSameRotation(mul(q, inverse(q)), quaternion.identity); + } + Assert.Equal(quaternion.identity, normalize(new quaternion(0.0f, 0.0f, 0.0f, 0.0f))); + } + + [Fact] + public void ClampConeNearAHalfTurnUsesTheSwingAxisOnlyBelowTheThreshold() + { + var z = new float3(0, 0, 1); + var twist = quaternion.AxisAngle(z, 0.5f); + // A near half turn about x with a twist, so that the swing's own axis differs from the cross direction. + foreach (var (w, usesSwingAxis) in new[] { (2.5e-7f, true), (5e-5f, false) }) + { + var q = mul(normalize(new quaternion(1.0f, 0.0f, 0.0f, w)), twist); + var c = clamp_cone(q, z, 0.4f); + var swingAxis = normalize(new float3(q.x, q.y, q.z)); + var expected = quaternion.AxisAngle(usesSwingAxis ? swingAxis : new float3(1, 0, 0), 0.4f); + AssertSameRotation(c, expected, 1e-5f); + } + } + + [Fact] + public void ClampConeOfATinySwingUsesTheCrossDirectionNotTheSwingAxis() + { + // Angle 1e-7 against 1e-8: the cross product is below the half-turn threshold but the swing points + // toward the axis, so the clamp plane is the cross direction (z component exactly zero), not the + // tilted swing axis. + var z = new float3(0, 0, 1); + var swing = quaternion.AxisAngle(normalize(new float3(1, 0, 0.5f)), 1e-7f); + var c = clamp_cone(swing, z, 1e-8f); + Assert.True(abs(c.x - 5e-9f) <= 1e-9f && abs(c.z) <= 1e-12f, $"{c}"); + } +} diff --git a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs.meta b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs.meta new file mode 100644 index 00000000..afb84c3e --- /dev/null +++ b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 4bee56d64b8862632f92e8fdbe20379c