import { v2_dot } from "../../../vec2/v2_dot.js";

/*
@source https://aras-p.info/texts/CompactNormalStorage.html
@source https://en.wikipedia.org/wiki/Lambert_azimuthal_equal-area_projection

half2 encode (half3 n, float3 view)
{
    half f = sqrt(8*n.z+8);
    return n.xy / f + 0.5;
}
half3 decode (half4 enc, float3 view)
{
    half2 fenc = enc*4-2;
    half f = dot(fenc,fenc);
    half g = sqrt(1-f/4);
    half3 n;
    n.xy = fenc*g;
    n.z = 1-f/2;
    return n;
}
 */

/**
 *
 * @param {number[]} output
 * @param {number} output_offset
 * @param {number} x
 * @param {number} y
 * @param {number} z
 */
export function encode_unit_to_azimuth(output, output_offset, x, y, z) {
    const f = Math.sqrt(8 * z + 8);

    output[output_offset] = x / f + 0.5;
    output[output_offset + 1] = y / f + 0.5;
}

/**
 *
 * @param {number[]} output
 * @param {number} output_offset
 * @param {number} x range [-1,1]
 * @param {number} y range [-1,1]
 */
export function decode_azimuth_to_unit(output, output_offset, x, y) {
    const fenc_x = x * 4 - 2;
    const fenc_y = y * 4 - 2;

    const f = v2_dot(fenc_x, fenc_y, fenc_x, fenc_y);

    const g = Math.sqrt(1 - f / 4);

    const n_x = fenc_x * g;
    const n_y = fenc_y * g;
    const n_z = 1 - f / 2;

    output[output_offset] = n_x;
    output[output_offset + 1] = n_y;
    output[output_offset + 2] = n_z;
}
