diff --git a/packages/cultmath/src/CultMath/math.Quaternion.cs b/packages/cultmath/src/CultMath/math.Quaternion.cs index 857f51b6..fc9f45a9 100644 --- a/packages/cultmath/src/CultMath/math.Quaternion.cs +++ b/packages/cultmath/src/CultMath/math.Quaternion.cs @@ -103,15 +103,20 @@ public static partial class math /// 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. + /// 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); + if (float.IsNaN(angle) || float.IsNaN(min) || float.IsNaN(max)) return new quaternion(float.NaN, float.NaN, float.NaN, float.NaN); 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)); diff --git a/packages/cultmath/src/CultMath/math.cs b/packages/cultmath/src/CultMath/math.cs index 76df64e7..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; diff --git a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs index ff5c2602..22fec3de 100644 --- a/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/QuaternionTests.cs @@ -376,4 +376,88 @@ public sealed class QuaternionTests 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}"); + } }