using System.Numerics;
namespace GamePort.Game;
/// OMT2 vector::angles second output used by the original shrink ray.
public static class OriginalHeading
{
private static readonly ushort[] halfAcos = BuildHalfAcos();
public static float Degrees(Vector3 vector)
=> HeadingUnits(vector) * 0.02197265625f;
private static int HeadingUnits(Vector3 vector)
{
if (!float.IsFinite(vector.X) || !float.IsFinite(vector.Y) || !float.IsFinite(vector.Z))
throw new ArgumentOutOfRangeException(nameof(vector), "A finite direction is required.");
double x = vector.X, z = vector.Z;
if (x == 0 && z == 0) return 0;
// DLL1001FDCB..1001FE3D: truncate the squared ratio, table lookup,
// quadrant correction, negate and mask to the original 14-bit circle.
// Double intermediates approximate x87 extended precision; see findings.
int index = (int)(16384.0 * z * z / (x * x + z * z));
int angle = halfAcos[index];
if (z < 0)
angle = x < 0 ? 8192 + angle : 8192 - angle;
else if (x < 0)
angle = 16384 - angle;
return (-angle) & 0x3fff;
}
///
/// Signed circle representation used by movement consumers of OMT2 angles.
/// Mask yaw with16383 when matching the DLL's raw14-bit circle output.
///
public static (int Pitch,int Yaw) Angles(Vector3 vector)
{
var heading=HeadingUnits(vector);
var radians=((-heading)&16383)*(Math.Tau/16384);
float sine=(float)Math.Sin(radians), cosine=(float)Math.Cos(radians);
var h=(double)vector.X*sine+(double)vector.Z*cosine;
double y=vector.Y;
int value=0;
if (h!=0||y!=0)
{
var index=(int)(16384*y*y/(h*h+y*y));
value=halfAcos[Math.Clamp(index,0,16384)];
if(y<0) value=h<0 ? 8192+value : 8192-value;
else if(h<0) value=16384-value;
}
var pitch=(4096-value)&16383;
if(pitch>8192)pitch-=16384;
if(heading>8192)heading-=16384;
return (pitch,heading);
}
private static ushort[] BuildHalfAcos()
{
var table = new ushort[16385];
// Stored DLL constants; final endpoint is explicitly zero at100EDD0D.
for (int i = 0; i < 16384; i++)
table[i] = (ushort)(Math.Acos(i * 0.0001220703125 - 1)
* 2607.5945876921437 * 0.5);
return table;
}
}