From ad2c40da87e168294502216c965eb6b46bfdb4b4 Mon Sep 17 00:00:00 2001 From: Antoine Pilote Date: Sat, 10 Aug 2024 18:51:37 -0400 Subject: [PATCH] Added useful maths function to the .Net API --- NuakeNet/src/Math.cs | 77 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/NuakeNet/src/Math.cs b/NuakeNet/src/Math.cs index ae268dd4..05cd1368 100644 --- a/NuakeNet/src/Math.cs +++ b/NuakeNet/src/Math.cs @@ -1,10 +1,87 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Numerics; using System.Text; using System.Threading.Tasks; namespace Nuake.Net { + public class Maths + { + public static float AngleRepeat(float value, float max) + { + return (value % max + max) % max; + } + + /// + /// Lerps euler angles and prevents flipping. + /// + /// + /// + /// + /// + public static float LerpAngle(float from, float to, float t) + { + float delta = AngleRepeat(to - from, 360f); + if (delta > 180f) + { + delta -= 360f; + } + return from + delta * Math.Max(0f, Math.Min(1f, t)); + } + + /// + /// Normalize a 3D vector but if the length of the input vector is 0, then the return vector is of length 0. + /// + /// + /// + public static Vector3 NormalizeSafe(Vector3 v) + { + if (v.LengthSquared() == 0.0) + return new Vector3(); + return Vector3.Normalize(v); + } + + /// + /// Normalize a 2D vector but if the length of the input vector is 0, then the return vector is of length 0. + /// + /// + /// + public static Vector2 NormalizeSafe(Vector2 v) + { + if (v.LengthSquared() == 0.0) + return new Vector2(); + return Vector2.Normalize(v); + } + + + /// + /// Normalize a 3D vector, and sets the Y component to 0. If the input length of the input vector is zero, then the return vector is of length 0. + /// + /// + /// + public static Vector3 NormalizeSafe2D(Vector3 v) + { + v.Y = 0f; + if (v.LengthSquared() == 0.0) + return new Vector3(); + + return Vector3.Normalize(v); + } + + + /// + /// Returns the length of a 3D vector taking only the X & Z components into account. + /// + /// + /// + private float Length2D(Vector3 input) + { + input.Y = 0; + return input.Length(); + } + } + }