]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_backend.c
made r_showtris transparent (quite faint actually), color coded different types of...
[xonotic/darkplaces.git] / gl_backend.c
index 4a15b6d852e332f9ed20317301a0674570b683f3..f4ccc39f4f7d6d8d0d1c8e847eead00014912613 100644 (file)
@@ -1,16 +1,23 @@
 
 #include "quakedef.h"
+#include "image.h"
+#include "jpeg.h"
+#include "cl_collision.h"
 
-//cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "21760"};
-cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "8192"};
-//cvar_t gl_mesh_batchtriangles = {0, "gl_mesh_batchtriangles", "1024"};
-cvar_t gl_mesh_batchtriangles = {0, "gl_mesh_batchtriangles", "0"};
-cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "0"};
+cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
+cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0"};
+cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0"};
+cvar_t gl_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
+cvar_t gl_paranoid = {0, "gl_paranoid", "0"};
+cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
 
 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"};
 
+int gl_maxdrawrangeelementsvertices;
+int gl_maxdrawrangeelementsindices;
+
 #ifdef DEBUGGL
 int errornumber = 0;
 
@@ -49,7 +56,7 @@ void GL_PrintError(int errornumber, char *filename, int linenumber)
                break;
 #endif
 #ifdef GL_TABLE_TOO_LARGE
-    case GL_TABLE_TOO_LARGE:
+       case GL_TABLE_TOO_LARGE:
                Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
                break;
 #endif
@@ -60,1362 +67,1004 @@ void GL_PrintError(int errornumber, char *filename, int linenumber)
 }
 #endif
 
-float r_farclip, r_newfarclip;
+#define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
 
-int polyindexarray[768];
+int c_meshs, c_meshelements;
 
-static float viewdist;
+void SCR_ScreenShot_f (void);
 
-int c_meshs, c_meshtris, c_transmeshs, c_transtris;
+static matrix4x4_t backend_viewmatrix;
+static matrix4x4_t backend_modelmatrix;
+static matrix4x4_t backend_modelviewmatrix;
+static matrix4x4_t backend_glmodelviewmatrix;
+static matrix4x4_t backend_projectmatrix;
 
-int                    lightscalebit;
-float          lightscale;
-float          overbrightscale;
+static int backendunits, backendactive;
+static mempool_t *gl_backend_mempool;
 
-void SCR_ScreenShot_f (void);
+/*
+note: here's strip order for a terrain row:
+0--1--2--3--4
+|\ |\ |\ |\ |
+| \| \| \| \|
+A--B--C--D--E
+clockwise
 
-static int max_meshs;
-static int max_batch;
-static int max_verts; // always max_meshs * 3
-#define TRANSDEPTHRES 4096
+A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
 
-typedef struct buf_mesh_s
-{
-       int depthmask;
-       int depthtest;
-       int blendfunc1, blendfunc2;
-       int textures[MAX_TEXTUREUNITS];
-       float texturergbscale[MAX_TEXTUREUNITS];
-       int firsttriangle;
-       int triangles;
-       int firstvert;
-       int verts;
-       struct buf_mesh_s *chain;
-       struct buf_transtri_s *transchain;
-}
-buf_mesh_t;
+*elements++ = i + row;
+*elements++ = i;
+*elements++ = i + row + 1;
+*elements++ = i;
+*elements++ = i + 1;
+*elements++ = i + row + 1;
 
-typedef struct buf_transtri_s
-{
-       struct buf_transtri_s *next;
-       struct buf_transtri_s *meshsortchain;
-       buf_mesh_t *mesh;
-       int index[3];
-}
-buf_transtri_t;
 
-typedef struct buf_tri_s
+for (y = 0;y < rows - 1;y++)
 {
-       int index[3];
+       for (x = 0;x < columns - 1;x++)
+       {
+               i = y * rows + x;
+               *elements++ = i + columns;
+               *elements++ = i;
+               *elements++ = i + columns + 1;
+               *elements++ = i;
+               *elements++ = i + 1;
+               *elements++ = i + columns + 1;
+       }
 }
-buf_tri_t;
 
-typedef struct
-{
-       float v[4];
-}
-buf_vertex_t;
+alternative:
+0--1--2--3--4
+| /| /|\ | /|
+|/ |/ | \|/ |
+A--B--C--D--E
+counterclockwise
 
-typedef struct
+for (y = 0;y < rows - 1;y++)
 {
-       float c[4];
+       for (x = 0;x < columns - 1;x++)
+       {
+               i = y * rows + x;
+               *elements++ = i;
+               *elements++ = i + columns;
+               *elements++ = i + columns + 1;
+               *elements++ = i + columns;
+               *elements++ = i + columns + 1;
+               *elements++ = i + 1;
+       }
 }
-buf_fcolor_t;
+*/
+
+int polygonelements[768];
 
-typedef struct
+static void R_Mesh_CacheArray_Startup(void);
+static void R_Mesh_CacheArray_Shutdown(void);
+void GL_Backend_AllocArrays(void)
 {
-       qbyte c[4];
+       if (!gl_backend_mempool)
+               gl_backend_mempool = Mem_AllocPool("GL_Backend");
+       R_Mesh_CacheArray_Startup();
 }
-buf_bcolor_t;
 
-typedef struct
+void GL_Backend_FreeArrays(void)
 {
-       float t[2];
+       R_Mesh_CacheArray_Shutdown();
+       Mem_FreePool(&gl_backend_mempool);
 }
-buf_texcoord_t;
-
-static float meshfarclip;
-static int currentmesh, currenttriangle, currentvertex, backendunits, backendactive, 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_sorttranstri;
-static buf_transtri_t **buf_sorttranstri_list;
-static buf_tri_t *buf_transtri;
-static buf_vertex_t *buf_transvertex;
-static buf_fcolor_t *buf_transfcolor;
-static buf_texcoord_t *buf_transtexcoord[MAX_TEXTUREUNITS];
-
-static mempool_t *gl_backend_mempool;
-static int resizingbuffers = false;
 
 static void gl_backend_start(void)
 {
-       int i;
-
-       max_verts = max_meshs * 3;
-
-       if (!gl_backend_mempool)
-               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));\
+       Con_DPrintf("OpenGL Backend started\n");
+       if (qglDrawRangeElements != NULL)
+       {
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
+               CHECKGLERROR
+               Con_DPrintf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
        }
 
-       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)
+       backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
 
-       BACKENDALLOC(buf_transmesh, max_meshs, buf_mesh_t)
-       BACKENDALLOC(buf_sorttranstri, max_meshs, buf_transtri_t)
-       BACKENDALLOC(buf_sorttranstri_list, TRANSDEPTHRES, buf_transtri_t *)
-       BACKENDALLOC(buf_transtri, max_meshs, buf_tri_t)
-       BACKENDALLOC(buf_transvertex, max_verts, buf_vertex_t)
-       BACKENDALLOC(buf_transfcolor, max_verts, buf_fcolor_t)
+       GL_Backend_AllocArrays();
 
-       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;
 }
 
 static void gl_backend_shutdown(void)
 {
-       if (resizingbuffers)
-               Mem_EmptyPool(gl_backend_mempool);
-       else
-               Mem_FreePool(&gl_backend_mempool);
-
        backendunits = 0;
        backendactive = false;
-}
-
-static void gl_backend_bufferchanges(int init)
-{
-       // 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);
-
-       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);
-
-       max_batch = gl_mesh_batchtriangles.integer;
 
-       if (max_meshs != gl_mesh_maxtriangles.integer)
-       {
-               max_meshs = gl_mesh_maxtriangles.integer;
+       Con_DPrintf("OpenGL Backend shutting down\n");
 
-               if (!init)
-               {
-                       resizingbuffers = true;
-                       gl_backend_shutdown();
-                       gl_backend_start();
-                       resizingbuffers = false;
-               }
-       }
+       GL_Backend_FreeArrays();
 }
 
 static void gl_backend_newmap(void)
 {
-       r_farclip = r_newfarclip = 2048.0f;
 }
 
+cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0"};
+cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20"};
+cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20"};
+cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20"};
+
 void gl_backend_init(void)
 {
        int i;
 
+       for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
+       {
+               polygonelements[i * 3 + 0] = 0;
+               polygonelements[i * 3 + 1] = i + 1;
+               polygonelements[i * 3 + 2] = i + 2;
+       }
+
        Cvar_RegisterVariable(&r_render);
        Cvar_RegisterVariable(&gl_dither);
        Cvar_RegisterVariable(&gl_lockarrays);
+       Cvar_RegisterVariable(&gl_delayfinish);
+       Cvar_RegisterVariable(&gl_paranoid);
+       Cvar_RegisterVariable(&gl_printcheckerror);
 #ifdef NORENDER
        Cvar_SetValue("r_render", 0);
 #endif
 
-       Cvar_RegisterVariable(&gl_mesh_maxtriangles);
-       Cvar_RegisterVariable(&gl_mesh_batchtriangles);
-       Cvar_RegisterVariable(&gl_mesh_floatcolors);
+       Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
+       Cvar_RegisterVariable(&gl_mesh_testarrayelement);
+       Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
+
+       Cvar_RegisterVariable(&scr_zoomwindow);
+       Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
+       Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
+       Cvar_RegisterVariable(&scr_zoomwindow_fov);
+
        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;
-       }
 }
 
-int arraylocked = false;
-
-void GL_LockArray(int first, int count)
+void GL_SetupView_Orientation_Identity (void)
 {
-       if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer)
-       {
-               qglLockArraysEXT(first, count);
-               CHECKGLERROR
-               arraylocked = true;
-       }
+       Matrix4x4_CreateIdentity(&backend_viewmatrix);
+       memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
 }
 
-void GL_UnlockArray(void)
+void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
 {
-       if (arraylocked)
-       {
-               qglUnlockArraysEXT();
-               CHECKGLERROR
-               arraylocked = false;
-       }
+       matrix4x4_t tempmatrix, basematrix;
+       Matrix4x4_Invert_Simple(&tempmatrix, matrix);
+       Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
+       Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
+       Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
+       //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
+       //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
+       //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
+       //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
+       memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
 }
 
-//static float gldepthmin, gldepthmax;
-
-/*
-=============
-GL_SetupFrame
-=============
-*/
-static void GL_SetupFrame (void)
+void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
 {
        double xmax, ymax;
-       double fovx, fovy, zNear, zFar, aspect;
-
-       // update farclip based on previous frame
-       r_farclip = r_newfarclip;
 
        if (!r_render.integer)
                return;
 
-//     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LordHavoc: moved to SCR_UpdateScreen
-//     gldepthmin = 0;
-//     gldepthmax = 1;
-       glDepthFunc (GL_LEQUAL);CHECKGLERROR
-
-//     glDepthRange (gldepthmin, gldepthmax);CHECKGLERROR
-
        // set up viewpoint
-       glMatrixMode(GL_PROJECTION);CHECKGLERROR
-       glLoadIdentity ();CHECKGLERROR
+       qglMatrixMode(GL_PROJECTION);CHECKGLERROR
+       qglLoadIdentity();CHECKGLERROR
+       // pyramid slopes
+       xmax = zNear * tan(fovx * M_PI / 360.0);
+       ymax = zNear * tan(fovy * M_PI / 360.0);
+       // set view pyramid
+       qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
+       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+       GL_SetupView_Orientation_Identity();
+}
+
+void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
+{
+       float nudge, m[16];
 
-       // y is weird beause OpenGL is bottom to top, we use top to bottom
-       glViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
+       if (!r_render.integer)
+               return;
 
-       // depth range
-       zNear = 1.0;
-       zFar = r_farclip;
+       // set up viewpoint
+       qglMatrixMode(GL_PROJECTION);CHECKGLERROR
+       qglLoadIdentity();CHECKGLERROR
+       // set view pyramid
+       nudge = 1.0 - 1.0 / (1<<23);
+       m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
+       m[ 1] = 0;
+       m[ 2] = 0;
+       m[ 3] = 0;
+       m[ 4] = 0;
+       m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
+       m[ 6] = 0;
+       m[ 7] = 0;
+       m[ 8] = 0;
+       m[ 9] = 0;
+       m[10] = -nudge;
+       m[11] = -1;
+       m[12] = 0;
+       m[13] = 0;
+       m[14] = -2 * zNear * nudge;
+       m[15] = 0;
+       qglLoadMatrixf(m);
+       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+       GL_SetupView_Orientation_Identity();
+       backend_projectmatrix.m[0][0] = m[0];
+       backend_projectmatrix.m[1][0] = m[1];
+       backend_projectmatrix.m[2][0] = m[2];
+       backend_projectmatrix.m[3][0] = m[3];
+       backend_projectmatrix.m[0][1] = m[4];
+       backend_projectmatrix.m[1][1] = m[5];
+       backend_projectmatrix.m[2][1] = m[6];
+       backend_projectmatrix.m[3][1] = m[7];
+       backend_projectmatrix.m[0][2] = m[8];
+       backend_projectmatrix.m[1][2] = m[9];
+       backend_projectmatrix.m[2][2] = m[10];
+       backend_projectmatrix.m[3][2] = m[11];
+       backend_projectmatrix.m[0][3] = m[12];
+       backend_projectmatrix.m[1][3] = m[13];
+       backend_projectmatrix.m[2][3] = m[14];
+       backend_projectmatrix.m[3][3] = m[15];
+}
 
-       // fov angles
-       fovx = r_refdef.fov_x;
-       fovy = r_refdef.fov_y;
-       aspect = r_refdef.width / r_refdef.height;
+void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
+{
+       if (!r_render.integer)
+               return;
 
-       // pyramid slopes
-       xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
-       ymax = zNear * tan(fovy * M_PI / 360.0);
+       // set up viewpoint
+       qglMatrixMode(GL_PROJECTION);CHECKGLERROR
+       qglLoadIdentity();CHECKGLERROR
+       qglOrtho(x1, x2, y2, y1, zNear, zFar);
+       qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
+       GL_SetupView_Orientation_Identity();
+}
 
-       // set view pyramid
-       glFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
-
-//     glCullFace(GL_FRONT);CHECKGLERROR
-
-       glMatrixMode(GL_MODELVIEW);CHECKGLERROR
-       glLoadIdentity ();CHECKGLERROR
-
-       // put Z going up
-       glRotatef (-90,  1, 0, 0);CHECKGLERROR
-       glRotatef (90,  0, 0, 1);CHECKGLERROR
-       // camera rotation
-       glRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
-       glRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
-       glRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
-       // camera location
-       glTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
-
-//     glGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix);
-
-       //
-       // set drawing parms
-       //
-//     if (gl_cull.integer)
-//     {
-//             glEnable(GL_CULL_FACE);CHECKGLERROR
-//     }
-//     else
-//     {
-//             glDisable(GL_CULL_FACE);CHECKGLERROR
-//     }
-
-//     glEnable(GL_BLEND);CHECKGLERROR
-//     glEnable(GL_DEPTH_TEST);CHECKGLERROR
-//     glDepthMask(1);CHECKGLERROR
+typedef struct gltextureunit_s
+{
+       int t1d, t2d, t3d, tcubemap;
+       int arrayenabled;
+       int arrayis3d;
+       const void *pointer_texcoord;
+       float rgbscale, alphascale;
+       int combinergb, combinealpha;
+       // FIXME: add more combine stuff
+       matrix4x4_t matrix;
 }
+gltextureunit_t;
 
-static int mesh_blendfunc1;
-static int mesh_blendfunc2;
-static int mesh_blend;
-static GLboolean mesh_depthmask;
-static int mesh_depthtest;
-static int mesh_unit;
-static int mesh_clientunit;
-static int mesh_texture[MAX_TEXTUREUNITS];
-static float mesh_texturergbscale[MAX_TEXTUREUNITS];
+static struct
+{
+       int blendfunc1;
+       int blendfunc2;
+       int blend;
+       GLboolean depthmask;
+       int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
+       int depthtest;
+       int scissortest;
+       int unit;
+       int clientunit;
+       gltextureunit_t units[MAX_TEXTUREUNITS];
+       float color4f[4];
+       int lockrange_first;
+       int lockrange_count;
+       const void *pointer_vertex;
+       const void *pointer_color;
+}
+gl_state;
 
 void GL_SetupTextureState(void)
 {
        int i;
-       if (backendunits > 1)
+       gltextureunit_t *unit;
+       gl_state.unit = -1;
+       gl_state.clientunit = -1;
+       for (i = 0;i < backendunits;i++)
        {
-               for (i = 0;i < backendunits;i++)
+               GL_ActiveTexture(i);
+               GL_ClientActiveTexture(i);
+               unit = gl_state.units + i;
+               unit->t1d = 0;
+               unit->t2d = 0;
+               unit->t3d = 0;
+               unit->tcubemap = 0;
+               unit->pointer_texcoord = NULL;
+               unit->rgbscale = 1;
+               unit->alphascale = 1;
+               unit->combinergb = GL_MODULATE;
+               unit->combinealpha = GL_MODULATE;
+
+               qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
+               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+
+               qglDisable(GL_TEXTURE_1D);CHECKGLERROR
+               qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+               if (gl_texture3d)
                {
-                       qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
-                       glBindTexture(GL_TEXTURE_2D, mesh_texture[i]);CHECKGLERROR
-                       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, mesh_texturergbscale[i]);CHECKGLERROR
-                               glTexEnvf(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1.0f);CHECKGLERROR
-                       }
-                       else
-                       {
-                               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
-                       }
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
-                       glTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
-                       if (mesh_texture[i])
-                       {
-                               glEnable(GL_TEXTURE_2D);CHECKGLERROR
-                               glEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
-                       else
-                       {
-                               glDisable(GL_TEXTURE_2D);CHECKGLERROR
-                               glDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
+                       qglDisable(GL_TEXTURE_3D);CHECKGLERROR
                }
-       }
-       else
-       {
-               glBindTexture(GL_TEXTURE_2D, mesh_texture[0]);CHECKGLERROR
-               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
-               glTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
-               if (mesh_texture[0])
+               if (gl_texturecubemap)
+               {
+                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
+               }
+               if (gl_combine.integer)
                {
-                       glEnable(GL_TEXTURE_2D);CHECKGLERROR
-                       glEnableClientState(GL_TEXTURE_COORD_ARRAY);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_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
+                       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, 1);CHECKGLERROR
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
                }
                else
                {
-                       glDisable(GL_TEXTURE_2D);CHECKGLERROR
-                       glDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
                }
        }
 }
 
-// called at beginning of frame
-void R_Mesh_Start(void)
+void GL_Backend_ResetState(void)
 {
-       int i;
-       if (!backendactive)
-               Sys_Error("R_Mesh_Clear: called when backend is not active\n");
+       memset(&gl_state, 0, sizeof(gl_state));
+       gl_state.depthtest = true;
+       gl_state.blendfunc1 = GL_ONE;
+       gl_state.blendfunc2 = GL_ZERO;
+       gl_state.blend = false;
+       gl_state.depthmask = GL_TRUE;
+       gl_state.colormask = 15;
+       gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
+       gl_state.lockrange_first = 0;
+       gl_state.lockrange_count = 0;
+       gl_state.pointer_vertex = NULL;
+       gl_state.pointer_color = NULL;
 
        CHECKGLERROR
 
-       gl_backend_bufferchanges(false);
-
-       currentmesh = 0;
-       currenttriangle = 0;
-       currentvertex = 0;
-       currenttransmesh = 0;
-       currenttranstriangle = 0;
-       currenttransvertex = 0;
-       meshfarclip = 0;
-       transranout = false;
-       viewdist = DotProduct(r_origin, vpn);
-
-       c_meshs = 0;
-       c_meshtris = 0;
-       c_transmeshs = 0;
-       c_transtris = 0;
-
-       GL_SetupFrame();
-
-       mesh_unit = 0;
-       mesh_clientunit = 0;
+       qglColorMask(1, 1, 1, 1);
+       qglEnable(GL_CULL_FACE);CHECKGLERROR
+       qglCullFace(GL_FRONT);CHECKGLERROR
+       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+       qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
+       qglDisable(GL_BLEND);CHECKGLERROR
+       qglDepthMask(gl_state.depthmask);CHECKGLERROR
 
-       for (i = 0;i < backendunits;i++)
-       {
-               mesh_texture[i] = 0;
-               mesh_texturergbscale[i] = 1;
-       }
-
-       glEnable(GL_CULL_FACE);CHECKGLERROR
-       glCullFace(GL_FRONT);CHECKGLERROR
+       qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
+       qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
 
-       mesh_depthtest = true;
-       glEnable(GL_DEPTH_TEST);CHECKGLERROR
+       qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
+       qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
 
-       mesh_blendfunc1 = GL_ONE;
-       mesh_blendfunc2 = GL_ZERO;
-       glBlendFunc(mesh_blendfunc1, mesh_blendfunc2);CHECKGLERROR
-
-       mesh_blend = 0;
-       glDisable(GL_BLEND);CHECKGLERROR
-
-       mesh_depthmask = GL_TRUE;
-       glDepthMask(mesh_depthmask);CHECKGLERROR
-
-       glVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), &buf_vertex[0].v[0]);CHECKGLERROR
-       glEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
-       if (gl_mesh_floatcolors.integer)
-       {
-               glColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), &buf_fcolor[0].c[0]);CHECKGLERROR
-       }
-       else
-       {
-               glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), &buf_bcolor[0].c[0]);CHECKGLERROR
-       }
-       glEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+       GL_Color(0, 0, 0, 0);
+       GL_Color(1, 1, 1, 1);
 
        GL_SetupTextureState();
 }
 
-int gl_backend_rebindtextures;
-
-void GL_UpdateFarclip(void)
+void GL_ActiveTexture(int num)
 {
-       int i;
-       float farclip;
-
-       // push out farclip based on vertices
-       // FIXME: wouldn't this be slow when using matrix transforms?
-       for (i = 0;i < currentvertex;i++)
+       if (gl_state.unit != num)
        {
-               farclip = DotProduct(buf_vertex[i].v, vpn);
-               if (meshfarclip < farclip)
-                       meshfarclip = farclip;
+               gl_state.unit = num;
+               if (qglActiveTexture)
+               {
+                       qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
+                       CHECKGLERROR
+               }
        }
-
-       farclip = meshfarclip + 256.0f - viewdist; // + 256 just to be safe
-
-       // push out farclip for next frame
-       if (farclip > r_newfarclip)
-               r_newfarclip = ceil((farclip + 255) / 256) * 256 + 256;
 }
 
-void GL_ConvertColorsFloatToByte(void)
+void GL_ClientActiveTexture(int num)
 {
-       int i, k, *icolor;
-       float *fcolor;
-       qbyte *bcolor;
-
-       // shift float to have 8bit fraction at base of number
-       for (i = 0, fcolor = &buf_fcolor->c[0];i < currentvertex;i++)
-       {
-               *fcolor++ += 32768.0f;
-               *fcolor++ += 32768.0f;
-               *fcolor++ += 32768.0f;
-               *fcolor++ += 32768.0f;
-       }
-       // then read as integer and kill float bits...
-       for (i = 0, icolor = (int *)&buf_fcolor->c[0], bcolor = &buf_bcolor->c[0];i < currentvertex;i++)
+       if (gl_state.clientunit != num)
        {
-               k = (*icolor++) & 0x7FFFFF;*bcolor++ = k > 255 ? 255 : k;
-               k = (*icolor++) & 0x7FFFFF;*bcolor++ = k > 255 ? 255 : k;
-               k = (*icolor++) & 0x7FFFFF;*bcolor++ = k > 255 ? 255 : k;
-               k = (*icolor++) & 0x7FFFFF;*bcolor++ = k > 255 ? 255 : k;
+               gl_state.clientunit = num;
+               if (qglActiveTexture)
+               {
+                       qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
+                       CHECKGLERROR
+               }
        }
 }
 
-void GL_MeshState(buf_mesh_t *mesh)
+void GL_BlendFunc(int blendfunc1, int blendfunc2)
 {
-       int i;
-       if (backendunits > 1)
+       if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
        {
-               for (i = 0;i < backendunits;i++)
+               if (r_showtrispass)
+                       return;
+               qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
+               if (gl_state.blendfunc2 == GL_ZERO)
                {
-                       if (mesh_texture[i] != mesh->textures[i])
+                       if (gl_state.blendfunc1 == GL_ONE)
                        {
-                               if (mesh_unit != i)
-                               {
-                                       qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
-                               }
-                               if (mesh_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 (mesh_clientunit != i)
-                                       {
-                                               qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
-                                       }
-                                       glEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                               }
-                               glBindTexture(GL_TEXTURE_2D, (mesh_texture[i] = mesh->textures[i]));CHECKGLERROR
-                               if (mesh_texture[i] == 0)
+                               if (gl_state.blend)
                                {
-                                       glDisable(GL_TEXTURE_2D);CHECKGLERROR
-                                       // have to disable texcoord array on disabled texture
-                                       // units due to NVIDIA driver bug with
-                                       // compiled_vertex_array
-                                       if (mesh_clientunit != i)
-                                       {
-                                               qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
-                                       }
-                                       glDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                                       gl_state.blend = 0;
+                                       qglDisable(GL_BLEND);CHECKGLERROR
                                }
                        }
-                       if (mesh_texturergbscale[i] != mesh->texturergbscale[i])
+                       else
                        {
-                               if (mesh_unit != i)
+                               if (!gl_state.blend)
                                {
-                                       qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
+                                       gl_state.blend = 1;
+                                       qglEnable(GL_BLEND);CHECKGLERROR
                                }
-                               glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (mesh_texturergbscale[i] = mesh->texturergbscale[i]));CHECKGLERROR
                        }
                }
-       }
-       else
-       {
-               if (mesh_texture[0] != mesh->textures[0])
+               else
                {
-                       if (mesh_texture[0] == 0)
+                       if (!gl_state.blend)
                        {
-                               glEnable(GL_TEXTURE_2D);CHECKGLERROR
-                               glEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
-                       glBindTexture(GL_TEXTURE_2D, (mesh_texture[0] = mesh->textures[0]));CHECKGLERROR
-                       if (mesh_texture[0] == 0)
-                       {
-                               glDisable(GL_TEXTURE_2D);CHECKGLERROR
-                               glDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               gl_state.blend = 1;
+                               qglEnable(GL_BLEND);CHECKGLERROR
                        }
                }
        }
-       if (mesh_blendfunc1 != mesh->blendfunc1 || mesh_blendfunc2 != mesh->blendfunc2)
+}
+
+void GL_DepthMask(int state)
+{
+       if (gl_state.depthmask != state)
+       {
+               if (r_showtrispass)
+                       return;
+               qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
+       }
+}
+
+void GL_DepthTest(int state)
+{
+       if (gl_state.depthtest != state)
        {
-               glBlendFunc(mesh_blendfunc1 = mesh->blendfunc1, mesh_blendfunc2 = mesh->blendfunc2);CHECKGLERROR
-               if (mesh_blendfunc2 == GL_ZERO)
+               if (r_showtrispass)
+                       return;
+               gl_state.depthtest = state;
+               if (gl_state.depthtest)
                {
-                       if (mesh_blendfunc1 == GL_ONE)
-                       {
-                               if (mesh_blend)
-                               {
-                                       mesh_blend = 0;
-                                       glDisable(GL_BLEND);CHECKGLERROR
-                               }
-                       }
-                       else
-                       {
-                               if (!mesh_blend)
-                               {
-                                       mesh_blend = 1;
-                                       glEnable(GL_BLEND);CHECKGLERROR
-                               }
-                       }
+                       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
                }
                else
                {
-                       if (!mesh_blend)
-                       {
-                               mesh_blend = 1;
-                               glEnable(GL_BLEND);CHECKGLERROR
-                       }
+                       qglDisable(GL_DEPTH_TEST);CHECKGLERROR
                }
        }
-       if (mesh_depthtest != mesh->depthtest)
-       {
-               mesh_depthtest = mesh->depthtest;
-               if (mesh_depthtest)
-                       glEnable(GL_DEPTH_TEST);
-               else
-                       glDisable(GL_DEPTH_TEST);
-       }
-       if (mesh_depthmask != mesh->depthmask)
-       {
-               glDepthMask(mesh_depthmask = mesh->depthmask);CHECKGLERROR
-       }
 }
 
-// renders mesh buffers, called to flush buffers when full
-void R_Mesh_Render(void)
+void GL_ColorMask(int r, int g, int b, int a)
 {
-       int i;
-       int k;
-       int indexcount;
-       int firstvert;
-       buf_mesh_t *mesh;
-       unsigned int *index;
-
-       if (!backendactive)
-               Sys_Error("R_Mesh_Render: called when backend is not active\n");
-
-       if (!currentmesh)
-               return;
-
-       CHECKGLERROR
-
-       GL_UpdateFarclip();
-
-       if (!gl_mesh_floatcolors.integer)
-               GL_ConvertColorsFloatToByte();
-
-       // lock the arrays now that they will have no further modifications
-       //GL_LockArray(0, currentvertex);CHECKGLERROR
-       if (gl_backend_rebindtextures)
+       int state = r*8 + g*4 + b*2 + a*1;
+       if (gl_state.colormask != state)
        {
-               gl_backend_rebindtextures = false;
-               GL_SetupTextureState();
+               if (r_showtrispass)
+                       return;
+               gl_state.colormask = state;
+               qglColorMask(r, g, b, a);CHECKGLERROR
        }
+}
 
-       GL_MeshState(buf_mesh);
-       GL_LockArray(0, currentvertex);
-       #ifdef WIN32
-       // FIXME: dynamic link to GL so we can get DrawRangeElements on WIN32
-       glDrawElements(GL_TRIANGLES, buf_mesh->triangles * 3, GL_UNSIGNED_INT, (unsigned int *)&buf_tri[buf_mesh->firsttriangle].index[0]);CHECKGLERROR
-       #else
-       glDrawRangeElements(GL_TRIANGLES, buf_mesh->firstvert, buf_mesh->firstvert + buf_mesh->verts, buf_mesh->triangles * 3, GL_UNSIGNED_INT, (unsigned int *)&buf_tri[buf_mesh->firsttriangle].index[0]);CHECKGLERROR
-       #endif
-
-       if (currentmesh >= 2)
+void GL_VertexPointer(const float *p)
+{
+       if (gl_state.pointer_vertex != p)
        {
-               for (k = 1, mesh = buf_mesh + k;k < currentmesh;k++, mesh++)
-               {
-                       GL_MeshState(mesh);
-
-                       firstvert = mesh->firstvert;
-                       indexcount = mesh->triangles * 3;
-                       index = (unsigned int *)&buf_tri[mesh->firsttriangle].index[0];
-
-                       // if not using batching, skip the index adjustment
-                       if (firstvert != 0)
-                               for (i = 0;i < indexcount;i++)
-                                       index[i] += firstvert;
-
-                       #ifdef WIN32
-                       // FIXME: dynamic link to GL so we can get DrawRangeElements on WIN32
-                       glDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);CHECKGLERROR
-                       #else
-                       glDrawRangeElements(GL_TRIANGLES, firstvert, firstvert + mesh->verts, indexcount, GL_UNSIGNED_INT, index);CHECKGLERROR
-                       #endif
-               }
+               gl_state.pointer_vertex = p;
+               CHECKGLERROR
+               qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
+               CHECKGLERROR
        }
-
-       currentmesh = 0;
-       currenttriangle = 0;
-       currentvertex = 0;
-
-       GL_UnlockArray();CHECKGLERROR
 }
 
-// restores backend state, used when done with 3D rendering
-void R_Mesh_Finish(void)
+void GL_ColorPointer(const float *p)
 {
-       int i;
-       // flush any queued meshs
-       R_Mesh_Render();
-
-       if (backendunits > 1)
+       if (gl_state.pointer_color != p)
        {
-               for (i = backendunits - 1;i >= 0;i--)
+               if (r_showtrispass)
+                       return;
+               CHECKGLERROR
+               if (!gl_state.pointer_color)
                {
-                       qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
-                       glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
-                       if (gl_combine.integer)
-                       {
-                               glTexEnvf(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1.0f);CHECKGLERROR
-                       }
-                       if (i > 0)
-                       {
-                               glDisable(GL_TEXTURE_2D);CHECKGLERROR
-                       }
-                       else
-                       {
-                               glEnable(GL_TEXTURE_2D);CHECKGLERROR
-                       }
-                       glBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
-
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
-                       glDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                       qglEnableClientState(GL_COLOR_ARRAY);
+                       CHECKGLERROR
                }
+               else if (!p)
+               {
+                       qglDisableClientState(GL_COLOR_ARRAY);
+                       CHECKGLERROR
+               }
+               gl_state.pointer_color = p;
+               qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
+               CHECKGLERROR
        }
-       else
-       {
-               glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
-               glEnable(GL_TEXTURE_2D);CHECKGLERROR
-               glDisableClientState(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_ClearDepth(void)
+void GL_Color(float cr, float cg, float cb, float ca)
 {
-       R_Mesh_AddTransparent();
-       R_Mesh_Finish();
-       glClear(GL_DEPTH_BUFFER_BIT);
-       R_Mesh_Start();
+       if (gl_state.pointer_color || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
+       {
+               if (r_showtrispass)
+                       return;
+               GL_ColorPointer(NULL);
+               gl_state.color4f[0] = cr;
+               gl_state.color4f[1] = cg;
+               gl_state.color4f[2] = cb;
+               gl_state.color4f[3] = ca;
+               CHECKGLERROR
+               qglColor4f(cr, cg, cb, ca);
+               CHECKGLERROR
+       }
 }
 
-void R_Mesh_AddTransparent(void)
+void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
 {
-       int i, j, k, *index;
-       float viewdistcompare, centerscaler, dist1, dist2, dist3, center, maxdist;
-       buf_vertex_t *vert1, *vert2, *vert3;
-       buf_transtri_t *tri;
-       buf_mesh_t *mesh, *transmesh;
-
-       if (!currenttransmesh)
+       if (!r_showtrispass)
                return;
+       r_showtrispass = false;
+       GL_Color(cr,cg,cb,ca);
+       r_showtrispass = true;
+}
 
-       // convert index data to transtris for sorting
-       for (j = 0;j < currenttransmesh;j++)
+
+void GL_LockArrays(int first, int count)
+{
+       if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
        {
-               mesh = buf_transmesh + j;
-               k = mesh->firsttriangle;
-               index = &buf_transtri[k].index[0];
-               for (i = 0;i < mesh->triangles;i++)
+               if (gl_state.lockrange_count)
                {
-                       tri = &buf_sorttranstri[k++];
-                       tri->mesh = mesh;
-                       tri->index[0] = *index++;
-                       tri->index[1] = *index++;
-                       tri->index[2] = *index++;
+                       gl_state.lockrange_count = 0;
+                       CHECKGLERROR
+                       qglUnlockArraysEXT();
+                       CHECKGLERROR
+               }
+               if (count && gl_supportslockarrays && gl_lockarrays.integer)
+               {
+                       gl_state.lockrange_first = first;
+                       gl_state.lockrange_count = count;
+                       CHECKGLERROR
+                       qglLockArraysEXT(first, count);
+                       CHECKGLERROR
                }
        }
+}
 
-       // map farclip to 0-4095 list range
-       centerscaler = (TRANSDEPTHRES / r_farclip) * (1.0f / 3.0f);
-       viewdistcompare = viewdist + 4.0f;
+void GL_Scissor (int x, int y, int width, int height)
+{
+       CHECKGLERROR
+       qglScissor(x, vid.realheight - (y + height),width,height);
+       CHECKGLERROR
+}
 
-       memset(buf_sorttranstri_list, 0, TRANSDEPTHRES * sizeof(buf_transtri_t *));
+void GL_ScissorTest(int state)
+{
+       if(gl_state.scissortest == state)
+               return;
 
-       k = 0;
-       for (j = 0;j < currenttranstriangle;j++)
-       {
-               tri = &buf_sorttranstri[j];
-               i = tri->mesh->firstvert;
-
-               vert1 = &buf_transvertex[tri->index[0] + i];
-               vert2 = &buf_transvertex[tri->index[1] + i];
-               vert3 = &buf_transvertex[tri->index[2] + i];
-
-               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 = *((int *)&center) & 0x7FFFFF;
-               i = min(i, (TRANSDEPTHRES - 1));
-#endif
-               tri->next = buf_sorttranstri_list[i];
-               buf_sorttranstri_list[i] = tri;
-               k++;
-       }
-
-       for (i = 0;i < currenttransmesh;i++)
-               buf_transmesh[i].transchain = NULL;
-       transmesh = NULL;
-       for (j = 0;j < TRANSDEPTHRES;j++)
-       {
-               if ((tri = buf_sorttranstri_list[j]))
-               {
-                       for (;tri;tri = tri->next)
-                       {
-                               if (!tri->mesh->transchain)
-                               {
-                                       tri->mesh->chain = transmesh;
-                                       transmesh = tri->mesh;
-                               }
-                               tri->meshsortchain = tri->mesh->transchain;
-                               tri->mesh->transchain = tri;
-                       }
-               }
-       }
-
-       for (;transmesh;transmesh = transmesh->chain)
-       {
-               if (currentmesh >= max_meshs || currenttriangle + transmesh->triangles > max_batch || currentvertex + transmesh->verts > max_verts)
-                       R_Mesh_Render();
-
-               mesh = &buf_mesh[currentmesh++];
-               *mesh = *transmesh; // copy mesh properties
-
-               mesh->firstvert = currentvertex;
-               memcpy(&buf_vertex[currentvertex], &buf_transvertex[transmesh->firstvert], transmesh->verts * sizeof(buf_vertex_t));
-               memcpy(&buf_fcolor[currentvertex], &buf_transfcolor[transmesh->firstvert], transmesh->verts * sizeof(buf_fcolor_t));
-               for (i = 0;i < backendunits && transmesh->textures[i];i++)
-                       memcpy(&buf_texcoord[i][currentvertex], &buf_transtexcoord[i][transmesh->firstvert], transmesh->verts * sizeof(buf_texcoord_t));
-               currentvertex += mesh->verts;
-
-               mesh->firsttriangle = currenttriangle;
-               for (tri = transmesh->transchain;tri;tri = tri->meshsortchain)
-               {
-                       buf_tri[currenttriangle].index[0] = tri->index[0];
-                       buf_tri[currenttriangle].index[1] = tri->index[1];
-                       buf_tri[currenttriangle].index[2] = tri->index[2];
-                       currenttriangle++;
-               }
-               mesh->triangles = currenttriangle - mesh->firsttriangle;
-       }
-
-       currenttransmesh = 0;
-       currenttranstriangle = 0;
-       currenttransvertex = 0;
+       CHECKGLERROR
+       if((gl_state.scissortest = state))
+               qglEnable(GL_SCISSOR_TEST);
+       else
+               qglDisable(GL_SCISSOR_TEST);
+       CHECKGLERROR
 }
 
-void R_Mesh_Draw(const rmeshinfo_t *m)
+void GL_Clear(int mask)
 {
-       // these are static because gcc runs out of virtual registers otherwise
-       static int i, j, overbright, *index;
-       static float *in, scaler;
-       static float cr, cg, cb, ca;
-       static buf_mesh_t *mesh;
-       static buf_vertex_t *vert;
-       static buf_fcolor_t *fcolor;
-       static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
-
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
-
-       if (m->index == NULL
-        || !m->numtriangles
-        || m->vertex == NULL
-        || !m->numverts)
-               Host_Error("R_Mesh_Draw: no triangles or verts\n");
-
-       // ignore meaningless alpha meshs
-       if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
-       {
-               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;
-       }
-
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
-
-#ifdef DEBUGGL
-       for (i = 0;i < m->numtriangles * 3;i++)
-               if ((unsigned int) m->index[i] >= (unsigned int) m->numverts)
-                       Host_Error("R_Mesh_Draw: invalid index (%i of %i verts)\n", m->index, m->numverts);
-#endif
-
-       if (m->transparent)
-       {
-               if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
-               {
-                       if (!transranout)
-                       {
-                               Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
-                               transranout = true;
-                       }
-                       return;
-               }
-
-               c_transmeshs++;
-               c_transtris += m->numtriangles;
-               vert = &buf_transvertex[currenttransvertex];
-               fcolor = &buf_transfcolor[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->firsttriangle = currenttranstriangle;
-               mesh->firstvert = currenttransvertex;
-               index = &buf_transtri[currenttranstriangle].index[0];
-
-               currenttranstriangle += m->numtriangles;
-               currenttransvertex += m->numverts;
-       }
-       else
-       {
-               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();
+       if (r_showtrispass)
+               return;
+       qglClear(mask);CHECKGLERROR
+}
 
-               c_meshs++;
-               c_meshtris += m->numtriangles;
-               vert = &buf_vertex[currentvertex];
-               fcolor = &buf_fcolor[currentvertex];
-               for (i = 0;i < backendunits;i++)
-                       texcoord[i] = &buf_texcoord[i][currentvertex];
+void GL_TransformToScreen(const vec4_t in, vec4_t out)
+{
+       vec4_t temp;
+       float iw;
+       Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
+       Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
+       iw = 1.0f / out[3];
+       out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
+       out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
+       out[2] = out[2] * iw;
+}
 
-               // opaque meshs are rendered directly
-               mesh = &buf_mesh[currentmesh++];
-               mesh->firsttriangle = currenttriangle;
-               mesh->firstvert = currentvertex;
-               index = &buf_tri[currenttriangle].index[0];
+// called at beginning of frame
+void R_Mesh_Start(void)
+{
+       BACKENDACTIVECHECK
+       CHECKGLERROR
+       GL_Backend_ResetState();
+}
 
-               currenttriangle += m->numtriangles;
-               currentvertex += m->numverts;
-       }
+int gl_backend_rebindtextures;
 
-       // code shared for transparent and opaque meshs
-       memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
-       mesh->blendfunc1 = m->blendfunc1;
-       mesh->blendfunc2 = m->blendfunc2;
-       mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
-       mesh->depthtest = !m->depthdisable;
-       mesh->triangles = m->numtriangles;
-       mesh->verts = m->numverts;
-
-       overbright = false;
-       scaler = 1;
-       if (m->blendfunc2 == GL_SRC_COLOR)
+void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
+{
+       int i;
+       if (offset)
        {
-               if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
-                       scaler *= 0.5f;
+               for (i = 0;i < count;i++)
+                       *out++ = *in++ + offset;
        }
        else
-       {
-               if (m->tex[0])
-               {
-                       overbright = gl_combine.integer;
-                       if (overbright)
-                               scaler *= 0.25f;
-               }
-               scaler *= overbrightscale;
-       }
-
+               memcpy(out, in, sizeof(*out) * count);
+}
 
-       j = -1;
-       for (i = 0;i < backendunits;i++)
+// renders triangles using vertices from the active arrays
+int paranoidblah = 0;
+void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
+{
+       int numelements = numtriangles * 3;
+       if (numverts == 0 || numtriangles == 0)
        {
-               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;
+               Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
+               return;
        }
-       if (overbright && j >= 0)
-               mesh->texturergbscale[j] = 4;
-
-       if (m->vertexstep != sizeof(buf_vertex_t))
+       if (r_showtrispass)
        {
-               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];
-               }
+               R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
+               return;
        }
-       else
-               memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
-
-       if (m->color)
+       c_meshs++;
+       c_meshelements += numelements;
+       CHECKGLERROR
+       if (r_render.integer)
        {
-               for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
+               if (gl_paranoid.integer)
                {
-                       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];
+                       int i, j, size;
+                       const int *p;
+                       if (!qglIsEnabled(GL_VERTEX_ARRAY))
+                               Con_Printf("R_Mesh_Draw: vertex array not enabled\n");
+                       for (j = 0, size = numverts * (int)sizeof(float[3]), p = gl_state.pointer_vertex;j < size;j += sizeof(int), p++)
+                               paranoidblah += *p;
+                       if (gl_state.pointer_color)
+                       {
+                               if (!qglIsEnabled(GL_COLOR_ARRAY))
+                                       Con_Printf("R_Mesh_Draw: color array set but not enabled\n");
+                               for (j = 0, size = numverts * (int)sizeof(float[4]), p = gl_state.pointer_color;j < size;j += sizeof(int), p++)
+                                       paranoidblah += *p;
+                       }
+                       for (i = 0;i < backendunits;i++)
+                       {
+                               if (gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap || gl_state.units[i].arrayenabled)
+                               {
+                                       if (gl_state.units[i].arrayenabled && !(gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap))
+                                               Con_Printf("R_Mesh_Draw: array enabled but no texture bound\n");
+                                       GL_ActiveTexture(i);
+                                       if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
+                                               Con_Printf("R_Mesh_Draw: texcoord array set but not enabled\n");
+                                       for (j = 0, size = numverts * ((gl_state.units[i].t3d || gl_state.units[i].tcubemap) ? (int)sizeof(float[3]) : (int)sizeof(float[2])), p = gl_state.units[i].pointer_texcoord;j < size;j += sizeof(int), p++)
+                                               paranoidblah += *p;
+                               }
+                       }
+                       for (i = 0;i < numtriangles * 3;i++)
+                       {
+                               if (elements[i] < 0 || elements[i] >= numverts)
+                               {
+                                       Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
+                                       return;
+                               }
+                       }
                }
-       }
-       else
-       {
-               cr = m->cr * scaler;
-               cg = m->cg * scaler;
-               cb = m->cb * scaler;
-               ca = m->ca;
-               for (i = 0;i < m->numverts;i++)
+               CHECKGLERROR
+               GL_LockArrays(0, numverts);
+               CHECKGLERROR
+               if (gl_mesh_testmanualfeeding.integer)
                {
-                       fcolor[i].c[0] = cr;
-                       fcolor[i].c[1] = cg;
-                       fcolor[i].c[2] = cb;
-                       fcolor[i].c[3] = ca;
+                       int i, j;
+                       const GLfloat *p;
+                       qglBegin(GL_TRIANGLES);
+                       for (i = 0;i < numtriangles * 3;i++)
+                       {
+                               for (j = 0;j < backendunits;j++)
+                               {
+                                       if (gl_state.units[j].pointer_texcoord)
+                                       {
+                                               if (backendunits > 1)
+                                               {
+                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
+                                                               qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
+                                                       }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
+                                                               qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
+                                                       }
+                                               }
+                                               else
+                                               {
+                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
+                                                               qglTexCoord3f(p[0], p[1], p[2]);
+                                                       }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
+                                                               qglTexCoord2f(p[0], p[1]);
+                                                       }
+                                               }
+                                       }
+                               }
+                               if (gl_state.pointer_color)
+                               {
+                                       p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
+                                       qglColor4f(p[0], p[1], p[2], p[3]);
+                               }
+                               p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
+                               qglVertex3f(p[0], p[1], p[2]);
+                       }
+                       qglEnd();
+                       CHECKGLERROR
                }
-       }
-
-       for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
-       {
-               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))
+               else if (gl_mesh_testarrayelement.integer)
                {
-                       for (i = 0, in = m->texcoords[j];i < m->numverts;i++, (int)in += m->texcoordstep[j])
+                       int i;
+                       qglBegin(GL_TRIANGLES);
+                       for (i = 0;i < numtriangles * 3;i++)
                        {
-                               texcoord[j][i].t[0] = in[0];
-                               texcoord[j][i].t[1] = in[1];
+                               qglArrayElement(elements[i]);
                        }
+                       qglEnd();
+                       CHECKGLERROR
+               }
+               else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
+               {
+                       qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
                }
                else
-                       memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
+               {
+                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
+               }
+               CHECKGLERROR
+               GL_LockArrays(0, 0);
+               CHECKGLERROR
        }
-       #if 0
-       for (;j < backendunits;j++)
-               memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
-       #endif
 }
 
-void R_Mesh_Draw_NativeOnly(const rmeshinfo_t *m)
+// restores backend state, used when done with 3D rendering
+void R_Mesh_Finish(void)
 {
-       // these are static because gcc runs out of virtual registers otherwise
-       static int i, j, overbright, *index;
-       static float *in, scaler;
-       static buf_mesh_t *mesh;
-       static buf_vertex_t *vert;
-       static buf_fcolor_t *fcolor;
-       static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
-
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
-
-       if (m->index == NULL
-        || !m->numtriangles
-        || m->vertex == NULL
-        || !m->numverts)
-               Host_Error("R_Mesh_Draw: no triangles or verts\n");
-
-       // ignore meaningless alpha meshs
-       if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
-       {
-               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;
-       }
+       int i;
+       BACKENDACTIVECHECK
+       CHECKGLERROR
+       GL_LockArrays(0, 0);
+       CHECKGLERROR
 
-       if (m->transparent)
+       for (i = backendunits - 1;i >= 0;i--)
        {
-               if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
+               if (qglActiveTexture)
+                       qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+               if (qglClientActiveTexture)
+                       qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               qglDisable(GL_TEXTURE_1D);CHECKGLERROR
+               qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+               if (gl_texture3d)
                {
-                       if (!transranout)
-                       {
-                               Con_Printf("R_Mesh_Draw_NativeOnly: ran out of room for transparent meshs\n");
-                               transranout = true;
-                       }
-                       return;
+                       qglDisable(GL_TEXTURE_3D);CHECKGLERROR
                }
-
-               c_transmeshs++;
-               c_transtris += m->numtriangles;
-               vert = &buf_transvertex[currenttransvertex];
-               fcolor = &buf_transfcolor[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->firsttriangle = currenttranstriangle;
-               mesh->firstvert = currenttransvertex;
-               index = &buf_transtri[currenttranstriangle].index[0];
-               currenttranstriangle += m->numtriangles;
-               currenttransvertex += m->numverts;
-       }
-       else
-       {
-               if (m->numtriangles > max_meshs || m->numverts > max_verts)
+               if (gl_texturecubemap)
                {
-                       Con_Printf("R_Mesh_Draw_NativeOnly: mesh too big for buffers\n");
-                       return;
+                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
                }
-
-               if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
-                       R_Mesh_Render();
-
-               c_meshs++;
-               c_meshtris += m->numtriangles;
-               vert = &buf_vertex[currentvertex];
-               fcolor = &buf_fcolor[currentvertex];
-               for (i = 0;i < backendunits;i++)
-                       texcoord[i] = &buf_texcoord[i][currentvertex];
-
-               // opaque meshs are rendered directly
-               mesh = &buf_mesh[currentmesh++];
-               mesh->firsttriangle = currenttriangle;
-               mesh->firstvert = currentvertex;
-               index = &buf_tri[currenttriangle].index[0];
-               currenttriangle += m->numtriangles;
-               currentvertex += m->numverts;
-       }
-
-       // code shared for transparent and opaque meshs
-       memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
-       mesh->blendfunc1 = m->blendfunc1;
-       mesh->blendfunc2 = m->blendfunc2;
-       mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
-       mesh->depthtest = !m->depthdisable;
-       mesh->triangles = m->numtriangles;
-       mesh->verts = m->numverts;
-
-       overbright = false;
-       scaler = 1;
-       if (m->blendfunc2 == GL_SRC_COLOR)
-       {
-               if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
-                       scaler *= 0.5f;
-       }
-       else
-       {
-               if (m->tex[0])
+               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
+               if (gl_combine.integer)
                {
-                       overbright = gl_combine.integer;
-                       if (overbright)
-                               scaler *= 0.25f;
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
                }
-               scaler *= overbrightscale;
        }
+       qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
+       qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
 
-       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;
-
-       if (m->vertexstep != sizeof(buf_vertex_t))
-               Host_Error("R_Mesh_Draw_NativeOnly: unsupported vertexstep\n");
-       if (m->colorstep != sizeof(buf_fcolor_t))
-               Host_Error("R_Mesh_Draw_NativeOnly: unsupported colorstep\n");
-       if (m->color == NULL)
-               Host_Error("R_Mesh_Draw_NativeOnly: must provide color array\n");
-       for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
+       qglDisable(GL_BLEND);CHECKGLERROR
+       qglEnable(GL_DEPTH_TEST);CHECKGLERROR
+       qglDepthMask(GL_TRUE);CHECKGLERROR
+       qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
+}
+
+void R_Mesh_Matrix(const matrix4x4_t *matrix)
+{
+       if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
        {
-               if (j >= backendunits)
-                       Sys_Error("R_Mesh_Draw_NativeOnly: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
-               if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
-                       Host_Error("R_Mesh_Draw_NativeOnly: unsupported texcoordstep\n");
+               backend_modelmatrix = *matrix;
+               Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
+               Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
+               qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
        }
+}
 
-       memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
-       for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
-               memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
-       #if 0
-       for (;j < backendunits;j++)
-               memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
-       #endif
-
-       memcpy(fcolor, m->color, m->numverts * sizeof(buf_fcolor_t));
-
-       // do this as a second step because memcpy preloaded the cache, which we can't easily do
-       if (scaler != 1)
+void R_Mesh_TextureMatrix(int unitnumber, const matrix4x4_t *matrix)
+{
+       if (memcmp(&gl_state.units[unitnumber].matrix, matrix, sizeof(matrix4x4_t)))
        {
-               for (i = 0;i < m->numverts;i++)
-               {
-                       fcolor[i].c[0] *= scaler;
-                       fcolor[i].c[1] *= scaler;
-                       fcolor[i].c[2] *= scaler;
-               }
+               matrix4x4_t tempmatrix;
+               gl_state.units[unitnumber].matrix = *matrix;
+               Matrix4x4_Transpose(&tempmatrix, &gl_state.units[unitnumber].matrix);
+               qglMatrixMode(GL_TEXTURE);
+               GL_ActiveTexture(unitnumber);
+               qglLoadMatrixf(&tempmatrix.m[0][0]);
+               qglMatrixMode(GL_MODELVIEW);
        }
 }
 
-// allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
-// (this is used for very high speed rendering, no copying)
-int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m)
+void R_Mesh_State_Texture(const rmeshstate_t *m)
 {
-       // these are static because gcc runs out of virtual registers otherwise
-       int i, j, overbright;
-       float scaler;
-       buf_mesh_t *mesh;
+       int i, combinergb, combinealpha, scale, arrayis3d;
+       gltextureunit_t *unit;
 
-       if (!backendactive)
-               Sys_Error("R_Mesh_Draw: called when backend is not active\n");
+       BACKENDACTIVECHECK
 
-       if (!m->numtriangles
-        || !m->numverts)
-               Host_Error("R_Mesh_Draw: no triangles or verts\n");
+       if (gl_backend_rebindtextures)
+       {
+               gl_backend_rebindtextures = false;
+               GL_SetupTextureState();
+       }
 
-       if (m->transparent)
+       if (r_showtrispass)
+               return;
+       for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
        {
-               if (currenttransmesh >= max_meshs || (currenttranstriangle + m->numtriangles) > max_meshs || (currenttransvertex + m->numverts) > max_verts)
+               if (unit->t1d != m->tex1d[i])
                {
-                       if (!transranout)
+                       GL_ActiveTexture(i);
+                       if (m->tex1d[i])
                        {
-                               Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
-                               transranout = true;
+                               if (unit->t1d == 0)
+                                       qglEnable(GL_TEXTURE_1D);CHECKGLERROR
                        }
-                       return false;
+                       else
+                       {
+                               if (unit->t1d)
+                                       qglDisable(GL_TEXTURE_1D);CHECKGLERROR
+                       }
+                       qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
                }
-
-               c_transmeshs++;
-               c_transtris += m->numtriangles;
-               m->index = &buf_transtri[currenttranstriangle].index[0];
-               m->vertex = &buf_transvertex[currenttransvertex].v[0];
-               m->color = &buf_transfcolor[currenttransvertex].c[0];
-               for (i = 0;i < backendunits;i++)
-                       m->texcoords[i] = &buf_transtexcoord[i][currenttransvertex].t[0];
-
-               // transmesh is only for storage of transparent meshs until they
-               // are inserted into the main mesh array
-               mesh = &buf_transmesh[currenttransmesh++];
-               mesh->firsttriangle = currenttranstriangle;
-               mesh->firstvert = currenttransvertex;
-               currenttranstriangle += m->numtriangles;
-               currenttransvertex += m->numverts;
-       }
-       else
-       {
-               if (m->numtriangles > max_meshs || m->numverts > max_verts)
+               if (unit->t2d != m->tex[i])
                {
-                       Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for buffers\n");
-                       return false;
+                       GL_ActiveTexture(i);
+                       if (m->tex[i])
+                       {
+                               if (unit->t2d == 0)
+                                       qglEnable(GL_TEXTURE_2D);CHECKGLERROR
+                       }
+                       else
+                       {
+                               if (unit->t2d)
+                                       qglDisable(GL_TEXTURE_2D);CHECKGLERROR
+                       }
+                       qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
                }
-
-               if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
-                       R_Mesh_Render();
-
-               c_meshs++;
-               c_meshtris += m->numtriangles;
-               m->index = &buf_tri[currenttriangle].index[0];
-               m->vertex = &buf_vertex[currentvertex].v[0];
-               m->color = &buf_fcolor[currentvertex].c[0];
-               for (i = 0;i < backendunits;i++)
-                       m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
-
-               // opaque meshs are rendered directly
-               mesh = &buf_mesh[currentmesh++];
-               mesh->firsttriangle = currenttriangle;
-               mesh->firstvert = currentvertex;
-               currenttriangle += m->numtriangles;
-               currentvertex += m->numverts;
-       }
-
-       // code shared for transparent and opaque meshs
-       mesh->blendfunc1 = m->blendfunc1;
-       mesh->blendfunc2 = m->blendfunc2;
-       mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
-       mesh->depthtest = !m->depthdisable;
-       mesh->triangles = m->numtriangles;
-       mesh->verts = m->numverts;
-
-       overbright = false;
-       scaler = 1;
-       if (m->blendfunc2 == GL_SRC_COLOR)
-       {
-               if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
-                       scaler *= 0.5f;
-       }
-       else
-       {
-               if (m->tex[0])
+               if (unit->t3d != m->tex3d[i])
                {
-                       overbright = gl_combine.integer;
-                       if (overbright)
-                               scaler *= 0.25f;
+                       GL_ActiveTexture(i);
+                       if (m->tex3d[i])
+                       {
+                               if (unit->t3d == 0)
+                                       qglEnable(GL_TEXTURE_3D);CHECKGLERROR
+                       }
+                       else
+                       {
+                               if (unit->t3d)
+                                       qglDisable(GL_TEXTURE_3D);CHECKGLERROR
+                       }
+                       qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
                }
-               scaler *= overbrightscale;
-       }
-       m->colorscale = scaler;
-
-       j = -1;
-       for (i = 0;i < MAX_TEXTUREUNITS;i++)
-       {
-               if ((mesh->textures[i] = m->tex[i]))
+               if (unit->tcubemap != m->texcubemap[i])
                {
-                       j = i;
-                       if (i >= backendunits)
-                               Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
+                       GL_ActiveTexture(i);
+                       if (m->texcubemap[i])
+                       {
+                               if (unit->tcubemap == 0)
+                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
+                       }
+                       else
+                       {
+                               if (unit->tcubemap)
+                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
+                       }
+                       qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
+               }
+               combinergb = m->texcombinergb[i];
+               if (!combinergb)
+                       combinergb = GL_MODULATE;
+               if (unit->combinergb != combinergb)
+               {
+                       GL_ActiveTexture(i);
+                       unit->combinergb = combinergb;
+                       if (gl_combine.integer) 
+                       {
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
+                       }
+                       else
+                       {
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
+                       }
+               }
+               combinealpha = m->texcombinealpha[i];
+               if (!combinealpha)
+                       combinealpha = GL_MODULATE;
+               if (unit->combinealpha != combinealpha)
+               {
+                       GL_ActiveTexture(i);
+                       unit->combinealpha = combinealpha;
+                       if (gl_combine.integer)
+                       {
+                               qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
+                       }
+               }
+               scale = max(m->texrgbscale[i], 1);
+               if (unit->rgbscale != scale)
+               {
+                       GL_ActiveTexture(i);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = scale));CHECKGLERROR
+               }
+               scale = max(m->texalphascale[i], 1);
+               if (unit->alphascale != scale)
+               {
+                       GL_ActiveTexture(i);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = scale));CHECKGLERROR
+               }
+               arrayis3d = unit->t3d || unit->tcubemap;
+               if (unit->pointer_texcoord != m->pointer_texcoord[i] || unit->arrayis3d != arrayis3d)
+               {
+                       GL_ClientActiveTexture(i);
+                       if (m->pointer_texcoord[i])
+                       {
+                               if (!unit->arrayenabled)
+                               {
+                                       unit->arrayenabled = true;
+                                       qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               }
+                       }
+                       else
+                       {
+                               if (unit->arrayenabled)
+                               {
+                                       unit->arrayenabled = false;
+                                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               }
+                       }
+                       unit->pointer_texcoord = m->pointer_texcoord[i];
+                       unit->arrayis3d = arrayis3d;
+                       if (unit->arrayis3d)
+                               qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
+                       else
+                               qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
+                       CHECKGLERROR
                }
-               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;
-
-       return true;
 }
 
-void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
+void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
 {
-       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)
+       qglBegin(GL_LINES);
+       for (;numtriangles;numtriangles--, elements += 3)
        {
-               Con_Printf("R_Mesh_DrawPolygon: only up to 256 triangles (258 verts) supported\n");
-               return;
+               qglArrayElement(elements[0]);qglArrayElement(elements[1]);
+               qglArrayElement(elements[1]);qglArrayElement(elements[2]);
+               qglArrayElement(elements[2]);qglArrayElement(elements[0]);
        }
-       R_Mesh_Draw(m);
+       qglEnd();
+       CHECKGLERROR
 }
 
 /*
@@ -1426,25 +1075,22 @@ void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
 ==============================================================================
 */
 
-qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
+qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
 {
        qboolean ret;
-       int i;
        qbyte *buffer;
 
        if (!r_render.integer)
                return false;
 
        buffer = Mem_Alloc(tempmempool, width*height*3);
-       glReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
+       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);
+       if (jpeg)
+               ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
+       else
+               ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
 
        Mem_Free(buffer);
        return ret;
@@ -1457,21 +1103,40 @@ void R_ClearScreen(void)
        if (r_render.integer)
        {
                // clear to black
-               glClearColor(0,0,0,0);CHECKGLERROR
+               qglClearColor(0,0,0,0);CHECKGLERROR
+               qglClearDepth(1);CHECKGLERROR
+               if (gl_stencil)
+               {
+                       // LordHavoc: we use a stencil centered around 128 instead of 0,
+                       // to avoid clamping interfering with strange shadow volume
+                       // drawing orders
+                       qglClearStencil(128);CHECKGLERROR
+               }
                // clear the screen
-               glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
+               GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
                // set dithering mode
                if (gl_dither.integer)
                {
-                       glEnable(GL_DITHER);CHECKGLERROR
+                       qglEnable(GL_DITHER);CHECKGLERROR
                }
                else
                {
-                       glDisable(GL_DITHER);CHECKGLERROR
+                       qglDisable(GL_DITHER);CHECKGLERROR
                }
        }
 }
 
+/*
+====================
+CalcFov
+====================
+*/
+float CalcFov (float fov_x, float width, float height)
+{
+       // calculate vision size and alter by aspect, then convert back to angle
+       return atan (height / (width / tan(fov_x/360*M_PI))) * 360 / M_PI;
+}
+
 /*
 ==================
 SCR_UpdateScreen
@@ -1482,36 +1147,393 @@ text to the screen.
 */
 void SCR_UpdateScreen (void)
 {
-       //Mem_CheckSentinelsGlobal();
-       //R_TimeReport("memtest");
-
-       VID_Finish ();
-
-       R_TimeReport("finish");
+       if (gl_delayfinish.integer)
+       {
+               R_Mesh_Finish();
+               R_TimeReport("meshfinish");
+               VID_Finish();
+               R_TimeReport("finish");
+       }
 
-       if (gl_combine.integer && !gl_combine_extension)
-               Cvar_SetValue("gl_combine", 0);
+       R_Mesh_Start();
 
-       lightscalebit = v_overbrightbits.integer;
-       if (gl_combine.integer && r_multitexture.integer)
-               lightscalebit += 2;
+       if (r_textureunits.integer > gl_textureunits)
+               Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
+       if (r_textureunits.integer < 1)
+               Cvar_SetValueQuick(&r_textureunits, 1);
 
-       lightscale = 1.0f / (float) (1 << lightscalebit);
-       overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
+       if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
+               Cvar_SetValueQuick(&gl_combine, 0);
 
+showtris:
        R_TimeReport("setup");
 
        R_ClearScreen();
 
        R_TimeReport("clear");
 
-       if (scr_conlines < vid.conheight)
+       if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
+       {
+               float size;
+               int contents;
+
+               // bound viewsize
+               if (scr_viewsize.value < 30)
+                       Cvar_Set ("viewsize","30");
+               if (scr_viewsize.value > 120)
+                       Cvar_Set ("viewsize","120");
+               
+               // bound field of view
+               if (scr_fov.value < 1)
+                       Cvar_Set ("fov","1");
+               if (scr_fov.value > 170)
+                       Cvar_Set ("fov","170");
+       
+               // intermission is always full screen
+               if (cl.intermission)
+               {
+                       size = 1;
+                       sb_lines = 0;
+               }
+               else
+               {
+                       if (scr_viewsize.value >= 120)
+                               sb_lines = 0;           // no status bar at all
+                       else if (scr_viewsize.value >= 110)
+                               sb_lines = 24;          // no inventory
+                       else
+                               sb_lines = 24+16+8;
+                       size = scr_viewsize.value * (1.0 / 100.0);
+                       size = min(size, 1);
+               }
+       
+               r_refdef.width = vid.realwidth * size;
+               r_refdef.height = vid.realheight * size;
+               r_refdef.x = (vid.realwidth - r_refdef.width)/2;
+               r_refdef.y = (vid.realheight - r_refdef.height)/2;
+       
+               // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
+               r_refdef.fov_x = scr_fov.value * cl.viewzoom;
+               r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height);
+       
+               if (cl.worldmodel)
+               {
+                       Mod_CheckLoaded(cl.worldmodel);
+                       contents = CL_PointSuperContents(r_vieworigin);
+                       if (contents & SUPERCONTENTS_LIQUIDSMASK)
+                       {
+                               r_refdef.fov_x *= (sin(cl.time * 4.7) * 0.015 + 0.985);
+                               r_refdef.fov_y *= (sin(cl.time * 3.0) * 0.015 + 0.985);
+                       }
+               }
+
                R_RenderView();
 
+               if (scr_zoomwindow.integer)
+               {
+                       float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
+                       float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
+                       r_refdef.width = vid.realwidth * sizex;
+                       r_refdef.height = vid.realheight * sizey;
+                       r_refdef.x = (vid.realwidth - r_refdef.width)/2;
+                       r_refdef.y = 0;
+                       r_refdef.fov_x = scr_zoomwindow_fov.value;
+                       r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height);
+
+                       R_RenderView();
+               }
+       }
+
        // draw 2D stuff
        R_DrawQueue();
 
-       // tell driver to commit it's partially full geometry queue to the rendering queue
-       // (this doesn't wait for the commands themselves to complete)
-       glFlush();
+       if (r_showtrispass)
+               r_showtrispass = false;
+       else if (r_showtris.integer)
+       {
+               rmeshstate_t m;
+               GL_BlendFunc(GL_ONE, GL_ONE);
+               GL_DepthTest(GL_FALSE);
+               GL_DepthMask(GL_FALSE);
+               memset(&m, 0, sizeof(m));
+               R_Mesh_State_Texture(&m);
+               r_showtrispass = true;
+               GL_ShowTrisColor(0.2,0.2,0.2,1);
+               goto showtris;
+       }
+
+       if (gl_delayfinish.integer)
+       {
+               // 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();
+       }
+       else
+       {
+               R_Mesh_Finish();
+               R_TimeReport("meshfinish");
+               VID_Finish();
+               R_TimeReport("finish");
+       }
 }
+
+
+//===========================================================================
+// dynamic vertex array buffer subsystem
+//===========================================================================
+
+float varray_vertex3f[65536*3];
+float varray_color4f[65536*4];
+float varray_texcoord2f[4][65536*2];
+float varray_texcoord3f[4][65536*3];
+float varray_normal3f[65536*3];
+int earray_element3i[65536];
+
+//===========================================================================
+// vertex array caching subsystem
+//===========================================================================
+
+typedef struct rcachearraylink_s
+{
+       struct rcachearraylink_s *next, *prev;
+       struct rcachearrayitem_s *data;
+}
+rcachearraylink_t;
+
+typedef struct rcachearrayitem_s
+{
+       // the original request structure
+       rcachearrayrequest_t request;
+       // active
+       int active;
+       // offset into r_mesh_rcachedata
+       int offset;
+       // for linking this into the sequential list
+       rcachearraylink_t sequentiallink;
+       // for linking this into the lookup list
+       rcachearraylink_t hashlink;
+}
+rcachearrayitem_t;
+
+#define RCACHEARRAY_HASHSIZE 65536
+#define RCACHEARRAY_ITEMS 4096
+#define RCACHEARRAY_DEFAULTSIZE (4 << 20)
+
+// all active items are linked into this chain in sorted order
+static rcachearraylink_t r_mesh_rcachesequentialchain;
+// all inactive items are linked into this chain in unknown order
+static rcachearraylink_t r_mesh_rcachefreechain;
+// all active items are also linked into these chains (using their hashlink)
+static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
+
+// all items are stored here, whether active or inactive
+static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
+
+// size of data buffer
+static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
+// data buffer
+static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
+
+// current state
+static int r_mesh_rcachedata_offset;
+static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
+
+static void R_Mesh_CacheArray_Startup(void)
+{
+       int i;
+       rcachearraylink_t *l;
+       // prepare all the linked lists
+       l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
+       l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
+       memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
+       for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
+       {
+               l = &r_mesh_rcachechain[i];
+               l->next = l->prev = l;
+               l->data = NULL;
+       }
+       memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
+       for (i = 0;i < RCACHEARRAY_ITEMS;i++)
+       {
+               r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
+               l = &r_mesh_rcacheitems[i].sequentiallink;
+               l->next = &r_mesh_rcachefreechain;
+               l->prev = l->next->prev;
+               l->next->prev = l->prev->next = l;
+       }
+       // clear other state
+       r_mesh_rcachedata_offset = 0;
+       r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
+}
+
+static void R_Mesh_CacheArray_Shutdown(void)
+{
+}
+
+/*
+static void R_Mesh_CacheArray_ValidateState(int num)
+{
+       rcachearraylink_t *l, *lhead;
+       lhead = &r_mesh_rcachesequentialchain;
+       if (r_mesh_rcachesequentialchain_current == lhead)
+               return;
+       for (l = lhead->next;l != lhead;l = l->next)
+               if (r_mesh_rcachesequentialchain_current == l)
+                       return;
+       Sys_Error("%i", num);
+}
+*/
+
+int R_Mesh_CacheArray(rcachearrayrequest_t *r)
+{
+       rcachearraylink_t *l, *lhead, *lnext;
+       rcachearrayitem_t *d;
+       int hashindex, offset, offsetend;
+
+       //R_Mesh_CacheArray_ValidateState(3);
+       // calculate a hashindex to choose a cache chain
+       r->data = NULL;
+       hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
+
+       // is it already cached?
+       for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
+       {
+               if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
+               {
+                       // we have it cached already
+                       r->data = r_mesh_rcachedata + l->data->offset;
+                       return false;
+               }
+       }
+
+       // we need to add a new cache item, this means finding a place for the new
+       // data and making sure we have a free item available, lots of work...
+
+       // check if buffer needs to wrap
+       if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
+       {
+               /*
+               if (r->data_size * 10 > r_mesh_rcachedata_size)
+               {
+                       // realloc whole cache
+               }
+               */
+               // reset back to start
+               r_mesh_rcachedata_offset = 0;
+               r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
+       }
+       offset = r_mesh_rcachedata_offset;
+       r_mesh_rcachedata_offset += r->data_size;
+       offsetend = r_mesh_rcachedata_offset;
+       //R_Mesh_CacheArray_ValidateState(4);
+
+       /*
+       {
+               int n;
+               for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
+               Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
+       }
+       */
+
+       // make room for the new data (remove old items)
+       lhead = &r_mesh_rcachesequentialchain;
+       l = r_mesh_rcachesequentialchain_current;
+       if (l == lhead)
+               l = l->next;
+       while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
+       {
+       //r_mesh_rcachesequentialchain_current = l;
+       //R_Mesh_CacheArray_ValidateState(8);
+               lnext = l->next;
+               // if at the end of the chain, wrap around
+               if (lnext == lhead)
+                       lnext = lnext->next;
+       //r_mesh_rcachesequentialchain_current = lnext;
+       //R_Mesh_CacheArray_ValidateState(10);
+
+               // unlink from sequential chain
+               l->next->prev = l->prev;
+               l->prev->next = l->next;
+       //R_Mesh_CacheArray_ValidateState(11);
+               // link into free chain
+               l->next = &r_mesh_rcachefreechain;
+               l->prev = l->next->prev;
+               l->next->prev = l->prev->next = l;
+       //R_Mesh_CacheArray_ValidateState(12);
+
+               l = &l->data->hashlink;
+               // unlink from hash chain
+               l->next->prev = l->prev;
+               l->prev->next = l->next;
+
+               l = lnext;
+       //r_mesh_rcachesequentialchain_current = l;
+       //R_Mesh_CacheArray_ValidateState(9);
+       }
+       //r_mesh_rcachesequentialchain_current = l;
+       //R_Mesh_CacheArray_ValidateState(5);
+       // gobble an extra item if we have no free items available
+       if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
+       {
+               lnext = l->next;
+
+               // unlink from sequential chain
+               l->next->prev = l->prev;
+               l->prev->next = l->next;
+               // link into free chain
+               l->next = &r_mesh_rcachefreechain;
+               l->prev = l->next->prev;
+               l->next->prev = l->prev->next = l;
+
+               l = &l->data->hashlink;
+               // unlink from hash chain
+               l->next->prev = l->prev;
+               l->prev->next = l->next;
+
+               l = lnext;
+       }
+       r_mesh_rcachesequentialchain_current = l;
+       //R_Mesh_CacheArray_ValidateState(6);
+
+       // now take an item from the free chain
+       l = r_mesh_rcachefreechain.next;
+       // set it up
+       d = l->data;
+       d->request = *r;
+       d->offset = offset;
+       // unlink
+       l->next->prev = l->prev;
+       l->prev->next = l->next;
+       // relink to sequential
+       l->next = r_mesh_rcachesequentialchain_current->prev;
+       l->prev = l->next->prev;
+       while (l->next->data && l->data && l->next->data->offset <= d->offset)
+       {
+               //Con_Printf(">\n");
+               l->next = l->next->next;
+               l->prev = l->prev->next;
+       }
+       while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
+       {
+               //Con_Printf("<\n");
+               l->prev = l->prev->prev;
+               l->next = l->next->prev;
+       }
+       l->next->prev = l->prev->next = l;
+       // also link into hash chain
+       l = &l->data->hashlink;
+       l->next = &r_mesh_rcachechain[hashindex];
+       l->prev = l->next->prev;
+       l->prev->next = l;
+       l->next->prev = l->prev->next = l;
+
+
+       //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
+
+       //R_Mesh_CacheArray_ValidateState(7);
+       // and finally set the data pointer
+       r->data = r_mesh_rcachedata + d->offset;
+       // and tell the caller to fill the array
+       return true;
+}
+