import { v3_dot } from "../../vec3/v3_dot.js";

/**
 *
 * @param {Float32Array|number[]|vec3} result
 * @param {number} result_offset
 * @param {number} x0 first point defining line
 * @param {number} y0 first point defining line
 * @param {number} z0 first point defining line
 * @param {number} x1 second point defining line
 * @param {number} y1 second point defining line
 * @param {number} z1 second point defining line
 * @param {number} plane_normal_x
 * @param {number} plane_normal_y
 * @param {number} plane_normal_z
 * @param {number} plane_offset
 * @returns {boolean} if intersection exists, false if line is parallel to the plane
 */
export function plane3_compute_line_segment_intersection(
    result, result_offset,
    x0, y0, z0,
    x1, y1, z1,
    plane_normal_x, plane_normal_y, plane_normal_z, plane_offset
) {

    const directionX = x1 - x0;
    const directionY = y1 - y0;
    const directionZ = z1 - z0;

    const denom = v3_dot(directionX, directionY, directionZ, plane_normal_x, plane_normal_y, plane_normal_z);

    if (denom === 0) {
        return false;
    }

    const p = v3_dot(plane_normal_x, plane_normal_y, plane_normal_z, x0, y0, z0) + plane_offset;

    const t = -p / denom;

    if (t < 0 || t > 1) {
        return false;
    }

    result[result_offset] = directionX * t + x0;
    result[result_offset + 1] = directionY * t + y0;
    result[result_offset + 2] = directionZ * t + z0;

    return true;

}
