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