import { clamp } from "../../../math/clamp.js";
import { v3_length } from "../../vec3/v3_length.js";

/**
 * Convert cartesian coordinates to spherical
 * @param {number[]} out
 * @param {number} out_offset
 * @param {number} x
 * @param {number} y
 * @param {number} z
 */
export function spherical_from_cartesian(out, out_offset, x, y, z) {

    const radius = v3_length(x, y, z);

    let theta = 0;
    let phi = 0;

    if (radius !== 0) {

        theta = Math.atan2(x, z);
        phi = Math.acos(clamp(y / radius, -1, 1));

    }

    out[out_offset + 0] = phi;
    out[out_offset + 1] = theta;
    out[out_offset + 2] = radius;
}