]> de.git.xonotic.org Git - xonotic/darkplaces.git/blobdiff - gl_backend.c
changed behavior of r_showtris (now only affects geometry in the game view, not sky...
[xonotic/darkplaces.git] / gl_backend.c
index 143387522bf38e72559aa4eb29b9ae71d1b77db1..8e4ec15895bd29c83d50abff0de154e6871041b1 100644 (file)
@@ -4,22 +4,22 @@
 #include "jpeg.h"
 #include "cl_collision.h"
 
-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_paranoid = {0, "gl_paranoid", "0"};
-cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
-cvar_t r_stereo_separation = {0, "r_stereo_separation", "4"};
-cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0"};
-cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0"};
-cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0"};
-cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0"};
-
-cvar_t r_render = {0, "r_render", "1"};
-cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1"};
-cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1"};
-cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
-cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
+cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
+cvar_t gl_mesh_testarrayelement = {0, "gl_mesh_testarrayelement", "0", "use glBegin(GL_TRIANGLES);glArrayElement();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
+cvar_t gl_mesh_testmanualfeeding = {0, "gl_mesh_testmanualfeeding", "0", "use glBegin(GL_TRIANGLES);glTexCoord2f();glVertex3f();glEnd(); primitives instead of glDrawElements (useful to test for driver bugs with glDrawElements)"};
+cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
+cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
+cvar_t r_stereo_separation = {0, "r_stereo_separation", "4", "separation of eyes in the world (try negative values too)"};
+cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0", "side by side views (for those who can't afford glasses but can afford eye strain)"};
+cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
+cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0", "red/cyan anaglyph stereo glasses, the kind given away at drive-in movies like Creature From The Black Lagoon In 3D"};
+cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
+
+cvar_t r_render = {0, "r_render", "1", "enables rendering calls (you want this on!)"};
+cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
+cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
+cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
+cvar_t gl_lockarrays = {0, "gl_lockarrays", "1", "enables use of glLockArraysEXT, may cause glitches with some broken drivers"};
 
 int gl_maxdrawrangeelementsvertices;
 int gl_maxdrawrangeelementsindices;
@@ -73,7 +73,7 @@ void GL_PrintError(int errornumber, char *filename, int linenumber)
 }
 #endif
 
-#define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
+#define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active");
 
 void SCR_ScreenShot_f (void);
 
@@ -83,8 +83,7 @@ static matrix4x4_t backend_modelviewmatrix;
 static matrix4x4_t backend_glmodelviewmatrix;
 static matrix4x4_t backend_projectmatrix;
 
-static int backendunits, backendactive;
-static mempool_t *gl_backend_mempool;
+static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
 
 /*
 note: here's strip order for a terrain row:
@@ -146,20 +145,19 @@ static void R_Mesh_CacheArray_Startup(void);
 static void R_Mesh_CacheArray_Shutdown(void);
 void GL_Backend_AllocArrays(void)
 {
-       if (!gl_backend_mempool)
-               gl_backend_mempool = Mem_AllocPool("GL_Backend", 0, NULL);
        R_Mesh_CacheArray_Startup();
 }
 
 void GL_Backend_FreeArrays(void)
 {
        R_Mesh_CacheArray_Shutdown();
-       Mem_FreePool(&gl_backend_mempool);
 }
 
 static void gl_backend_start(void)
 {
-       Con_Print("OpenGL Backend started\n");
+       Con_Print("OpenGL Backend starting...\n");
+       CHECKGLERROR
+
        if (qglDrawRangeElements != NULL)
        {
                CHECKGLERROR
@@ -171,15 +169,36 @@ static void gl_backend_start(void)
        }
 
        backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
+       backendimageunits = backendunits;
+       backendarrayunits = backendunits;
+       if (gl_support_fragment_shader)
+       {
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (int *)&backendimageunits);
+               CHECKGLERROR
+               qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, (int *)&backendarrayunits);
+               CHECKGLERROR
+               Con_Printf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
+       }
+       else if (backendunits > 1)
+               Con_Printf("multitexture detected: texture units = %i\n", backendunits);
+       else
+               Con_Printf("singletexture\n");
 
        GL_Backend_AllocArrays();
 
+       Con_Printf("OpenGL backend started.\n");
+
+       CHECKGLERROR
+
        backendactive = true;
 }
 
 static void gl_backend_shutdown(void)
 {
        backendunits = 0;
+       backendimageunits = 0;
+       backendarrayunits = 0;
        backendactive = false;
 
        Con_Print("OpenGL Backend shutting down\n");
@@ -191,10 +210,10 @@ static void gl_backend_newmap(void)
 {
 }
 
-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"};
+cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0", "displays a zoomed in overlay window"};
+cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20", "horizontal viewsize of zoom window"};
+cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20", "vertical viewsize of zoom window"};
+cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20", "fov of zoom window"};
 
 void gl_backend_init(void)
 {
@@ -255,9 +274,8 @@ void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
        memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
 }
 
-void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
+void GL_SetupView_Mode_Perspective (double frustumx, double frustumy, double zNear, double zFar)
 {
-       double xmax, ymax;
        double m[16];
 
        if (!r_render.integer)
@@ -266,11 +284,8 @@ void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, doub
        // set up viewpoint
        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
+       qglFrustum(-frustumx * zNear, frustumx * zNear, -frustumy * zNear, frustumy * zNear, zNear, zFar);CHECKGLERROR
        qglGetDoublev(GL_PROJECTION_MATRIX, m);
        backend_projectmatrix.m[0][0] = m[0];
        backend_projectmatrix.m[1][0] = m[1];
@@ -292,7 +307,7 @@ void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, doub
        GL_SetupView_Orientation_Identity();
 }
 
-void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
+void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double frustumx, double frustumy, double zNear)
 {
        double nudge, m[16];
 
@@ -304,12 +319,12 @@ void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, dou
        qglLoadIdentity();CHECKGLERROR
        // set view pyramid
        nudge = 1.0 - 1.0 / (1<<23);
-       m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
+       m[ 0] = 1.0 / frustumx;
        m[ 1] = 0;
        m[ 2] = 0;
        m[ 3] = 0;
        m[ 4] = 0;
-       m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
+       m[ 5] = 1.0 / frustumy;
        m[ 6] = 0;
        m[ 7] = 0;
        m[ 8] = 0;
@@ -377,7 +392,7 @@ typedef struct gltextureunit_s
 {
        int t1d, t2d, t3d, tcubemap;
        int arrayenabled;
-       int arrayis3d;
+       unsigned int arraycomponents;
        const void *pointer_texcoord;
        float rgbscale, alphascale;
        int combinergb, combinealpha;
@@ -388,7 +403,7 @@ typedef struct gltextureunit_s
 }
 gltextureunit_t;
 
-static struct
+static struct gl_state_s
 {
        int blendfunc1;
        int blendfunc2;
@@ -397,8 +412,8 @@ static struct
        int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
        int depthtest;
        int scissortest;
-       int unit;
-       int clientunit;
+       unsigned int unit;
+       unsigned int clientunit;
        gltextureunit_t units[MAX_TEXTUREUNITS];
        float color4f[4];
        int lockrange_first;
@@ -410,22 +425,20 @@ gl_state;
 
 void GL_SetupTextureState(void)
 {
-       int i;
+       unsigned int i;
        gltextureunit_t *unit;
        CHECKGLERROR
-       gl_state.unit = -1;
-       gl_state.clientunit = -1;
-       for (i = 0;i < backendunits;i++)
+       gl_state.unit = MAX_TEXTUREUNITS;
+       gl_state.clientunit = MAX_TEXTUREUNITS;
+       for (i = 0;i < MAX_TEXTUREUNITS;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->arrayenabled = false;
-               unit->arrayis3d = false;
+               unit->arraycomponents = 0;
                unit->pointer_texcoord = NULL;
                unit->rgbscale = 1;
                unit->alphascale = 1;
@@ -433,13 +446,33 @@ void GL_SetupTextureState(void)
                unit->combinealpha = GL_MODULATE;
                unit->texmatrixenabled = false;
                unit->matrix = r_identitymatrix;
-               qglMatrixMode(GL_TEXTURE);
-               qglLoadIdentity();
-               qglMatrixMode(GL_MODELVIEW);
+       }
+
+       for (i = 0;i < backendimageunits;i++)
+       {
+               GL_ActiveTexture(i);
+               qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
+               qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
+               if (gl_texture3d)
+               {
+                       qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
+               }
+               if (gl_texturecubemap)
+               {
+                       qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
+               }
+       }
 
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               GL_ClientActiveTexture(i);
                qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
                qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+       }
 
+       for (i = 0;i < backendunits;i++)
+       {
+               GL_ActiveTexture(i);
                qglDisable(GL_TEXTURE_1D);CHECKGLERROR
                qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                if (gl_texture3d)
@@ -450,6 +483,9 @@ void GL_SetupTextureState(void)
                {
                        qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
                }
+               qglMatrixMode(GL_TEXTURE);
+               qglLoadIdentity();
+               qglMatrixMode(GL_MODELVIEW);
                if (gl_combine.integer)
                {
                        qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
@@ -515,7 +551,7 @@ void GL_Backend_ResetState(void)
        GL_SetupTextureState();
 }
 
-void GL_ActiveTexture(int num)
+void GL_ActiveTexture(unsigned int num)
 {
        if (gl_state.unit != num)
        {
@@ -528,7 +564,7 @@ void GL_ActiveTexture(int num)
        }
 }
 
-void GL_ClientActiveTexture(int num)
+void GL_ClientActiveTexture(unsigned int num)
 {
        if (gl_state.clientunit != num)
        {
@@ -592,7 +628,7 @@ void GL_DepthTest(int state)
 {
        if (gl_state.depthtest != state)
        {
-               if (r_showtrispass)
+               if (r_showtrispass && r_showdisabledepthtest.integer)
                        return;
                gl_state.depthtest = state;
                if (gl_state.depthtest)
@@ -611,8 +647,6 @@ void GL_ColorMask(int r, int g, int b, int a)
        int state = r*8 + g*4 + b*2 + a*1;
        if (gl_state.colormask != state)
        {
-               if (r_showtrispass)
-                       return;
                gl_state.colormask = state;
                qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
        }
@@ -638,9 +672,9 @@ void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
 {
        if (!r_showtrispass)
                return;
-       r_showtrispass = false;
+       r_showtrispass = 0;
        GL_Color(cr * r_showtris.value, cg * r_showtris.value, cb * r_showtris.value, ca);
-       r_showtrispass = true;
+       r_showtrispass = 1;
 }
 
 
@@ -669,7 +703,7 @@ void GL_LockArrays(int first, int count)
 void GL_Scissor (int x, int y, int width, int height)
 {
        CHECKGLERROR
-       qglScissor(x, vid.realheight - (y + height),width,height);
+       qglScissor(x, vid.height - (y + height),width,height);
        CHECKGLERROR
 }
 
@@ -688,8 +722,10 @@ void GL_ScissorTest(int state)
 
 void GL_Clear(int mask)
 {
+       // in showtris rendering, don't clear the color buffer as that would hide
+       // the accumulated lines
        if (r_showtrispass)
-               return;
+               mask &= ~GL_COLOR_BUFFER_BIT;
        qglClear(mask);CHECKGLERROR
 }
 
@@ -713,6 +749,109 @@ void R_Mesh_Start(void)
        GL_Backend_ResetState();
 }
 
+unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
+{
+       GLint vertexshadercompiled, fragmentshadercompiled, programlinked;
+       GLuint vertexshaderobject, fragmentshaderobject, programobject = 0;
+       char compilelog[MAX_INPUTLINE];
+       CHECKGLERROR
+
+       programobject = qglCreateProgramObjectARB();
+       CHECKGLERROR
+       if (!programobject)
+               return 0;
+
+       if (vertexstrings_count)
+       {
+               CHECKGLERROR
+               vertexshaderobject = qglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
+               if (!vertexshaderobject)
+               {
+                       qglDeleteObjectARB(programobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglShaderSourceARB(vertexshaderobject, vertexstrings_count, vertexstrings_list, NULL);
+               qglCompileShaderARB(vertexshaderobject);
+               CHECKGLERROR
+               qglGetObjectParameterivARB(vertexshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &vertexshadercompiled);
+               qglGetInfoLogARB(vertexshaderobject, sizeof(compilelog), NULL, compilelog);
+               if (compilelog[0])
+                       Con_DPrintf("vertex shader compile log:\n%s\n", compilelog);
+               if (!vertexshadercompiled)
+               {
+                       qglDeleteObjectARB(programobject);
+                       qglDeleteObjectARB(vertexshaderobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglAttachObjectARB(programobject, vertexshaderobject);
+               qglDeleteObjectARB(vertexshaderobject);
+               CHECKGLERROR
+       }
+
+       if (fragmentstrings_count)
+       {
+               CHECKGLERROR
+               fragmentshaderobject = qglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
+               if (!fragmentshaderobject)
+               {
+                       qglDeleteObjectARB(programobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglShaderSourceARB(fragmentshaderobject, fragmentstrings_count, fragmentstrings_list, NULL);
+               qglCompileShaderARB(fragmentshaderobject);
+               CHECKGLERROR
+               qglGetObjectParameterivARB(fragmentshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &fragmentshadercompiled);
+               qglGetInfoLogARB(fragmentshaderobject, sizeof(compilelog), NULL, compilelog);
+               if (compilelog[0])
+                       Con_DPrintf("fragment shader compile log:\n%s\n", compilelog);
+               if (!fragmentshadercompiled)
+               {
+                       qglDeleteObjectARB(programobject);
+                       qglDeleteObjectARB(fragmentshaderobject);
+                       CHECKGLERROR
+                       return 0;
+               }
+               qglAttachObjectARB(programobject, fragmentshaderobject);
+               qglDeleteObjectARB(fragmentshaderobject);
+               CHECKGLERROR
+       }
+
+       qglLinkProgramARB(programobject);
+       CHECKGLERROR
+       qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);
+       qglGetInfoLogARB(programobject, sizeof(compilelog), NULL, compilelog);
+       if (compilelog[0])
+       {
+               Con_DPrintf("program link log:\n%s\n", compilelog);
+               // software vertex shader is ok but software fragment shader is WAY
+               // too slow, fail program if so.
+               // NOTE: this string might be ATI specific, but that's ok because the
+               // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
+               // software fragment shader due to low instruction and dependent
+               // texture limits.
+               if (strstr(compilelog, "fragment shader will run in software"))
+                       programlinked = false;
+       }
+       CHECKGLERROR
+       if (!programlinked)
+       {
+               qglDeleteObjectARB(programobject);
+               return 0;
+       }
+       CHECKGLERROR
+       return programobject;
+}
+
+void GL_Backend_FreeProgram(unsigned int prog)
+{
+       CHECKGLERROR
+       qglDeleteObjectARB(prog);
+       CHECKGLERROR
+}
+
 int gl_backend_rebindtextures;
 
 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
@@ -729,55 +868,53 @@ void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
 
 // renders triangles using vertices from the active arrays
 int paranoidblah = 0;
-void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
+void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements)
 {
-       int numelements = numtriangles * 3;
-       if (numverts == 0 || numtriangles == 0)
+       unsigned int numelements = numtriangles * 3;
+       if (numvertices < 3 || numtriangles < 1)
        {
-               Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
+               Con_Printf("R_Mesh_Draw(%d, %d, %d, %08p);\n", firstvertex, numvertices, numtriangles, elements);
                return;
        }
-       CHECKGLERROR
+       //CHECKGLERROR
        if (r_showtrispass)
        {
-               R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
+               R_Mesh_Draw_ShowTris(firstvertex, numvertices, numtriangles, elements);
                return;
        }
-       c_meshs++;
-       c_meshelements += numelements;
+       renderstats.meshes++;
+       renderstats.meshes_elements += numelements;
        if (gl_paranoid.integer)
        {
-               int i, j, size;
+               unsigned int i, j, size;
                const int *p;
                if (!qglIsEnabled(GL_VERTEX_ARRAY))
                        Con_Print("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++)
+               for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
                        paranoidblah += *p;
                if (gl_state.pointer_color)
                {
                        if (!qglIsEnabled(GL_COLOR_ARRAY))
                                Con_Print("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++)
+                       for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
                                paranoidblah += *p;
                }
-               for (i = 0;i < backendunits;i++)
+               for (i = 0;i < backendarrayunits;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)
                        {
-                               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_Print("R_Mesh_Draw: array enabled but no texture bound\n");
                                GL_ClientActiveTexture(i);
                                if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
                                        Con_Print("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++)
+                               for (j = 0, size = numvertices * gl_state.units[i].arraycomponents, p = (int *)((float *)gl_state.units[i].pointer_texcoord + firstvertex * gl_state.units[i].arraycomponents);j < size;j++, p++)
                                        paranoidblah += *p;
                        }
                }
-               for (i = 0;i < numtriangles * 3;i++)
+               for (i = 0;i < (unsigned int) numtriangles * 3;i++)
                {
-                       if (elements[i] < 0 || elements[i] >= numverts)
+                       if (elements[i] < firstvertex || elements[i] >= firstvertex + numvertices)
                        {
-                               Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
+                               Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in elements list\n", elements[i], firstvertex, firstvertex + numvertices);
                                return;
                        }
                }
@@ -788,40 +925,60 @@ void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
                CHECKGLERROR
                if (gl_mesh_testmanualfeeding.integer)
                {
-                       int i, j;
+                       unsigned int i, j;
                        const GLfloat *p;
                        qglBegin(GL_TRIANGLES);
-                       for (i = 0;i < numtriangles * 3;i++)
+                       for (i = 0;i < (unsigned int) numtriangles * 3;i++)
                        {
-                               for (j = 0;j < backendunits;j++)
+                               for (j = 0;j < backendarrayunits;j++)
                                {
                                        if (gl_state.units[j].pointer_texcoord)
                                        {
-                                               if (backendunits > 1)
+                                               if (backendarrayunits > 1)
                                                {
-                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       if (gl_state.units[j].arraycomponents == 4)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
+                                                               qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
+                                                       }
+                                                       else if (gl_state.units[j].arraycomponents == 3)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
                                                                qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].arraycomponents == 2)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
                                                                qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
                                                        }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
+                                                               qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
+                                                       }
                                                }
                                                else
                                                {
-                                                       if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
+                                                       if (gl_state.units[j].arraycomponents == 4)
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
+                                                               qglTexCoord4f(p[0], p[1], p[2], p[3]);
+                                                       }
+                                                       else if (gl_state.units[j].arraycomponents == 3)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
                                                                qglTexCoord3f(p[0], p[1], p[2]);
                                                        }
-                                                       else
+                                                       else if (gl_state.units[j].arraycomponents == 2)
                                                        {
                                                                p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
                                                                qglTexCoord2f(p[0], p[1]);
                                                        }
+                                                       else
+                                                       {
+                                                               p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
+                                                               qglTexCoord1f(p[0]);
+                                                       }
                                                }
                                        }
                                }
@@ -849,32 +1006,48 @@ void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
                }
                else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
                {
-                       qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
+                       qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, elements);
+                       CHECKGLERROR
                }
                else
                {
-                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
+                       qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);
+                       CHECKGLERROR
                }
-               CHECKGLERROR
        }
 }
 
 // restores backend state, used when done with 3D rendering
 void R_Mesh_Finish(void)
 {
-       int i;
+       unsigned int i;
        BACKENDACTIVECHECK
        CHECKGLERROR
        GL_LockArrays(0, 0);
        CHECKGLERROR
 
-       for (i = backendunits - 1;i >= 0;i--)
+       for (i = 0;i < backendimageunits;i++)
        {
-               if (qglActiveTexture)
-                       qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
-               if (qglClientActiveTexture)
-                       qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
+               GL_ActiveTexture(i);
+               qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
+               qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
+               if (gl_texture3d)
+               {
+                       qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
+               }
+               if (gl_texturecubemap)
+               {
+                       qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
+               }
+       }
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               GL_ActiveTexture(backendarrayunits - 1 - i);
                qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+       }
+       for (i = 0;i < backendunits;i++)
+       {
+               GL_ActiveTexture(backendunits - 1 - i);
                qglDisable(GL_TEXTURE_1D);CHECKGLERROR
                qglDisable(GL_TEXTURE_2D);CHECKGLERROR
                if (gl_texture3d)
@@ -912,26 +1085,22 @@ void R_Mesh_Matrix(const matrix4x4_t *matrix)
        }
 }
 
-void R_Mesh_State(const rmeshstate_t *m)
+void R_Mesh_VertexPointer(const float *vertex3f)
 {
-       int i, combinergb, combinealpha, scale;
-       gltextureunit_t *unit;
-       matrix4x4_t tempmatrix;
-
-       BACKENDACTIVECHECK
-
-       if (gl_state.pointer_vertex != m->pointer_vertex)
+       if (gl_state.pointer_vertex != vertex3f)
        {
-               gl_state.pointer_vertex = m->pointer_vertex;
+               gl_state.pointer_vertex = vertex3f;
                CHECKGLERROR
                qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
                CHECKGLERROR
        }
+}
 
+void R_Mesh_ColorPointer(const float *color4f)
+{
        if (r_showtrispass)
                return;
-
-       if (gl_state.pointer_color != m->pointer_color)
+       if (gl_state.pointer_color != color4f)
        {
                CHECKGLERROR
                if (!gl_state.pointer_color)
@@ -939,7 +1108,7 @@ void R_Mesh_State(const rmeshstate_t *m)
                        qglEnableClientState(GL_COLOR_ARRAY);
                        CHECKGLERROR
                }
-               else if (!m->pointer_color)
+               else if (!color4f)
                {
                        qglDisableClientState(GL_COLOR_ARRAY);
                        CHECKGLERROR
@@ -947,235 +1116,537 @@ void R_Mesh_State(const rmeshstate_t *m)
                        qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
                        CHECKGLERROR
                }
-               gl_state.pointer_color = m->pointer_color;
+               gl_state.pointer_color = color4f;
                qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
                CHECKGLERROR
        }
+}
 
-       if (gl_backend_rebindtextures)
+void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       // update array settings
+       if (texcoord)
        {
-               gl_backend_rebindtextures = false;
-               GL_SetupTextureState();
+               // texcoord array
+               if (unit->pointer_texcoord != texcoord || unit->arraycomponents != numcomponents)
+               {
+                       unit->pointer_texcoord = texcoord;
+                       unit->arraycomponents = numcomponents;
+                       GL_ClientActiveTexture(unitnum);
+                       qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, unit->pointer_texcoord);
+                       CHECKGLERROR
+               }
+               // texture array unit is enabled, enable the array
+               if (!unit->arrayenabled)
+               {
+                       unit->arrayenabled = true;
+                       GL_ClientActiveTexture(unitnum);
+                       qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               }
        }
+       else
+       {
+               // texture array unit is disabled, disable the array
+               if (unit->arrayenabled)
+               {
+                       unit->arrayenabled = false;
+                       GL_ClientActiveTexture(unitnum);
+                       qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+               }
+       }
+}
 
-       for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
+void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendimageunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d != tex1d)
        {
-               // update 1d texture binding
-               if (unit->t1d != m->tex1d[i])
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex1d[i])
+                       if (tex1d)
                        {
                                if (unit->t1d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_1D);CHECKGLERROR
-                               }
-                               unit->t1d = m->tex1d[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_1D);
                        }
                        else
                        {
                                if (unit->t1d)
-                               {
-                                       unit->t1d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_1D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_1D);
                        }
                }
-               // update 2d texture binding
-               if (unit->t2d != m->tex[i])
+               unit->t1d = tex1d;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d != tex2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex[i])
+                       if (tex2d)
                        {
                                if (unit->t2d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_2D);CHECKGLERROR
-                               }
-                               unit->t2d = m->tex[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_2D);
                        }
                        else
                        {
                                if (unit->t2d)
-                               {
-                                       unit->t2d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_2D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_2D);
                        }
                }
-               // update 3d texture binding
-               if (unit->t3d != m->tex3d[i])
+               unit->t2d = tex2d;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d != tex3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->tex3d[i])
+                       if (tex3d)
                        {
                                if (unit->t3d == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_3D);CHECKGLERROR
-                               }
-                               unit->t3d = m->tex3d[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_3D);
                        }
                        else
                        {
                                if (unit->t3d)
-                               {
-                                       unit->t3d = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_3D);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_3D);
                        }
                }
-               // update cubemap texture binding
-               if (unit->tcubemap != m->texcubemap[i])
+               unit->t3d = tex3d;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != texcubemap)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       if (m->texcubemap[i])
+                       if (texcubemap)
                        {
                                if (unit->tcubemap == 0)
-                               {
-                                       GL_ActiveTexture(i);
-                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
-                               }
-                               unit->tcubemap = m->texcubemap[i];
-                               GL_ActiveTexture(i);
-                               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
+                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
                        }
                        else
                        {
                                if (unit->tcubemap)
-                               {
-                                       unit->tcubemap = 0;
-                                       GL_ActiveTexture(i);
-                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
-                               }
+                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
                        }
                }
-               // update texture unit settings if the unit is enabled
-               if (unit->t1d || unit->t2d || unit->t3d || unit->tcubemap)
+               unit->tcubemap = texcubemap;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendimageunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       // texture unit is enabled, enable the array
-                       if (!unit->arrayenabled)
-                       {
-                               unit->arrayenabled = true;
-                               GL_ClientActiveTexture(i);
-                               qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
-                       }
-                       // update combine settings
-                       if (gl_combine.integer)
+                       if (texnum)
                        {
-                               // GL_ARB_texture_env_combine
-                               combinergb = m->texcombinergb[i] ? m->texcombinergb[i] : GL_MODULATE;
-                               if (unit->combinergb != combinergb)
-                               {
-                                       unit->combinergb = combinergb;
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
-                               }
-                               combinealpha = m->texcombinealpha[i] ? m->texcombinealpha[i] : GL_MODULATE;
-                               if (unit->combinealpha != combinealpha)
-                               {
-                                       unit->combinealpha = combinealpha;
-                                       GL_ActiveTexture(i);
-                                       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
-                               }
+                               if (unit->t1d == 0)
+                                       qglEnable(GL_TEXTURE_1D);
                        }
                        else
                        {
-                               // normal GL texenv
-                               combinergb = m->texcombinergb[i] ? m->texcombinergb[i] : GL_MODULATE;
-                               if (unit->combinergb != combinergb)
-                               {
-                                       unit->combinergb = combinergb;
-                                       GL_ActiveTexture(i);
-                                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
-                               }
+                               if (unit->t1d)
+                                       qglDisable(GL_TEXTURE_1D);
                        }
-                       // update array settings
-                       if (m->pointer_texcoord3f[i])
+               }
+               unit->t1d = texnum;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t2d)
+                               qglDisable(GL_TEXTURE_2D);
+               }
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t3d)
+                               qglDisable(GL_TEXTURE_3D);
+               }
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->tcubemap)
+                               qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               }
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendimageunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t1d)
+                               qglDisable(GL_TEXTURE_1D);
+               }
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (texnum)
                        {
-                               // 3d texcoord array
-                               if (unit->pointer_texcoord != m->pointer_texcoord3f[i] || !unit->arrayis3d)
-                               {
-                                       unit->pointer_texcoord = m->pointer_texcoord3f[i];
-                                       unit->arrayis3d = true;
-                                       GL_ClientActiveTexture(i);
-                                       qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
-                                       CHECKGLERROR
-                               }
+                               if (unit->t2d == 0)
+                                       qglEnable(GL_TEXTURE_2D);
                        }
                        else
                        {
-                               // 2d texcoord array
-                               if (unit->pointer_texcoord != m->pointer_texcoord[i] || unit->arrayis3d)
-                               {
-                                       unit->pointer_texcoord = m->pointer_texcoord[i];
-                                       unit->arrayis3d = false;
-                                       GL_ClientActiveTexture(i);
-                                       qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
-                                       CHECKGLERROR
-                               }
+                               if (unit->t2d)
+                                       qglDisable(GL_TEXTURE_2D);
                        }
-                       // update texmatrix
-                       if (m->texmatrix[i].m[3][3])
+               }
+               unit->t2d = texnum;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t3d)
+                               qglDisable(GL_TEXTURE_3D);
+               }
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != 0)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->tcubemap)
+                               qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               }
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendimageunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t1d)
+                               qglDisable(GL_TEXTURE_1D);
+               }
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t2d)
+                               qglDisable(GL_TEXTURE_2D);
+               }
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (texnum)
                        {
-                               // texmatrix specified, check if it is different
-                               if (!unit->texmatrixenabled || memcmp(&unit->matrix, &m->texmatrix[i], sizeof(matrix4x4_t)))
-                               {
-                                       unit->texmatrixenabled = true;
-                                       unit->matrix = m->texmatrix[i];
-                                       Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
-                                       qglMatrixMode(GL_TEXTURE);
-                                       GL_ActiveTexture(i);
-                                       qglLoadMatrixf(&tempmatrix.m[0][0]);
-                                       qglMatrixMode(GL_MODELVIEW);
-                               }
+                               if (unit->t3d == 0)
+                                       qglEnable(GL_TEXTURE_3D);
                        }
                        else
                        {
-                               // no texmatrix specified, revert to identity
-                               if (unit->texmatrixenabled)
-                               {
-                                       unit->texmatrixenabled = false;
-                                       qglMatrixMode(GL_TEXTURE);
-                                       GL_ActiveTexture(i);
-                                       qglLoadIdentity();
-                                       qglMatrixMode(GL_MODELVIEW);
-                               }
+                               if (unit->t3d)
+                                       qglDisable(GL_TEXTURE_3D);
                        }
                }
-               else
+               unit->t3d = texnum;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != 0)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->tcubemap)
+                               qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+               }
+               unit->tcubemap = 0;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (unitnum >= backendimageunits)
+               return;
+       if (r_showtrispass)
+               return;
+       // update 1d texture binding
+       if (unit->t1d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t1d)
+                               qglDisable(GL_TEXTURE_1D);
+               }
+               unit->t1d = 0;
+               qglBindTexture(GL_TEXTURE_1D, unit->t1d);
+               CHECKGLERROR
+       }
+       // update 2d texture binding
+       if (unit->t2d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t2d)
+                               qglDisable(GL_TEXTURE_2D);
+               }
+               unit->t2d = 0;
+               qglBindTexture(GL_TEXTURE_2D, unit->t2d);
+               CHECKGLERROR
+       }
+       // update 3d texture binding
+       if (unit->t3d)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
+               {
+                       if (unit->t3d)
+                               qglDisable(GL_TEXTURE_3D);
+               }
+               unit->t3d = 0;
+               qglBindTexture(GL_TEXTURE_3D, unit->t3d);
+               CHECKGLERROR
+       }
+       // update cubemap texture binding
+       if (unit->tcubemap != texnum)
+       {
+               GL_ActiveTexture(unitnum);
+               if (unitnum < backendunits)
                {
-                       // texture unit is disabled, disable the array
-                       if (unit->arrayenabled)
+                       if (texnum)
                        {
-                               unit->arrayenabled = false;
-                               GL_ClientActiveTexture(i);
-                               qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
+                               if (unit->tcubemap == 0)
+                                       qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
                        }
-                       // no need to update most settings on a disabled texture unit
+                       else
+                       {
+                               if (unit->tcubemap)
+                                       qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
+                       }
+               }
+               unit->tcubemap = texnum;
+               qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
+               CHECKGLERROR
+       }
+}
+
+void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       if (matrix->m[3][3])
+       {
+               // texmatrix specified, check if it is different
+               if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
+               {
+                       matrix4x4_t tempmatrix;
+                       unit->texmatrixenabled = true;
+                       unit->matrix = *matrix;
+                       Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
+                       qglMatrixMode(GL_TEXTURE);
+                       GL_ActiveTexture(unitnum);
+                       qglLoadMatrixf(&tempmatrix.m[0][0]);
+                       qglMatrixMode(GL_MODELVIEW);
+               }
+       }
+       else
+       {
+               // no texmatrix specified, revert to identity
+               if (unit->texmatrixenabled)
+               {
+                       unit->texmatrixenabled = false;
+                       qglMatrixMode(GL_TEXTURE);
+                       GL_ActiveTexture(unitnum);
+                       qglLoadIdentity();
+                       qglMatrixMode(GL_MODELVIEW);
+               }
+       }
+}
+
+void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
+{
+       gltextureunit_t *unit = gl_state.units + unitnum;
+       if (r_showtrispass)
+               return;
+       if (gl_combine.integer)
+       {
+               // GL_ARB_texture_env_combine
+               if (!combinergb)
+                       combinergb = GL_MODULATE;
+               if (!combinealpha)
+                       combinealpha = GL_MODULATE;
+               if (!rgbscale)
+                       rgbscale = 1;
+               if (!alphascale)
+                       alphascale = 1;
+               if (unit->combinergb != combinergb)
+               {
+                       unit->combinergb = combinergb;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
+               }
+               if (unit->combinealpha != combinealpha)
+               {
+                       unit->combinealpha = combinealpha;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
+               }
+               if (unit->rgbscale != rgbscale)
+               {
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
+               }
+               if (unit->alphascale != alphascale)
+               {
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
+               }
+       }
+       else
+       {
+               // normal GL texenv
+               if (!combinergb)
+                       combinergb = GL_MODULATE;
+               if (unit->combinergb != combinergb)
+               {
+                       unit->combinergb = combinergb;
+                       GL_ActiveTexture(unitnum);
+                       qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
                }
        }
 }
 
-void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
+void R_Mesh_State(const rmeshstate_t *m)
+{
+       unsigned int i;
+
+       BACKENDACTIVECHECK
+
+       R_Mesh_VertexPointer(m->pointer_vertex);
+       R_Mesh_ColorPointer(m->pointer_color);
+
+       if (gl_backend_rebindtextures)
+       {
+               gl_backend_rebindtextures = false;
+               GL_SetupTextureState();
+       }
+
+       for (i = 0;i < backendimageunits;i++)
+               R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i]);
+       for (i = 0;i < backendarrayunits;i++)
+       {
+               if (m->pointer_texcoord3f[i])
+                       R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i]);
+               else
+                       R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i]);
+       }
+       for (i = 0;i < backendunits;i++)
+       {
+               R_Mesh_TexMatrix(i, &m->texmatrix[i]);
+               R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
+       }
+}
+
+void R_Mesh_Draw_ShowTris(int firstvertex, int numvertices, int numtriangles, const int *elements)
 {
        qglBegin(GL_LINES);
        for (;numtriangles;numtriangles--, elements += 3)
@@ -1196,7 +1667,7 @@ void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
 ==============================================================================
 */
 
-qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg)
+qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, unsigned char *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg, qboolean gammacorrect)
 {
        int     indices[3] = {0,1,2};
        qboolean ret;
@@ -1207,7 +1678,7 @@ qboolean SCR_ScreenShot(char *filename, qbyte *buffer1, qbyte *buffer2, qbyte *b
        qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer1);
        CHECKGLERROR
 
-       if (scr_screenshot_gamma.value != 1)
+       if (scr_screenshot_gamma.value != 1 && gammacorrect)
        {
                int i;
                double igamma = 1.0 / scr_screenshot_gamma.value;
@@ -1235,7 +1706,11 @@ void R_ClearScreen(void)
        if (r_render.integer)
        {
                // clear to black
-               qglClearColor(0,0,0,0);CHECKGLERROR
+               if (fogenabled)
+                       qglClearColor(fogcolor[0],fogcolor[1],fogcolor[2],0);
+               else
+                       qglClearColor(0,0,0,0);
+               CHECKGLERROR
                qglClearDepth(1);CHECKGLERROR
                if (gl_stencil)
                {
@@ -1258,101 +1733,92 @@ void R_ClearScreen(void)
        }
 }
 
-/*
-====================
-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)/vid_pixelaspect.value)*tan(fov_x/360.0*M_PI))*360.0/M_PI; 
-}
+qboolean CL_VM_UpdateView (void);
+void SCR_DrawConsole (void);
 
 int r_stereo_side;
 
 void SCR_DrawScreen (void)
 {
-       for (r_showtrispass = 0;r_showtrispass <= (r_showtris.value > 0);r_showtrispass++)
+       R_Mesh_Start();
+
+       R_TimeReport("setup");
+
+       if (cls.signon == SIGNONS)
        {
-               R_Mesh_Start();
+               float size;
 
-               R_TimeReport("setup");
+               size = scr_viewsize.value * (1.0 / 100.0);
+               size = min(size, 1);
 
-               if (r_showtrispass)
+               if (r_stereo_sidebyside.integer)
                {
-                       rmeshstate_t m;
-                       r_showtrispass = 0;
-                       GL_BlendFunc(GL_ONE, GL_ONE);
-                       GL_DepthTest(GL_FALSE);
-                       GL_DepthMask(GL_FALSE);
-                       memset(&m, 0, sizeof(m));
-                       R_Mesh_State(&m);
-                       GL_ShowTrisColor(0.2,0.2,0.2,1);
-                       r_showtrispass = 1;
+                       r_refdef.width = vid.width * size / 2.5;
+                       r_refdef.height = vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100);
+                       r_refdef.x = (vid.width - r_refdef.width * 2.5) * 0.5;
+                       r_refdef.y = (vid.height - r_refdef.height)/2;
+                       if (r_stereo_side)
+                               r_refdef.x += r_refdef.width * 1.5;
                }
-
-               if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
+               else
                {
-                       float size;
+                       r_refdef.width = vid.width * size;
+                       r_refdef.height = vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100);
+                       r_refdef.x = (vid.width - r_refdef.width)/2;
+                       r_refdef.y = (vid.height - r_refdef.height)/2;
+               }
 
-                       size = scr_viewsize.value * (1.0 / 100.0);
-                       size = min(size, 1);
+               // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
+               // LordHavoc: this is designed to produce widescreen fov values
+               // when the screen is wider than 4/3 width/height aspect, to do
+               // this it simply assumes the requested fov is the vertical fov
+               // for a 4x3 display, if the ratio is not 4x3 this makes the fov
+               // higher/lower according to the ratio
+               r_refdef.frustum_y = tan(scr_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
+               r_refdef.frustum_x = r_refdef.frustum_y * (float)r_refdef.width / (float)r_refdef.height / vid_pixelheight.value;
 
-                       if (r_stereo_sidebyside.integer)
-                       {
-                               r_refdef.width = vid.realwidth * size / 2.5;
-                               r_refdef.height = vid.realheight * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100);
-                               r_refdef.x = (vid.realwidth - r_refdef.width * 2.5) * 0.5;
-                               r_refdef.y = (vid.realheight - r_refdef.height)/2;
-                               if (r_stereo_side)
-                                       r_refdef.x += r_refdef.width * 1.5;
-                       }
-                       else
-                       {
-                               r_refdef.width = vid.realwidth * size;
-                               r_refdef.height = vid.realheight * size * (1 - bound(0, r_letterbox.value, 100) / 100);
-                               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.fovscale_x;
-                       r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
+               r_refdef.frustum_x *= r_refdef.frustumscale_x;
+               r_refdef.frustum_y *= r_refdef.frustumscale_y;
 
+               if(!CL_VM_UpdateView())
                        R_RenderView();
+               else
+                       SCR_DrawConsole();
 
-                       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.fovscale_x;
-                               r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height) * r_refdef.fovscale_y;
+               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.width * sizex;
+                       r_refdef.height = vid.height * sizey;
+                       r_refdef.x = (vid.width - r_refdef.width)/2;
+                       r_refdef.y = 0;
 
+                       r_refdef.frustum_y = tan(scr_zoomwindow_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
+                       r_refdef.frustum_x = r_refdef.frustum_y * vid_pixelheight.value * (float)r_refdef.width / (float)r_refdef.height;
+
+                       r_refdef.frustum_x *= r_refdef.frustumscale_x;
+                       r_refdef.frustum_y *= r_refdef.frustumscale_y;
+
+                       if(!CL_VM_UpdateView())
                                R_RenderView();
-                       }
                }
+       }
 
-               if (!r_stereo_sidebyside.integer)
-               {
-                       r_refdef.width = vid.realwidth;
-                       r_refdef.height = vid.realheight;
-                       r_refdef.x = 0;
-                       r_refdef.y = 0;
-               }
+       if (!r_stereo_sidebyside.integer)
+       {
+               r_refdef.width = vid.width;
+               r_refdef.height = vid.height;
+               r_refdef.x = 0;
+               r_refdef.y = 0;
+       }
 
-               // draw 2D stuff
-               R_DrawQueue();
+       // draw 2D stuff
+       R_DrawQueue();
 
-               R_Mesh_Finish();
+       R_Mesh_Finish();
 
-               R_TimeReport("meshfinish");
-       }
-       r_showtrispass = 0;
+       R_TimeReport("meshfinish");
 }
 
 void SCR_UpdateLoadingScreen (void)
@@ -1364,9 +1830,8 @@ void SCR_UpdateLoadingScreen (void)
        if (vid_hidden)
                return;
        r_showtrispass = 0;
-       VID_GetWindowSize(&vid.realx, &vid.realy, &vid.realwidth, &vid.realheight);
        VID_UpdateGamma(false);
-       qglViewport(0, 0, vid.realwidth, vid.realheight);
+       qglViewport(0, 0, vid.width, vid.height);
        //qglDisable(GL_SCISSOR_TEST);
        //qglDepthMask(1);
        qglColorMask(1,1,1,1);
@@ -1380,7 +1845,7 @@ void SCR_UpdateLoadingScreen (void)
        R_Mesh_Start();
        R_Mesh_Matrix(&r_identitymatrix);
        // draw the loading plaque
-       pic = Draw_CachePic("gfx/loading.lmp");
+       pic = Draw_CachePic("gfx/loading", false);
        x = (vid_conwidth.integer - pic->width)/2;
        y = (vid_conheight.integer - pic->height)/2;
        GL_Color(1,1,1,1);
@@ -1400,7 +1865,7 @@ void SCR_UpdateLoadingScreen (void)
        varray_texcoord2f[0][4] = 1;varray_texcoord2f[0][5] = 1;
        varray_texcoord2f[0][6] = 0;varray_texcoord2f[0][7] = 1;
        GL_LockArrays(0, 4);
-       R_Mesh_Draw(4, 2, polygonelements);
+       R_Mesh_Draw(0, 4, 2, polygonelements);
        GL_LockArrays(0, 0);
        R_Mesh_Finish();
        // refresh
@@ -1425,11 +1890,13 @@ void SCR_UpdateScreen (void)
        if (r_textureunits.integer < 1)
                Cvar_SetValueQuick(&r_textureunits, 1);
 
-       if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
+       if (gl_combine.integer && !gl_combine_extension)
                Cvar_SetValueQuick(&gl_combine, 0);
 
+       r_showtrispass = 0;
+
        CHECKGLERROR
-       qglViewport(0, 0, vid.realwidth, vid.realheight);
+       qglViewport(0, 0, vid.width, vid.height);
        qglDisable(GL_SCISSOR_TEST);
        qglDepthMask(1);
        qglColorMask(1,1,1,1);
@@ -1477,24 +1944,7 @@ void SCR_UpdateScreen (void)
                r_refdef.viewentitymatrix = originalmatrix;
        }
        else
-       {
-               r_showtrispass = false;
                SCR_DrawScreen();
-       
-               if (r_showtris.value > 0)
-               {
-                       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(&m);
-                       r_showtrispass = true;
-                       GL_ShowTrisColor(0.2,0.2,0.2,1);
-                       SCR_DrawScreen();
-                       r_showtrispass = false;
-               }
-       }
 
        VID_Finish();
        R_TimeReport("finish");
@@ -1559,7 +2009,7 @@ 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];
+static unsigned char r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
 
 // current state
 static int r_mesh_rcachedata_offset;
@@ -1620,7 +2070,7 @@ int R_Mesh_CacheArray(rcachearrayrequest_t *r)
        //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;
+       hashindex = CRC_Block((unsigned char *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
 
        // is it already cached?
        for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)