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