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