import { apply_mat4_transform_to_v3_array } from "../../../../../core/geom/3d/mat4/apply_mat4_transform_to_v3_array.js";
import { Miniball } from "../../../../../core/geom/packing/miniball/Miniball.js";
import { PointSet } from "../../../../../core/geom/packing/miniball/PointSet.js";

/**
 *
 * @param {{mesh:ShadedGeometry, transform:mat4}[]} objects
 */
export function compute_bounding_sphere(objects) {
    let total_point_count = 0;
    const object_count = objects.length;

    for (let i = 0; i < object_count; i++) {
        const object = objects[i];

        const geometry = object.mesh.geometry;

        const attribute = geometry.getAttribute('position');

        total_point_count += attribute.count;
    }

    const final_buffer = new Float32Array(total_point_count * 3);

    let pointer = 0;

    for (let i = 0; i < object_count; i++) {
        const object = objects[i];

        const geometry = object.mesh.geometry;

        const attribute = geometry.getAttribute('position');

        const source_length = attribute.array.length;

        apply_mat4_transform_to_v3_array(attribute.array, 0, final_buffer, pointer, attribute.count, object.transform);

        pointer += source_length;
    }

    const points = new PointSet(total_point_count, 3, final_buffer);
    const miniball = new Miniball(points);

    return [...miniball.center(), miniball.radius()];
}
