]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_backend.c
implemented a fixed function fallback for water, but it is disabled
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "cl_collision.h"
4
5 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
6 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)"};
7 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)"};
8 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
9 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
10
11 cvar_t r_render = {0, "r_render", "1", "enables rendering calls (you want this on!)"};
12 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
13 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
14 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
15 cvar_t gl_lockarrays = {0, "gl_lockarrays", "0", "enables use of glLockArraysEXT, may cause glitches with some broken drivers, and may be slower than normal"};
16 cvar_t gl_lockarrays_minimumvertices = {0, "gl_lockarrays_minimumvertices", "1", "minimum number of vertices required for use of glLockArraysEXT, setting this too low may reduce performance"};
17 cvar_t gl_vbo = {CVAR_SAVE, "gl_vbo", "1", "make use of GL_ARB_vertex_buffer_object extension to store static geometry in video memory for faster rendering"};
18
19 cvar_t v_flipped = {0, "v_flipped", "0", "mirror the screen (poor man's left handed mode)"};
20 qboolean v_flipped_state = false;
21
22 int gl_maxdrawrangeelementsvertices;
23 int gl_maxdrawrangeelementsindices;
24
25 #ifdef DEBUGGL
26 int errornumber = 0;
27
28 void GL_PrintError(int errornumber, char *filename, int linenumber)
29 {
30         switch(errornumber)
31         {
32 #ifdef GL_INVALID_ENUM
33         case GL_INVALID_ENUM:
34                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
35                 break;
36 #endif
37 #ifdef GL_INVALID_VALUE
38         case GL_INVALID_VALUE:
39                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
40                 break;
41 #endif
42 #ifdef GL_INVALID_OPERATION
43         case GL_INVALID_OPERATION:
44                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
45                 break;
46 #endif
47 #ifdef GL_STACK_OVERFLOW
48         case GL_STACK_OVERFLOW:
49                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
50                 break;
51 #endif
52 #ifdef GL_STACK_UNDERFLOW
53         case GL_STACK_UNDERFLOW:
54                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
55                 break;
56 #endif
57 #ifdef GL_OUT_OF_MEMORY
58         case GL_OUT_OF_MEMORY:
59                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
60                 break;
61 #endif
62 #ifdef GL_TABLE_TOO_LARGE
63         case GL_TABLE_TOO_LARGE:
64                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
65                 break;
66 #endif
67         default:
68                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
69                 break;
70         }
71 }
72 #endif
73
74 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active");
75
76 void SCR_ScreenShot_f (void);
77
78 static matrix4x4_t backend_viewmatrix;
79 static matrix4x4_t backend_modelmatrix;
80 static matrix4x4_t backend_modelviewmatrix;
81 static matrix4x4_t backend_projectmatrix;
82
83 static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
84
85 /*
86 note: here's strip order for a terrain row:
87 0--1--2--3--4
88 |\ |\ |\ |\ |
89 | \| \| \| \|
90 A--B--C--D--E
91 clockwise
92
93 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
94
95 *elements++ = i + row;
96 *elements++ = i;
97 *elements++ = i + row + 1;
98 *elements++ = i;
99 *elements++ = i + 1;
100 *elements++ = i + row + 1;
101
102
103 for (y = 0;y < rows - 1;y++)
104 {
105         for (x = 0;x < columns - 1;x++)
106         {
107                 i = y * rows + x;
108                 *elements++ = i + columns;
109                 *elements++ = i;
110                 *elements++ = i + columns + 1;
111                 *elements++ = i;
112                 *elements++ = i + 1;
113                 *elements++ = i + columns + 1;
114         }
115 }
116
117 alternative:
118 0--1--2--3--4
119 | /| /|\ | /|
120 |/ |/ | \|/ |
121 A--B--C--D--E
122 counterclockwise
123
124 for (y = 0;y < rows - 1;y++)
125 {
126         for (x = 0;x < columns - 1;x++)
127         {
128                 i = y * rows + x;
129                 *elements++ = i;
130                 *elements++ = i + columns;
131                 *elements++ = i + columns + 1;
132                 *elements++ = i + columns;
133                 *elements++ = i + columns + 1;
134                 *elements++ = i + 1;
135         }
136 }
137 */
138
139 int polygonelements[(POLYGONELEMENTS_MAXPOINTS-2)*3];
140 int quadelements[QUADELEMENTS_MAXQUADS*6];
141
142 void GL_Backend_AllocArrays(void)
143 {
144 }
145
146 void GL_Backend_FreeArrays(void)
147 {
148 }
149
150 void GL_VBOStats_f(void)
151 {
152         GL_Mesh_ListVBOs(true);
153 }
154
155 typedef struct gl_bufferobjectinfo_s
156 {
157         int target;
158         int object;
159         size_t size;
160         char name[MAX_QPATH];
161 }
162 gl_bufferobjectinfo_t;
163
164 memexpandablearray_t gl_bufferobjectinfoarray;
165
166 static void gl_backend_start(void)
167 {
168         Con_Print("OpenGL Backend starting...\n");
169         CHECKGLERROR
170
171         if (qglDrawRangeElements != NULL)
172         {
173                 CHECKGLERROR
174                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
175                 CHECKGLERROR
176                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
177                 CHECKGLERROR
178                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
179         }
180
181         backendunits = bound(1, gl_textureunits, MAX_TEXTUREUNITS);
182         backendimageunits = backendunits;
183         backendarrayunits = backendunits;
184         if (gl_support_fragment_shader)
185         {
186                 CHECKGLERROR
187                 qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (int *)&backendimageunits);
188                 CHECKGLERROR
189                 qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, (int *)&backendarrayunits);
190                 CHECKGLERROR
191                 Con_Printf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
192                 backendimageunits = bound(1, backendimageunits, MAX_TEXTUREUNITS);
193                 backendarrayunits = bound(1, backendarrayunits, MAX_TEXTUREUNITS);
194         }
195         else if (backendunits > 1)
196                 Con_Printf("multitexture detected: texture units = %i\n", backendunits);
197         else
198                 Con_Printf("singletexture\n");
199
200         GL_Backend_AllocArrays();
201
202         Mem_ExpandableArray_NewArray(&gl_bufferobjectinfoarray, r_main_mempool, sizeof(gl_bufferobjectinfo_t), 128);
203
204         Con_Printf("OpenGL backend started.\n");
205
206         CHECKGLERROR
207
208         backendactive = true;
209 }
210
211 static void gl_backend_shutdown(void)
212 {
213         backendunits = 0;
214         backendimageunits = 0;
215         backendarrayunits = 0;
216         backendactive = false;
217
218         Con_Print("OpenGL Backend shutting down\n");
219
220         Mem_ExpandableArray_FreeArray(&gl_bufferobjectinfoarray);
221
222         GL_Backend_FreeArrays();
223 }
224
225 static void gl_backend_newmap(void)
226 {
227 }
228
229 void gl_backend_init(void)
230 {
231         int i;
232
233         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
234         {
235                 polygonelements[i * 3 + 0] = 0;
236                 polygonelements[i * 3 + 1] = i + 1;
237                 polygonelements[i * 3 + 2] = i + 2;
238         }
239         // elements for rendering a series of quads as triangles
240         for (i = 0;i < QUADELEMENTS_MAXQUADS;i++)
241         {
242                 quadelements[i * 6 + 0] = i * 4;
243                 quadelements[i * 6 + 1] = i * 4 + 1;
244                 quadelements[i * 6 + 2] = i * 4 + 2;
245                 quadelements[i * 6 + 3] = i * 4;
246                 quadelements[i * 6 + 4] = i * 4 + 2;
247                 quadelements[i * 6 + 5] = i * 4 + 3;
248         }
249
250         Cvar_RegisterVariable(&r_render);
251         Cvar_RegisterVariable(&r_waterwarp);
252         Cvar_RegisterVariable(&gl_polyblend);
253         Cvar_RegisterVariable(&v_flipped);
254         Cvar_RegisterVariable(&gl_dither);
255         Cvar_RegisterVariable(&gl_lockarrays);
256         Cvar_RegisterVariable(&gl_lockarrays_minimumvertices);
257         Cvar_RegisterVariable(&gl_vbo);
258         Cvar_RegisterVariable(&gl_paranoid);
259         Cvar_RegisterVariable(&gl_printcheckerror);
260 #ifdef NORENDER
261         Cvar_SetValue("r_render", 0);
262 #endif
263
264         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
265         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
266         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
267
268         Cmd_AddCommand("gl_vbostats", GL_VBOStats_f, "prints a list of all buffer objects (vertex data and triangle elements) and total video memory used by them\n");
269
270         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
271 }
272
273 void GL_SetMirrorState(qboolean state);
274
275 void GL_SetupView_Orientation_Identity (void)
276 {
277         backend_viewmatrix = identitymatrix;
278         GL_SetMirrorState(false);
279         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
280 }
281
282 void GL_SetupView_Orientation_FromEntity(const matrix4x4_t *matrix)
283 {
284         matrix4x4_t tempmatrix, basematrix;
285         Matrix4x4_Invert_Full(&tempmatrix, matrix);
286         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
287         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
288         Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
289
290         GL_SetMirrorState(v_flipped.integer);
291         if(v_flipped_state)
292         {
293                 Matrix4x4_Transpose(&basematrix, &backend_viewmatrix);
294                 Matrix4x4_ConcatScale3(&basematrix, -1, 1, 1);
295                 Matrix4x4_Transpose(&backend_viewmatrix, &basematrix);
296         }
297
298         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
299         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
300         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
301         //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
302         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
303 }
304
305 void GL_SetupView_Mode_Perspective (double frustumx, double frustumy, double zNear, double zFar)
306 {
307         double m[16];
308
309         // set up viewpoint
310         CHECKGLERROR
311         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
312         qglLoadIdentity();CHECKGLERROR
313         // set view pyramid
314         qglFrustum(-frustumx * zNear, frustumx * zNear, -frustumy * zNear, frustumy * zNear, zNear, zFar);CHECKGLERROR
315         qglGetDoublev(GL_PROJECTION_MATRIX, m);CHECKGLERROR
316         Matrix4x4_FromArrayDoubleGL(&backend_projectmatrix, m);
317         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
318         GL_SetupView_Orientation_Identity();
319         CHECKGLERROR
320 }
321
322 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double frustumx, double frustumy, double zNear)
323 {
324         double nudge, m[16];
325
326         // set up viewpoint
327         CHECKGLERROR
328         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
329         qglLoadIdentity();CHECKGLERROR
330         // set view pyramid
331         nudge = 1.0 - 1.0 / (1<<23);
332         m[ 0] = 1.0 / frustumx;
333         m[ 1] = 0;
334         m[ 2] = 0;
335         m[ 3] = 0;
336         m[ 4] = 0;
337         m[ 5] = 1.0 / frustumy;
338         m[ 6] = 0;
339         m[ 7] = 0;
340         m[ 8] = 0;
341         m[ 9] = 0;
342         m[10] = -nudge;
343         m[11] = -1;
344         m[12] = 0;
345         m[13] = 0;
346         m[14] = -2 * zNear * nudge;
347         m[15] = 0;
348         qglLoadMatrixd(m);CHECKGLERROR
349         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
350         GL_SetupView_Orientation_Identity();
351         CHECKGLERROR
352         Matrix4x4_FromArrayDoubleGL(&backend_projectmatrix, m);
353 }
354
355 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
356 {
357         double m[16];
358
359         // set up viewpoint
360         CHECKGLERROR
361         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
362         qglLoadIdentity();CHECKGLERROR
363         qglOrtho(x1, x2, y2, y1, zNear, zFar);CHECKGLERROR
364         qglGetDoublev(GL_PROJECTION_MATRIX, m);CHECKGLERROR
365         Matrix4x4_FromArrayDoubleGL(&backend_projectmatrix, m);
366         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
367         GL_SetupView_Orientation_Identity();
368         CHECKGLERROR
369 }
370
371 void GL_SetupView_ApplyCustomNearClipPlane(double normalx, double normaly, double normalz, double dist)
372 {
373         double matrix[16];
374         double q[4];
375         double d;
376         float clipPlane[4], v3[3], v4[3];
377         float normal[3];
378
379         // This is Olique Depth Projection from http://www.terathon.com/code/oblique.php
380         // modified to fit in this codebase.
381
382         VectorSet(normal, normalx, normaly, normalz);
383         Matrix4x4_Transform3x3(&backend_viewmatrix, normal, clipPlane);
384         VectorScale(normal, dist, v3);
385         Matrix4x4_Transform(&backend_viewmatrix, v3, v4);
386         // FIXME: LordHavoc: I think this can be done more efficiently somehow but I can't remember the technique
387         clipPlane[3] = -DotProduct(v4, clipPlane);
388
389 #if 0
390 {
391         // testing code for comparing results
392         float clipPlane2[4];
393         VectorCopy4(clipPlane, clipPlane2);
394         R_Mesh_Matrix(&identitymatrix);
395         VectorSet(q, normal[0], normal[1], normal[2], -dist);
396         qglClipPlane(GL_CLIP_PLANE0, q);
397         qglGetClipPlane(GL_CLIP_PLANE0, q);
398         VectorCopy4(q, clipPlane);
399 }
400 #endif
401
402         // Calculate the clip-space corner point opposite the clipping plane
403         // as (sgn(clipPlane.x), sgn(clipPlane.y), 1, 1) and
404         // transform it into camera space by multiplying it
405         // by the inverse of the projection matrix
406         Matrix4x4_ToArrayDoubleGL(&backend_projectmatrix, matrix);
407
408         q[0] = ((clipPlane[0] < 0.0f ? -1.0f : clipPlane[0] > 0.0f ? 1.0f : 0.0f) + matrix[8]) / matrix[0];
409         q[1] = ((clipPlane[1] < 0.0f ? -1.0f : clipPlane[1] > 0.0f ? 1.0f : 0.0f) + matrix[9]) / matrix[5];
410         q[2] = -1.0f;
411         q[3] = (1.0f + matrix[10]) / matrix[14];
412
413         // Calculate the scaled plane vector
414         d = 2.0f / DotProduct4(clipPlane, q);
415
416         // Replace the third row of the projection matrix
417         matrix[2] = clipPlane[0] * d;
418         matrix[6] = clipPlane[1] * d;
419         matrix[10] = clipPlane[2] * d + 1.0f;
420         matrix[14] = clipPlane[3] * d;
421
422         // Load it back into OpenGL
423         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
424         qglLoadMatrixd(matrix);CHECKGLERROR
425         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
426         CHECKGLERROR
427         Matrix4x4_FromArrayDoubleGL(&backend_projectmatrix, matrix);
428 }
429
430 typedef struct gltextureunit_s
431 {
432         const void *pointer_texcoord;
433         size_t pointer_texcoord_offset;
434         int pointer_texcoord_buffer;
435         int t1d, t2d, t3d, tcubemap;
436         int arrayenabled;
437         unsigned int arraycomponents;
438         int rgbscale, alphascale;
439         int combinergb, combinealpha;
440         // FIXME: add more combine stuff
441         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
442         int texmatrixenabled;
443         matrix4x4_t matrix;
444 }
445 gltextureunit_t;
446
447 static struct gl_state_s
448 {
449         int cullface;
450         int cullfaceenable;
451         int blendfunc1;
452         int blendfunc2;
453         int blend;
454         GLboolean depthmask;
455         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
456         int depthtest;
457         float depthrange[2];
458         float polygonoffset[2];
459         int alphatest;
460         int scissortest;
461         unsigned int unit;
462         unsigned int clientunit;
463         gltextureunit_t units[MAX_TEXTUREUNITS];
464         float color4f[4];
465         int lockrange_first;
466         int lockrange_count;
467         int vertexbufferobject;
468         int elementbufferobject;
469         qboolean pointer_color_enabled;
470         const void *pointer_vertex;
471         const void *pointer_color;
472         size_t pointer_vertex_offset;
473         size_t pointer_color_offset;
474         int pointer_vertex_buffer;
475         int pointer_color_buffer;
476 }
477 gl_state;
478
479 static void GL_BindVBO(int bufferobject)
480 {
481         if (gl_state.vertexbufferobject != bufferobject)
482         {
483                 gl_state.vertexbufferobject = bufferobject;
484                 CHECKGLERROR
485                 qglBindBufferARB(GL_ARRAY_BUFFER_ARB, bufferobject);
486                 CHECKGLERROR
487         }
488 }
489
490 static void GL_BindEBO(int bufferobject)
491 {
492         if (gl_state.elementbufferobject != bufferobject)
493         {
494                 gl_state.elementbufferobject = bufferobject;
495                 CHECKGLERROR
496                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, bufferobject);
497                 CHECKGLERROR
498         }
499 }
500
501 void GL_SetupTextureState(void)
502 {
503         unsigned int i;
504         gltextureunit_t *unit;
505         CHECKGLERROR
506         gl_state.unit = MAX_TEXTUREUNITS;
507         gl_state.clientunit = MAX_TEXTUREUNITS;
508         for (i = 0;i < MAX_TEXTUREUNITS;i++)
509         {
510                 unit = gl_state.units + i;
511                 unit->t1d = 0;
512                 unit->t2d = 0;
513                 unit->t3d = 0;
514                 unit->tcubemap = 0;
515                 unit->arrayenabled = false;
516                 unit->arraycomponents = 0;
517                 unit->pointer_texcoord = NULL;
518                 unit->pointer_texcoord_buffer = 0;
519                 unit->pointer_texcoord_offset = 0;
520                 unit->rgbscale = 1;
521                 unit->alphascale = 1;
522                 unit->combinergb = GL_MODULATE;
523                 unit->combinealpha = GL_MODULATE;
524                 unit->texmatrixenabled = false;
525                 unit->matrix = identitymatrix;
526         }
527
528         for (i = 0;i < backendimageunits;i++)
529         {
530                 GL_ActiveTexture(i);
531                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
532                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
533                 if (gl_texture3d)
534                 {
535                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
536                 }
537                 if (gl_texturecubemap)
538                 {
539                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
540                 }
541         }
542
543         for (i = 0;i < backendarrayunits;i++)
544         {
545                 GL_ClientActiveTexture(i);
546                 GL_BindVBO(0);
547                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
548                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
549         }
550
551         for (i = 0;i < backendunits;i++)
552         {
553                 GL_ActiveTexture(i);
554                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
555                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
556                 if (gl_texture3d)
557                 {
558                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
559                 }
560                 if (gl_texturecubemap)
561                 {
562                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
563                 }
564                 qglMatrixMode(GL_TEXTURE);CHECKGLERROR
565                 qglLoadIdentity();CHECKGLERROR
566                 qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
567                 if (gl_combine.integer)
568                 {
569                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
570                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
571                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
572                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
573                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
574                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
575                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
576                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
577                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
578                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
579                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
580                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
581                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
582                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
583                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
584                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
585                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
586                 }
587                 else
588                 {
589                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
590                 }
591                 CHECKGLERROR
592         }
593         CHECKGLERROR
594 }
595
596 void GL_Backend_ResetState(void)
597 {
598         memset(&gl_state, 0, sizeof(gl_state));
599         gl_state.depthtest = true;
600         gl_state.alphatest = false;
601         gl_state.blendfunc1 = GL_ONE;
602         gl_state.blendfunc2 = GL_ZERO;
603         gl_state.blend = false;
604         gl_state.depthmask = GL_TRUE;
605         gl_state.colormask = 15;
606         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
607         gl_state.lockrange_first = 0;
608         gl_state.lockrange_count = 0;
609         gl_state.cullface = v_flipped_state ? GL_BACK : GL_FRONT; // quake is backwards, this culls back faces
610         gl_state.cullfaceenable = true;
611         gl_state.polygonoffset[0] = 0;
612         gl_state.polygonoffset[1] = 0;
613
614         CHECKGLERROR
615
616         qglColorMask(1, 1, 1, 1);
617         qglAlphaFunc(GL_GEQUAL, 0.5);CHECKGLERROR
618         qglDisable(GL_ALPHA_TEST);CHECKGLERROR
619         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
620         qglDisable(GL_BLEND);CHECKGLERROR
621         qglCullFace(gl_state.cullface);CHECKGLERROR
622         qglEnable(GL_CULL_FACE);CHECKGLERROR
623         qglDepthFunc(GL_LEQUAL);CHECKGLERROR
624         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
625         qglDepthMask(gl_state.depthmask);CHECKGLERROR
626         qglPolygonOffset(gl_state.polygonoffset[0], gl_state.polygonoffset[1]);
627
628         if (gl_support_arb_vertex_buffer_object)
629         {
630                 qglBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);
631                 qglBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, 0);
632         }
633
634         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
635         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
636
637         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
638         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
639
640         GL_Color(0, 0, 0, 0);
641         GL_Color(1, 1, 1, 1);
642
643         GL_SetupTextureState();
644 }
645
646 void GL_ActiveTexture(unsigned int num)
647 {
648         if (gl_state.unit != num)
649         {
650                 gl_state.unit = num;
651                 if (qglActiveTexture)
652                 {
653                         CHECKGLERROR
654                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
655                         CHECKGLERROR
656                 }
657         }
658 }
659
660 void GL_ClientActiveTexture(unsigned int num)
661 {
662         if (gl_state.clientunit != num)
663         {
664                 gl_state.clientunit = num;
665                 if (qglActiveTexture)
666                 {
667                         CHECKGLERROR
668                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
669                         CHECKGLERROR
670                 }
671         }
672 }
673
674 void GL_BlendFunc(int blendfunc1, int blendfunc2)
675 {
676         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
677         {
678                 CHECKGLERROR
679                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
680                 if (gl_state.blendfunc2 == GL_ZERO)
681                 {
682                         if (gl_state.blendfunc1 == GL_ONE)
683                         {
684                                 if (gl_state.blend)
685                                 {
686                                         gl_state.blend = 0;
687                                         qglDisable(GL_BLEND);CHECKGLERROR
688                                 }
689                         }
690                         else
691                         {
692                                 if (!gl_state.blend)
693                                 {
694                                         gl_state.blend = 1;
695                                         qglEnable(GL_BLEND);CHECKGLERROR
696                                 }
697                         }
698                 }
699                 else
700                 {
701                         if (!gl_state.blend)
702                         {
703                                 gl_state.blend = 1;
704                                 qglEnable(GL_BLEND);CHECKGLERROR
705                         }
706                 }
707         }
708 }
709
710 void GL_DepthMask(int state)
711 {
712         if (gl_state.depthmask != state)
713         {
714                 CHECKGLERROR
715                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
716         }
717 }
718
719 void GL_DepthTest(int state)
720 {
721         if (gl_state.depthtest != state)
722         {
723                 gl_state.depthtest = state;
724                 CHECKGLERROR
725                 if (gl_state.depthtest)
726                 {
727                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
728                 }
729                 else
730                 {
731                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
732                 }
733         }
734 }
735
736 void GL_DepthRange(float nearfrac, float farfrac)
737 {
738         if (gl_state.depthrange[0] != nearfrac || gl_state.depthrange[1] != farfrac)
739         {
740                 gl_state.depthrange[0] = nearfrac;
741                 gl_state.depthrange[1] = farfrac;
742                 qglDepthRange(nearfrac, farfrac);
743         }
744 }
745
746 void GL_PolygonOffset(float planeoffset, float depthoffset)
747 {
748         if (gl_state.polygonoffset[0] != planeoffset || gl_state.polygonoffset[1] != depthoffset)
749         {
750                 gl_state.polygonoffset[0] = planeoffset;
751                 gl_state.polygonoffset[1] = depthoffset;
752                 qglPolygonOffset(planeoffset, depthoffset);
753         }
754 }
755
756 void GL_SetMirrorState(qboolean state)
757 {
758         if(!state != !v_flipped_state)
759         {
760                 // change cull face mode!
761                 if(gl_state.cullface == GL_BACK)
762                         qglCullFace((gl_state.cullface = GL_FRONT));
763                 else if(gl_state.cullface == GL_FRONT)
764                         qglCullFace((gl_state.cullface = GL_BACK));
765         }
766         v_flipped_state = state;
767 }
768
769 void GL_CullFace(int state)
770 {
771         CHECKGLERROR
772
773         if(v_flipped_state)
774         {
775                 if(state == GL_FRONT)
776                         state = GL_BACK;
777                 else if(state == GL_BACK)
778                         state = GL_FRONT;
779         }
780
781         if (state != GL_NONE)
782         {
783                 if (!gl_state.cullfaceenable)
784                 {
785                         gl_state.cullfaceenable = true;
786                         qglEnable(GL_CULL_FACE);CHECKGLERROR
787                 }
788                 if (gl_state.cullface != state)
789                 {
790                         gl_state.cullface = state;
791                         qglCullFace(gl_state.cullface);CHECKGLERROR
792                 }
793         }
794         else
795         {
796                 if (gl_state.cullfaceenable)
797                 {
798                         gl_state.cullfaceenable = false;
799                         qglDisable(GL_CULL_FACE);CHECKGLERROR
800                 }
801         }
802 }
803
804 void GL_AlphaTest(int state)
805 {
806         if (gl_state.alphatest != state)
807         {
808                 gl_state.alphatest = state;
809                 CHECKGLERROR
810                 if (gl_state.alphatest)
811                 {
812                         qglEnable(GL_ALPHA_TEST);CHECKGLERROR
813                 }
814                 else
815                 {
816                         qglDisable(GL_ALPHA_TEST);CHECKGLERROR
817                 }
818         }
819 }
820
821 void GL_ColorMask(int r, int g, int b, int a)
822 {
823         int state = r*8 + g*4 + b*2 + a*1;
824         if (gl_state.colormask != state)
825         {
826                 gl_state.colormask = state;
827                 CHECKGLERROR
828                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
829         }
830 }
831
832 void GL_Color(float cr, float cg, float cb, float ca)
833 {
834         if (gl_state.pointer_color_enabled || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
835         {
836                 gl_state.color4f[0] = cr;
837                 gl_state.color4f[1] = cg;
838                 gl_state.color4f[2] = cb;
839                 gl_state.color4f[3] = ca;
840                 CHECKGLERROR
841                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
842                 CHECKGLERROR
843         }
844 }
845
846 void GL_LockArrays(int first, int count)
847 {
848         if (count < gl_lockarrays_minimumvertices.integer)
849         {
850                 first = 0;
851                 count = 0;
852         }
853         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
854         {
855                 if (gl_state.lockrange_count)
856                 {
857                         gl_state.lockrange_count = 0;
858                         CHECKGLERROR
859                         qglUnlockArraysEXT();
860                         CHECKGLERROR
861                 }
862                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
863                 {
864                         gl_state.lockrange_first = first;
865                         gl_state.lockrange_count = count;
866                         CHECKGLERROR
867                         qglLockArraysEXT(first, count);
868                         CHECKGLERROR
869                 }
870         }
871 }
872
873 void GL_Scissor (int x, int y, int width, int height)
874 {
875         CHECKGLERROR
876         qglScissor(x, vid.height - (y + height),width,height);
877         CHECKGLERROR
878 }
879
880 void GL_ScissorTest(int state)
881 {
882         if(gl_state.scissortest == state)
883                 return;
884
885         CHECKGLERROR
886         if((gl_state.scissortest = state))
887                 qglEnable(GL_SCISSOR_TEST);
888         else
889                 qglDisable(GL_SCISSOR_TEST);
890         CHECKGLERROR
891 }
892
893 void GL_Clear(int mask)
894 {
895         CHECKGLERROR
896         qglClear(mask);CHECKGLERROR
897 }
898
899 void GL_TransformToScreen(const vec4_t in, vec4_t out)
900 {
901         vec4_t temp;
902         float iw;
903         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
904         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
905         iw = 1.0f / out[3];
906         out[0] = r_view.x + (out[0] * iw + 1.0f) * r_view.width * 0.5f;
907         out[1] = r_view.y + r_view.height - (out[1] * iw + 1.0f) * r_view.height * 0.5f;
908         out[2] = r_view.z + (out[2] * iw + 1.0f) * r_view.depth * 0.5f;
909 }
910
911 /*
912 void GL_TransformToScreenTexCoords(int numverts, const float *in3f, float *out2f, float scalex, float scaley, float basex, float basey)
913 {
914         int i;
915         vec4_t in, temp;
916         float iw;
917         matrix4x4_t mat;
918         in[3] = 1;
919         Matrix4x4_Concat(&mat, &backend_projectmatrix, &backend_viewmatrix);
920         for (i = 0;i < numverts;i++)
921         {
922                 VectorCopy(in3f + i * 3, in);
923                 Matrix4x4_Transform4 (&mat, in, temp);
924                 iw = 1.0f / temp[3];
925                 out2f[i*2+0] = (temp[0] * iw) * scalex + basex;
926                 out2f[i*2+1] = (temp[1] * iw) * scaley + basey;
927         }
928 }
929 */
930
931 // called at beginning of frame
932 void R_Mesh_Start(void)
933 {
934         BACKENDACTIVECHECK
935         CHECKGLERROR
936         if (gl_printcheckerror.integer && !gl_paranoid.integer)
937         {
938                 Con_Printf("WARNING: gl_printcheckerror is on but gl_paranoid is off, turning it on...\n");
939                 Cvar_SetValueQuick(&gl_paranoid, 1);
940         }
941         GL_Backend_ResetState();
942 }
943
944 qboolean GL_Backend_CompileShader(int programobject, GLenum shadertypeenum, const char *shadertype, int numstrings, const char **strings)
945 {
946         int shaderobject;
947         int shadercompiled;
948         char compilelog[MAX_INPUTLINE];
949         shaderobject = qglCreateShaderObjectARB(shadertypeenum);CHECKGLERROR
950         if (!shaderobject)
951                 return false;
952         qglShaderSourceARB(shaderobject, numstrings, strings, NULL);CHECKGLERROR
953         qglCompileShaderARB(shaderobject);CHECKGLERROR
954         qglGetObjectParameterivARB(shaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &shadercompiled);CHECKGLERROR
955         qglGetInfoLogARB(shaderobject, sizeof(compilelog), NULL, compilelog);CHECKGLERROR
956         if (compilelog[0])
957                 Con_DPrintf("%s shader compile log:\n%s\n", shadertype, compilelog);
958         if (!shadercompiled)
959         {
960                 qglDeleteObjectARB(shaderobject);CHECKGLERROR
961                 return false;
962         }
963         qglAttachObjectARB(programobject, shaderobject);CHECKGLERROR
964         qglDeleteObjectARB(shaderobject);CHECKGLERROR
965         return true;
966 }
967
968 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int geometrystrings_count, const char **geometrystrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
969 {
970         GLint programlinked;
971         GLuint programobject = 0;
972         char linklog[MAX_INPUTLINE];
973         CHECKGLERROR
974
975         programobject = qglCreateProgramObjectARB();CHECKGLERROR
976         if (!programobject)
977                 return 0;
978
979         if (vertexstrings_count && !GL_Backend_CompileShader(programobject, GL_VERTEX_SHADER_ARB, "vertex", vertexstrings_count, vertexstrings_list))
980                 goto cleanup;
981
982 #ifdef GL_GEOMETRY_SHADER_ARB
983         if (geometrystrings_count && !GL_Backend_CompileShader(programobject, GL_GEOMETRY_SHADER_ARB, "geometry", geometrystrings_count, geometrystrings_list))
984                 goto cleanup;
985 #endif
986
987         if (fragmentstrings_count && !GL_Backend_CompileShader(programobject, GL_FRAGMENT_SHADER_ARB, "fragment", fragmentstrings_count, fragmentstrings_list))
988                 goto cleanup;
989
990         qglLinkProgramARB(programobject);CHECKGLERROR
991         qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);CHECKGLERROR
992         qglGetInfoLogARB(programobject, sizeof(linklog), NULL, linklog);CHECKGLERROR
993         if (linklog[0])
994         {
995                 Con_DPrintf("program link log:\n%s\n", linklog);
996                 // software vertex shader is ok but software fragment shader is WAY
997                 // too slow, fail program if so.
998                 // NOTE: this string might be ATI specific, but that's ok because the
999                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
1000                 // software fragment shader due to low instruction and dependent
1001                 // texture limits.
1002                 if (strstr(linklog, "fragment shader will run in software"))
1003                         programlinked = false;
1004         }
1005         if (!programlinked)
1006                 goto cleanup;
1007         return programobject;
1008 cleanup:
1009         qglDeleteObjectARB(programobject);CHECKGLERROR
1010         return 0;
1011 }
1012
1013 void GL_Backend_FreeProgram(unsigned int prog)
1014 {
1015         CHECKGLERROR
1016         qglDeleteObjectARB(prog);
1017         CHECKGLERROR
1018 }
1019
1020 int gl_backend_rebindtextures;
1021
1022 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
1023 {
1024         int i;
1025         if (offset)
1026         {
1027                 for (i = 0;i < count;i++)
1028                         *out++ = *in++ + offset;
1029         }
1030         else
1031                 memcpy(out, in, sizeof(*out) * count);
1032 }
1033
1034 // renders triangles using vertices from the active arrays
1035 int paranoidblah = 0;
1036 void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements, int bufferobject, size_t bufferoffset)
1037 {
1038         unsigned int numelements = numtriangles * 3;
1039         if (numvertices < 3 || numtriangles < 1)
1040         {
1041                 Con_Printf("R_Mesh_Draw(%d, %d, %d, %8p, %i, %p);\n", firstvertex, numvertices, numtriangles, elements, bufferobject, (void *)bufferoffset);
1042                 return;
1043         }
1044         if (!gl_vbo.integer)
1045                 bufferobject = 0;
1046         CHECKGLERROR
1047         r_refdef.stats.meshes++;
1048         r_refdef.stats.meshes_elements += numelements;
1049         if (gl_paranoid.integer)
1050         {
1051                 unsigned int i, j, size;
1052                 const int *p;
1053                 // note: there's no validation done here on buffer objects because it
1054                 // is somewhat difficult to get at the data, and gl_paranoid can be
1055                 // used without buffer objects if the need arises
1056                 // (the data could be gotten using glMapBuffer but it would be very
1057                 //  slow due to uncachable video memory reads)
1058                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
1059                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
1060                 CHECKGLERROR
1061                 if (gl_state.pointer_vertex)
1062                         for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
1063                                 paranoidblah += *p;
1064                 if (gl_state.pointer_color_enabled)
1065                 {
1066                         if (!qglIsEnabled(GL_COLOR_ARRAY))
1067                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
1068                         CHECKGLERROR
1069                         if (gl_state.pointer_color && gl_state.pointer_color_enabled)
1070                                 for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
1071                                         paranoidblah += *p;
1072                 }
1073                 for (i = 0;i < backendarrayunits;i++)
1074                 {
1075                         if (gl_state.units[i].arrayenabled)
1076                         {
1077                                 GL_ClientActiveTexture(i);
1078                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
1079                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
1080                                 CHECKGLERROR
1081                                 if (gl_state.units[i].pointer_texcoord && gl_state.units[i].arrayenabled)
1082                                         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++)
1083                                                 paranoidblah += *p;
1084                         }
1085                 }
1086                 for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1087                 {
1088                         if (elements[i] < firstvertex || elements[i] >= firstvertex + numvertices)
1089                         {
1090                                 Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in elements list\n", elements[i], firstvertex, firstvertex + numvertices);
1091                                 return;
1092                         }
1093                 }
1094                 CHECKGLERROR
1095         }
1096         if (r_render.integer)
1097         {
1098                 CHECKGLERROR
1099                 if (gl_mesh_testmanualfeeding.integer)
1100                 {
1101                         unsigned int i, j;
1102                         const GLfloat *p;
1103                         qglBegin(GL_TRIANGLES);
1104                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
1105                         {
1106                                 for (j = 0;j < backendarrayunits;j++)
1107                                 {
1108                                         if (gl_state.units[j].pointer_texcoord && gl_state.units[j].arrayenabled)
1109                                         {
1110                                                 if (backendarrayunits > 1)
1111                                                 {
1112                                                         if (gl_state.units[j].arraycomponents == 4)
1113                                                         {
1114                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
1115                                                                 qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
1116                                                         }
1117                                                         else if (gl_state.units[j].arraycomponents == 3)
1118                                                         {
1119                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
1120                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
1121                                                         }
1122                                                         else if (gl_state.units[j].arraycomponents == 2)
1123                                                         {
1124                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
1125                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
1126                                                         }
1127                                                         else
1128                                                         {
1129                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
1130                                                                 qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
1131                                                         }
1132                                                 }
1133                                                 else
1134                                                 {
1135                                                         if (gl_state.units[j].arraycomponents == 4)
1136                                                         {
1137                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
1138                                                                 qglTexCoord4f(p[0], p[1], p[2], p[3]);
1139                                                         }
1140                                                         else if (gl_state.units[j].arraycomponents == 3)
1141                                                         {
1142                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
1143                                                                 qglTexCoord3f(p[0], p[1], p[2]);
1144                                                         }
1145                                                         else if (gl_state.units[j].arraycomponents == 2)
1146                                                         {
1147                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
1148                                                                 qglTexCoord2f(p[0], p[1]);
1149                                                         }
1150                                                         else
1151                                                         {
1152                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
1153                                                                 qglTexCoord1f(p[0]);
1154                                                         }
1155                                                 }
1156                                         }
1157                                 }
1158                                 if (gl_state.pointer_color && gl_state.pointer_color_enabled)
1159                                 {
1160                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
1161                                         qglColor4f(p[0], p[1], p[2], p[3]);
1162                                 }
1163                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
1164                                 qglVertex3f(p[0], p[1], p[2]);
1165                         }
1166                         qglEnd();
1167                         CHECKGLERROR
1168                 }
1169                 else if (gl_mesh_testarrayelement.integer)
1170                 {
1171                         int i;
1172                         qglBegin(GL_TRIANGLES);
1173                         for (i = 0;i < numtriangles * 3;i++)
1174                         {
1175                                 qglArrayElement(elements[i]);
1176                         }
1177                         qglEnd();
1178                         CHECKGLERROR
1179                 }
1180                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1181                 {
1182                         GL_BindEBO(bufferobject);
1183                         qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, bufferobject ? (void *)bufferoffset : elements);
1184                         CHECKGLERROR
1185                 }
1186                 else
1187                 {
1188                         GL_BindEBO(bufferobject);
1189                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, bufferobject ? (void *)bufferoffset : elements);
1190                         CHECKGLERROR
1191                 }
1192         }
1193 }
1194
1195 // restores backend state, used when done with 3D rendering
1196 void R_Mesh_Finish(void)
1197 {
1198         unsigned int i;
1199         BACKENDACTIVECHECK
1200         CHECKGLERROR
1201         GL_LockArrays(0, 0);
1202         CHECKGLERROR
1203
1204         for (i = 0;i < backendimageunits;i++)
1205         {
1206                 GL_ActiveTexture(i);
1207                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
1208                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1209                 if (gl_texture3d)
1210                 {
1211                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1212                 }
1213                 if (gl_texturecubemap)
1214                 {
1215                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
1216                 }
1217         }
1218         for (i = 0;i < backendarrayunits;i++)
1219         {
1220                 GL_ActiveTexture(backendarrayunits - 1 - i);
1221                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1222         }
1223         for (i = 0;i < backendunits;i++)
1224         {
1225                 GL_ActiveTexture(backendunits - 1 - i);
1226                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1227                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1228                 if (gl_texture3d)
1229                 {
1230                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1231                 }
1232                 if (gl_texturecubemap)
1233                 {
1234                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1235                 }
1236                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1237                 if (gl_combine.integer)
1238                 {
1239                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
1240                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
1241                 }
1242         }
1243         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1244         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1245
1246         qglDisable(GL_BLEND);CHECKGLERROR
1247         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1248         qglDepthMask(GL_TRUE);CHECKGLERROR
1249         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
1250 }
1251
1252 int R_Mesh_CreateStaticBufferObject(unsigned int target, void *data, size_t size, const char *name)
1253 {
1254         gl_bufferobjectinfo_t *info;
1255         GLuint bufferobject;
1256
1257         if (!gl_vbo.integer)
1258                 return 0;
1259
1260         qglGenBuffersARB(1, &bufferobject);
1261         switch(target)
1262         {
1263         case GL_ELEMENT_ARRAY_BUFFER_ARB: GL_BindEBO(bufferobject);break;
1264         case GL_ARRAY_BUFFER_ARB: GL_BindVBO(bufferobject);break;
1265         default: Sys_Error("R_Mesh_CreateStaticBufferObject: unknown target type %i\n", target);return 0;
1266         }
1267         qglBufferDataARB(target, size, data, GL_STATIC_DRAW_ARB);
1268
1269         info = Mem_ExpandableArray_AllocRecord(&gl_bufferobjectinfoarray);
1270         memset(info, 0, sizeof(*info));
1271         info->target = target;
1272         info->object = bufferobject;
1273         info->size = size;
1274         strlcpy(info->name, name, sizeof(info->name));
1275
1276         return (int)bufferobject;
1277 }
1278
1279 void R_Mesh_DestroyBufferObject(int bufferobject)
1280 {
1281         int i, endindex;
1282         gl_bufferobjectinfo_t *info;
1283
1284         qglDeleteBuffersARB(1, (GLuint *)&bufferobject);
1285
1286         endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
1287         for (i = 0;i < endindex;i++)
1288         {
1289                 info = Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
1290                 if (!info)
1291                         continue;
1292                 if (info->object == bufferobject)
1293                 {
1294                         Mem_ExpandableArray_FreeRecord(&gl_bufferobjectinfoarray, (void *)info);
1295                         break;
1296                 }
1297         }
1298 }
1299
1300 void GL_Mesh_ListVBOs(qboolean printeach)
1301 {
1302         int i, endindex;
1303         size_t ebocount = 0, ebomemory = 0;
1304         size_t vbocount = 0, vbomemory = 0;
1305         gl_bufferobjectinfo_t *info;
1306         endindex = Mem_ExpandableArray_IndexRange(&gl_bufferobjectinfoarray);
1307         for (i = 0;i < endindex;i++)
1308         {
1309                 info = Mem_ExpandableArray_RecordAtIndex(&gl_bufferobjectinfoarray, i);
1310                 if (!info)
1311                         continue;
1312                 switch(info->target)
1313                 {
1314                 case GL_ELEMENT_ARRAY_BUFFER_ARB: ebocount++;ebomemory += info->size;if (printeach) Con_Printf("EBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
1315                 case GL_ARRAY_BUFFER_ARB: vbocount++;vbomemory += info->size;if (printeach) Con_Printf("VBO #%i %s = %i bytes\n", info->object, info->name, (int)info->size);break;
1316                 default: Con_Printf("gl_vbostats: unknown target type %i\n", info->target);break;
1317                 }
1318         }
1319         Con_Printf("vertex buffers: %i element buffers totalling %i bytes (%.3f MB), %i vertex buffers totalling %i bytes (%.3f MB), combined %i bytes (%.3fMB)\n", (int)ebocount, (int)ebomemory, ebomemory / 1048576.0, (int)vbocount, (int)vbomemory, vbomemory / 1048576.0, (int)(ebomemory + vbomemory), (ebomemory + vbomemory) / 1048576.0);
1320 }
1321
1322 void R_Mesh_Matrix(const matrix4x4_t *matrix)
1323 {
1324         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
1325         {
1326                 double glmatrix[16];
1327                 backend_modelmatrix = *matrix;
1328                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
1329                 Matrix4x4_ToArrayDoubleGL(&backend_modelviewmatrix, glmatrix);
1330                 CHECKGLERROR
1331                 qglLoadMatrixd(glmatrix);CHECKGLERROR
1332         }
1333 }
1334
1335 void R_Mesh_VertexPointer(const float *vertex3f, int bufferobject, size_t bufferoffset)
1336 {
1337         if (!gl_vbo.integer)
1338                 bufferobject = 0;
1339         if (gl_state.pointer_vertex != vertex3f || gl_state.pointer_vertex_buffer != bufferobject || gl_state.pointer_vertex_offset != bufferoffset)
1340         {
1341                 gl_state.pointer_vertex = vertex3f;
1342                 gl_state.pointer_vertex_buffer = bufferobject;
1343                 gl_state.pointer_vertex_offset = bufferoffset;
1344                 CHECKGLERROR
1345                 GL_BindVBO(bufferobject);
1346                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), bufferobject ? (void *)bufferoffset : vertex3f);CHECKGLERROR
1347         }
1348 }
1349
1350 void R_Mesh_ColorPointer(const float *color4f, int bufferobject, size_t bufferoffset)
1351 {
1352         // note: this can not rely on bufferobject to decide whether a color array
1353         // is supplied, because surfmesh_t shares one vbo for all arrays, which
1354         // means that a valid vbo may be supplied even if there is no color array.
1355         if (color4f)
1356         {
1357                 if (!gl_vbo.integer)
1358                         bufferobject = 0;
1359                 // caller wants color array enabled
1360                 if (!gl_state.pointer_color_enabled)
1361                 {
1362                         gl_state.pointer_color_enabled = true;
1363                         CHECKGLERROR
1364                         qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1365                 }
1366                 if (gl_state.pointer_color != color4f || gl_state.pointer_color_buffer != bufferobject || gl_state.pointer_color_offset != bufferoffset)
1367                 {
1368                         gl_state.pointer_color = color4f;
1369                         gl_state.pointer_color_buffer = bufferobject;
1370                         gl_state.pointer_color_offset = bufferoffset;
1371                         CHECKGLERROR
1372                         GL_BindVBO(bufferobject);
1373                         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), bufferobject ? (void *)bufferoffset : color4f);CHECKGLERROR
1374                 }
1375         }
1376         else
1377         {
1378                 // caller wants color array disabled
1379                 if (gl_state.pointer_color_enabled)
1380                 {
1381                         gl_state.pointer_color_enabled = false;
1382                         CHECKGLERROR
1383                         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1384                         // when color array is on the glColor gets trashed, set it again
1385                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);CHECKGLERROR
1386                 }
1387         }
1388 }
1389
1390 void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord, int bufferobject, size_t bufferoffset)
1391 {
1392         gltextureunit_t *unit = gl_state.units + unitnum;
1393         // update array settings
1394         CHECKGLERROR
1395         // note: there is no need to check bufferobject here because all cases
1396         // that involve a valid bufferobject also supply a texcoord array
1397         if (texcoord)
1398         {
1399                 if (!gl_vbo.integer)
1400                         bufferobject = 0;
1401                 // texture array unit is enabled, enable the array
1402                 if (!unit->arrayenabled)
1403                 {
1404                         unit->arrayenabled = true;
1405                         GL_ClientActiveTexture(unitnum);
1406                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1407                 }
1408                 // texcoord array
1409                 if (unit->pointer_texcoord != texcoord || unit->pointer_texcoord_buffer != bufferobject || unit->pointer_texcoord_offset != bufferoffset || unit->arraycomponents != numcomponents)
1410                 {
1411                         unit->pointer_texcoord = texcoord;
1412                         unit->pointer_texcoord_buffer = bufferobject;
1413                         unit->pointer_texcoord_offset = bufferoffset;
1414                         unit->arraycomponents = numcomponents;
1415                         GL_ClientActiveTexture(unitnum);
1416                         GL_BindVBO(bufferobject);
1417                         qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, bufferobject ? (void *)bufferoffset : texcoord);CHECKGLERROR
1418                 }
1419         }
1420         else
1421         {
1422                 // texture array unit is disabled, disable the array
1423                 if (unit->arrayenabled)
1424                 {
1425                         unit->arrayenabled = false;
1426                         GL_ClientActiveTexture(unitnum);
1427                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1428                 }
1429         }
1430 }
1431
1432 void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap)
1433 {
1434         gltextureunit_t *unit = gl_state.units + unitnum;
1435         if (unitnum >= backendimageunits)
1436                 return;
1437         // update 1d texture binding
1438         if (unit->t1d != tex1d)
1439         {
1440                 GL_ActiveTexture(unitnum);
1441                 if (unitnum < backendunits)
1442                 {
1443                         if (tex1d)
1444                         {
1445                                 if (unit->t1d == 0)
1446                                 {
1447                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
1448                                 }
1449                         }
1450                         else
1451                         {
1452                                 if (unit->t1d)
1453                                 {
1454                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1455                                 }
1456                         }
1457                 }
1458                 unit->t1d = tex1d;
1459                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1460         }
1461         // update 2d texture binding
1462         if (unit->t2d != tex2d)
1463         {
1464                 GL_ActiveTexture(unitnum);
1465                 if (unitnum < backendunits)
1466                 {
1467                         if (tex2d)
1468                         {
1469                                 if (unit->t2d == 0)
1470                                 {
1471                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
1472                                 }
1473                         }
1474                         else
1475                         {
1476                                 if (unit->t2d)
1477                                 {
1478                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1479                                 }
1480                         }
1481                 }
1482                 unit->t2d = tex2d;
1483                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1484         }
1485         // update 3d texture binding
1486         if (unit->t3d != tex3d)
1487         {
1488                 GL_ActiveTexture(unitnum);
1489                 if (unitnum < backendunits)
1490                 {
1491                         if (tex3d)
1492                         {
1493                                 if (unit->t3d == 0)
1494                                 {
1495                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
1496                                 }
1497                         }
1498                         else
1499                         {
1500                                 if (unit->t3d)
1501                                 {
1502                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1503                                 }
1504                         }
1505                 }
1506                 unit->t3d = tex3d;
1507                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1508         }
1509         // update cubemap texture binding
1510         if (unit->tcubemap != texcubemap)
1511         {
1512                 GL_ActiveTexture(unitnum);
1513                 if (unitnum < backendunits)
1514                 {
1515                         if (texcubemap)
1516                         {
1517                                 if (unit->tcubemap == 0)
1518                                 {
1519                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1520                                 }
1521                         }
1522                         else
1523                         {
1524                                 if (unit->tcubemap)
1525                                 {
1526                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1527                                 }
1528                         }
1529                 }
1530                 unit->tcubemap = texcubemap;
1531                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1532         }
1533 }
1534
1535 void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
1536 {
1537         gltextureunit_t *unit = gl_state.units + unitnum;
1538         if (unitnum >= backendimageunits)
1539                 return;
1540         // update 1d texture binding
1541         if (unit->t1d != texnum)
1542         {
1543                 GL_ActiveTexture(unitnum);
1544                 if (unitnum < backendunits)
1545                 {
1546                         if (texnum)
1547                         {
1548                                 if (unit->t1d == 0)
1549                                 {
1550                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
1551                                 }
1552                         }
1553                         else
1554                         {
1555                                 if (unit->t1d)
1556                                 {
1557                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1558                                 }
1559                         }
1560                 }
1561                 unit->t1d = texnum;
1562                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1563         }
1564         // update 2d texture binding
1565         if (unit->t2d)
1566         {
1567                 GL_ActiveTexture(unitnum);
1568                 if (unitnum < backendunits)
1569                 {
1570                         if (unit->t2d)
1571                         {
1572                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1573                         }
1574                 }
1575                 unit->t2d = 0;
1576                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1577         }
1578         // update 3d texture binding
1579         if (unit->t3d)
1580         {
1581                 GL_ActiveTexture(unitnum);
1582                 if (unitnum < backendunits)
1583                 {
1584                         if (unit->t3d)
1585                         {
1586                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1587                         }
1588                 }
1589                 unit->t3d = 0;
1590                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1591         }
1592         // update cubemap texture binding
1593         if (unit->tcubemap)
1594         {
1595                 GL_ActiveTexture(unitnum);
1596                 if (unitnum < backendunits)
1597                 {
1598                         if (unit->tcubemap)
1599                         {
1600                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1601                         }
1602                 }
1603                 unit->tcubemap = 0;
1604                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1605         }
1606 }
1607
1608 void R_Mesh_TexBind(unsigned int unitnum, int texnum)
1609 {
1610         gltextureunit_t *unit = gl_state.units + unitnum;
1611         if (unitnum >= backendimageunits)
1612                 return;
1613         // update 1d texture binding
1614         if (unit->t1d)
1615         {
1616                 GL_ActiveTexture(unitnum);
1617                 if (unitnum < backendunits)
1618                 {
1619                         if (unit->t1d)
1620                         {
1621                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1622                         }
1623                 }
1624                 unit->t1d = 0;
1625                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1626         }
1627         // update 2d texture binding
1628         if (unit->t2d != texnum)
1629         {
1630                 GL_ActiveTexture(unitnum);
1631                 if (unitnum < backendunits)
1632                 {
1633                         if (texnum)
1634                         {
1635                                 if (unit->t2d == 0)
1636                                 {
1637                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
1638                                 }
1639                         }
1640                         else
1641                         {
1642                                 if (unit->t2d)
1643                                 {
1644                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1645                                 }
1646                         }
1647                 }
1648                 unit->t2d = texnum;
1649                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1650         }
1651         // update 3d texture binding
1652         if (unit->t3d)
1653         {
1654                 GL_ActiveTexture(unitnum);
1655                 if (unitnum < backendunits)
1656                 {
1657                         if (unit->t3d)
1658                         {
1659                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1660                         }
1661                 }
1662                 unit->t3d = 0;
1663                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1664         }
1665         // update cubemap texture binding
1666         if (unit->tcubemap != 0)
1667         {
1668                 GL_ActiveTexture(unitnum);
1669                 if (unitnum < backendunits)
1670                 {
1671                         if (unit->tcubemap)
1672                         {
1673                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1674                         }
1675                 }
1676                 unit->tcubemap = 0;
1677                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1678         }
1679 }
1680
1681 void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
1682 {
1683         gltextureunit_t *unit = gl_state.units + unitnum;
1684         if (unitnum >= backendimageunits)
1685                 return;
1686         // update 1d texture binding
1687         if (unit->t1d)
1688         {
1689                 GL_ActiveTexture(unitnum);
1690                 if (unitnum < backendunits)
1691                 {
1692                         if (unit->t1d)
1693                         {
1694                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1695                         }
1696                 }
1697                 unit->t1d = 0;
1698                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1699         }
1700         // update 2d texture binding
1701         if (unit->t2d)
1702         {
1703                 GL_ActiveTexture(unitnum);
1704                 if (unitnum < backendunits)
1705                 {
1706                         if (unit->t2d)
1707                         {
1708                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1709                         }
1710                 }
1711                 unit->t2d = 0;
1712                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1713         }
1714         // update 3d texture binding
1715         if (unit->t3d != texnum)
1716         {
1717                 GL_ActiveTexture(unitnum);
1718                 if (unitnum < backendunits)
1719                 {
1720                         if (texnum)
1721                         {
1722                                 if (unit->t3d == 0)
1723                                 {
1724                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
1725                                 }
1726                         }
1727                         else
1728                         {
1729                                 if (unit->t3d)
1730                                 {
1731                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1732                                 }
1733                         }
1734                 }
1735                 unit->t3d = texnum;
1736                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1737         }
1738         // update cubemap texture binding
1739         if (unit->tcubemap != 0)
1740         {
1741                 GL_ActiveTexture(unitnum);
1742                 if (unitnum < backendunits)
1743                 {
1744                         if (unit->tcubemap)
1745                         {
1746                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1747                         }
1748                 }
1749                 unit->tcubemap = 0;
1750                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1751         }
1752 }
1753
1754 void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
1755 {
1756         gltextureunit_t *unit = gl_state.units + unitnum;
1757         if (unitnum >= backendimageunits)
1758                 return;
1759         // update 1d texture binding
1760         if (unit->t1d)
1761         {
1762                 GL_ActiveTexture(unitnum);
1763                 if (unitnum < backendunits)
1764                 {
1765                         if (unit->t1d)
1766                         {
1767                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1768                         }
1769                 }
1770                 unit->t1d = 0;
1771                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1772         }
1773         // update 2d texture binding
1774         if (unit->t2d)
1775         {
1776                 GL_ActiveTexture(unitnum);
1777                 if (unitnum < backendunits)
1778                 {
1779                         if (unit->t2d)
1780                         {
1781                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1782                         }
1783                 }
1784                 unit->t2d = 0;
1785                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1786         }
1787         // update 3d texture binding
1788         if (unit->t3d)
1789         {
1790                 GL_ActiveTexture(unitnum);
1791                 if (unitnum < backendunits)
1792                 {
1793                         if (unit->t3d)
1794                         {
1795                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1796                         }
1797                 }
1798                 unit->t3d = 0;
1799                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1800         }
1801         // update cubemap texture binding
1802         if (unit->tcubemap != texnum)
1803         {
1804                 GL_ActiveTexture(unitnum);
1805                 if (unitnum < backendunits)
1806                 {
1807                         if (texnum)
1808                         {
1809                                 if (unit->tcubemap == 0)
1810                                 {
1811                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1812                                 }
1813                         }
1814                         else
1815                         {
1816                                 if (unit->tcubemap)
1817                                 {
1818                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1819                                 }
1820                         }
1821                 }
1822                 unit->tcubemap = texnum;
1823                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
1824         }
1825 }
1826
1827 void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
1828 {
1829         gltextureunit_t *unit = gl_state.units + unitnum;
1830         if (matrix->m[3][3])
1831         {
1832                 // texmatrix specified, check if it is different
1833                 if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
1834                 {
1835                         double glmatrix[16];
1836                         unit->texmatrixenabled = true;
1837                         unit->matrix = *matrix;
1838                         CHECKGLERROR
1839                         Matrix4x4_ToArrayDoubleGL(&unit->matrix, glmatrix);
1840                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
1841                         GL_ActiveTexture(unitnum);
1842                         qglLoadMatrixd(glmatrix);CHECKGLERROR
1843                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1844                 }
1845         }
1846         else
1847         {
1848                 // no texmatrix specified, revert to identity
1849                 if (unit->texmatrixenabled)
1850                 {
1851                         unit->texmatrixenabled = false;
1852                         CHECKGLERROR
1853                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
1854                         GL_ActiveTexture(unitnum);
1855                         qglLoadIdentity();CHECKGLERROR
1856                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
1857                 }
1858         }
1859 }
1860
1861 void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
1862 {
1863         gltextureunit_t *unit = gl_state.units + unitnum;
1864         CHECKGLERROR
1865         if (gl_combine.integer)
1866         {
1867                 // GL_ARB_texture_env_combine
1868                 if (!combinergb)
1869                         combinergb = GL_MODULATE;
1870                 if (!combinealpha)
1871                         combinealpha = GL_MODULATE;
1872                 if (!rgbscale)
1873                         rgbscale = 1;
1874                 if (!alphascale)
1875                         alphascale = 1;
1876                 if (unit->combinergb != combinergb)
1877                 {
1878                         unit->combinergb = combinergb;
1879                         GL_ActiveTexture(unitnum);
1880                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
1881                 }
1882                 if (unit->combinealpha != combinealpha)
1883                 {
1884                         unit->combinealpha = combinealpha;
1885                         GL_ActiveTexture(unitnum);
1886                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1887                 }
1888                 if (unit->rgbscale != rgbscale)
1889                 {
1890                         GL_ActiveTexture(unitnum);
1891                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
1892                 }
1893                 if (unit->alphascale != alphascale)
1894                 {
1895                         GL_ActiveTexture(unitnum);
1896                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
1897                 }
1898         }
1899         else
1900         {
1901                 // normal GL texenv
1902                 if (!combinergb)
1903                         combinergb = GL_MODULATE;
1904                 if (unit->combinergb != combinergb)
1905                 {
1906                         unit->combinergb = combinergb;
1907                         GL_ActiveTexture(unitnum);
1908                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
1909                 }
1910         }
1911 }
1912
1913 void R_Mesh_TextureState(const rmeshstate_t *m)
1914 {
1915         unsigned int i;
1916
1917         BACKENDACTIVECHECK
1918
1919         CHECKGLERROR
1920         if (gl_backend_rebindtextures)
1921         {
1922                 gl_backend_rebindtextures = false;
1923                 GL_SetupTextureState();
1924                 CHECKGLERROR
1925         }
1926
1927         for (i = 0;i < backendimageunits;i++)
1928                 R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i]);
1929         for (i = 0;i < backendarrayunits;i++)
1930         {
1931                 if (m->pointer_texcoord3f[i])
1932                         R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
1933                 else
1934                         R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i], m->pointer_texcoord_bufferobject[i], m->pointer_texcoord_bufferoffset[i]);
1935         }
1936         for (i = 0;i < backendunits;i++)
1937         {
1938                 R_Mesh_TexMatrix(i, &m->texmatrix[i]);
1939                 R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
1940         }
1941         CHECKGLERROR
1942 }
1943
1944 void R_Mesh_ResetTextureState(void)
1945 {
1946         unsigned int unitnum;
1947
1948         BACKENDACTIVECHECK
1949
1950         CHECKGLERROR
1951         if (gl_backend_rebindtextures)
1952         {
1953                 gl_backend_rebindtextures = false;
1954                 GL_SetupTextureState();
1955                 CHECKGLERROR
1956         }
1957
1958         for (unitnum = 0;unitnum < backendimageunits;unitnum++)
1959         {
1960                 gltextureunit_t *unit = gl_state.units + unitnum;
1961                 // update 1d texture binding
1962                 if (unit->t1d)
1963                 {
1964                         GL_ActiveTexture(unitnum);
1965                         if (unitnum < backendunits)
1966                         {
1967                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1968                         }
1969                         unit->t1d = 0;
1970                         qglBindTexture(GL_TEXTURE_1D, unit->t1d);CHECKGLERROR
1971                 }
1972                 // update 2d texture binding
1973                 if (unit->t2d)
1974                 {
1975                         GL_ActiveTexture(unitnum);
1976                         if (unitnum < backendunits)
1977                         {
1978                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1979                         }
1980                         unit->t2d = 0;
1981                         qglBindTexture(GL_TEXTURE_2D, unit->t2d);CHECKGLERROR
1982                 }
1983                 // update 3d texture binding
1984                 if (unit->t3d)
1985                 {
1986                         GL_ActiveTexture(unitnum);
1987                         if (unitnum < backendunits)
1988                         {
1989                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1990                         }
1991                         unit->t3d = 0;
1992                         qglBindTexture(GL_TEXTURE_3D, unit->t3d);CHECKGLERROR
1993                 }
1994                 // update cubemap texture binding
1995                 if (unit->tcubemap)
1996                 {
1997                         GL_ActiveTexture(unitnum);
1998                         if (unitnum < backendunits)
1999                         {
2000                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
2001                         }
2002                         unit->tcubemap = 0;
2003                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);CHECKGLERROR
2004                 }
2005         }
2006         for (unitnum = 0;unitnum < backendarrayunits;unitnum++)
2007         {
2008                 gltextureunit_t *unit = gl_state.units + unitnum;
2009                 // texture array unit is disabled, disable the array
2010                 if (unit->arrayenabled)
2011                 {
2012                         unit->arrayenabled = false;
2013                         GL_ClientActiveTexture(unitnum);
2014                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
2015                 }
2016         }
2017         for (unitnum = 0;unitnum < backendunits;unitnum++)
2018         {
2019                 gltextureunit_t *unit = gl_state.units + unitnum;
2020                 // no texmatrix specified, revert to identity
2021                 if (unit->texmatrixenabled)
2022                 {
2023                         unit->texmatrixenabled = false;
2024                         CHECKGLERROR
2025                         qglMatrixMode(GL_TEXTURE);CHECKGLERROR
2026                         GL_ActiveTexture(unitnum);
2027                         qglLoadIdentity();CHECKGLERROR
2028                         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
2029                 }
2030                 if (gl_combine.integer)
2031                 {
2032                         // GL_ARB_texture_env_combine
2033                         if (unit->combinergb != GL_MODULATE)
2034                         {
2035                                 unit->combinergb = GL_MODULATE;
2036                                 GL_ActiveTexture(unitnum);
2037                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
2038                         }
2039                         if (unit->combinealpha != GL_MODULATE)
2040                         {
2041                                 unit->combinealpha = GL_MODULATE;
2042                                 GL_ActiveTexture(unitnum);
2043                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
2044                         }
2045                         if (unit->rgbscale != 1)
2046                         {
2047                                 GL_ActiveTexture(unitnum);
2048                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = 1));CHECKGLERROR
2049                         }
2050                         if (unit->alphascale != 1)
2051                         {
2052                                 GL_ActiveTexture(unitnum);
2053                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = 1));CHECKGLERROR
2054                         }
2055                 }
2056                 else
2057                 {
2058                         // normal GL texenv
2059                         if (unit->combinergb != GL_MODULATE)
2060                         {
2061                                 unit->combinergb = GL_MODULATE;
2062                                 GL_ActiveTexture(unitnum);
2063                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
2064                         }
2065                 }
2066         }
2067 }
2068
2069 void R_Mesh_Draw_ShowTris(int firstvertex, int numvertices, int numtriangles, const int *elements)
2070 {
2071         CHECKGLERROR
2072         qglBegin(GL_LINES);
2073         for (;numtriangles;numtriangles--, elements += 3)
2074         {
2075                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
2076                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
2077                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
2078         }
2079         qglEnd();
2080         CHECKGLERROR
2081 }