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