import { max2 } from "../../../math/max2.js";
import { min2 } from "../../../math/min2.js";

/**
 * @see Ray Tracing Gems II, Chapter 2 "RAY AXIS-ALIGNED BOUNDING BOX INTERSECTION"
 * @param {number} x0
 * @param {number} y0
 * @param {number} z0
 * @param {number} x1
 * @param {number} y1
 * @param {number} z1
 * @param {number} origin_x
 * @param {number} origin_y
 * @param {number} origin_z
 * @param {number} inv_direction_x 1/ direction_X
 * @param {number} inv_direction_y 1/ direction_Y
 * @param {number} inv_direction_z 1/ direction_Z
 * @param {number} min_distance
 * @param {number} max_distance
 * @returns {boolean}
 */
export function aabb3_intersects_ray_segment(
    x0, y0, z0,
    x1, y1, z1,
    origin_x, origin_y, origin_z,
    inv_direction_x, inv_direction_y, inv_direction_z,
    min_distance, max_distance
) {

    // move aabb into ray space
    const _x0 = x0 - origin_x;
    const _y0 = y0 - origin_y;
    const _z0 = z0 - origin_z;

    const _x1 = x1 - origin_x;
    const _y1 = y1 - origin_y;
    const _z1 = z1 - origin_z;


    // Absolute distances to lower and upper box coordinates
    const t_lower_x = _x0 * inv_direction_x;
    const t_lower_y = _y0 * inv_direction_y;
    const t_lower_z = _z0 * inv_direction_z;

    const t_upper_x = _x1 * inv_direction_x;
    const t_upper_y = _y1 * inv_direction_y;
    const t_upper_z = _z1 * inv_direction_z;

    // The four t-intervals (for x-/y-/z-slabs, and ray p(t))
    const t_min_x = min2(t_lower_x, t_upper_x);
    const t_min_y = min2(t_lower_y, t_upper_y);
    const t_min_z = min2(t_lower_z, t_upper_z);

    const t_max_x = max2(t_lower_x, t_upper_x);
    const t_max_y = max2(t_lower_y, t_upper_y);
    const t_max_z = max2(t_lower_z, t_upper_z);

    // Easy to remember: ``max of mins, and min of maxes''
    const t_box_min = Math.max(t_min_x, t_min_y, t_min_z, min_distance);
    const t_box_max = Math.min(t_max_x, t_max_y, t_max_z, max_distance);

    return t_box_min <= t_box_max;
}

