set depth and stencil clear values
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4
5 cvar_t gl_mesh_maxverts = {0, "gl_mesh_maxverts", "1024"};
6 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "1"};
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1"};
8
9 cvar_t r_render = {0, "r_render", "1"};
10 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
11 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
12
13 int gl_maxdrawrangeelementsvertices;
14 int gl_maxdrawrangeelementsindices;
15
16 #ifdef DEBUGGL
17 int errornumber = 0;
18
19 void GL_PrintError(int errornumber, char *filename, int linenumber)
20 {
21         switch(errornumber)
22         {
23 #ifdef GL_INVALID_ENUM
24         case GL_INVALID_ENUM:
25                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
26                 break;
27 #endif
28 #ifdef GL_INVALID_VALUE
29         case GL_INVALID_VALUE:
30                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
31                 break;
32 #endif
33 #ifdef GL_INVALID_OPERATION
34         case GL_INVALID_OPERATION:
35                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
36                 break;
37 #endif
38 #ifdef GL_STACK_OVERFLOW
39         case GL_STACK_OVERFLOW:
40                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
41                 break;
42 #endif
43 #ifdef GL_STACK_UNDERFLOW
44         case GL_STACK_UNDERFLOW:
45                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
46                 break;
47 #endif
48 #ifdef GL_OUT_OF_MEMORY
49         case GL_OUT_OF_MEMORY:
50                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
51                 break;
52 #endif
53 #ifdef GL_TABLE_TOO_LARGE
54     case GL_TABLE_TOO_LARGE:
55                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
56                 break;
57 #endif
58         default:
59                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
60                 break;
61         }
62 }
63 #endif
64
65 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
66
67 int c_meshs, c_meshelements;
68
69 void SCR_ScreenShot_f (void);
70
71 // these are externally accessible
72 int r_lightmapscalebit;
73 float r_colorscale;
74 float *varray_vertex;
75 float *varray_color;
76 float *varray_texcoord[MAX_TEXTUREUNITS];
77 int mesh_maxverts;
78
79 static matrix4x4_t backend_viewmatrix;
80 static matrix4x4_t backend_modelmatrix;
81 static matrix4x4_t backend_modelviewmatrix;
82 static matrix4x4_t backend_glmodelviewmatrix;
83
84 static int backendunits, backendactive;
85 static qbyte *varray_bcolor;
86 static mempool_t *gl_backend_mempool;
87
88 /*
89 note: here's strip order for a terrain row:
90 0--1--2--3--4
91 |\ |\ |\ |\ |
92 | \| \| \| \|
93 A--B--C--D--E
94
95 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
96
97 *elements++ = i + row;
98 *elements++ = i;
99 *elements++ = i + row + 1;
100 *elements++ = i;
101 *elements++ = i + 1;
102 *elements++ = i + row + 1;
103 */
104
105 int polygonelements[768];
106
107 void GL_Backend_AllocArrays(void)
108 {
109         int i;
110
111         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
112         {
113                 polygonelements[i * 3 + 0] = 0;
114                 polygonelements[i * 3 + 1] = i + 1;
115                 polygonelements[i * 3 + 2] = i + 2;
116         }
117
118         if (!gl_backend_mempool)
119                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
120
121         varray_vertex = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
122         varray_color = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
123         varray_bcolor = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(qbyte[4]));
124         for (i = 0;i < backendunits;i++)
125                 varray_texcoord[i] = Mem_Alloc(gl_backend_mempool, mesh_maxverts * sizeof(float[4]));
126         for (;i < MAX_TEXTUREUNITS;i++)
127                 varray_texcoord[i] = NULL;
128 }
129
130 void GL_Backend_FreeArrays(int resizingbuffers)
131 {
132         int i;
133         if (resizingbuffers)
134                 Mem_EmptyPool(gl_backend_mempool);
135         else
136                 Mem_FreePool(&gl_backend_mempool);
137         varray_vertex = NULL;
138         varray_color = NULL;
139         varray_bcolor = NULL;
140         for (i = 0;i < MAX_TEXTUREUNITS;i++)
141                 varray_texcoord[i] = NULL;
142 }
143
144 static void gl_backend_start(void)
145 {
146         Con_Printf("OpenGL Backend started with gl_mesh_maxverts %i\n", gl_mesh_maxverts.integer);
147         if (qglDrawRangeElements != NULL)
148         {
149                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
150                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
151                 CHECKGLERROR
152                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
153         }
154         if (strstr(gl_renderer, "3Dfx"))
155         {
156                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
157                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
158         }
159
160         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
161
162         GL_Backend_AllocArrays();
163
164         backendactive = true;
165 }
166
167 static void gl_backend_shutdown(void)
168 {
169         backendunits = 0;
170         backendactive = false;
171
172         Con_Printf("OpenGL Backend shutting down\n");
173
174         GL_Backend_FreeArrays(false);
175 }
176
177 void GL_Backend_CheckCvars(void)
178 {
179         // 21760 is (65536 / 3) rounded off to a multiple of 128
180         if (gl_mesh_maxverts.integer < 1024)
181                 Cvar_SetValueQuick(&gl_mesh_maxverts, 1024);
182         if (gl_mesh_maxverts.integer > 21760)
183                 Cvar_SetValueQuick(&gl_mesh_maxverts, 21760);
184 }
185
186 void GL_Backend_ResizeArrays(int numtriangles)
187 {
188         Cvar_SetValueQuick(&gl_mesh_maxverts, numtriangles);
189         GL_Backend_CheckCvars();
190         mesh_maxverts = gl_mesh_maxverts.integer;
191         GL_Backend_FreeArrays(true);
192         GL_Backend_AllocArrays();
193 }
194
195 static void gl_backend_newmap(void)
196 {
197 }
198
199 void gl_backend_init(void)
200 {
201         Cvar_RegisterVariable(&r_render);
202         Cvar_RegisterVariable(&gl_dither);
203         Cvar_RegisterVariable(&gl_lockarrays);
204 #ifdef NORENDER
205         Cvar_SetValue("r_render", 0);
206 #endif
207
208         Cvar_RegisterVariable(&gl_mesh_maxverts);
209         Cvar_RegisterVariable(&gl_mesh_floatcolors);
210         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
211         GL_Backend_CheckCvars();
212         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
213 }
214
215 void GL_SetupView_ViewPort (int x, int y, int width, int height)
216 {
217         if (!r_render.integer)
218                 return;
219
220         // y is weird beause OpenGL is bottom to top, we use top to bottom
221         qglViewport(x, vid.realheight - (y + height), width, height);
222         CHECKGLERROR
223 }
224
225 void GL_SetupView_Orientation_Identity (void)
226 {
227         Matrix4x4_CreateIdentity(&backend_viewmatrix);
228         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
229 }
230
231 void GL_SetupView_Orientation_FromEntity (vec3_t origin, vec3_t angles)
232 {
233         Matrix4x4_CreateRotate(&backend_viewmatrix, -90, 1, 0, 0);
234         Matrix4x4_ConcatRotate(&backend_viewmatrix, 90, 0, 0, 1);
235         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
236         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
237         Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
238         Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
239         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
240 }
241
242 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
243 {
244         double xmax, ymax;
245
246         if (!r_render.integer)
247                 return;
248
249         // set up viewpoint
250         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
251         qglLoadIdentity ();CHECKGLERROR
252         // pyramid slopes
253         xmax = zNear * tan(fovx * M_PI / 360.0);
254         ymax = zNear * tan(fovy * M_PI / 360.0);
255         // set view pyramid
256         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
257         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
258         GL_SetupView_Orientation_Identity();
259 }
260
261 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
262 {
263         double nudge, m[16];
264
265         if (!r_render.integer)
266                 return;
267
268         // set up viewpoint
269         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
270         qglLoadIdentity ();CHECKGLERROR
271         // set view pyramid
272         nudge = 1.0 - 1.0 / (1<<23);
273         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
274         m[ 1] = 0;
275         m[ 2] = 0;
276         m[ 3] = 0;
277         m[ 4] = 0;
278         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
279         m[ 6] = 0;
280         m[ 7] = 0;
281         m[ 8] = 0;
282         m[ 9] = 0;
283         m[10] = -1 * nudge;
284         m[11] = -1 * nudge;
285         m[12] = 0;
286         m[13] = 0;
287         m[14] = -2 * zNear * nudge;
288         m[15] = 0;
289         qglLoadMatrixd(m);
290         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
291         GL_SetupView_Orientation_Identity();
292 }
293
294 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
295 {
296         if (!r_render.integer)
297                 return;
298
299         // set up viewpoint
300         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
301         qglLoadIdentity ();CHECKGLERROR
302         qglOrtho(x1, x2, y2, y1, zNear, zFar);
303         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
304         GL_SetupView_Orientation_Identity();
305 }
306
307 typedef struct gltextureunit_s
308 {
309         unsigned int t1d, t2d, t3d, tcubemap;
310         unsigned int arrayenabled;
311         float rgbscale, alphascale;
312         int combinergb, combinealpha;
313         // FIXME: add more combine stuff
314 }
315 gltextureunit_t;
316
317 static struct
318 {
319         int blendfunc1;
320         int blendfunc2;
321         int blend;
322         GLboolean depthmask;
323         int depthdisable;
324         int unit;
325         int clientunit;
326         gltextureunit_t units[MAX_TEXTUREUNITS];
327         int colorarray;
328 }
329 gl_state;
330
331 void GL_SetupTextureState(void)
332 {
333         int i;
334         gltextureunit_t *unit;
335         for (i = 0;i < backendunits;i++)
336         {
337                 if (qglActiveTexture)
338                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
339                 if (qglClientActiveTexture)
340                         qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
341                 unit = gl_state.units + i;
342                 unit->t1d = 0;
343                 unit->t2d = 0;
344                 unit->t3d = 0;
345                 unit->tcubemap = 0;
346                 unit->rgbscale = 1;
347                 unit->alphascale = 1;
348                 unit->combinergb = GL_MODULATE;
349                 unit->combinealpha = GL_MODULATE;
350                 unit->arrayenabled = false;
351                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
352                 if (gl_texture3d)
353                 {
354                         qglTexCoordPointer(3, GL_FLOAT, sizeof(float[4]), varray_texcoord[i]);CHECKGLERROR
355                 }
356                 else
357                 {
358                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[4]), varray_texcoord[i]);CHECKGLERROR
359                 }
360                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
361                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
362                 if (gl_texture3d)
363                 {
364                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
365                 }
366                 if (gl_texturecubemap)
367                 {
368                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
369                 }
370                 if (gl_combine.integer)
371                 {
372                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
373                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
374                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
375                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
376                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
377                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
378                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
379                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
380                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
381                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
382                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
383                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
384                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
385                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
386                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
387                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
388                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
389                 }
390                 else
391                 {
392                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
393                 }
394         }
395 }
396
397 void GL_Backend_ResetState(void)
398 {
399         memset(&gl_state, 0, sizeof(gl_state));
400         gl_state.depthdisable = false;
401         gl_state.blendfunc1 = GL_ONE;
402         gl_state.blendfunc2 = GL_ZERO;
403         gl_state.blend = false;
404         gl_state.depthmask = GL_TRUE;
405         gl_state.colorarray = false;
406
407         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
408         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
409
410         qglEnable(GL_CULL_FACE);CHECKGLERROR
411         qglCullFace(GL_FRONT);CHECKGLERROR
412         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
413         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
414         qglDisable(GL_BLEND);CHECKGLERROR
415         qglDepthMask(gl_state.depthmask);CHECKGLERROR
416         qglVertexPointer(3, GL_FLOAT, sizeof(float[4]), varray_vertex);CHECKGLERROR
417         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
418         if (gl_mesh_floatcolors.integer)
419         {
420                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), varray_color);CHECKGLERROR
421         }
422         else
423         {
424                 qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(qbyte[4]), varray_bcolor);CHECKGLERROR
425         }
426         GL_Color(1, 1, 1, 1);
427
428         GL_SetupTextureState();
429 }
430
431 void GL_UseColorArray(void)
432 {
433         if (!gl_state.colorarray)
434         {
435                 gl_state.colorarray = true;
436                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
437         }
438 }
439
440 void GL_Color(float cr, float cg, float cb, float ca)
441 {
442         if (gl_state.colorarray)
443         {
444                 gl_state.colorarray = false;
445                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
446         }
447         qglColor4f(cr, cg, cb, ca);
448 }
449
450 // called at beginning of frame
451 void R_Mesh_Start(void)
452 {
453         BACKENDACTIVECHECK
454
455         CHECKGLERROR
456
457         GL_Backend_CheckCvars();
458         if (mesh_maxverts != gl_mesh_maxverts.integer)
459                 GL_Backend_ResizeArrays(gl_mesh_maxverts.integer);
460
461         GL_Backend_ResetState();
462 }
463
464 int gl_backend_rebindtextures;
465
466 void GL_ConvertColorsFloatToByte(int numverts)
467 {
468         int i, k, total;
469         // LordHavoc: to avoid problems with aliasing (treating memory as two
470         // different types - exactly what this is doing), these must be volatile
471         // (or a union)
472         volatile int *icolor;
473         volatile float *fcolor;
474         qbyte *bcolor;
475
476         total = numverts * 4;
477
478         // shift float to have 8bit fraction at base of number
479         fcolor = varray_color;
480         for (i = 0;i < total;)
481         {
482                 fcolor[i    ] += 32768.0f;
483                 fcolor[i + 1] += 32768.0f;
484                 fcolor[i + 2] += 32768.0f;
485                 fcolor[i + 3] += 32768.0f;
486                 i += 4;
487         }
488
489         // then read as integer and kill float bits...
490         icolor = (int *)varray_color;
491         bcolor = varray_bcolor;
492         for (i = 0;i < total;)
493         {
494                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
495                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
496                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
497                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
498                 i += 4;
499         }
500 }
501
502 void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, const int *index)
503 {
504         int arraylocked = false;
505         c_meshs++;
506         c_meshelements += indexcount;
507         if (indexcount == 0 || endvert == firstvert)
508         {
509                 Con_Printf("GL_DrawRangeElements(%d, %d, %d, %08p);\n", firstvert, endvert, indexcount, index);
510                 return;
511         }
512         if (gl_supportslockarrays && gl_lockarrays.integer)
513         {
514                 qglLockArraysEXT(firstvert, endvert - firstvert);
515                 CHECKGLERROR
516                 arraylocked = true;
517         }
518         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
519                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, (const GLuint *) index);
520         else
521                 qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, (const GLuint *) index);
522         CHECKGLERROR
523         if (arraylocked)
524         {
525                 qglUnlockArraysEXT();
526                 CHECKGLERROR
527                 arraylocked = false;
528         }
529 }
530
531 // enlarges geometry buffers if they are too small
532 void _R_Mesh_ResizeCheck(int numverts)
533 {
534         if (numverts > mesh_maxverts)
535         {
536                 BACKENDACTIVECHECK
537                 GL_Backend_ResizeArrays(numverts + 100);
538                 GL_Backend_ResetState();
539         }
540 }
541
542 // renders the mesh
543 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
544 {
545         BACKENDACTIVECHECK
546
547         CHECKGLERROR
548
549         if (gl_state.colorarray && !gl_mesh_floatcolors.integer)
550                 GL_ConvertColorsFloatToByte(numverts);
551         if (!r_render.integer)
552                 return;
553         GL_DrawRangeElements(0, numverts, numtriangles * 3, elements);
554 }
555
556 // restores backend state, used when done with 3D rendering
557 void R_Mesh_Finish(void)
558 {
559         int i;
560         BACKENDACTIVECHECK
561
562         for (i = backendunits - 1;i >= 0;i--)
563         {
564                 if (qglActiveTexture)
565                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
566                 if (qglClientActiveTexture)
567                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
568                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
569                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
570                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
571                 if (gl_texture3d)
572                 {
573                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
574                 }
575                 if (gl_texturecubemap)
576                 {
577                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
578                 }
579                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
580                 if (gl_combine.integer)
581                 {
582                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
583                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
584                 }
585         }
586         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
587         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
588
589         qglDisable(GL_BLEND);CHECKGLERROR
590         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
591         qglDepthMask(GL_TRUE);CHECKGLERROR
592         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
593 }
594
595 void R_Mesh_Matrix(const matrix4x4_t *matrix)
596 {
597         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
598         {
599                 backend_modelmatrix = *matrix;
600                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
601                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
602                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
603         }
604 }
605
606 // sets up the requested state
607 void R_Mesh_MainState(const rmeshstate_t *m)
608 {
609         BACKENDACTIVECHECK
610
611         if (gl_state.blendfunc1 != m->blendfunc1 || gl_state.blendfunc2 != m->blendfunc2)
612         {
613                 qglBlendFunc(gl_state.blendfunc1 = m->blendfunc1, gl_state.blendfunc2 = m->blendfunc2);CHECKGLERROR
614                 if (gl_state.blendfunc2 == GL_ZERO)
615                 {
616                         if (gl_state.blendfunc1 == GL_ONE)
617                         {
618                                 if (gl_state.blend)
619                                 {
620                                         gl_state.blend = 0;
621                                         qglDisable(GL_BLEND);CHECKGLERROR
622                                 }
623                         }
624                         else
625                         {
626                                 if (!gl_state.blend)
627                                 {
628                                         gl_state.blend = 1;
629                                         qglEnable(GL_BLEND);CHECKGLERROR
630                                 }
631                         }
632                 }
633                 else
634                 {
635                         if (!gl_state.blend)
636                         {
637                                 gl_state.blend = 1;
638                                 qglEnable(GL_BLEND);CHECKGLERROR
639                         }
640                 }
641         }
642         if (gl_state.depthdisable != m->depthdisable)
643         {
644                 gl_state.depthdisable = m->depthdisable;
645                 if (gl_state.depthdisable)
646                         qglDisable(GL_DEPTH_TEST);
647                 else
648                         qglEnable(GL_DEPTH_TEST);
649         }
650         if (gl_state.depthmask != (m->blendfunc2 == GL_ZERO || m->depthwrite))
651         {
652                 qglDepthMask(gl_state.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite));CHECKGLERROR
653         }
654 }
655
656 void R_Mesh_TextureState(const rmeshstate_t *m)
657 {
658         int i, combinergb, combinealpha;
659         float scale;
660         gltextureunit_t *unit;
661
662         BACKENDACTIVECHECK
663
664         if (gl_backend_rebindtextures)
665         {
666                 gl_backend_rebindtextures = false;
667                 GL_SetupTextureState();
668         }
669
670         for (i = 0;i < backendunits;i++)
671         {
672                 unit = gl_state.units + i;
673                 if (unit->t1d != m->tex1d[i] || unit->t2d != m->tex[i] || unit->t3d != m->tex3d[i] || unit->tcubemap != m->texcubemap[i])
674                 {
675                         if (gl_state.unit != i)
676                         {
677                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
678                         }
679                         if (m->tex1d[i] || m->tex[i] || m->tex3d[i] || m->texcubemap[i])
680                         {
681                                 if (!unit->arrayenabled)
682                                 {
683                                         unit->arrayenabled = true;
684                                         if (gl_state.clientunit != i)
685                                         {
686                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
687                                         }
688                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
689                                 }
690                         }
691                         else
692                         {
693                                 if (unit->arrayenabled)
694                                 {
695                                         unit->arrayenabled = false;
696                                         if (gl_state.clientunit != i)
697                                         {
698                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
699                                         }
700                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
701                                 }
702                         }
703                         combinergb = m->texcombinergb[i];
704                         combinealpha = m->texcombinealpha[i];
705                         if (!combinergb)
706                                 combinergb = GL_MODULATE;
707                         if (!combinealpha)
708                                 combinealpha = GL_MODULATE;
709                         if (unit->combinergb != combinergb)
710                         {
711                                 unit->combinergb = combinergb;
712                                 if (gl_combine.integer)
713                                 {
714                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
715                                 }
716                                 else
717                                 {
718                                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
719                                 }
720                         }
721                         if (unit->combinealpha != combinealpha)
722                         {
723                                 unit->combinealpha = combinealpha;
724                                 if (gl_combine.integer)
725                                 {
726                                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
727                                 }
728                         }
729                         if (unit->t1d != m->tex1d[i])
730                         {
731                                 if (m->tex1d[i])
732                                 {
733                                         if (unit->t1d == 0)
734                                                 qglEnable(GL_TEXTURE_1D);CHECKGLERROR
735                                 }
736                                 else
737                                 {
738                                         if (unit->t1d)
739                                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
740                                 }
741                                 qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
742                         }
743                         if (unit->t2d != m->tex[i])
744                         {
745                                 if (m->tex[i])
746                                 {
747                                         if (unit->t2d == 0)
748                                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
749                                 }
750                                 else
751                                 {
752                                         if (unit->t2d)
753                                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
754                                 }
755                                 qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
756                         }
757                         if (unit->t3d != m->tex3d[i])
758                         {
759                                 if (m->tex3d[i])
760                                 {
761                                         if (unit->t3d == 0)
762                                                 qglEnable(GL_TEXTURE_3D);CHECKGLERROR
763                                 }
764                                 else
765                                 {
766                                         if (unit->t3d)
767                                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
768                                 }
769                                 qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
770                         }
771                         if (unit->tcubemap != m->texcubemap[i])
772                         {
773                                 if (m->texcubemap[i])
774                                 {
775                                         if (unit->tcubemap == 0)
776                                                 qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
777                                 }
778                                 else
779                                 {
780                                         if (unit->tcubemap)
781                                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
782                                 }
783                                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
784                         }
785                 }
786                 scale = max(m->texrgbscale[i], 1);
787                 if (gl_state.units[i].rgbscale != scale)
788                 {
789                         if (gl_state.unit != i)
790                         {
791                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
792                         }
793                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.units[i].rgbscale = scale));CHECKGLERROR
794                 }
795                 scale = max(m->texalphascale[i], 1);
796                 if (gl_state.units[i].alphascale != scale)
797                 {
798                         if (gl_state.unit != i)
799                         {
800                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
801                         }
802                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (gl_state.units[i].alphascale = scale));CHECKGLERROR
803                 }
804         }
805 }
806
807 void R_Mesh_State(const rmeshstate_t *m)
808 {
809         R_Mesh_MainState(m);
810         R_Mesh_TextureState(m);
811 }
812
813 /*
814 ==============================================================================
815
816                                                 SCREEN SHOTS
817
818 ==============================================================================
819 */
820
821 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
822 {
823         qboolean ret;
824         int i;
825         qbyte *buffer;
826
827         if (!r_render.integer)
828                 return false;
829
830         buffer = Mem_Alloc(tempmempool, width*height*3);
831         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
832         CHECKGLERROR
833
834         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
835         if (v_hwgamma.integer)
836                 for (i = 0;i < width * height * 3;i++)
837                         buffer[i] <<= v_overbrightbits.integer;
838
839         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
840
841         Mem_Free(buffer);
842         return ret;
843 }
844
845 //=============================================================================
846
847 void R_ClearScreen(void)
848 {
849         if (r_render.integer)
850         {
851                 // clear to black
852                 qglClearColor(0,0,0,0);CHECKGLERROR
853                 qglClearDepth(1);CHECKGLERROR
854                 if (gl_stencil)
855                 {
856                         qglClearStencil(0);CHECKGLERROR
857                 }
858                 // clear the screen
859                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));CHECKGLERROR
860                 // set dithering mode
861                 if (gl_dither.integer)
862                 {
863                         qglEnable(GL_DITHER);CHECKGLERROR
864                 }
865                 else
866                 {
867                         qglDisable(GL_DITHER);CHECKGLERROR
868                 }
869         }
870 }
871
872 /*
873 ==================
874 SCR_UpdateScreen
875
876 This is called every frame, and can also be called explicitly to flush
877 text to the screen.
878 ==================
879 */
880 void SCR_UpdateScreen (void)
881 {
882         VID_Finish ();
883
884         R_TimeReport("finish");
885
886         if (r_textureunits.integer > gl_textureunits)
887                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
888         if (r_textureunits.integer < 1)
889                 Cvar_SetValueQuick(&r_textureunits, 1);
890
891         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
892                 Cvar_SetValueQuick(&gl_combine, 0);
893
894         // lighting scale
895         r_colorscale = 1.0f / (float) (1 << v_overbrightbits.integer);
896
897         // lightmaps only
898         r_lightmapscalebit = v_overbrightbits.integer;
899         if (gl_combine.integer && r_textureunits.integer > 1)
900                 r_lightmapscalebit += 2;
901
902         R_TimeReport("setup");
903
904         R_ClearScreen();
905
906         R_TimeReport("clear");
907
908         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
909                 R_RenderView();
910
911         // draw 2D stuff
912         R_DrawQueue();
913
914         // tell driver to commit it's partially full geometry queue to the rendering queue
915         // (this doesn't wait for the commands themselves to complete)
916         qglFlush();
917 }
918