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

#include "core_math_private.h"

long double DistanceSquared2D(const vec2_t left, const vec2_t right)
{
#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x0806667b): the two deltas
     * right[i]-left[i] are rounded to float slots (fstps), squared in 80-bit
     * (fld d; fmul d) and summed in 80-bit (faddp), the unrounded sum left in
     * st0. Rounded to float at the return for the same reason as
     * DistanceSquared (see distance_squared.c); the x86 #else path keeps the raw
     * 80-bit st0 return. */
    const float deltaX =
        x87f_store_f32(x87f_sub(x87f_load_f32(right[0]), x87f_load_f32(left[0])));
    const float deltaY =
        x87f_store_f32(x87f_sub(x87f_load_f32(right[1]), x87f_load_f32(left[1])));
    x87f sum = x87f_mul(x87f_load_f32(deltaX), x87f_load_f32(deltaX));
    sum = x87f_add(sum, x87f_mul(x87f_load_f32(deltaY), x87f_load_f32(deltaY)));
    return (long double)x87f_store_f32(sum);
#else
    const float deltaX = right[0] - left[0];
    const float deltaY = right[1] - left[1];

    return ((long double)deltaX * (long double)deltaX) +
           ((long double)deltaY * (long double)deltaY);
#endif
}
