#include "cm_patch_private.h"
#include "cm_terrain_private.h"
#include "cm_trace_core_private.h"

void CM_TraceThroughPatch(
    traceWork_t *traceWork,
    const coduo_collision_terrain_patch_t *terrainPatch)
{
    if (CM_TraceMayIntersectBox(traceWork, terrainPatch->mins,
                                     terrainPatch->maxs) == 0) {
        return;
    }

    const float savedFraction =
        traceWork->trace.fraction;

    if (terrainPatch->terrainCollide != NULL) {
        CM_TraceThroughTerrainCollide(traceWork, terrainPatch->terrainCollide);
    } else {
        CM_TraceThroughPatchCollide(traceWork, terrainPatch->patchCollide);
    }

    if (traceWork->trace.fraction < savedFraction) {
        dshader_t *material =
            &cm_materials[terrainPatch->materialIndex];

        traceWork->trace.surfaceFlags = material->surfaceFlags;
        traceWork->trace.contents = terrainPatch->contents;
        traceWork->trace.material = material->shader;
    }
}
