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