#include "coduo_x87emu.h" /* defines EMULATE_X87; x87 shim when it is 1 */

#include "core_math_private.h"

void VectorNormalizeFast(vec3_t vector)
{
    float lengthSquared;
    float scale;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x0806692c): the squared
     * length is an 80-bit three-term sum rounded to float, scaled by the Q_rsqrt
     * inverse-square-root approximation; each component scale is an 80-bit
     * product rounded to float. */
    lengthSquared = x87f_store_f32(x87f_add(
        x87f_add(x87f_mul(x87f_load_f32(vector[0]), x87f_load_f32(vector[0])),
                 x87f_mul(x87f_load_f32(vector[1]), x87f_load_f32(vector[1]))),
        x87f_mul(x87f_load_f32(vector[2]), x87f_load_f32(vector[2]))));
    scale = (float)Q_rsqrt(lengthSquared);

    vector[0] =
        x87f_store_f32(x87f_mul(x87f_load_f32(vector[0]), x87f_load_f32(scale)));
    vector[1] =
        x87f_store_f32(x87f_mul(x87f_load_f32(vector[1]), x87f_load_f32(scale)));
    vector[2] =
        x87f_store_f32(x87f_mul(x87f_load_f32(vector[2]), x87f_load_f32(scale)));
#else
    lengthSquared = ((vector[0] * vector[0]) + (vector[1] * vector[1])) +
                    (vector[2] * vector[2]);
    scale = (float)Q_rsqrt(lengthSquared);

    vector[0] = vector[0] * scale;
    vector[1] = vector[1] * scale;
    vector[2] = vector[2] * scale;
#endif
}
