import { v3_length } from "../../../../../core/geom/vec3/v3_length.js";
import { PI2 } from "../../../../../core/math/PI2.js";

/**
 * @see https://www.shadertoy.com/view/stVfWc
 * @param {number[]} out
 * @param {number} out_offset
 * @param {number[]} normal
 * @param {number} normal_offset
 * @param {function():number} random
 */
export function getCosineDirection(
    out,
    out_offset,
    normal,
    normal_offset,
    random
) {

    const dir_x = normal[normal_offset];
    const dir_y = normal[normal_offset + 1];
    const dir_z = normal[normal_offset + 2];

    const r_x = random() * PI2;
    const r_y = 2 * random() - 1;

    const oneminus = Math.sqrt(1.0 - r_y * r_y);

    const k0 = Math.cos(r_x) * oneminus;
    const k1 = Math.sin(r_x) * oneminus;


    let out_dir_x = dir_x + k0;
    let out_dir_y = dir_y + k1;
    let out_dir_z = dir_z + r_y;

    const len2 = 1 / v3_length(out_dir_x, out_dir_y, out_dir_z);

    out[out_offset] = out_dir_x * len2;
    out[out_offset + 1] = out_dir_y * len2;
    out[out_offset + 2] = out_dir_z * len2;
}