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