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

/**
 *
 * @param {Vector3} out Result will be written here
 * @param {number} originX Ray origin
 * @param {number} originY Ray origin
 * @param {number} originZ Ray origin
 * @param {number} directionX Ray direction
 * @param {number} directionY Ray direction
 * @param {number} directionZ Ray direction
 * @param {number} normalX Plane normal
 * @param {number} normalY Plane normal
 * @param {number} normalZ Plane normal
 * @param {number} dist Plane distance
 * @returns {boolean} true if intersection is found, false otherwise
 */
export function plane3_compute_ray_intersection(
    out,
    originX, originY, originZ,
    directionX, directionY, directionZ,
    normalX, normalY, normalZ, dist
) {
    const denom = v3_dot(directionX, directionY, directionZ, normalX, normalY, normalZ);

    const p = v3_dot(normalX, normalY, normalZ, originX, originY, originZ) + dist;

    if (denom !== 0) {

        const t = -p / denom;

        if (t < 0) {
            // ray starts and points behind the plane
            return false;
        }

        out.set(
            directionX * t + originX,
            directionY * t + originY,
            directionZ * t + originZ
        );

        return true;

    } else {
        // ray direction is perpendicular to the plane normal. In other words ray runs parallel to the plane

        if (p === 0) {
            // ray origin lies on the plane
            out.set(originX, originY, originZ);

            return true;

        } else {

            //no intersection
            return false;

        }

    }
}
