//

import { SCRATCH_UINT32_TRAVERSAL_STACK } from "../../../collection/SCRATCH_UINT32_TRAVERSAL_STACK.js";
import { NULL_NODE } from "../BVH.js";

const stack = SCRATCH_UINT32_TRAVERSAL_STACK;

/**
 *
 * @param {number[]} destination
 * @param {number} destination_offset
 * @param {BVH} bvh
 * @param {number} root
 * @returns {number} number of collected elements
 */
export function bvh_collect_user_data(
    destination, destination_offset,
    bvh, root
) {

    if (root === NULL_NODE) {
        return 0;
    }

    /**
     *
     * @type {number}
     */
    const stack_top = stack.pointer++;

    stack[stack_top] = root;

    let result_cursor = destination_offset;

    while (stack.pointer > stack_top) {
        stack.pointer--;

        /**
         *
         * @type {number}
         */
        const node = stack[stack.pointer];

        const node_is_leaf = bvh.node_is_leaf(node);

        if (!node_is_leaf) {

            // read in-order
            const child1 = bvh.node_get_child1(node);
            const child2 = bvh.node_get_child2(node);

            // write to stack in reverse order, so that fist child ends up being visited first
            stack[stack.pointer++] = child1;
            stack[stack.pointer++] = child2;

        } else {
            // leaf root

            destination[result_cursor++] = bvh.node_get_user_data(node);
        }
    }

    // drop stack frame

    return result_cursor - destination_offset;
}
