From d008ce4875bf245658dbf16c973cba8d7b9200e4 Mon Sep 17 00:00:00 2001 From: gered Date: Sat, 24 Aug 2013 20:08:26 -0400 Subject: [PATCH] add fast inverse sqrt method --- Blarg.GameFramework/Math/MathHelpers.cs | 30 +++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/Blarg.GameFramework/Math/MathHelpers.cs b/Blarg.GameFramework/Math/MathHelpers.cs index c35020a..421ddfe 100644 --- a/Blarg.GameFramework/Math/MathHelpers.cs +++ b/Blarg.GameFramework/Math/MathHelpers.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; namespace Blarg.GameFramework { @@ -198,6 +199,24 @@ namespace Blarg.GameFramework return degrees * MathConstants.PiOver180; } + /// + /// A fast method for calculating the inverse square root of a nunmber. + /// + /// The inverse square root of the given number. + /// The value to get the inverse square root of. + /// Copy of the famous method from the Quake 3 source. + public static float FastInverseSqrt(float x) + { + FloatIntUnion convert; + convert.i = 0; + convert.x = x; + float xhalf = 0.5f * x; + convert.i = 0x5f3759df - (convert.i >> 1); + x = convert.x; + x = x * (1.5f - xhalf * x * x); + return x; + } + /// /// Checks two floats for equality using a defined "tolerance" to account /// for floating point rounding errors, etc. @@ -311,5 +330,16 @@ namespace Blarg.GameFramework float n = Clamp(t, 0.0f, 1.0f); return Lerp(low, high, (n * n) * (3.0f - (2.0f * n))); } + + // this is to allow access to raw float bits + [StructLayout(LayoutKind.Explicit)] + public struct FloatIntUnion + { + [FieldOffset(0)] + public float x; + + [FieldOffset(0)] + public int i; + } } }