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