]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_backend.c
corrected function names reported in various backend not active errors (by using...
[xonotic/darkplaces.git] / gl_backend.c
index aff67a440c10e6f15fdfdd8c7681723b3f2c2fc6..16178e65f892c4ea9eed3e19848256c10792d879 100644 (file)
 
 #include "quakedef.h"
 
 
 #include "quakedef.h"
 
-static int max_meshs;
-static int max_batch;
-static int max_verts; // always max_meshs * 3
-#define TRANSDEPTHRES 4096
+cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "1024"};
+cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
+cvar_t gl_mesh_drawmode = {CVAR_SAVE, "gl_mesh_drawmode", "3"};
 
 
-static cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "21760"};
-static cvar_t gl_mesh_batchtriangles = {0, "gl_mesh_batchtriangles", "1024"};
-static cvar_t gl_mesh_merge = {0, "gl_mesh_merge", "1"};
-static cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
+cvar_t r_render = {0, "r_render", "1"};
+cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
+cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
 
 
-typedef struct buf_mesh_s
-{
-       struct buf_mesh_s *next;
-       int depthmask;
-       int depthtest;
-       int blendfunc1, blendfunc2;
-       int textures[MAX_TEXTUREUNITS];
-       float texturergbscale[MAX_TEXTUREUNITS];
-       int firsttriangle;
-       int triangles;
-       int firstvert;
-       int lastvert;
-}
-buf_mesh_t;
+// this is used to increase gl_mesh_maxtriangles automatically if a mesh was
+// too large for the buffers in the previous frame
+int overflowedverts = 0;
 
 
-typedef struct buf_transtri_s
-{
-       struct buf_transtri_s *next;
-       buf_mesh_t *mesh;
-       int index[3];
-}
-buf_transtri_t;
+int gl_maxdrawrangeelementsvertices;
+int gl_maxdrawrangeelementsindices;
 
 
-typedef struct buf_tri_s
-{
-       int index[3];
-}
-buf_tri_t;
+#ifdef DEBUGGL
+int errornumber = 0;
 
 
-typedef struct
+void GL_PrintError(int errornumber, char *filename, int linenumber)
 {
 {
-       float v[4];
+       switch(errornumber)
+       {
+#ifdef GL_INVALID_ENUM
+       case GL_INVALID_ENUM:
+               Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_INVALID_VALUE
+       case GL_INVALID_VALUE:
+               Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_INVALID_OPERATION
+       case GL_INVALID_OPERATION:
+               Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_STACK_OVERFLOW
+       case GL_STACK_OVERFLOW:
+               Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_STACK_UNDERFLOW
+       case GL_STACK_UNDERFLOW:
+               Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_OUT_OF_MEMORY
+       case GL_OUT_OF_MEMORY:
+               Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
+               break;
+#endif
+#ifdef GL_TABLE_TOO_LARGE
+    case GL_TABLE_TOO_LARGE:
+               Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
+               break;
+#endif
+       default:
+               Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
+               break;
+       }
 }
 }
-buf_vertex_t;
+#endif
 
 
-typedef struct
-{
-       float c[4];
-}
-buf_fcolor_t;
+#define BACKENDACTIVECHECK if (!backendactive) Sys_Error(__func__ " called when backend is not active\n");
 
 
-typedef struct
-{
-       byte c[4];
-}
-buf_bcolor_t;
+float r_mesh_farclip;
 
 
-typedef struct
-{
-       float t[2];
-}
-buf_texcoord_t;
-
-static float meshfarclip;
-static int currentmesh, currenttriangle, currentvertex, backendunits, backendactive, meshmerge, floatcolors, transranout;
-static buf_mesh_t *buf_mesh;
-static buf_tri_t *buf_tri;
-static buf_vertex_t *buf_vertex;
-static buf_fcolor_t *buf_fcolor;
-static buf_bcolor_t *buf_bcolor;
-static buf_texcoord_t *buf_texcoord[MAX_TEXTUREUNITS];
-
-static int currenttransmesh, currenttransvertex, currenttranstriangle;
-static buf_mesh_t *buf_transmesh;
-static buf_transtri_t *buf_transtri;
-static buf_transtri_t **buf_transtri_list;
-static buf_vertex_t *buf_transvertex;
-static buf_fcolor_t *buf_transfcolor;
-static buf_bcolor_t *buf_transbcolor;
-static buf_texcoord_t *buf_transtexcoord[MAX_TEXTUREUNITS];
+static float viewdist;
+// sign bits (true if negative) for vpn[] entries, so quick integer compares can be used instead of float compares
+static int vpnbit0, vpnbit1, vpnbit2;
+
+int c_meshs, c_meshtris;
+
+int lightscalebit;
+float lightscale;
+float overbrightscale;
 
 
+void SCR_ScreenShot_f (void);
+
+// these are externally accessible
+float mesh_colorscale;
+int *varray_element;
+float *varray_vertex;
+float *varray_color;
+float *varray_texcoord[MAX_TEXTUREUNITS];
+int mesh_maxtris;
+int mesh_maxverts; // always mesh_maxtris * 3
+
+static matrix4x4_t backendmatrix;
+
+static int backendunits, backendactive;
+static qbyte *varray_bcolor;
 static mempool_t *gl_backend_mempool;
 
 static mempool_t *gl_backend_mempool;
 
-static void gl_backend_start(void)
+void GL_Backend_AllocArrays(void)
 {
        int i;
 
 {
        int i;
 
-       max_verts = max_meshs * 3;
-
-       gl_backend_mempool = Mem_AllocPool("GL_Backend");
-
-#define BACKENDALLOC(var, count, sizeofstruct)\
-       {\
-               var = Mem_Alloc(gl_backend_mempool, count * sizeof(sizeofstruct));\
-               if (var == NULL)\
-                       Sys_Error("gl_backend_start: unable to allocate memory\n");\
-               memset(var, 0, count * sizeof(sizeofstruct));\
-       }
+       if (!gl_backend_mempool)
+               gl_backend_mempool = Mem_AllocPool("GL_Backend");
 
 
-       BACKENDALLOC(buf_mesh, max_meshs, buf_mesh_t)
-       BACKENDALLOC(buf_tri, max_meshs, buf_tri_t)
-       BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t)
-       BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t)
-       BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t)
+       mesh_maxverts = mesh_maxtris * 3;
 
 
-       BACKENDALLOC(buf_transmesh, max_meshs, buf_mesh_t)
-       BACKENDALLOC(buf_transtri, max_meshs, buf_transtri_t)
-       BACKENDALLOC(buf_transtri_list, TRANSDEPTHRES, buf_transtri_t *)
-       BACKENDALLOC(buf_transvertex, max_verts, buf_vertex_t)
-       BACKENDALLOC(buf_transfcolor, max_verts, buf_fcolor_t)
-       BACKENDALLOC(buf_transbcolor, max_verts, buf_bcolor_t)
+       varray_element = Mem_Alloc(gl_backend_mempool, mesh_maxtris * sizeof(int[3]));
+       varray_vertex = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
+       varray_color = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
+       varray_bcolor = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(qbyte[4]));
+       for (i = 0;i < backendunits;i++)
+               varray_texcoord[i] = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[2]));
+       for (;i < MAX_TEXTUREUNITS;i++)
+               varray_texcoord[i] = NULL;
+}
 
 
+void GL_Backend_FreeArrays(int resizingbuffers)
+{
+       int i;
+       if (resizingbuffers)
+               Mem_EmptyPool(gl_backend_mempool);
+       else
+               Mem_FreePool(&gl_backend_mempool);
+       varray_element = NULL;
+       varray_vertex = NULL;
+       varray_color = NULL;
+       varray_bcolor = NULL;
        for (i = 0;i < MAX_TEXTUREUNITS;i++)
        for (i = 0;i < MAX_TEXTUREUNITS;i++)
-       {
-               // only allocate as many texcoord arrays as we need
-               if (i < gl_textureunits)
-               {
-                       BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t)
-                       BACKENDALLOC(buf_transtexcoord[i], max_verts, buf_texcoord_t)
-               }
-               else
-               {
-                       buf_texcoord[i] = NULL;
-                       buf_transtexcoord[i] = NULL;
-               }
-       }
-       backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
-       backendactive = true;
+               varray_texcoord[i] = NULL;
 }
 
 }
 
-static void gl_backend_shutdown(void)
+static void gl_backend_start(void)
 {
 {
-       int i;
-       /*
-#define BACKENDFREE(var)\
-       if (var)\
-       {\
-               Mem_Free(var);\
-               var = NULL;\
+       Con_Printf("OpenGL Backend started with gl_mesh_maxtriangles %i\n", gl_mesh_maxtriangles.integer);
+       if (qglDrawRangeElements != NULL)
+       {
+               qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
+               qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
+               CHECKGLERROR
+               Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
        }
        }
-       */
-#define BACKENDFREE(var) var = NULL;
-
-       BACKENDFREE(buf_mesh)
-       BACKENDFREE(buf_tri)
-       BACKENDFREE(buf_vertex)
-       BACKENDFREE(buf_fcolor)
-       BACKENDFREE(buf_bcolor)
-
-       BACKENDFREE(buf_transmesh)
-       BACKENDFREE(buf_transtri)
-       BACKENDFREE(buf_transtri_list)
-       BACKENDFREE(buf_transvertex)
-       BACKENDFREE(buf_transfcolor)
-       BACKENDFREE(buf_transbcolor)
-
-       for (i = 0;i < MAX_TEXTUREUNITS;i++)
+       if (strstr(gl_renderer, "3Dfx"))
        {
        {
-               BACKENDFREE(buf_texcoord[i])
-               BACKENDFREE(buf_transtexcoord[i])
+               Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
+               Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
        }
 
        }
 
-       Mem_FreePool(&gl_backend_mempool);
+       backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
 
 
-       backendunits = 0;
-       backendactive = false;
+       GL_Backend_AllocArrays();
+
+       backendactive = true;
 }
 
 }
 
-static void gl_backend_bufferchanges(int init)
+static void gl_backend_shutdown(void)
 {
 {
-       // 21760 is (65536 / 3) rounded off to a multiple of 128
-       if (gl_mesh_maxtriangles.integer < 256)
-               Cvar_SetValue("gl_mesh_maxtriangles", 256);
-       if (gl_mesh_maxtriangles.integer > 21760)
-               Cvar_SetValue("gl_mesh_maxtriangles", 21760);
+       backendunits = 0;
+       backendactive = false;
 
 
-       if (gl_mesh_batchtriangles.integer < 0)
-               Cvar_SetValue("gl_mesh_batchtriangles", 0);
-       if (gl_mesh_batchtriangles.integer > gl_mesh_maxtriangles.integer)
-               Cvar_SetValue("gl_mesh_batchtriangles", gl_mesh_maxtriangles.integer);
+       Con_Printf("OpenGL Backend shutting down\n");
 
 
-       max_batch = gl_mesh_batchtriangles.integer;
+       GL_Backend_FreeArrays(false);
+}
 
 
-       if (max_meshs != gl_mesh_maxtriangles.integer)
-       {
-               max_meshs = gl_mesh_maxtriangles.integer;
+void GL_Backend_CheckCvars(void)
+{
+       if (gl_mesh_drawmode.integer < 0)
+               Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
+       if (gl_mesh_drawmode.integer > 3)
+               Cvar_SetValueQuick(&gl_mesh_drawmode, 3);
 
 
-               if (!init)
-               {
-                       gl_backend_shutdown();
-                       gl_backend_start();
-               }
-       }
+       // change drawmode 3 to 2 if 3 won't work
+       if (gl_mesh_drawmode.integer >= 3 && qglDrawRangeElements == NULL)
+               Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
+
+       // 21760 is (65536 / 3) rounded off to a multiple of 128
+       if (gl_mesh_maxtriangles.integer < 1024)
+               Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
+       if (gl_mesh_maxtriangles.integer > 21760)
+               Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
 }
 
 }
 
-float r_farclip, r_newfarclip;
+void GL_Backend_ResizeArrays(int numtriangles)
+{
+       Cvar_SetValueQuick(&gl_mesh_maxtriangles, numtriangles);
+       GL_Backend_CheckCvars();
+       mesh_maxtris = gl_mesh_maxtriangles.integer;
+       GL_Backend_FreeArrays(true);
+       GL_Backend_AllocArrays();
+}
 
 static void gl_backend_newmap(void)
 {
 
 static void gl_backend_newmap(void)
 {
-       r_farclip = r_newfarclip = 2048.0f;
 }
 
 }
 
-int polyindexarray[768];
-
 void gl_backend_init(void)
 {
 void gl_backend_init(void)
 {
-       int i;
+       Cvar_RegisterVariable(&r_render);
+       Cvar_RegisterVariable(&gl_dither);
+       Cvar_RegisterVariable(&gl_lockarrays);
+#ifdef NORENDER
+       Cvar_SetValue("r_render", 0);
+#endif
+
        Cvar_RegisterVariable(&gl_mesh_maxtriangles);
        Cvar_RegisterVariable(&gl_mesh_maxtriangles);
-       Cvar_RegisterVariable(&gl_mesh_batchtriangles);
-       Cvar_RegisterVariable(&gl_mesh_merge);
        Cvar_RegisterVariable(&gl_mesh_floatcolors);
        Cvar_RegisterVariable(&gl_mesh_floatcolors);
+       Cvar_RegisterVariable(&gl_mesh_drawmode);
+       GL_Backend_CheckCvars();
        R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
        R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
-       gl_backend_bufferchanges(true);
-       for (i = 0;i < 256;i++)
-       {
-               polyindexarray[i*3+0] = 0;
-               polyindexarray[i*3+1] = i + 1;
-               polyindexarray[i*3+2] = i + 2;
-       }
 }
 
 }
 
-static float viewdist;
-
-int c_meshtris;
+int arraylocked = false;
 
 
-// called at beginning of frame
-void R_Mesh_Clear(void)
+void GL_LockArray(int first, int count)
 {
 {
-       if (!backendactive)
-               Sys_Error("R_Mesh_Clear: called when backend is not active\n");
-
-       gl_backend_bufferchanges(false);
-
-       currentmesh = 0;
-       currenttriangle = 0;
-       currentvertex = 0;
-       currenttransmesh = 0;
-       currenttranstriangle = 0;
-       currenttransvertex = 0;
-       meshfarclip = 0;
-       meshmerge = gl_mesh_merge.integer;
-       floatcolors = gl_mesh_floatcolors.integer;
-       transranout = false;
-       viewdist = DotProduct(r_origin, vpn);
-
-       c_meshtris = 0;
+       if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer > 0)
+       {
+               qglLockArraysEXT(first, count);
+               CHECKGLERROR
+               arraylocked = true;
+       }
 }
 
 }
 
-#ifdef DEBUGGL
-void GL_PrintError(int errornumber, char *filename, int linenumber)
+void GL_UnlockArray(void)
 {
 {
-       switch(errornumber)
+       if (arraylocked)
        {
        {
-       case GL_INVALID_ENUM:
-               Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
-               break;
-       case GL_INVALID_VALUE:
-               Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
-               break;
-       case GL_INVALID_OPERATION:
-               Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
-               break;
-       case GL_STACK_OVERFLOW:
-               Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
-               break;
-       case GL_STACK_UNDERFLOW:
-               Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
-               break;
-       case GL_OUT_OF_MEMORY:
-               Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
-               break;
-#ifdef GL_TABLE_TOO_LARGE
-    case GL_TABLE_TOO_LARGE:
-               Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
-               break;
-#endif
-       default:
-               Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
-               break;
+               qglUnlockArraysEXT();
+               CHECKGLERROR
+               arraylocked = false;
        }
 }
 
        }
 }
 
-int errornumber = 0;
-#endif
-
-// renders mesh buffers, called to flush buffers when full
-void R_Mesh_Render(void)
+/*
+=============
+GL_SetupFrame
+=============
+*/
+static void GL_SetupFrame (void)
 {
 {
-       int i, k, blendfunc1, blendfunc2, blend, depthmask, depthtest, unit = 0, clientunit = 0, firsttriangle, triangles, firstvert, lastvert, texture[MAX_TEXTUREUNITS];
-       float farclip, texturergbscale[MAX_TEXTUREUNITS];
-       buf_mesh_t *mesh;
-       if (!backendactive)
-               Sys_Error("R_Mesh_Render: called when backend is not active\n");
-       if (!currentmesh)
-               return;
+       double xmax, ymax;
+       double fovx, fovy, zNear, zFar, aspect;
 
 
-CHECKGLERROR
-
-       farclip = meshfarclip + 256.0f - viewdist; // + 256 just to be safe
+       if (!r_render.integer)
+               return;
 
 
-       // push out farclip for next frame
-       if (farclip > r_newfarclip)
-               r_newfarclip = ceil((farclip + 255) / 256) * 256 + 256;
+       qglDepthFunc (GL_LEQUAL);CHECKGLERROR
+
+       // set up viewpoint
+       qglMatrixMode(GL_PROJECTION);CHECKGLERROR
+       qglLoadIdentity ();CHECKGLERROR
+
+       // y is weird beause OpenGL is bottom to top, we use top to bottom
+       qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
+
+       // depth range
+       zNear = 1.0;
+       zFar = r_mesh_farclip;
+       if (zFar < 64)
+               zFar = 64;
+
+       // fov angles
+       fovx = r_refdef.fov_x;
+       fovy = r_refdef.fov_y;
+       aspect = r_refdef.width / r_refdef.height;
+
+       // pyramid slopes
+       xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
+       ymax = zNear * tan(fovy * M_PI / 360.0);
+
+       // set view pyramid
+       qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
+
+       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+       qglLoadIdentity ();CHECKGLERROR
+
+       // put Z going up
+       qglRotatef (-90,  1, 0, 0);CHECKGLERROR
+       qglRotatef (90,  0, 0, 1);CHECKGLERROR
+       // camera rotation
+       qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
+       qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
+       qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
+       // camera location
+       qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
+}
 
 
-       for (i = 0;i < backendunits;i++)
-               texturergbscale[i] = 1;
-
-       glEnable(GL_CULL_FACE);
-CHECKGLERROR
-       glCullFace(GL_FRONT);
-CHECKGLERROR
-       depthtest = true;
-       glEnable(GL_DEPTH_TEST);
-CHECKGLERROR
-       blendfunc1 = GL_ONE;
-       blendfunc2 = GL_ZERO;
-       glBlendFunc(blendfunc1, blendfunc2);
-CHECKGLERROR
-       blend = 0;
-       glDisable(GL_BLEND);
-CHECKGLERROR
-       depthmask = true;
-       glDepthMask((GLboolean) depthmask);
-CHECKGLERROR
-
-CHECKGLERROR
-       glVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), buf_vertex);
-CHECKGLERROR
-       glEnableClientState(GL_VERTEX_ARRAY);
-CHECKGLERROR
-       if (floatcolors)
-       {
-               glColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), buf_fcolor);
-CHECKGLERROR
-       }
-       else
-       {
-               glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), buf_bcolor);
-CHECKGLERROR
-       }
-       glEnableClientState(GL_COLOR_ARRAY);
-CHECKGLERROR
+static struct
+{
+       int blendfunc1;
+       int blendfunc2;
+       int blend;
+       GLboolean depthmask;
+       int depthdisable;
+       int unit;
+       int clientunit;
+       int texture[MAX_TEXTUREUNITS];
+       float texturergbscale[MAX_TEXTUREUNITS];
+}
+gl_state;
 
 
+void GL_SetupTextureState(void)
+{
+       int i;
        if (backendunits > 1)
        {
                for (i = 0;i < backendunits;i++)
                {
        if (backendunits > 1)
        {
                for (i = 0;i < backendunits;i++)
                {
-                       qglActiveTexture(GL_TEXTURE0_ARB + (unit = i));
-CHECKGLERROR
-                       glBindTexture(GL_TEXTURE_2D, (texture[i] = 0));
-CHECKGLERROR
-                       glDisable(GL_TEXTURE_2D);
-CHECKGLERROR
+                       qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
+                       qglBindTexture(GL_TEXTURE_2D, gl_state.texture[i]);CHECKGLERROR
                        if (gl_combine.integer)
                        {
                        if (gl_combine.integer)
                        {
-                               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);
-CHECKGLERROR
-                               glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);
-CHECKGLERROR
-                               glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0f);
-CHECKGLERROR
-                               glTexEnvf(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1.0f);
-CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, gl_state.texturergbscale[i]);CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
                        }
                        else
                        {
                        }
                        else
                        {
-                               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
                        }
                        }
-
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + (clientunit = i));
-CHECKGLERROR
-                       glTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);
-CHECKGLERROR
-                       glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-               }
-       }
-       else
-       {
-               glBindTexture(GL_TEXTURE_2D, (texture[0] = 0));
-CHECKGLERROR
-               glDisable(GL_TEXTURE_2D);
-CHECKGLERROR
-               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-CHECKGLERROR
-
-               glTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);
-CHECKGLERROR
-               glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-       }
-
-       // lock as early as possible
-       GL_LockArray(0, currentvertex);
-CHECKGLERROR
-
-       for (k = 0;k < currentmesh;)
-       {
-               mesh = &buf_mesh[k];
-
-               if (backendunits > 1)
-               {
-//                     int topunit = 0;
-                       for (i = 0;i < backendunits;i++)
+                       if (gl_state.texture[i])
                        {
                        {
-                               if (texture[i] != mesh->textures[i])
+                               qglEnable(GL_TEXTURE_2D);CHECKGLERROR
+                       }
+                       else
+                       {
+                               qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+                       }
+                       if (gl_mesh_drawmode.integer > 0)
+                       {
+                               qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
+                               qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), varray_texcoord[i]);CHECKGLERROR
+                               if (gl_state.texture[i])
                                {
                                {
-                                       if (unit != i)
-                                       {
-                                               qglActiveTexture(GL_TEXTURE0_ARB + (unit = i));
-CHECKGLERROR
-                                       }
-                                       if (texture[i] == 0)
-                                       {
-                                               glEnable(GL_TEXTURE_2D);
-CHECKGLERROR
-                                               // have to disable texcoord array on disabled texture
-                                               // units due to NVIDIA driver bug with
-                                               // compiled_vertex_array
-                                               if (clientunit != i)
-                                               {
-                                                       qglClientActiveTexture(GL_TEXTURE0_ARB + (clientunit = i));
-CHECKGLERROR
-                                               }
-                                               glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-                                       }
-                                       glBindTexture(GL_TEXTURE_2D, (texture[i] = mesh->textures[i]));
-CHECKGLERROR
-                                       if (texture[i] == 0)
-                                       {
-                                               glDisable(GL_TEXTURE_2D);
-CHECKGLERROR
-                                               // have to disable texcoord array on disabled texture
-                                               // units due to NVIDIA driver bug with
-                                               // compiled_vertex_array
-                                               if (clientunit != i)
-                                               {
-                                                       qglClientActiveTexture(GL_TEXTURE0_ARB + (clientunit = i));
-CHECKGLERROR
-                                               }
-                                               glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-                                       }
+                                       qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                                }
                                }
-                               if (texturergbscale[i] != mesh->texturergbscale[i])
+                               else
                                {
                                {
-                                       if (unit != i)
-                                       {
-                                               qglActiveTexture(GL_TEXTURE0_ARB + (unit = i));
-CHECKGLERROR
-                                       }
-                                       glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (texturergbscale[i] = mesh->texturergbscale[i]));
-CHECKGLERROR
+                                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                                }
                                }
-//                             if (texture[i])
-//                                     topunit = i;
                        }
                        }
-//                     if (unit != topunit)
-//                     {
-//                             qglActiveTexture(GL_TEXTURE0_ARB + (unit = topunit));
-//CHECKGLERROR
-//                     }
+               }
+       }
+       else
+       {
+               qglBindTexture(GL_TEXTURE_2D, gl_state.texture[0]);CHECKGLERROR
+               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
+               if (gl_state.texture[0])
+               {
+                       qglEnable(GL_TEXTURE_2D);CHECKGLERROR
                }
                else
                {
                }
                else
                {
-                       if (texture[0] != mesh->textures[0])
-                       {
-                               if (texture[0] == 0)
-                               {
-                                       glEnable(GL_TEXTURE_2D);
-CHECKGLERROR
-                                       glEnableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-                               }
-                               glBindTexture(GL_TEXTURE_2D, (texture[0] = mesh->textures[0]));
-CHECKGLERROR
-                               if (texture[0] == 0)
-                               {
-                                       glDisable(GL_TEXTURE_2D);
-CHECKGLERROR
-                                       glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
-                               }
-                       }
+                       qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                }
                }
-               if (blendfunc1 != mesh->blendfunc1 || blendfunc2 != mesh->blendfunc2)
+               if (gl_mesh_drawmode.integer > 0)
                {
                {
-                       blendfunc1 = mesh->blendfunc1;
-                       blendfunc2 = mesh->blendfunc2;
-                       glBlendFunc(blendfunc1, blendfunc2);
-CHECKGLERROR
-                       if (blendfunc2 == GL_ZERO)
+                       qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), varray_texcoord[0]);CHECKGLERROR
+                       if (gl_state.texture[0])
                        {
                        {
-                               if (blendfunc1 == GL_ONE)
-                               {
-                                       if (blend)
-                                       {
-                                               blend = 0;
-                                               glDisable(GL_BLEND);
-CHECKGLERROR
-                                       }
-                               }
-                               else
-                               {
-                                       if (!blend)
-                                       {
-                                               blend = 1;
-                                               glEnable(GL_BLEND);
-CHECKGLERROR
-                                       }
-                               }
+                               qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                        }
                        else
                        {
                        }
                        else
                        {
-                               if (!blend)
-                               {
-                                       blend = 1;
-                                       glEnable(GL_BLEND);
-CHECKGLERROR
-                               }
+                               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                        }
                }
                        }
                }
-               if (depthtest != mesh->depthtest)
+       }
+}
+
+int usedarrays;
+void GL_Backend_ResetState(void)
+{
+       int i;
+       gl_state.unit = 0;
+       gl_state.clientunit = 0;
+
+       for (i = 0;i < backendunits;i++)
+       {
+               gl_state.texture[i] = 0;
+               gl_state.texturergbscale[i] = 1;
+       }
+
+       qglEnable(GL_CULL_FACE);CHECKGLERROR
+       qglCullFace(GL_FRONT);CHECKGLERROR
+
+       gl_state.depthdisable = false;
+       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+
+       gl_state.blendfunc1 = GL_ONE;
+       gl_state.blendfunc2 = GL_ZERO;
+       qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
+
+       gl_state.blend = 0;
+       qglDisable(GL_BLEND);CHECKGLERROR
+
+       gl_state.depthmask = GL_TRUE;
+       qglDepthMask(gl_state.depthmask);CHECKGLERROR
+
+       usedarrays = false;
+       if (gl_mesh_drawmode.integer > 0)
+       {
+               usedarrays = true;
+               qglVertexPointer(3, GL_FLOAT, sizeof(float[4]), varray_vertex);CHECKGLERROR
+               qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
+               if (gl_mesh_floatcolors.integer)
                {
                {
-                       depthtest = mesh->depthtest;
-                       if (depthtest)
-                               glEnable(GL_DEPTH_TEST);
-                       else
-                               glDisable(GL_DEPTH_TEST);
+                       qglColorPointer(4, GL_FLOAT, sizeof(float[4]), varray_color);CHECKGLERROR
                }
                }
-               if (depthmask != mesh->depthmask)
+               else
                {
                {
-                       depthmask = mesh->depthmask;
-                       glDepthMask((GLboolean) depthmask);
-CHECKGLERROR
+                       qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(qbyte[4]), varray_bcolor);CHECKGLERROR
                }
                }
+               qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+       }
+
+       GL_SetupTextureState();
+}
+
+// called at beginning of frame
+void R_Mesh_Start(float farclip)
+{
+       BACKENDACTIVECHECK
+
+       CHECKGLERROR
+
+       r_mesh_farclip = farclip;
+       viewdist = DotProduct(r_origin, vpn);
+       vpnbit0 = vpn[0] < 0;
+       vpnbit1 = vpn[1] < 0;
+       vpnbit2 = vpn[2] < 0;
+
+       c_meshs = 0;
+       c_meshtris = 0;
+
+       GL_Backend_CheckCvars();
+       if (mesh_maxtris != gl_mesh_maxtriangles.integer)
+               GL_Backend_ResizeArrays(gl_mesh_maxtriangles.integer);
+
+       GL_SetupFrame();
+
+       GL_Backend_ResetState();
+}
 
 
-               firsttriangle = mesh->firsttriangle;
-               triangles = mesh->triangles;
-               firstvert = mesh->firstvert;
-               lastvert = mesh->lastvert;
-               mesh = &buf_mesh[++k];
+int gl_backend_rebindtextures;
 
 
-               if (meshmerge)
+void GL_ConvertColorsFloatToByte(int numverts)
+{
+       int i, k, total;
+       // LordHavoc: to avoid problems with aliasing (treating memory as two
+       // different types - exactly what this is doing), these must be volatile
+       // (or a union)
+       volatile int *icolor;
+       volatile float *fcolor;
+       qbyte *bcolor;
+
+       total = numverts * 4;
+
+       // shift float to have 8bit fraction at base of number
+       fcolor = varray_color;
+       for (i = 0;i < total;)
+       {
+               fcolor[i    ] += 32768.0f;
+               fcolor[i + 1] += 32768.0f;
+               fcolor[i + 2] += 32768.0f;
+               fcolor[i + 3] += 32768.0f;
+               i += 4;
+       }
+
+       // then read as integer and kill float bits...
+       icolor = (int *)varray_color;
+       bcolor = varray_bcolor;
+       for (i = 0;i < total;)
+       {
+               k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
+               k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
+               k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
+               k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
+               i += 4;
+       }
+}
+
+void GL_TransformVertices(int numverts)
+{
+       int i;
+       float m[12], tempv[4], *v;
+       m[0] = backendmatrix.m[0][0];
+       m[1] = backendmatrix.m[0][1];
+       m[2] = backendmatrix.m[0][2];
+       m[3] = backendmatrix.m[0][3];
+       m[4] = backendmatrix.m[1][0];
+       m[5] = backendmatrix.m[1][1];
+       m[6] = backendmatrix.m[1][2];
+       m[7] = backendmatrix.m[1][3];
+       m[8] = backendmatrix.m[2][0];
+       m[9] = backendmatrix.m[2][1];
+       m[10] = backendmatrix.m[2][2];
+       m[11] = backendmatrix.m[2][3];
+       for (i = 0, v = varray_vertex;i < numverts;i++, v += 4)
+       {
+               VectorCopy(v, tempv);
+               v[0] = tempv[0] * m[0] + tempv[1] * m[1] + tempv[2] * m[2] + m[3];
+               v[1] = tempv[0] * m[4] + tempv[1] * m[5] + tempv[2] * m[6] + m[7];
+               v[2] = tempv[0] * m[8] + tempv[1] * m[9] + tempv[2] * m[10] + m[11];
+       }
+}
+
+void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, GLuint *index)
+{
+       unsigned int i, j, in;
+       qbyte *c;
+       float *v;
+       GL_LockArray(firstvert, endvert - firstvert);
+       if (gl_mesh_drawmode.integer >= 3/* && (endvert - firstvert) <= gl_maxdrawrangeelementsvertices && (indexcount) <= gl_maxdrawrangeelementsindices*/)
+       {
+               // GL 1.2 or GL 1.1 with extension
+               qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, index);
+               CHECKGLERROR
+       }
+       else if (gl_mesh_drawmode.integer >= 2)
+       {
+               // GL 1.1
+               qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);
+               CHECKGLERROR
+       }
+       else if (gl_mesh_drawmode.integer >= 1)
+       {
+               // GL 1.1
+               // feed it manually using glArrayElement
+               qglBegin(GL_TRIANGLES);
+               for (i = 0;i < indexcount;i++)
+                       qglArrayElement(index[i]);
+               qglEnd();
+               CHECKGLERROR
+       }
+       else
+       {
+               // GL 1.1 but not using vertex arrays - 3dfx glquake minigl driver
+               // feed it manually
+               qglBegin(GL_TRIANGLES);
+               if (gl_state.texture[1]) // if the mesh uses multiple textures
+               {
+                       // the minigl doesn't have this (because it does not have ARB_multitexture)
+                       for (i = 0;i < indexcount;i++)
+                       {
+                               in = index[i];
+                               c = varray_bcolor + in * 4;
+                               qglColor4ub(c[0], c[1], c[2], c[3]);
+                               for (j = 0;j < backendunits;j++)
+                               {
+                                       if (gl_state.texture[j])
+                                       {
+                                               v = varray_texcoord[j] + in * 2;
+                                               qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, v[0], v[1]);
+                                       }
+                               }
+                               v = varray_vertex + in * 4;
+                               qglVertex3f(v[0], v[1], v[2]);
+                       }
+               }
+               else
                {
                {
-                       #if MAX_TEXTUREUNITS != 4
-                       #error update this code
-                       #endif
-                       while (k < currentmesh
-                               && mesh->blendfunc1 == blendfunc1
-                               && mesh->blendfunc2 == blendfunc2
-                               && mesh->depthtest == depthtest
-                               && mesh->depthmask == depthmask
-                               && mesh->textures[0] == texture[0]
-                               && mesh->textures[1] == texture[1]
-                               && mesh->textures[2] == texture[2]
-                               && mesh->textures[3] == texture[3]
-                               && mesh->texturergbscale[0] == texturergbscale[0]
-                               && mesh->texturergbscale[1] == texturergbscale[1]
-                               && mesh->texturergbscale[2] == texturergbscale[2]
-                               && mesh->texturergbscale[3] == texturergbscale[3])
+                       for (i = 0;i < indexcount;i++)
                        {
                        {
-                               triangles += mesh->triangles;
-                               if (firstvert > mesh->firstvert)
-                                       firstvert = mesh->firstvert;
-                               if (lastvert < mesh->lastvert)
-                                       lastvert = mesh->lastvert;
-                               mesh = &buf_mesh[++k];
+                               in = index[i];
+                               c = varray_bcolor + in * 4;
+                               qglColor4ub(c[0], c[1], c[2], c[3]);
+                               if (gl_state.texture[0])
+                               {
+                                       v = varray_texcoord[j] + in * 2;
+                                       qglTexCoord2f(v[0], v[1]);
+                               }
+                               v = varray_vertex + in * 4;
+                               qglVertex3f(v[0], v[1], v[2]);
                        }
                }
                        }
                }
+               qglEnd();
+               CHECKGLERROR
+       }
+       GL_UnlockArray();
+}
 
 
-#ifdef WIN32
-               // FIXME: dynamic link to GL so we can get DrawRangeElements on WIN32
-               glDrawElements(GL_TRIANGLES, triangles * 3, GL_UNSIGNED_INT, (unsigned int *)&buf_tri[firsttriangle]);
-#else
-               glDrawRangeElements(GL_TRIANGLES, firstvert, lastvert + 1, triangles * 3, GL_UNSIGNED_INT, (unsigned int *)&buf_tri[firsttriangle]);
-#endif
-CHECKGLERROR
+// enlarges geometry buffers if they are too small
+void _R_Mesh_ResizeCheck(int numverts, int numtriangles)
+{
+       if (numtriangles > mesh_maxtris || numverts > mesh_maxverts)
+       {
+               BACKENDACTIVECHECK
+               GL_Backend_ResizeArrays(max(numtriangles, (numverts + 2) / 3) + 100);
+               GL_Backend_ResetState();
        }
        }
+}
 
 
-       currentmesh = 0;
-       currenttriangle = 0;
-       currentvertex = 0;
+// renders the mesh
+void R_Mesh_Draw(int numverts, int numtriangles)
+{
+       BACKENDACTIVECHECK
 
 
-       GL_UnlockArray();
-CHECKGLERROR
+       c_meshs++;
+       c_meshtris += numtriangles;
+
+       CHECKGLERROR
+
+       // drawmode 0 always uses byte colors
+       if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer <= 0)
+               GL_ConvertColorsFloatToByte(numverts);
+       GL_TransformVertices(numverts);
+       if (!r_render.integer)
+               return;
+       GL_DrawRangeElements(0, numverts, numtriangles * 3, varray_element);
+}
+
+// restores backend state, used when done with 3D rendering
+void R_Mesh_Finish(void)
+{
+       int i;
+       BACKENDACTIVECHECK
 
        if (backendunits > 1)
        {
                for (i = backendunits - 1;i >= 0;i--)
                {
 
        if (backendunits > 1)
        {
                for (i = backendunits - 1;i >= 0;i--)
                {
-                       qglActiveTexture(GL_TEXTURE0_ARB + (unit = i));
-CHECKGLERROR
-                       glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-CHECKGLERROR
+                       qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
                        if (gl_combine.integer)
                        {
                        if (gl_combine.integer)
                        {
-                               glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0f);
-CHECKGLERROR
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
                        }
                        if (i > 0)
                        {
                        }
                        if (i > 0)
                        {
-                               glDisable(GL_TEXTURE_2D);
-CHECKGLERROR
+                               qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                        }
                        else
                        {
                        }
                        else
                        {
-                               glEnable(GL_TEXTURE_2D);
-CHECKGLERROR
+                               qglEnable(GL_TEXTURE_2D);CHECKGLERROR
                        }
                        }
-                       glBindTexture(GL_TEXTURE_2D, 0);
-CHECKGLERROR
+                       qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
 
 
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + (clientunit = i));
-CHECKGLERROR
-                       glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
+                       if (usedarrays)
+                       {
+                               qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+                               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                       }
                }
        }
        else
        {
                }
        }
        else
        {
-               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
-CHECKGLERROR
-               glEnable(GL_TEXTURE_2D);
-CHECKGLERROR
-               glDisableClientState(GL_TEXTURE_COORD_ARRAY);
-CHECKGLERROR
+               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
+               qglEnable(GL_TEXTURE_2D);CHECKGLERROR
+               if (usedarrays)
+               {
+                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               }
        }
        }
-       glDisableClientState(GL_COLOR_ARRAY);
-CHECKGLERROR
-       glDisableClientState(GL_VERTEX_ARRAY);
-CHECKGLERROR
-
-       glDisable(GL_BLEND);
-CHECKGLERROR
-       glEnable(GL_DEPTH_TEST);
-CHECKGLERROR
-       glDepthMask(true);
-CHECKGLERROR
-       glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
-CHECKGLERROR
-}
-
-void R_Mesh_AddTransparent(void)
-{
-       int i, j, k;
-       float viewdistcompare, centerscaler, dist1, dist2, dist3, center, maxdist;
-       buf_vertex_t *vert1, *vert2, *vert3;
-       buf_transtri_t *tri;
-       buf_mesh_t *mesh;
-
-       // process and add transparent mesh triangles
-       if (!currenttranstriangle)
-               return;
-
-       // map farclip to 0-4095 list range
-       centerscaler = (TRANSDEPTHRES / r_farclip) * (1.0f / 3.0f);
-       viewdistcompare = viewdist + 4.0f;
-
-       memset(buf_transtri_list, 0, TRANSDEPTHRES * sizeof(buf_transtri_t *));
-
-       // process in reverse because transtri_list adding code is in reverse as well
-       k = 0;
-       for (j = currenttranstriangle - 1;j >= 0;j--)
+       if (usedarrays)
        {
        {
-               tri = &buf_transtri[j];
-
-               vert1 = &buf_transvertex[tri->index[0]];
-               vert2 = &buf_transvertex[tri->index[1]];
-               vert3 = &buf_transvertex[tri->index[2]];
-
-               dist1 = DotProduct(vert1->v, vpn);
-               dist2 = DotProduct(vert2->v, vpn);
-               dist3 = DotProduct(vert3->v, vpn);
-
-               maxdist = max(dist1, max(dist2, dist3));
-               if (maxdist < viewdistcompare)
-                       continue;
-
-               center = (dist1 + dist2 + dist3) * centerscaler - viewdist;
-#if SLOWMATH
-               i = (int) center;
-               i = bound(0, i, (TRANSDEPTHRES - 1));
-#else
-               if (center < 0.0f)
-                       center = 0.0f;
-               center += 8388608.0f;
-               i = *((long *)&center) & 0x7FFFFF;
-               i = min(i, (TRANSDEPTHRES - 1));
-#endif
-               tri->next = buf_transtri_list[i];
-               buf_transtri_list[i] = tri;
-               k++;
+               qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+               qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
        }
 
        }
 
-       if (currentmesh + k > max_meshs || currenttriangle + k > max_batch || currentvertex + currenttransvertex > max_verts)
-               R_Mesh_Render();
+       qglDisable(GL_BLEND);CHECKGLERROR
+       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+       qglDepthMask(GL_TRUE);CHECKGLERROR
+       qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
+}
 
 
-       // note: can't batch these because they can be rendered in any order
-       // there can never be more transparent triangles than fit in main buffers
-       memcpy(&buf_vertex[currentvertex], &buf_transvertex[0], currenttransvertex * sizeof(buf_vertex_t));
-       if (floatcolors)
-               memcpy(&buf_fcolor[currentvertex], &buf_transfcolor[0], currenttransvertex * sizeof(buf_fcolor_t));
-       else
-               memcpy(&buf_fcolor[currentvertex], &buf_transbcolor[0], currenttransvertex * sizeof(buf_bcolor_t));
-       for (i = 0;i < backendunits;i++)
-               memcpy(&buf_texcoord[i][currentvertex], &buf_transtexcoord[i][0], currenttransvertex * sizeof(buf_texcoord_t));
+void R_Mesh_ClearDepth(void)
+{
+       BACKENDACTIVECHECK
 
 
-       for (j = TRANSDEPTHRES - 1;j >= 0;j--)
-       {
-               if ((tri = buf_transtri_list[j]))
-               {
-                       while(tri)
-                       {
-                               mesh = &buf_mesh[currentmesh++];
-                               *mesh = *tri->mesh; // copy mesh properties
-                               buf_tri[currenttriangle].index[0] = tri->index[0] + currentvertex;
-                               buf_tri[currenttriangle].index[1] = tri->index[1] + currentvertex;
-                               buf_tri[currenttriangle].index[2] = tri->index[2] + currentvertex;
-                               mesh->firstvert = min(buf_tri[currenttriangle].index[0], min(buf_tri[currenttriangle].index[1], buf_tri[currenttriangle].index[2]));
-                               mesh->lastvert = max(buf_tri[currenttriangle].index[0], max(buf_tri[currenttriangle].index[1], buf_tri[currenttriangle].index[2]));
-                               mesh->firsttriangle = currenttriangle++;
-                               mesh->triangles = 1;
-                               tri = tri->next;
-                       }
-               }
-       }
-       currentvertex += currenttransvertex;
-       currenttransmesh = 0;
-       currenttranstriangle = 0;
-       currenttransvertex = 0;
+       R_Mesh_Finish();
+       qglClear(GL_DEPTH_BUFFER_BIT);
+       R_Mesh_Start(r_mesh_farclip);
 }
 
 }
 
-void R_Mesh_Draw(const rmeshinfo_t *m)
+// sets up the requested state
+void R_Mesh_State(const rmeshstate_t *m)
 {
 {
-       // these are static because gcc runs out of virtual registers otherwise
-       static int i, j, *index, overbright;
-       static float c, *in, scaler, cr, cg, cb, ca;
-       static buf_mesh_t *mesh;
-       static buf_vertex_t *vert;
-       static buf_fcolor_t *fcolor;
-       static buf_bcolor_t *bcolor;
-       static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
-       static buf_transtri_t *tri;
-       static byte br, bg, bb, ba;
-
-       if (m->index == NULL
-        || !m->numtriangles
-        || m->vertex == NULL
-        || !m->numverts)
-               return;
-       // ignore meaningless alpha meshs
-       if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
+       int i, overbright;
+       int texturergbscale[MAX_TEXTUREUNITS];
+       float scaler;
+
+       BACKENDACTIVECHECK
+
+       if (gl_backend_rebindtextures)
        {
        {
-               if (m->color)
-               {
-                       for (i = 0, in = m->color + 3;i < m->numverts;i++, (int)in += m->colorstep)
-                               if (*in >= 0.01f)
-                                       break;
-                       if (i == m->numverts)
-                               return;
-               }
-               else if (m->ca < 0.01f)
-                       return;
+               gl_backend_rebindtextures = false;
+               GL_SetupTextureState();
        }
 
        }
 
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
+       backendmatrix = m->matrix; // this copies the struct
 
 
+       overbright = false;
        scaler = 1;
        scaler = 1;
-       if (m->blendfunc2 == GL_SRC_COLOR)
+       if (m->blendfunc1 == GL_DST_COLOR)
        {
        {
-               if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
+               // check if it is a 2x modulate with framebuffer
+               if (m->blendfunc2 == GL_SRC_COLOR)
                        scaler *= 0.5f;
        }
                        scaler *= 0.5f;
        }
-       else
+       else if (m->blendfunc2 != GL_SRC_COLOR)
        {
                if (m->tex[0])
                {
        {
                if (m->tex[0])
                {
-                       overbright = gl_combine.integer;
+                       overbright = m->wantoverbright && gl_combine.integer;
                        if (overbright)
                                scaler *= 0.25f;
                }
                        if (overbright)
                                scaler *= 0.25f;
                }
-               if (lighthalf)
-                       scaler *= 0.5f;
+               scaler *= overbrightscale;
        }
        }
+       mesh_colorscale = scaler;
 
 
-       if (m->transparent)
+       if (gl_state.blendfunc1 != m->blendfunc1 || gl_state.blendfunc2 != m->blendfunc2)
        {
        {
-               if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
+               qglBlendFunc(gl_state.blendfunc1 = m->blendfunc1, gl_state.blendfunc2 = m->blendfunc2);CHECKGLERROR
+               if (gl_state.blendfunc2 == GL_ZERO)
                {
                {
-                       if (!transranout)
+                       if (gl_state.blendfunc1 == GL_ONE)
+                       {
+                               if (gl_state.blend)
+                               {
+                                       gl_state.blend = 0;
+                                       qglDisable(GL_BLEND);CHECKGLERROR
+                               }
+                       }
+                       else
                        {
                        {
-                               Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
-                               transranout = true;
+                               if (!gl_state.blend)
+                               {
+                                       gl_state.blend = 1;
+                                       qglEnable(GL_BLEND);CHECKGLERROR
+                               }
                        }
                        }
-                       return;
-               }
-
-               vert = &buf_transvertex[currenttransvertex];
-               fcolor = &buf_transfcolor[currenttransvertex];
-               bcolor = &buf_transbcolor[currenttransvertex];
-               for (i = 0;i < backendunits;i++)
-                       texcoord[i] = &buf_transtexcoord[i][currenttransvertex];
-
-               // transmesh is only for storage of transparent meshs until they
-               // are inserted into the main mesh array
-               mesh = &buf_transmesh[currenttransmesh++];
-               mesh->blendfunc1 = m->blendfunc1;
-               mesh->blendfunc2 = m->blendfunc2;
-               mesh->depthmask = false;
-               mesh->depthtest = !m->depthdisable;
-               j = -1;
-               for (i = 0;i < backendunits;i++)
-               {
-                       if ((mesh->textures[i] = m->tex[i]))
-                               j = i;
-                       mesh->texturergbscale[i] = m->texrgbscale[i];
-                       if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
-                               mesh->texturergbscale[i] = 1;
                }
                }
-               if (overbright && j >= 0)
-                       mesh->texturergbscale[j] = 4;
-
-               // transparent meshs are broken up into individual triangles which can
-               // be sorted by depth
-               index = m->index;
-               for (i = 0;i < m->numtriangles;i++)
+               else
                {
                {
-                       tri = &buf_transtri[currenttranstriangle++];
-                       tri->mesh = mesh;
-                       tri->index[0] = *index++ + currenttransvertex;
-                       tri->index[1] = *index++ + currenttransvertex;
-                       tri->index[2] = *index++ + currenttransvertex;
+                       if (!gl_state.blend)
+                       {
+                               gl_state.blend = 1;
+                               qglEnable(GL_BLEND);CHECKGLERROR
+                       }
                }
                }
-
-               currenttransvertex += m->numverts;
        }
        }
-       else
+       if (gl_state.depthdisable != m->depthdisable)
        {
        {
-               if (m->numtriangles > max_meshs || m->numverts > max_verts)
-               {
-                       Con_Printf("R_Mesh_Draw: mesh too big for buffers\n");
-                       return;
-               }
-
-               if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
-                       R_Mesh_Render();
-
-               vert = &buf_vertex[currentvertex];
-               fcolor = &buf_fcolor[currentvertex];
-               bcolor = &buf_bcolor[currentvertex];
-               for (i = 0;i < backendunits;i++)
-                       texcoord[i] = &buf_texcoord[i][currentvertex];
-
-               mesh = &buf_mesh[currentmesh++];
-               mesh->blendfunc1 = m->blendfunc1;
-               mesh->blendfunc2 = m->blendfunc2;
-               mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
-               mesh->depthtest = !m->depthdisable;
-               mesh->firsttriangle = currenttriangle;
-               mesh->triangles = m->numtriangles;
-               j = -1;
-               for (i = 0;i < backendunits;i++)
-               {
-                       if ((mesh->textures[i] = m->tex[i]))
-                               j = i;
-                       mesh->texturergbscale[i] = m->texrgbscale[i];
-                       if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
-                               mesh->texturergbscale[i] = 1;
-               }
-               if (overbright && j >= 0)
-                       mesh->texturergbscale[j] = 4;
-
-               // opaque meshs are rendered directly
-               index = (int *)&buf_tri[currenttriangle];
-               for (i = 0;i < m->numtriangles * 3;i++)
-                       index[i] = m->index[i] + currentvertex;
-               mesh->firstvert = currentvertex;
-               currenttriangle += m->numtriangles;
-               currentvertex += m->numverts;
-               mesh->lastvert = currentvertex - 1;
+               gl_state.depthdisable = m->depthdisable;
+               if (gl_state.depthdisable)
+                       qglDisable(GL_DEPTH_TEST);
+               else
+                       qglEnable(GL_DEPTH_TEST);
        }
        }
-
-       // vertex array code is shared for transparent and opaque meshs
-
-       c_meshtris += m->numtriangles;
-
-       if (m->vertexstep != sizeof(buf_vertex_t))
+       if (gl_state.depthmask != (m->blendfunc2 == GL_ZERO || m->depthwrite))
        {
        {
-               for (i = 0, in = m->vertex;i < m->numverts;i++, (int)in += m->vertexstep)
-               {
-                       vert[i].v[0] = in[0];
-                       vert[i].v[1] = in[1];
-                       vert[i].v[2] = in[2];
-                       // push out farclip based on vertices encountered
-                       c = DotProduct(vert[i].v, vpn);
-                       if (meshfarclip < c)
-                               meshfarclip = c;
-               }
+               qglDepthMask(gl_state.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite));CHECKGLERROR
        }
        }
-       else
+
+       for (i = 0;i < backendunits;i++)
        {
        {
-               memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
-               // push out farclip based on vertices encountered
-               for (i = 0;i < m->numverts;i++)
-               {
-                       c = DotProduct(vert[i].v, vpn);
-                       if (meshfarclip < c)
-                               meshfarclip = c;
-               }
+               if (m->texrgbscale[i])
+                       texturergbscale[i] = m->texrgbscale[i];
+               else
+                       texturergbscale[i] = 1;
        }
        }
+       if (overbright)
+               for (i = backendunits - 1;i >= 0;i--)
+                       if (m->tex[i])
+                               texturergbscale[i] = 4;
 
 
-       if (floatcolors)
+       if (backendunits > 1)
        {
        {
-               if (m->color)
+               for (i = 0;i < backendunits;i++)
                {
                {
-                       for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
+                       if (gl_state.texture[i] != m->tex[i])
                        {
                        {
-                               fcolor[i].c[0] = in[0] * scaler;
-                               fcolor[i].c[1] = in[1] * scaler;
-                               fcolor[i].c[2] = in[2] * scaler;
-                               fcolor[i].c[3] = in[3];
+                               if (gl_state.unit != i)
+                               {
+                                       qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
+                               }
+                               if (gl_state.texture[i] == 0)
+                               {
+                                       qglEnable(GL_TEXTURE_2D);CHECKGLERROR
+                                       if (gl_state.clientunit != i)
+                                       {
+                                               qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
+                                       }
+                                       qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               }
+                               qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[i] = m->tex[i]));CHECKGLERROR
+                               if (gl_state.texture[i] == 0)
+                               {
+                                       qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+                                       if (gl_state.clientunit != i)
+                                       {
+                                               qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
+                                       }
+                                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               }
                        }
                        }
-               }
-               else
-               {
-                       cr = m->cr * scaler;
-                       cg = m->cg * scaler;
-                       cb = m->cb * scaler;
-                       ca = m->ca;
-                       for (i = 0;i < m->numverts;i++)
+                       if (gl_state.texturergbscale[i] != texturergbscale[i])
                        {
                        {
-                               fcolor[i].c[0] = cr;
-                               fcolor[i].c[1] = cg;
-                               fcolor[i].c[2] = cb;
-                               fcolor[i].c[3] = ca;
+                               if (gl_state.unit != i)
+                               {
+                                       qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
+                               }
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.texturergbscale[i] = texturergbscale[i]));CHECKGLERROR
                        }
                }
        }
        else
        {
                        }
                }
        }
        else
        {
-               if (m->color)
+               if (gl_state.texture[0] != m->tex[0])
                {
                {
-                       for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
+                       if (gl_state.texture[0] == 0)
                        {
                        {
-                               // shift float to have 8bit fraction at base of number,
-                               // then read as integer and kill float bits...
-                               c = in[0] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bcolor[i].c[0] = (byte) j;
-                               c = in[1] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bcolor[i].c[1] = (byte) j;
-                               c = in[2] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bcolor[i].c[2] = (byte) j;
-                               c = in[3]          + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bcolor[i].c[3] = (byte) j;
+                               qglEnable(GL_TEXTURE_2D);CHECKGLERROR
+                               qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                        }
                        }
-               }
-               else
-               {
-                       c = in[0] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;br = (byte) j;
-                       c = in[1] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bg = (byte) j;
-                       c = in[2] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bb = (byte) j;
-                       c = in[3]          + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;ba = (byte) j;
-                       for (i = 0;i < m->numverts;i++)
+                       qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[0] = m->tex[0]));CHECKGLERROR
+                       if (gl_state.texture[0] == 0)
                        {
                        {
-                               bcolor[i].c[0] = br;
-                               bcolor[i].c[1] = bg;
-                               bcolor[i].c[2] = bb;
-                               bcolor[i].c[3] = ba;
+                               qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+                               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
                        }
                }
        }
                        }
                }
        }
+}
+
+/*
+==============================================================================
+
+                                               SCREEN SHOTS
+
+==============================================================================
+*/
+
+qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
+{
+       qboolean ret;
+       int i;
+       qbyte *buffer;
+
+       if (!r_render.integer)
+               return false;
+
+       buffer = Mem_Alloc(tempmempool, width*height*3);
+       qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
+       CHECKGLERROR
+
+       // LordHavoc: compensate for v_overbrightbits when using hardware gamma
+       if (v_hwgamma.integer)
+               for (i = 0;i < width * height * 3;i++)
+                       buffer[i] <<= v_overbrightbits.integer;
+
+       ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
 
 
-       for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
+       Mem_Free(buffer);
+       return ret;
+}
+
+//=============================================================================
+
+void R_ClearScreen(void)
+{
+       if (r_render.integer)
        {
        {
-               if (j >= backendunits)
-                       Sys_Error("R_Mesh_Draw: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
-               if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
+               // clear to black
+               qglClearColor(0,0,0,0);CHECKGLERROR
+               // clear the screen
+               qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
+               // set dithering mode
+               if (gl_dither.integer)
                {
                {
-                       for (i = 0, in = m->texcoords[j];i < m->numverts;i++, (int)in += m->texcoordstep[j])
-                       {
-                               texcoord[j][i].t[0] = in[0];
-                               texcoord[j][i].t[1] = in[1];
-                       }
+                       qglEnable(GL_DITHER);CHECKGLERROR
                }
                else
                }
                else
-                       memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
+               {
+                       qglDisable(GL_DITHER);CHECKGLERROR
+               }
        }
        }
-       #if 0
-       for (;j < backendunits;j++)
-               memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
-       #endif
 }
 
 }
 
-void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
-{
-       m->index = polyindexarray;
-       m->numverts = numverts;
-       m->numtriangles = numverts - 2;
-       if (m->numtriangles < 1)
-       {
-               Con_Printf("R_Mesh_DrawPolygon: invalid vertex count\n");
-               return;
-       }
-       if (m->numtriangles >= 256)
-       {
-               Con_Printf("R_Mesh_DrawPolygon: only up to 256 triangles (258 verts) supported\n");
-               return;
-       }
-       R_Mesh_Draw(m);
-}
+/*
+==================
+SCR_UpdateScreen
 
 
-// LordHavoc: this thing is evil, but necessary because decals account for so much overhead
-void R_Mesh_DrawDecal(const rmeshinfo_t *m)
+This is called every frame, and can also be called explicitly to flush
+text to the screen.
+==================
+*/
+void SCR_UpdateScreen (void)
 {
 {
-       // these are static because gcc runs out of virtual registers otherwise
-       static int i, j, *index, overbright;
-       static float c, *in, scaler, cr, cg, cb, ca;
-       static buf_mesh_t *mesh;
-       static buf_vertex_t *vert;
-       static buf_fcolor_t *fcolor;
-       static buf_bcolor_t *bcolor;
-       static buf_texcoord_t *texcoord;
-       static buf_transtri_t *tri;
-       static byte br, bg, bb, ba;
-
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
+       VID_Finish ();
 
 
-       scaler = 1;
-       if (m->tex[0])
-       {
-               overbright = gl_combine.integer;
-               if (overbright)
-                       scaler *= 0.25f;
-       }
-       if (lighthalf)
-               scaler *= 0.5f;
+       R_TimeReport("finish");
 
 
-       if (m->transparent)
-       {
-               if (currenttransmesh >= max_meshs || (currenttranstriangle + 2) > max_meshs || (currenttransvertex + 4) > max_verts)
-               {
-                       if (!transranout)
-                       {
-                               Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
-                               transranout = true;
-                       }
-                       return;
-               }
+       if (r_textureunits.integer > gl_textureunits)
+               Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
+       if (r_textureunits.integer < 1)
+               Cvar_SetValueQuick(&r_textureunits, 1);
 
 
-               vert = &buf_transvertex[currenttransvertex];
-               fcolor = &buf_transfcolor[currenttransvertex];
-               bcolor = &buf_transbcolor[currenttransvertex];
-               texcoord = &buf_transtexcoord[0][currenttransvertex];
-
-               // transmesh is only for storage of transparent meshs until they
-               // are inserted into the main mesh array
-               mesh = &buf_transmesh[currenttransmesh++];
-               mesh->blendfunc1 = m->blendfunc1;
-               mesh->blendfunc2 = m->blendfunc2;
-               mesh->depthmask = false;
-               mesh->depthtest = true;
-               mesh->textures[0] = m->tex[0];
-               mesh->texturergbscale[0] = overbright ? 4 : 1;
-               for (i = 1;i < backendunits;i++)
-               {
-                       mesh->textures[i] = 0;
-                       mesh->texturergbscale[i] = 1;
-               }
+       if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
+               Cvar_SetValueQuick(&gl_combine, 0);
 
 
-               // transparent meshs are broken up into individual triangles which can
-               // be sorted by depth
-               index = m->index;
-               tri = &buf_transtri[currenttranstriangle++];
-               tri->mesh = mesh;
-               tri->index[0] = 0 + currenttransvertex;
-               tri->index[1] = 1 + currenttransvertex;
-               tri->index[2] = 2 + currenttransvertex;
-               tri = &buf_transtri[currenttranstriangle++];
-               tri->mesh = mesh;
-               tri->index[0] = 0 + currenttransvertex;
-               tri->index[1] = 2 + currenttransvertex;
-               tri->index[2] = 3 + currenttransvertex;
-
-               currenttransvertex += 4;
-       }
-       else
-       {
-               if (2 > max_meshs || 4 > max_verts)
-               {
-                       Con_Printf("R_Mesh_Draw: mesh too big for buffers\n");
-                       return;
-               }
+       // lighting scale
+       overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
 
 
-               if (currentmesh >= max_meshs || (currenttriangle + 2) > max_batch || (currentvertex + 4) > max_verts)
-                       R_Mesh_Render();
-
-               vert = &buf_vertex[currentvertex];
-               fcolor = &buf_fcolor[currentvertex];
-               bcolor = &buf_bcolor[currentvertex];
-               texcoord = &buf_texcoord[0][currentvertex];
-
-               mesh = &buf_mesh[currentmesh++];
-               mesh->blendfunc1 = m->blendfunc1;
-               mesh->blendfunc2 = m->blendfunc2;
-               mesh->depthmask = false;
-               mesh->depthtest = !m->depthdisable;
-               mesh->firsttriangle = currenttriangle;
-               mesh->triangles = 2;
-               mesh->textures[0] = m->tex[0];
-               mesh->texturergbscale[0] = overbright ? 4 : 1;
-               for (i = 1;i < backendunits;i++)
-               {
-                       mesh->textures[i] = 0;
-                       mesh->texturergbscale[i] = 1;
-               }
+       // lightmaps only
+       lightscalebit = v_overbrightbits.integer;
+       if (gl_combine.integer && r_textureunits.integer > 1)
+               lightscalebit += 2;
+       lightscale = 1.0f / (float) (1 << lightscalebit);
 
 
-               // opaque meshs are rendered directly
-               index = (int *)&buf_tri[currenttriangle];
-               index[0] = 0 + currentvertex;
-               index[1] = 1 + currentvertex;
-               index[2] = 2 + currentvertex;
-               index[3] = 0 + currentvertex;
-               index[4] = 2 + currentvertex;
-               index[5] = 3 + currentvertex;
-               mesh->firstvert = currentvertex;
-               currenttriangle += 2;
-               currentvertex += 4;
-               mesh->lastvert = currentvertex - 1;
-       }
+       R_TimeReport("setup");
 
 
-       // vertex array code is shared for transparent and opaque meshs
+       R_ClearScreen();
 
 
-       c_meshtris += 2;
+       R_TimeReport("clear");
 
 
-       // buf_vertex_t must match the size of the decal vertex array (or vice versa)
-       memcpy(vert, m->vertex, 4 * sizeof(buf_vertex_t));
-       // push out farclip based on vertices encountered
-       c = DotProduct(vert[0].v, vpn);if (meshfarclip < c) meshfarclip = c;
-       c = DotProduct(vert[1].v, vpn);if (meshfarclip < c) meshfarclip = c;
-       c = DotProduct(vert[2].v, vpn);if (meshfarclip < c) meshfarclip = c;
-       c = DotProduct(vert[3].v, vpn);if (meshfarclip < c) meshfarclip = c;
+       if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
+               R_RenderView();
 
 
-       if (floatcolors)
-       {
-               cr = m->cr * scaler;
-               cg = m->cg * scaler;
-               cb = m->cb * scaler;
-               ca = m->ca;
-               fcolor[0].c[0] = cr;
-               fcolor[0].c[1] = cg;
-               fcolor[0].c[2] = cb;
-               fcolor[0].c[3] = ca;
-               fcolor[1].c[0] = cr;
-               fcolor[1].c[1] = cg;
-               fcolor[1].c[2] = cb;
-               fcolor[1].c[3] = ca;
-               fcolor[2].c[0] = cr;
-               fcolor[2].c[1] = cg;
-               fcolor[2].c[2] = cb;
-               fcolor[2].c[3] = ca;
-               fcolor[3].c[0] = cr;
-               fcolor[3].c[1] = cg;
-               fcolor[3].c[2] = cb;
-               fcolor[3].c[3] = ca;
-       }
-       else
-       {
-               c = in[0] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;br = (byte) j;
-               c = in[1] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bg = (byte) j;
-               c = in[2] * scaler + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;bb = (byte) j;
-               c = in[3]          + 32768.0f;j = (*((long *)&c) & 0x7FFFFF);if (j > 255) j = 255;ba = (byte) j;
-               bcolor[0].c[0] = br;
-               bcolor[0].c[1] = bg;
-               bcolor[0].c[2] = bb;
-               bcolor[0].c[3] = ba;
-               bcolor[1].c[0] = br;
-               bcolor[1].c[1] = bg;
-               bcolor[1].c[2] = bb;
-               bcolor[1].c[3] = ba;
-               bcolor[2].c[0] = br;
-               bcolor[2].c[1] = bg;
-               bcolor[2].c[2] = bb;
-               bcolor[2].c[3] = ba;
-               bcolor[3].c[0] = br;
-               bcolor[3].c[1] = bg;
-               bcolor[3].c[2] = bb;
-               bcolor[3].c[3] = ba;
-       }
+       // draw 2D stuff
+       R_DrawQueue();
 
 
-       // buf_texcoord_t must be the same size as the decal texcoord array (or vice versa)
-       memcpy(&texcoord[0].t[0], m->texcoords[0], 4 * sizeof(buf_texcoord_t));
+       // tell driver to commit it's partially full geometry queue to the rendering queue
+       // (this doesn't wait for the commands themselves to complete)
+       qglFlush();
 }
 }
+