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