#include "cm_trace_core_private.h"

void CM_TraceThroughLeaf(traceWork_t *traceWork,
                         const coduo_collision_leaf_t *leaf)
{
    for (int32_t leafBrushIndex = 0;
         leafBrushIndex < (int32_t)leaf->numLeafBrushes; ++leafBrushIndex) {
        const int32_t brushIndex =
            cm_leafbrushes[leaf->firstLeafBrush + leafBrushIndex];
        coduo_collision_brush_t *brush = &cm_brushes[brushIndex];

        if (brush->checkcount == cm_checkcount) {
            continue;
        }

        brush->checkcount = cm_checkcount;

        if ((traceWork->contents & brush->contents) == 0) {
            continue;
        }

        CM_TraceThroughBrush(traceWork, brush);

        if (traceWork->trace.fraction == 0.0f) {
            return;
        }
    }

    if (cm_noCurves->integer != 0) {
        return;
    }

    for (int32_t leafSurfaceIndex = 0;
         leafSurfaceIndex < (int32_t)leaf->numLeafTerrainPatches;
         ++leafSurfaceIndex) {
        const int32_t terrainPatchIndex =
            cm_leafsurfaces[leaf->firstLeafTerrainPatch + leafSurfaceIndex];
        coduo_collision_terrain_patch_t *terrainPatch =
            &cm_terrainPatches[terrainPatchIndex];

        if (terrainPatch->checkcount == cm_checkcount) {
            continue;
        }

        terrainPatch->checkcount = cm_checkcount;

        if ((traceWork->contents & terrainPatch->contents) == 0) {
            continue;
        }

        CM_TraceThroughPatch(traceWork, terrainPatch);

        if (traceWork->trace.fraction == 0.0f) {
            return;
        }
    }
}
