#include "cm_leaf_queries_private.h"

int32_t CM_PointLeafnum_r(const vec3_t point,
                                             int32_t nodeNum)
{
    while (nodeNum >= 0) {
        const coduo_collision_node_t *node = &cm_nodes[nodeNum];
        const cplane_t *plane = node->plane;
        float d;

        if (plane->type <= 2) {
            d = point[plane->type] - plane->dist;
        } else {
            d = ((plane->normal[0] * point[0]) +
                 (plane->normal[1] * point[1])) +
                (plane->normal[2] * point[2]) - plane->dist;
        }

        if (d < 0.0f) {
            nodeNum = node->children[1];
        } else {
            nodeNum = node->children[0];
        }
    }

    return -1 - nodeNum;
}
