import { assert } from "../../../assert.js";

/**
 * NOTE: Based on Transforming Axis-Aligned Bounding Boxes by Jim Arvo from "Graphics Gems", Academic Press, 1990
 * NOTE: {@link result} and {@link aabb} must be different objects
 * @param {ArrayLike<number>|number[]|Float32Array} result
 * @param {ArrayLike<number>|number[]|Float32Array} aabb
 * @param {ArrayLike<number>|number[]|Float32Array} matrix 4x4 matrix
 */
export function aabb3_matrix4_project(result, aabb, matrix) {
    assert.notEqual(result, aabb, 'input and output must not be the same for algorithm to work correctly');

    // extract translation from matrix
    result[0] = result[3] = matrix[12];
    result[1] = result[4] = matrix[13];
    result[2] = result[5] = matrix[14];

    // apply 3x3 matrix transform
    for (let i = 0; i < 3; i++) {
        for (let j = 0; j < 3; j++) {

            const m_a = i + j * 4;
            const m_v = matrix[m_a];

            const a = m_v * aabb[j];
            const b = m_v * aabb[j + 3];

            if (a < b) {
                result[i] += a;
                result[i + 3] += b;
            } else {
                result[i] += b;
                result[i + 3] += a;
            }
        }
    }
}
