#ifndef GL
#include <drivers\drv_gl.txt>
#endif

#ifndef GLT

#define GLT
#define GLT_MAX_TRIANGLES 32

float __GLT_VERTBUFF[(GLT_MAX_TRIANGLES * 3) * 3];
float __GLT_VERTCNT = 0;

void gltVertex(float x, float y, float z)
{
    if ((__GLT_VERTCNT / 3) >= GLT_MAX_TRIANGLES)
        return;

    float* ptr = __GLT_VERTBUFF;
    ptr += (__GLT_VERTCNT * 3);

    *ptr = x;
    *(++ptr) = y;
    *(++ptr) = z;

    __GLT_VERTCNT++;
}

void gltTriangle(float x1, float y1, float z1,
                 float x2, float y2, float z2,
                 float x3, float y3, float z3)
{
    gltVertex(x1, y1, z1);
    gltVertex(x2, y2, z2);
    gltVertex(x3, y3, z3);
}

void gltQuad(float tlx, float tly, float tlz,
             float trx, float try, float trz,
             float brx, float bry, float brz,
             float blx, float bly, float blz)
{
    gltTriangle(
        trx, try, trz,
        tlx, tly, tlz,
        blx, bly, blz
    );

    gltTriangle(
        brx, bry, brz,
        trx, try, trz,
        blx, bly, blz
    );
}

void gltCube(float cex, float cey, float cez, float size)
{
    float s2 = size / 2;

    gltQuad(
        cex - s2, cey + s2, cez - s2,
        cex + s2, cey + s2, cez - s2,
        cex + s2, cey - s2, cez - s2,
        cex - s2, cey - s2, cez - s2
    );

    gltQuad(
        cex + s2, cey + s2, cez + s2,
        cex - s2, cey + s2, cez + s2,
        cex - s2, cey - s2, cez + s2,
        cex + s2, cey - s2, cez + s2
    );

    gltQuad(
        cex - s2, cey + s2, cez + s2,
        cex - s2, cey + s2, cez - s2,
        cex - s2, cey - s2, cez - s2,
        cex - s2, cey - s2, cez + s2
    );

    gltQuad(
        cex + s2, cey + s2, cez - s2,
        cex + s2, cey + s2, cez + s2,
        cex + s2, cey - s2, cez + s2,
        cex + s2, cey - s2, cez - s2
    );

    gltQuad(
        cex - s2, cey + s2, cez + s2,
        cex + s2, cey + s2, cez + s2,
        cex + s2, cey + s2, cez - s2,
        cex - s2, cey + s2, cez - s2
    );

    gltQuad(
        cex - s2, cey - s2, cez - s2,
        cex + s2, cey - s2, cez - s2,
        cex + s2, cey - s2, cez + s2,
        cex - s2, cey - s2, cez + s2
    );
}

void gltClearBuffer()
{
    __GLT_VERTCNT = 0;
}

void gltFlushBuffer()
{
    if (__GLT_VERTCNT <= 3)
        return;

    float vcnt = __GLT_VERTCNT;
    float tcnt = (vcnt / 3) - (vcnt % 3);

    if (tcnt > GLT_MAX_TRIANGLES)
        tcnt = GLT_MAX_TRIANGLES;

    glPoly3D(__GLT_VERTBUFF, tcnt);
    glFlush();
}

#endif
