5d63a28a7a82da5b5ae973c54800bebdade3be35
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3 #include "image.h"
4 #include "jpeg.h"
5 #include "cl_collision.h"
6
7 cvar_t gl_mesh_drawrangeelements = {0, "gl_mesh_drawrangeelements", "1", "use glDrawRangeElements function if available instead of glDrawElements (for performance comparisons or bug testing)"};
8 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)"};
9 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)"};
10 cvar_t gl_paranoid = {0, "gl_paranoid", "0", "enables OpenGL error checking and other tests"};
11 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0", "prints all OpenGL error checks, useful to identify location of driver crashes"};
12 cvar_t r_stereo_separation = {0, "r_stereo_separation", "4", "separation of eyes in the world (try negative values too)"};
13 cvar_t r_stereo_sidebyside = {0, "r_stereo_sidebyside", "0", "side by side views (for those who can't afford glasses but can afford eye strain)"};
14 cvar_t r_stereo_redblue = {0, "r_stereo_redblue", "0", "red/blue anaglyph stereo glasses (note: most of these glasses are actually red/cyan, try that one too)"};
15 cvar_t r_stereo_redcyan = {0, "r_stereo_redcyan", "0", "red/cyan anaglyph stereo glasses, the kind given away at drive-in movies like Creature From The Black Lagoon In 3D"};
16 cvar_t r_stereo_redgreen = {0, "r_stereo_redgreen", "0", "red/green anaglyph stereo glasses (for those who don't mind yellow)"};
17
18 cvar_t r_render = {0, "r_render", "1", "enables rendering calls (you want this on!)"};
19 cvar_t r_waterwarp = {CVAR_SAVE, "r_waterwarp", "1", "warp view while underwater"};
20 cvar_t gl_polyblend = {CVAR_SAVE, "gl_polyblend", "1", "tints view while underwater, hurt, etc"};
21 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1", "enables OpenGL dithering (16bit looks bad with this off)"};
22 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1", "enables use of glLockArraysEXT, may cause glitches with some broken drivers"};
23
24 int gl_maxdrawrangeelementsvertices;
25 int gl_maxdrawrangeelementsindices;
26
27 #ifdef DEBUGGL
28 int errornumber = 0;
29
30 void GL_PrintError(int errornumber, char *filename, int linenumber)
31 {
32         switch(errornumber)
33         {
34 #ifdef GL_INVALID_ENUM
35         case GL_INVALID_ENUM:
36                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
37                 break;
38 #endif
39 #ifdef GL_INVALID_VALUE
40         case GL_INVALID_VALUE:
41                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
42                 break;
43 #endif
44 #ifdef GL_INVALID_OPERATION
45         case GL_INVALID_OPERATION:
46                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
47                 break;
48 #endif
49 #ifdef GL_STACK_OVERFLOW
50         case GL_STACK_OVERFLOW:
51                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
52                 break;
53 #endif
54 #ifdef GL_STACK_UNDERFLOW
55         case GL_STACK_UNDERFLOW:
56                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
57                 break;
58 #endif
59 #ifdef GL_OUT_OF_MEMORY
60         case GL_OUT_OF_MEMORY:
61                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
62                 break;
63 #endif
64 #ifdef GL_TABLE_TOO_LARGE
65         case GL_TABLE_TOO_LARGE:
66                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
67                 break;
68 #endif
69         default:
70                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
71                 break;
72         }
73 }
74 #endif
75
76 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active");
77
78 void SCR_ScreenShot_f (void);
79
80 static matrix4x4_t backend_viewmatrix;
81 static matrix4x4_t backend_modelmatrix;
82 static matrix4x4_t backend_modelviewmatrix;
83 static matrix4x4_t backend_glmodelviewmatrix;
84 static matrix4x4_t backend_projectmatrix;
85
86 static unsigned int backendunits, backendimageunits, backendarrayunits, backendactive;
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 clockwise
95
96 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
97
98 *elements++ = i + row;
99 *elements++ = i;
100 *elements++ = i + row + 1;
101 *elements++ = i;
102 *elements++ = i + 1;
103 *elements++ = i + row + 1;
104
105
106 for (y = 0;y < rows - 1;y++)
107 {
108         for (x = 0;x < columns - 1;x++)
109         {
110                 i = y * rows + x;
111                 *elements++ = i + columns;
112                 *elements++ = i;
113                 *elements++ = i + columns + 1;
114                 *elements++ = i;
115                 *elements++ = i + 1;
116                 *elements++ = i + columns + 1;
117         }
118 }
119
120 alternative:
121 0--1--2--3--4
122 | /| /|\ | /|
123 |/ |/ | \|/ |
124 A--B--C--D--E
125 counterclockwise
126
127 for (y = 0;y < rows - 1;y++)
128 {
129         for (x = 0;x < columns - 1;x++)
130         {
131                 i = y * rows + x;
132                 *elements++ = i;
133                 *elements++ = i + columns;
134                 *elements++ = i + columns + 1;
135                 *elements++ = i + columns;
136                 *elements++ = i + columns + 1;
137                 *elements++ = i + 1;
138         }
139 }
140 */
141
142 int polygonelements[768];
143
144 static void R_Mesh_CacheArray_Startup(void);
145 static void R_Mesh_CacheArray_Shutdown(void);
146 void GL_Backend_AllocArrays(void)
147 {
148         R_Mesh_CacheArray_Startup();
149 }
150
151 void GL_Backend_FreeArrays(void)
152 {
153         R_Mesh_CacheArray_Shutdown();
154 }
155
156 static void gl_backend_start(void)
157 {
158         Con_Print("OpenGL Backend starting...\n");
159         CHECKGLERROR
160
161         if (qglDrawRangeElements != NULL)
162         {
163                 CHECKGLERROR
164                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
165                 CHECKGLERROR
166                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
167                 CHECKGLERROR
168                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
169         }
170
171         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
172         backendimageunits = backendunits;
173         backendarrayunits = backendunits;
174         if (gl_support_fragment_shader)
175         {
176                 CHECKGLERROR
177                 qglGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS_ARB, (int *)&backendimageunits);
178                 CHECKGLERROR
179                 qglGetIntegerv(GL_MAX_TEXTURE_COORDS_ARB, (int *)&backendarrayunits);
180                 CHECKGLERROR
181                 Con_Printf("GLSL shader support detected: texture units = %i texenv, %i image, %i array\n", backendunits, backendimageunits, backendarrayunits);
182         }
183         else if (backendunits > 1)
184                 Con_Printf("multitexture detected: texture units = %i\n", backendunits);
185         else
186                 Con_Printf("singletexture\n");
187
188         GL_Backend_AllocArrays();
189
190         Con_Printf("OpenGL backend started.\n");
191
192         CHECKGLERROR
193
194         backendactive = true;
195 }
196
197 static void gl_backend_shutdown(void)
198 {
199         backendunits = 0;
200         backendimageunits = 0;
201         backendarrayunits = 0;
202         backendactive = false;
203
204         Con_Print("OpenGL Backend shutting down\n");
205
206         GL_Backend_FreeArrays();
207 }
208
209 static void gl_backend_newmap(void)
210 {
211 }
212
213 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0", "displays a zoomed in overlay window"};
214 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20", "horizontal viewsize of zoom window"};
215 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20", "vertical viewsize of zoom window"};
216 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20", "fov of zoom window"};
217
218 void gl_backend_init(void)
219 {
220         int i;
221
222         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
223         {
224                 polygonelements[i * 3 + 0] = 0;
225                 polygonelements[i * 3 + 1] = i + 1;
226                 polygonelements[i * 3 + 2] = i + 2;
227         }
228
229         Cvar_RegisterVariable(&r_render);
230         Cvar_RegisterVariable(&r_waterwarp);
231         Cvar_RegisterVariable(&r_stereo_separation);
232         Cvar_RegisterVariable(&r_stereo_sidebyside);
233         Cvar_RegisterVariable(&r_stereo_redblue);
234         Cvar_RegisterVariable(&r_stereo_redcyan);
235         Cvar_RegisterVariable(&r_stereo_redgreen);
236         Cvar_RegisterVariable(&gl_polyblend);
237         Cvar_RegisterVariable(&gl_dither);
238         Cvar_RegisterVariable(&gl_lockarrays);
239         Cvar_RegisterVariable(&gl_paranoid);
240         Cvar_RegisterVariable(&gl_printcheckerror);
241 #ifdef NORENDER
242         Cvar_SetValue("r_render", 0);
243 #endif
244
245         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
246         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
247         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
248
249         Cvar_RegisterVariable(&scr_zoomwindow);
250         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
251         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
252         Cvar_RegisterVariable(&scr_zoomwindow_fov);
253
254         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
255 }
256
257 void GL_SetupView_Orientation_Identity (void)
258 {
259         backend_viewmatrix = identitymatrix;
260         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
261 }
262
263 void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
264 {
265         matrix4x4_t tempmatrix, basematrix;
266         Matrix4x4_Invert_Simple(&tempmatrix, matrix);
267         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
268         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
269         Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
270         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
271         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
272         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
273         //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
274         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
275 }
276
277 void GL_SetupView_Mode_Perspective (double frustumx, double frustumy, double zNear, double zFar)
278 {
279         double m[16];
280
281         if (!r_render.integer)
282                 return;
283
284         // set up viewpoint
285         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
286         qglLoadIdentity();CHECKGLERROR
287         // set view pyramid
288         qglFrustum(-frustumx * zNear, frustumx * zNear, -frustumy * zNear, frustumy * zNear, zNear, zFar);CHECKGLERROR
289         qglGetDoublev(GL_PROJECTION_MATRIX, m);
290         backend_projectmatrix.m[0][0] = m[0];
291         backend_projectmatrix.m[1][0] = m[1];
292         backend_projectmatrix.m[2][0] = m[2];
293         backend_projectmatrix.m[3][0] = m[3];
294         backend_projectmatrix.m[0][1] = m[4];
295         backend_projectmatrix.m[1][1] = m[5];
296         backend_projectmatrix.m[2][1] = m[6];
297         backend_projectmatrix.m[3][1] = m[7];
298         backend_projectmatrix.m[0][2] = m[8];
299         backend_projectmatrix.m[1][2] = m[9];
300         backend_projectmatrix.m[2][2] = m[10];
301         backend_projectmatrix.m[3][2] = m[11];
302         backend_projectmatrix.m[0][3] = m[12];
303         backend_projectmatrix.m[1][3] = m[13];
304         backend_projectmatrix.m[2][3] = m[14];
305         backend_projectmatrix.m[3][3] = m[15];
306         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
307         GL_SetupView_Orientation_Identity();
308 }
309
310 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double frustumx, double frustumy, double zNear)
311 {
312         double nudge, m[16];
313
314         if (!r_render.integer)
315                 return;
316
317         // set up viewpoint
318         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
319         qglLoadIdentity();CHECKGLERROR
320         // set view pyramid
321         nudge = 1.0 - 1.0 / (1<<23);
322         m[ 0] = 1.0 / frustumx;
323         m[ 1] = 0;
324         m[ 2] = 0;
325         m[ 3] = 0;
326         m[ 4] = 0;
327         m[ 5] = 1.0 / frustumy;
328         m[ 6] = 0;
329         m[ 7] = 0;
330         m[ 8] = 0;
331         m[ 9] = 0;
332         m[10] = -nudge;
333         m[11] = -1;
334         m[12] = 0;
335         m[13] = 0;
336         m[14] = -2 * zNear * nudge;
337         m[15] = 0;
338         qglLoadMatrixd(m);
339         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
340         GL_SetupView_Orientation_Identity();
341         backend_projectmatrix.m[0][0] = m[0];
342         backend_projectmatrix.m[1][0] = m[1];
343         backend_projectmatrix.m[2][0] = m[2];
344         backend_projectmatrix.m[3][0] = m[3];
345         backend_projectmatrix.m[0][1] = m[4];
346         backend_projectmatrix.m[1][1] = m[5];
347         backend_projectmatrix.m[2][1] = m[6];
348         backend_projectmatrix.m[3][1] = m[7];
349         backend_projectmatrix.m[0][2] = m[8];
350         backend_projectmatrix.m[1][2] = m[9];
351         backend_projectmatrix.m[2][2] = m[10];
352         backend_projectmatrix.m[3][2] = m[11];
353         backend_projectmatrix.m[0][3] = m[12];
354         backend_projectmatrix.m[1][3] = m[13];
355         backend_projectmatrix.m[2][3] = m[14];
356         backend_projectmatrix.m[3][3] = m[15];
357 }
358
359 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
360 {
361         double m[16];
362
363         if (!r_render.integer)
364                 return;
365
366         // set up viewpoint
367         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
368         qglLoadIdentity();CHECKGLERROR
369         qglOrtho(x1, x2, y2, y1, zNear, zFar);
370         qglGetDoublev(GL_PROJECTION_MATRIX, m);
371         backend_projectmatrix.m[0][0] = m[0];
372         backend_projectmatrix.m[1][0] = m[1];
373         backend_projectmatrix.m[2][0] = m[2];
374         backend_projectmatrix.m[3][0] = m[3];
375         backend_projectmatrix.m[0][1] = m[4];
376         backend_projectmatrix.m[1][1] = m[5];
377         backend_projectmatrix.m[2][1] = m[6];
378         backend_projectmatrix.m[3][1] = m[7];
379         backend_projectmatrix.m[0][2] = m[8];
380         backend_projectmatrix.m[1][2] = m[9];
381         backend_projectmatrix.m[2][2] = m[10];
382         backend_projectmatrix.m[3][2] = m[11];
383         backend_projectmatrix.m[0][3] = m[12];
384         backend_projectmatrix.m[1][3] = m[13];
385         backend_projectmatrix.m[2][3] = m[14];
386         backend_projectmatrix.m[3][3] = m[15];
387         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
388         GL_SetupView_Orientation_Identity();
389 }
390
391 typedef struct gltextureunit_s
392 {
393         int t1d, t2d, t3d, tcubemap;
394         int arrayenabled;
395         unsigned int arraycomponents;
396         const void *pointer_texcoord;
397         float rgbscale, alphascale;
398         int combinergb, combinealpha;
399         // FIXME: add more combine stuff
400         // texmatrixenabled exists only to avoid unnecessary texmatrix compares
401         int texmatrixenabled;
402         matrix4x4_t matrix;
403 }
404 gltextureunit_t;
405
406 static struct gl_state_s
407 {
408         int blendfunc1;
409         int blendfunc2;
410         int blend;
411         GLboolean depthmask;
412         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
413         int depthtest;
414         int scissortest;
415         unsigned int unit;
416         unsigned int clientunit;
417         gltextureunit_t units[MAX_TEXTUREUNITS];
418         float color4f[4];
419         int lockrange_first;
420         int lockrange_count;
421         const void *pointer_vertex;
422         const void *pointer_color;
423 }
424 gl_state;
425
426 void GL_SetupTextureState(void)
427 {
428         unsigned int i;
429         gltextureunit_t *unit;
430         CHECKGLERROR
431         gl_state.unit = MAX_TEXTUREUNITS;
432         gl_state.clientunit = MAX_TEXTUREUNITS;
433         for (i = 0;i < MAX_TEXTUREUNITS;i++)
434         {
435                 unit = gl_state.units + i;
436                 unit->t1d = 0;
437                 unit->t2d = 0;
438                 unit->t3d = 0;
439                 unit->tcubemap = 0;
440                 unit->arrayenabled = false;
441                 unit->arraycomponents = 0;
442                 unit->pointer_texcoord = NULL;
443                 unit->rgbscale = 1;
444                 unit->alphascale = 1;
445                 unit->combinergb = GL_MODULATE;
446                 unit->combinealpha = GL_MODULATE;
447                 unit->texmatrixenabled = false;
448                 unit->matrix = identitymatrix;
449         }
450
451         for (i = 0;i < backendimageunits;i++)
452         {
453                 GL_ActiveTexture(i);
454                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
455                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
456                 if (gl_texture3d)
457                 {
458                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
459                 }
460                 if (gl_texturecubemap)
461                 {
462                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
463                 }
464         }
465
466         for (i = 0;i < backendarrayunits;i++)
467         {
468                 GL_ClientActiveTexture(i);
469                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
470                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
471         }
472
473         for (i = 0;i < backendunits;i++)
474         {
475                 GL_ActiveTexture(i);
476                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
477                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
478                 if (gl_texture3d)
479                 {
480                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
481                 }
482                 if (gl_texturecubemap)
483                 {
484                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
485                 }
486                 qglMatrixMode(GL_TEXTURE);
487                 qglLoadIdentity();
488                 qglMatrixMode(GL_MODELVIEW);
489                 if (gl_combine.integer)
490                 {
491                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
492                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
493                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
494                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
495                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
496                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
497                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
498                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
499                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
500                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
501                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
502                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
503                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
504                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
505                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
506                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
507                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
508                 }
509                 else
510                 {
511                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
512                 }
513         }
514         CHECKGLERROR
515 }
516
517 void GL_Backend_ResetState(void)
518 {
519         memset(&gl_state, 0, sizeof(gl_state));
520         gl_state.depthtest = true;
521         gl_state.blendfunc1 = GL_ONE;
522         gl_state.blendfunc2 = GL_ZERO;
523         gl_state.blend = false;
524         gl_state.depthmask = GL_TRUE;
525         gl_state.colormask = 15;
526         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
527         gl_state.lockrange_first = 0;
528         gl_state.lockrange_count = 0;
529         gl_state.pointer_vertex = NULL;
530         gl_state.pointer_color = NULL;
531
532         CHECKGLERROR
533
534         qglColorMask(1, 1, 1, 1);
535         qglEnable(GL_CULL_FACE);CHECKGLERROR
536         qglCullFace(GL_FRONT);CHECKGLERROR
537         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
538         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
539         qglDisable(GL_BLEND);CHECKGLERROR
540         qglDepthMask(gl_state.depthmask);CHECKGLERROR
541
542         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
543         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
544
545         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
546         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
547
548         GL_Color(0, 0, 0, 0);
549         GL_Color(1, 1, 1, 1);
550
551         GL_SetupTextureState();
552 }
553
554 void GL_ActiveTexture(unsigned int num)
555 {
556         if (gl_state.unit != num)
557         {
558                 gl_state.unit = num;
559                 if (qglActiveTexture)
560                 {
561                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
562                         CHECKGLERROR
563                 }
564         }
565 }
566
567 void GL_ClientActiveTexture(unsigned int num)
568 {
569         if (gl_state.clientunit != num)
570         {
571                 gl_state.clientunit = num;
572                 if (qglActiveTexture)
573                 {
574                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
575                         CHECKGLERROR
576                 }
577         }
578 }
579
580 void GL_BlendFunc(int blendfunc1, int blendfunc2)
581 {
582         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
583         {
584                 if (r_showtrispass)
585                         return;
586                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
587                 if (gl_state.blendfunc2 == GL_ZERO)
588                 {
589                         if (gl_state.blendfunc1 == GL_ONE)
590                         {
591                                 if (gl_state.blend)
592                                 {
593                                         gl_state.blend = 0;
594                                         qglDisable(GL_BLEND);CHECKGLERROR
595                                 }
596                         }
597                         else
598                         {
599                                 if (!gl_state.blend)
600                                 {
601                                         gl_state.blend = 1;
602                                         qglEnable(GL_BLEND);CHECKGLERROR
603                                 }
604                         }
605                 }
606                 else
607                 {
608                         if (!gl_state.blend)
609                         {
610                                 gl_state.blend = 1;
611                                 qglEnable(GL_BLEND);CHECKGLERROR
612                         }
613                 }
614         }
615 }
616
617 void GL_DepthMask(int state)
618 {
619         if (gl_state.depthmask != state)
620         {
621                 if (r_showtrispass)
622                         return;
623                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
624         }
625 }
626
627 void GL_DepthTest(int state)
628 {
629         if (gl_state.depthtest != state)
630         {
631                 if (r_showtrispass && r_showdisabledepthtest.integer)
632                         return;
633                 gl_state.depthtest = state;
634                 if (gl_state.depthtest)
635                 {
636                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
637                 }
638                 else
639                 {
640                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
641                 }
642         }
643 }
644
645 void GL_ColorMask(int r, int g, int b, int a)
646 {
647         int state = r*8 + g*4 + b*2 + a*1;
648         if (gl_state.colormask != state)
649         {
650                 gl_state.colormask = state;
651                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
652         }
653 }
654
655 void GL_Color(float cr, float cg, float cb, float ca)
656 {
657         if (gl_state.pointer_color || gl_state.color4f[0] != cr || gl_state.color4f[1] != cg || gl_state.color4f[2] != cb || gl_state.color4f[3] != ca)
658         {
659                 if (r_showtrispass)
660                         return;
661                 gl_state.color4f[0] = cr;
662                 gl_state.color4f[1] = cg;
663                 gl_state.color4f[2] = cb;
664                 gl_state.color4f[3] = ca;
665                 CHECKGLERROR
666                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
667                 CHECKGLERROR
668         }
669 }
670
671 void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
672 {
673         if (!r_showtrispass)
674                 return;
675         r_showtrispass = 0;
676         GL_Color(cr * r_showtris.value, cg * r_showtris.value, cb * r_showtris.value, ca);
677         r_showtrispass = 1;
678 }
679
680
681 void GL_LockArrays(int first, int count)
682 {
683         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
684         {
685                 if (gl_state.lockrange_count)
686                 {
687                         gl_state.lockrange_count = 0;
688                         CHECKGLERROR
689                         qglUnlockArraysEXT();
690                         CHECKGLERROR
691                 }
692                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
693                 {
694                         gl_state.lockrange_first = first;
695                         gl_state.lockrange_count = count;
696                         CHECKGLERROR
697                         qglLockArraysEXT(first, count);
698                         CHECKGLERROR
699                 }
700         }
701 }
702
703 void GL_Scissor (int x, int y, int width, int height)
704 {
705         CHECKGLERROR
706         qglScissor(x, vid.height - (y + height),width,height);
707         CHECKGLERROR
708 }
709
710 void GL_ScissorTest(int state)
711 {
712         if(gl_state.scissortest == state)
713                 return;
714
715         CHECKGLERROR
716         if((gl_state.scissortest = state))
717                 qglEnable(GL_SCISSOR_TEST);
718         else
719                 qglDisable(GL_SCISSOR_TEST);
720         CHECKGLERROR
721 }
722
723 void GL_Clear(int mask)
724 {
725         // in showtris rendering, don't clear the color buffer as that would hide
726         // the accumulated lines
727         if (r_showtrispass)
728                 mask &= ~GL_COLOR_BUFFER_BIT;
729         qglClear(mask);CHECKGLERROR
730 }
731
732 void GL_TransformToScreen(const vec4_t in, vec4_t out)
733 {
734         vec4_t temp;
735         float iw;
736         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
737         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
738         iw = 1.0f / out[3];
739         out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
740         out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
741         out[2] = r_view_z + (out[2] * iw + 1.0f) * r_view_depth * 0.5f;
742 }
743
744 // called at beginning of frame
745 void R_Mesh_Start(void)
746 {
747         BACKENDACTIVECHECK
748         CHECKGLERROR
749         GL_Backend_ResetState();
750 }
751
752 unsigned int GL_Backend_CompileProgram(int vertexstrings_count, const char **vertexstrings_list, int fragmentstrings_count, const char **fragmentstrings_list)
753 {
754         GLint vertexshadercompiled, fragmentshadercompiled, programlinked;
755         GLuint vertexshaderobject, fragmentshaderobject, programobject = 0;
756         char compilelog[MAX_INPUTLINE];
757         CHECKGLERROR
758
759         programobject = qglCreateProgramObjectARB();
760         CHECKGLERROR
761         if (!programobject)
762                 return 0;
763
764         if (vertexstrings_count)
765         {
766                 CHECKGLERROR
767                 vertexshaderobject = qglCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
768                 if (!vertexshaderobject)
769                 {
770                         qglDeleteObjectARB(programobject);
771                         CHECKGLERROR
772                         return 0;
773                 }
774                 qglShaderSourceARB(vertexshaderobject, vertexstrings_count, vertexstrings_list, NULL);
775                 qglCompileShaderARB(vertexshaderobject);
776                 CHECKGLERROR
777                 qglGetObjectParameterivARB(vertexshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &vertexshadercompiled);
778                 qglGetInfoLogARB(vertexshaderobject, sizeof(compilelog), NULL, compilelog);
779                 if (compilelog[0])
780                         Con_DPrintf("vertex shader compile log:\n%s\n", compilelog);
781                 if (!vertexshadercompiled)
782                 {
783                         qglDeleteObjectARB(programobject);
784                         qglDeleteObjectARB(vertexshaderobject);
785                         CHECKGLERROR
786                         return 0;
787                 }
788                 qglAttachObjectARB(programobject, vertexshaderobject);
789                 qglDeleteObjectARB(vertexshaderobject);
790                 CHECKGLERROR
791         }
792
793         if (fragmentstrings_count)
794         {
795                 CHECKGLERROR
796                 fragmentshaderobject = qglCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
797                 if (!fragmentshaderobject)
798                 {
799                         qglDeleteObjectARB(programobject);
800                         CHECKGLERROR
801                         return 0;
802                 }
803                 qglShaderSourceARB(fragmentshaderobject, fragmentstrings_count, fragmentstrings_list, NULL);
804                 qglCompileShaderARB(fragmentshaderobject);
805                 CHECKGLERROR
806                 qglGetObjectParameterivARB(fragmentshaderobject, GL_OBJECT_COMPILE_STATUS_ARB, &fragmentshadercompiled);
807                 qglGetInfoLogARB(fragmentshaderobject, sizeof(compilelog), NULL, compilelog);
808                 if (compilelog[0])
809                         Con_DPrintf("fragment shader compile log:\n%s\n", compilelog);
810                 if (!fragmentshadercompiled)
811                 {
812                         qglDeleteObjectARB(programobject);
813                         qglDeleteObjectARB(fragmentshaderobject);
814                         CHECKGLERROR
815                         return 0;
816                 }
817                 qglAttachObjectARB(programobject, fragmentshaderobject);
818                 qglDeleteObjectARB(fragmentshaderobject);
819                 CHECKGLERROR
820         }
821
822         qglLinkProgramARB(programobject);
823         CHECKGLERROR
824         qglGetObjectParameterivARB(programobject, GL_OBJECT_LINK_STATUS_ARB, &programlinked);
825         qglGetInfoLogARB(programobject, sizeof(compilelog), NULL, compilelog);
826         if (compilelog[0])
827         {
828                 Con_DPrintf("program link log:\n%s\n", compilelog);
829                 // software vertex shader is ok but software fragment shader is WAY
830                 // too slow, fail program if so.
831                 // NOTE: this string might be ATI specific, but that's ok because the
832                 // ATI R300 chip (Radeon 9500-9800/X300) is the most likely to use a
833                 // software fragment shader due to low instruction and dependent
834                 // texture limits.
835                 if (strstr(compilelog, "fragment shader will run in software"))
836                         programlinked = false;
837         }
838         CHECKGLERROR
839         if (!programlinked)
840         {
841                 qglDeleteObjectARB(programobject);
842                 return 0;
843         }
844         CHECKGLERROR
845         return programobject;
846 }
847
848 void GL_Backend_FreeProgram(unsigned int prog)
849 {
850         CHECKGLERROR
851         qglDeleteObjectARB(prog);
852         CHECKGLERROR
853 }
854
855 int gl_backend_rebindtextures;
856
857 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
858 {
859         int i;
860         if (offset)
861         {
862                 for (i = 0;i < count;i++)
863                         *out++ = *in++ + offset;
864         }
865         else
866                 memcpy(out, in, sizeof(*out) * count);
867 }
868
869 // renders triangles using vertices from the active arrays
870 int paranoidblah = 0;
871 void R_Mesh_Draw(int firstvertex, int numvertices, int numtriangles, const int *elements)
872 {
873         unsigned int numelements = numtriangles * 3;
874         if (numvertices < 3 || numtriangles < 1)
875         {
876                 Con_Printf("R_Mesh_Draw(%d, %d, %d, %08p);\n", firstvertex, numvertices, numtriangles, elements);
877                 return;
878         }
879         //CHECKGLERROR
880         if (r_showtrispass)
881         {
882                 R_Mesh_Draw_ShowTris(firstvertex, numvertices, numtriangles, elements);
883                 return;
884         }
885         renderstats.meshes++;
886         renderstats.meshes_elements += numelements;
887         if (gl_paranoid.integer)
888         {
889                 unsigned int i, j, size;
890                 const int *p;
891                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
892                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
893                 for (j = 0, size = numvertices * 3, p = (int *)((float *)gl_state.pointer_vertex + firstvertex * 3);j < size;j++, p++)
894                         paranoidblah += *p;
895                 if (gl_state.pointer_color)
896                 {
897                         if (!qglIsEnabled(GL_COLOR_ARRAY))
898                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
899                         for (j = 0, size = numvertices * 4, p = (int *)((float *)gl_state.pointer_color + firstvertex * 4);j < size;j++, p++)
900                                 paranoidblah += *p;
901                 }
902                 for (i = 0;i < backendarrayunits;i++)
903                 {
904                         if (gl_state.units[i].arrayenabled)
905                         {
906                                 GL_ClientActiveTexture(i);
907                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
908                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
909                                 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++)
910                                         paranoidblah += *p;
911                         }
912                 }
913                 for (i = 0;i < (unsigned int) numtriangles * 3;i++)
914                 {
915                         if (elements[i] < firstvertex || elements[i] >= firstvertex + numvertices)
916                         {
917                                 Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range %i - %i) in elements list\n", elements[i], firstvertex, firstvertex + numvertices);
918                                 return;
919                         }
920                 }
921                 CHECKGLERROR
922         }
923         if (r_render.integer)
924         {
925                 CHECKGLERROR
926                 if (gl_mesh_testmanualfeeding.integer)
927                 {
928                         unsigned int i, j;
929                         const GLfloat *p;
930                         qglBegin(GL_TRIANGLES);
931                         for (i = 0;i < (unsigned int) numtriangles * 3;i++)
932                         {
933                                 for (j = 0;j < backendarrayunits;j++)
934                                 {
935                                         if (gl_state.units[j].pointer_texcoord)
936                                         {
937                                                 if (backendarrayunits > 1)
938                                                 {
939                                                         if (gl_state.units[j].arraycomponents == 4)
940                                                         {
941                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
942                                                                 qglMultiTexCoord4f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2], p[3]);
943                                                         }
944                                                         else if (gl_state.units[j].arraycomponents == 3)
945                                                         {
946                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
947                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
948                                                         }
949                                                         else if (gl_state.units[j].arraycomponents == 2)
950                                                         {
951                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
952                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
953                                                         }
954                                                         else
955                                                         {
956                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
957                                                                 qglMultiTexCoord1f(GL_TEXTURE0_ARB + j, p[0]);
958                                                         }
959                                                 }
960                                                 else
961                                                 {
962                                                         if (gl_state.units[j].arraycomponents == 4)
963                                                         {
964                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 4;
965                                                                 qglTexCoord4f(p[0], p[1], p[2], p[3]);
966                                                         }
967                                                         else if (gl_state.units[j].arraycomponents == 3)
968                                                         {
969                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
970                                                                 qglTexCoord3f(p[0], p[1], p[2]);
971                                                         }
972                                                         else if (gl_state.units[j].arraycomponents == 2)
973                                                         {
974                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
975                                                                 qglTexCoord2f(p[0], p[1]);
976                                                         }
977                                                         else
978                                                         {
979                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 1;
980                                                                 qglTexCoord1f(p[0]);
981                                                         }
982                                                 }
983                                         }
984                                 }
985                                 if (gl_state.pointer_color)
986                                 {
987                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
988                                         qglColor4f(p[0], p[1], p[2], p[3]);
989                                 }
990                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
991                                 qglVertex3f(p[0], p[1], p[2]);
992                         }
993                         qglEnd();
994                         CHECKGLERROR
995                 }
996                 else if (gl_mesh_testarrayelement.integer)
997                 {
998                         int i;
999                         qglBegin(GL_TRIANGLES);
1000                         for (i = 0;i < numtriangles * 3;i++)
1001                         {
1002                                 qglArrayElement(elements[i]);
1003                         }
1004                         qglEnd();
1005                         CHECKGLERROR
1006                 }
1007                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
1008                 {
1009                         qglDrawRangeElements(GL_TRIANGLES, firstvertex, firstvertex + numvertices, numelements, GL_UNSIGNED_INT, elements);
1010                         CHECKGLERROR
1011                 }
1012                 else
1013                 {
1014                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);
1015                         CHECKGLERROR
1016                 }
1017         }
1018 }
1019
1020 // restores backend state, used when done with 3D rendering
1021 void R_Mesh_Finish(void)
1022 {
1023         unsigned int i;
1024         BACKENDACTIVECHECK
1025         CHECKGLERROR
1026         GL_LockArrays(0, 0);
1027         CHECKGLERROR
1028
1029         for (i = 0;i < backendimageunits;i++)
1030         {
1031                 GL_ActiveTexture(i);
1032                 qglBindTexture(GL_TEXTURE_1D, 0);CHECKGLERROR
1033                 qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
1034                 if (gl_texture3d)
1035                 {
1036                         qglBindTexture(GL_TEXTURE_3D, 0);CHECKGLERROR
1037                 }
1038                 if (gl_texturecubemap)
1039                 {
1040                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, 0);CHECKGLERROR
1041                 }
1042         }
1043         for (i = 0;i < backendarrayunits;i++)
1044         {
1045                 GL_ActiveTexture(backendarrayunits - 1 - i);
1046                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1047         }
1048         for (i = 0;i < backendunits;i++)
1049         {
1050                 GL_ActiveTexture(backendunits - 1 - i);
1051                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1052                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1053                 if (gl_texture3d)
1054                 {
1055                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1056                 }
1057                 if (gl_texturecubemap)
1058                 {
1059                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1060                 }
1061                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1062                 if (gl_combine.integer)
1063                 {
1064                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
1065                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
1066                 }
1067         }
1068         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1069         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1070
1071         qglDisable(GL_BLEND);CHECKGLERROR
1072         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1073         qglDepthMask(GL_TRUE);CHECKGLERROR
1074         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
1075 }
1076
1077 void R_Mesh_Matrix(const matrix4x4_t *matrix)
1078 {
1079         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
1080         {
1081                 backend_modelmatrix = *matrix;
1082                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
1083                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
1084                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
1085         }
1086 }
1087
1088 void R_Mesh_VertexPointer(const float *vertex3f)
1089 {
1090         if (gl_state.pointer_vertex != vertex3f)
1091         {
1092                 gl_state.pointer_vertex = vertex3f;
1093                 CHECKGLERROR
1094                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
1095                 CHECKGLERROR
1096         }
1097 }
1098
1099 void R_Mesh_ColorPointer(const float *color4f)
1100 {
1101         if (r_showtrispass)
1102                 return;
1103         if (gl_state.pointer_color != color4f)
1104         {
1105                 CHECKGLERROR
1106                 if (!gl_state.pointer_color)
1107                 {
1108                         qglEnableClientState(GL_COLOR_ARRAY);
1109                         CHECKGLERROR
1110                 }
1111                 else if (!color4f)
1112                 {
1113                         qglDisableClientState(GL_COLOR_ARRAY);
1114                         CHECKGLERROR
1115                         // when color array is on the glColor gets trashed, set it again
1116                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
1117                         CHECKGLERROR
1118                 }
1119                 gl_state.pointer_color = color4f;
1120                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
1121                 CHECKGLERROR
1122         }
1123 }
1124
1125 void R_Mesh_TexCoordPointer(unsigned int unitnum, unsigned int numcomponents, const float *texcoord)
1126 {
1127         gltextureunit_t *unit = gl_state.units + unitnum;
1128         if (r_showtrispass)
1129                 return;
1130         // update array settings
1131         if (texcoord)
1132         {
1133                 // texcoord array
1134                 if (unit->pointer_texcoord != texcoord || unit->arraycomponents != numcomponents)
1135                 {
1136                         unit->pointer_texcoord = texcoord;
1137                         unit->arraycomponents = numcomponents;
1138                         GL_ClientActiveTexture(unitnum);
1139                         qglTexCoordPointer(unit->arraycomponents, GL_FLOAT, sizeof(float) * unit->arraycomponents, unit->pointer_texcoord);
1140                         CHECKGLERROR
1141                 }
1142                 // texture array unit is enabled, enable the array
1143                 if (!unit->arrayenabled)
1144                 {
1145                         unit->arrayenabled = true;
1146                         GL_ClientActiveTexture(unitnum);
1147                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1148                 }
1149         }
1150         else
1151         {
1152                 // texture array unit is disabled, disable the array
1153                 if (unit->arrayenabled)
1154                 {
1155                         unit->arrayenabled = false;
1156                         GL_ClientActiveTexture(unitnum);
1157                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1158                 }
1159         }
1160 }
1161
1162 void R_Mesh_TexBindAll(unsigned int unitnum, int tex1d, int tex2d, int tex3d, int texcubemap)
1163 {
1164         gltextureunit_t *unit = gl_state.units + unitnum;
1165         if (unitnum >= backendimageunits)
1166                 return;
1167         if (r_showtrispass)
1168                 return;
1169         // update 1d texture binding
1170         if (unit->t1d != tex1d)
1171         {
1172                 GL_ActiveTexture(unitnum);
1173                 if (unitnum < backendunits)
1174                 {
1175                         if (tex1d)
1176                         {
1177                                 if (unit->t1d == 0)
1178                                         qglEnable(GL_TEXTURE_1D);
1179                         }
1180                         else
1181                         {
1182                                 if (unit->t1d)
1183                                         qglDisable(GL_TEXTURE_1D);
1184                         }
1185                 }
1186                 unit->t1d = tex1d;
1187                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1188                 CHECKGLERROR
1189         }
1190         // update 2d texture binding
1191         if (unit->t2d != tex2d)
1192         {
1193                 GL_ActiveTexture(unitnum);
1194                 if (unitnum < backendunits)
1195                 {
1196                         if (tex2d)
1197                         {
1198                                 if (unit->t2d == 0)
1199                                         qglEnable(GL_TEXTURE_2D);
1200                         }
1201                         else
1202                         {
1203                                 if (unit->t2d)
1204                                         qglDisable(GL_TEXTURE_2D);
1205                         }
1206                 }
1207                 unit->t2d = tex2d;
1208                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1209                 CHECKGLERROR
1210         }
1211         // update 3d texture binding
1212         if (unit->t3d != tex3d)
1213         {
1214                 GL_ActiveTexture(unitnum);
1215                 if (unitnum < backendunits)
1216                 {
1217                         if (tex3d)
1218                         {
1219                                 if (unit->t3d == 0)
1220                                         qglEnable(GL_TEXTURE_3D);
1221                         }
1222                         else
1223                         {
1224                                 if (unit->t3d)
1225                                         qglDisable(GL_TEXTURE_3D);
1226                         }
1227                 }
1228                 unit->t3d = tex3d;
1229                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1230                 CHECKGLERROR
1231         }
1232         // update cubemap texture binding
1233         if (unit->tcubemap != texcubemap)
1234         {
1235                 GL_ActiveTexture(unitnum);
1236                 if (unitnum < backendunits)
1237                 {
1238                         if (texcubemap)
1239                         {
1240                                 if (unit->tcubemap == 0)
1241                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
1242                         }
1243                         else
1244                         {
1245                                 if (unit->tcubemap)
1246                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1247                         }
1248                 }
1249                 unit->tcubemap = texcubemap;
1250                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1251                 CHECKGLERROR
1252         }
1253 }
1254
1255 void R_Mesh_TexBind1D(unsigned int unitnum, int texnum)
1256 {
1257         gltextureunit_t *unit = gl_state.units + unitnum;
1258         if (unitnum >= backendimageunits)
1259                 return;
1260         if (r_showtrispass)
1261                 return;
1262         // update 1d texture binding
1263         if (unit->t1d != texnum)
1264         {
1265                 GL_ActiveTexture(unitnum);
1266                 if (unitnum < backendunits)
1267                 {
1268                         if (texnum)
1269                         {
1270                                 if (unit->t1d == 0)
1271                                         qglEnable(GL_TEXTURE_1D);
1272                         }
1273                         else
1274                         {
1275                                 if (unit->t1d)
1276                                         qglDisable(GL_TEXTURE_1D);
1277                         }
1278                 }
1279                 unit->t1d = texnum;
1280                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1281                 CHECKGLERROR
1282         }
1283         // update 2d texture binding
1284         if (unit->t2d)
1285         {
1286                 GL_ActiveTexture(unitnum);
1287                 if (unitnum < backendunits)
1288                 {
1289                         if (unit->t2d)
1290                                 qglDisable(GL_TEXTURE_2D);
1291                 }
1292                 unit->t2d = 0;
1293                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1294                 CHECKGLERROR
1295         }
1296         // update 3d texture binding
1297         if (unit->t3d)
1298         {
1299                 GL_ActiveTexture(unitnum);
1300                 if (unitnum < backendunits)
1301                 {
1302                         if (unit->t3d)
1303                                 qglDisable(GL_TEXTURE_3D);
1304                 }
1305                 unit->t3d = 0;
1306                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1307                 CHECKGLERROR
1308         }
1309         // update cubemap texture binding
1310         if (unit->tcubemap)
1311         {
1312                 GL_ActiveTexture(unitnum);
1313                 if (unitnum < backendunits)
1314                 {
1315                         if (unit->tcubemap)
1316                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1317                 }
1318                 unit->tcubemap = 0;
1319                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1320                 CHECKGLERROR
1321         }
1322 }
1323
1324 void R_Mesh_TexBind(unsigned int unitnum, int texnum)
1325 {
1326         gltextureunit_t *unit = gl_state.units + unitnum;
1327         if (unitnum >= backendimageunits)
1328                 return;
1329         if (r_showtrispass)
1330                 return;
1331         // update 1d texture binding
1332         if (unit->t1d)
1333         {
1334                 GL_ActiveTexture(unitnum);
1335                 if (unitnum < backendunits)
1336                 {
1337                         if (unit->t1d)
1338                                 qglDisable(GL_TEXTURE_1D);
1339                 }
1340                 unit->t1d = 0;
1341                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1342                 CHECKGLERROR
1343         }
1344         // update 2d texture binding
1345         if (unit->t2d != texnum)
1346         {
1347                 GL_ActiveTexture(unitnum);
1348                 if (unitnum < backendunits)
1349                 {
1350                         if (texnum)
1351                         {
1352                                 if (unit->t2d == 0)
1353                                         qglEnable(GL_TEXTURE_2D);
1354                         }
1355                         else
1356                         {
1357                                 if (unit->t2d)
1358                                         qglDisable(GL_TEXTURE_2D);
1359                         }
1360                 }
1361                 unit->t2d = texnum;
1362                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1363                 CHECKGLERROR
1364         }
1365         // update 3d texture binding
1366         if (unit->t3d)
1367         {
1368                 GL_ActiveTexture(unitnum);
1369                 if (unitnum < backendunits)
1370                 {
1371                         if (unit->t3d)
1372                                 qglDisable(GL_TEXTURE_3D);
1373                 }
1374                 unit->t3d = 0;
1375                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1376                 CHECKGLERROR
1377         }
1378         // update cubemap texture binding
1379         if (unit->tcubemap != 0)
1380         {
1381                 GL_ActiveTexture(unitnum);
1382                 if (unitnum < backendunits)
1383                 {
1384                         if (unit->tcubemap)
1385                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1386                 }
1387                 unit->tcubemap = 0;
1388                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1389                 CHECKGLERROR
1390         }
1391 }
1392
1393 void R_Mesh_TexBind3D(unsigned int unitnum, int texnum)
1394 {
1395         gltextureunit_t *unit = gl_state.units + unitnum;
1396         if (unitnum >= backendimageunits)
1397                 return;
1398         if (r_showtrispass)
1399                 return;
1400         // update 1d texture binding
1401         if (unit->t1d)
1402         {
1403                 GL_ActiveTexture(unitnum);
1404                 if (unitnum < backendunits)
1405                 {
1406                         if (unit->t1d)
1407                                 qglDisable(GL_TEXTURE_1D);
1408                 }
1409                 unit->t1d = 0;
1410                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1411                 CHECKGLERROR
1412         }
1413         // update 2d texture binding
1414         if (unit->t2d)
1415         {
1416                 GL_ActiveTexture(unitnum);
1417                 if (unitnum < backendunits)
1418                 {
1419                         if (unit->t2d)
1420                                 qglDisable(GL_TEXTURE_2D);
1421                 }
1422                 unit->t2d = 0;
1423                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1424                 CHECKGLERROR
1425         }
1426         // update 3d texture binding
1427         if (unit->t3d != texnum)
1428         {
1429                 GL_ActiveTexture(unitnum);
1430                 if (unitnum < backendunits)
1431                 {
1432                         if (texnum)
1433                         {
1434                                 if (unit->t3d == 0)
1435                                         qglEnable(GL_TEXTURE_3D);
1436                         }
1437                         else
1438                         {
1439                                 if (unit->t3d)
1440                                         qglDisable(GL_TEXTURE_3D);
1441                         }
1442                 }
1443                 unit->t3d = texnum;
1444                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1445                 CHECKGLERROR
1446         }
1447         // update cubemap texture binding
1448         if (unit->tcubemap != 0)
1449         {
1450                 GL_ActiveTexture(unitnum);
1451                 if (unitnum < backendunits)
1452                 {
1453                         if (unit->tcubemap)
1454                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1455                 }
1456                 unit->tcubemap = 0;
1457                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1458                 CHECKGLERROR
1459         }
1460 }
1461
1462 void R_Mesh_TexBindCubeMap(unsigned int unitnum, int texnum)
1463 {
1464         gltextureunit_t *unit = gl_state.units + unitnum;
1465         if (unitnum >= backendimageunits)
1466                 return;
1467         if (r_showtrispass)
1468                 return;
1469         // update 1d texture binding
1470         if (unit->t1d)
1471         {
1472                 GL_ActiveTexture(unitnum);
1473                 if (unitnum < backendunits)
1474                 {
1475                         if (unit->t1d)
1476                                 qglDisable(GL_TEXTURE_1D);
1477                 }
1478                 unit->t1d = 0;
1479                 qglBindTexture(GL_TEXTURE_1D, unit->t1d);
1480                 CHECKGLERROR
1481         }
1482         // update 2d texture binding
1483         if (unit->t2d)
1484         {
1485                 GL_ActiveTexture(unitnum);
1486                 if (unitnum < backendunits)
1487                 {
1488                         if (unit->t2d)
1489                                 qglDisable(GL_TEXTURE_2D);
1490                 }
1491                 unit->t2d = 0;
1492                 qglBindTexture(GL_TEXTURE_2D, unit->t2d);
1493                 CHECKGLERROR
1494         }
1495         // update 3d texture binding
1496         if (unit->t3d)
1497         {
1498                 GL_ActiveTexture(unitnum);
1499                 if (unitnum < backendunits)
1500                 {
1501                         if (unit->t3d)
1502                                 qglDisable(GL_TEXTURE_3D);
1503                 }
1504                 unit->t3d = 0;
1505                 qglBindTexture(GL_TEXTURE_3D, unit->t3d);
1506                 CHECKGLERROR
1507         }
1508         // update cubemap texture binding
1509         if (unit->tcubemap != texnum)
1510         {
1511                 GL_ActiveTexture(unitnum);
1512                 if (unitnum < backendunits)
1513                 {
1514                         if (texnum)
1515                         {
1516                                 if (unit->tcubemap == 0)
1517                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);
1518                         }
1519                         else
1520                         {
1521                                 if (unit->tcubemap)
1522                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);
1523                         }
1524                 }
1525                 unit->tcubemap = texnum;
1526                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, unit->tcubemap);
1527                 CHECKGLERROR
1528         }
1529 }
1530
1531 void R_Mesh_TexMatrix(unsigned int unitnum, const matrix4x4_t *matrix)
1532 {
1533         gltextureunit_t *unit = gl_state.units + unitnum;
1534         if (r_showtrispass)
1535                 return;
1536         if (matrix->m[3][3])
1537         {
1538                 // texmatrix specified, check if it is different
1539                 if (!unit->texmatrixenabled || memcmp(&unit->matrix, matrix, sizeof(matrix4x4_t)))
1540                 {
1541                         matrix4x4_t tempmatrix;
1542                         unit->texmatrixenabled = true;
1543                         unit->matrix = *matrix;
1544                         Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
1545                         qglMatrixMode(GL_TEXTURE);
1546                         GL_ActiveTexture(unitnum);
1547                         qglLoadMatrixf(&tempmatrix.m[0][0]);
1548                         qglMatrixMode(GL_MODELVIEW);
1549                 }
1550         }
1551         else
1552         {
1553                 // no texmatrix specified, revert to identity
1554                 if (unit->texmatrixenabled)
1555                 {
1556                         unit->texmatrixenabled = false;
1557                         qglMatrixMode(GL_TEXTURE);
1558                         GL_ActiveTexture(unitnum);
1559                         qglLoadIdentity();
1560                         qglMatrixMode(GL_MODELVIEW);
1561                 }
1562         }
1563 }
1564
1565 void R_Mesh_TexCombine(unsigned int unitnum, int combinergb, int combinealpha, int rgbscale, int alphascale)
1566 {
1567         gltextureunit_t *unit = gl_state.units + unitnum;
1568         if (r_showtrispass)
1569                 return;
1570         if (gl_combine.integer)
1571         {
1572                 // GL_ARB_texture_env_combine
1573                 if (!combinergb)
1574                         combinergb = GL_MODULATE;
1575                 if (!combinealpha)
1576                         combinealpha = GL_MODULATE;
1577                 if (!rgbscale)
1578                         rgbscale = 1;
1579                 if (!alphascale)
1580                         alphascale = 1;
1581                 if (unit->combinergb != combinergb)
1582                 {
1583                         unit->combinergb = combinergb;
1584                         GL_ActiveTexture(unitnum);
1585                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
1586                 }
1587                 if (unit->combinealpha != combinealpha)
1588                 {
1589                         unit->combinealpha = combinealpha;
1590                         GL_ActiveTexture(unitnum);
1591                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1592                 }
1593                 if (unit->rgbscale != rgbscale)
1594                 {
1595                         GL_ActiveTexture(unitnum);
1596                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = rgbscale));CHECKGLERROR
1597                 }
1598                 if (unit->alphascale != alphascale)
1599                 {
1600                         GL_ActiveTexture(unitnum);
1601                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = alphascale));CHECKGLERROR
1602                 }
1603         }
1604         else
1605         {
1606                 // normal GL texenv
1607                 if (!combinergb)
1608                         combinergb = GL_MODULATE;
1609                 if (unit->combinergb != combinergb)
1610                 {
1611                         unit->combinergb = combinergb;
1612                         GL_ActiveTexture(unitnum);
1613                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
1614                 }
1615         }
1616 }
1617
1618 void R_Mesh_State(const rmeshstate_t *m)
1619 {
1620         unsigned int i;
1621
1622         BACKENDACTIVECHECK
1623
1624         R_Mesh_VertexPointer(m->pointer_vertex);
1625         R_Mesh_ColorPointer(m->pointer_color);
1626
1627         if (gl_backend_rebindtextures)
1628         {
1629                 gl_backend_rebindtextures = false;
1630                 GL_SetupTextureState();
1631         }
1632
1633         for (i = 0;i < backendimageunits;i++)
1634                 R_Mesh_TexBindAll(i, m->tex1d[i], m->tex[i], m->tex3d[i], m->texcubemap[i]);
1635         for (i = 0;i < backendarrayunits;i++)
1636         {
1637                 if (m->pointer_texcoord3f[i])
1638                         R_Mesh_TexCoordPointer(i, 3, m->pointer_texcoord3f[i]);
1639                 else
1640                         R_Mesh_TexCoordPointer(i, 2, m->pointer_texcoord[i]);
1641         }
1642         for (i = 0;i < backendunits;i++)
1643         {
1644                 R_Mesh_TexMatrix(i, &m->texmatrix[i]);
1645                 R_Mesh_TexCombine(i, m->texcombinergb[i], m->texcombinealpha[i], m->texrgbscale[i], m->texalphascale[i]);
1646         }
1647 }
1648
1649 void R_Mesh_Draw_ShowTris(int firstvertex, int numvertices, int numtriangles, const int *elements)
1650 {
1651         qglBegin(GL_LINES);
1652         for (;numtriangles;numtriangles--, elements += 3)
1653         {
1654                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
1655                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
1656                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
1657         }
1658         qglEnd();
1659         CHECKGLERROR
1660 }
1661
1662 /*
1663 ==============================================================================
1664
1665                                                 SCREEN SHOTS
1666
1667 ==============================================================================
1668 */
1669
1670 qboolean SCR_ScreenShot(char *filename, unsigned char *buffer1, unsigned char *buffer2, unsigned char *buffer3, int x, int y, int width, int height, qboolean flipx, qboolean flipy, qboolean flipdiagonal, qboolean jpeg, qboolean gammacorrect)
1671 {
1672         int     indices[3] = {0,1,2};
1673         qboolean ret;
1674
1675         if (!r_render.integer)
1676                 return false;
1677
1678         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer1);
1679         CHECKGLERROR
1680
1681         if (scr_screenshot_gamma.value != 1 && gammacorrect)
1682         {
1683                 int i;
1684                 double igamma = 1.0 / scr_screenshot_gamma.value;
1685                 unsigned char ramp[256];
1686                 for (i = 0;i < 256;i++)
1687                         ramp[i] = (unsigned char) (pow(i * (1.0 / 255.0), igamma) * 255.0);
1688                 for (i = 0;i < width*height*3;i++)
1689                         buffer1[i] = ramp[buffer1[i]];
1690         }
1691
1692         Image_CopyMux (buffer2, buffer1, width, height, flipx, flipy, flipdiagonal, 3, 3, indices);
1693
1694         if (jpeg)
1695                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer2);
1696         else
1697                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer2, buffer3);
1698
1699         return ret;
1700 }
1701
1702 //=============================================================================
1703
1704 void R_ClearScreen(void)
1705 {
1706         if (r_render.integer)
1707         {
1708                 // clear to black
1709                 if (fogenabled)
1710                         qglClearColor(fogcolor[0],fogcolor[1],fogcolor[2],0);
1711                 else
1712                         qglClearColor(0,0,0,0);
1713                 CHECKGLERROR
1714                 qglClearDepth(1);CHECKGLERROR
1715                 if (gl_stencil)
1716                 {
1717                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1718                         // to avoid clamping interfering with strange shadow volume
1719                         // drawing orders
1720                         qglClearStencil(128);CHECKGLERROR
1721                 }
1722                 // clear the screen
1723                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1724                 // set dithering mode
1725                 if (gl_dither.integer)
1726                 {
1727                         qglEnable(GL_DITHER);CHECKGLERROR
1728                 }
1729                 else
1730                 {
1731                         qglDisable(GL_DITHER);CHECKGLERROR
1732                 }
1733         }
1734 }
1735
1736 qboolean CL_VM_UpdateView (void);
1737 void SCR_DrawConsole (void);
1738
1739 int r_stereo_side;
1740
1741 void SCR_DrawScreen (void)
1742 {
1743         R_Mesh_Start();
1744
1745         if (r_timereport_active)
1746                 R_TimeReport("setup");
1747
1748         if (cls.signon == SIGNONS)
1749         {
1750                 float size;
1751
1752                 size = scr_viewsize.value * (1.0 / 100.0);
1753                 size = min(size, 1);
1754
1755                 if (r_stereo_sidebyside.integer)
1756                 {
1757                         r_refdef.width = vid.width * size / 2.5;
1758                         r_refdef.height = vid.height * size / 2.5 * (1 - bound(0, r_letterbox.value, 100) / 100);
1759                         r_refdef.x = (vid.width - r_refdef.width * 2.5) * 0.5;
1760                         r_refdef.y = (vid.height - r_refdef.height)/2;
1761                         if (r_stereo_side)
1762                                 r_refdef.x += r_refdef.width * 1.5;
1763                 }
1764                 else
1765                 {
1766                         r_refdef.width = vid.width * size;
1767                         r_refdef.height = vid.height * size * (1 - bound(0, r_letterbox.value, 100) / 100);
1768                         r_refdef.x = (vid.width - r_refdef.width)/2;
1769                         r_refdef.y = (vid.height - r_refdef.height)/2;
1770                 }
1771
1772                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1773                 // LordHavoc: this is designed to produce widescreen fov values
1774                 // when the screen is wider than 4/3 width/height aspect, to do
1775                 // this it simply assumes the requested fov is the vertical fov
1776                 // for a 4x3 display, if the ratio is not 4x3 this makes the fov
1777                 // higher/lower according to the ratio
1778                 r_refdef.frustum_y = tan(scr_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
1779                 r_refdef.frustum_x = r_refdef.frustum_y * (float)r_refdef.width / (float)r_refdef.height / vid_pixelheight.value;
1780
1781                 r_refdef.frustum_x *= r_refdef.frustumscale_x;
1782                 r_refdef.frustum_y *= r_refdef.frustumscale_y;
1783
1784                 if(!CL_VM_UpdateView())
1785                         R_RenderView();
1786                 else
1787                         SCR_DrawConsole();
1788
1789                 if (scr_zoomwindow.integer)
1790                 {
1791                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1792                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1793                         r_refdef.width = vid.width * sizex;
1794                         r_refdef.height = vid.height * sizey;
1795                         r_refdef.x = (vid.width - r_refdef.width)/2;
1796                         r_refdef.y = 0;
1797
1798                         r_refdef.frustum_y = tan(scr_zoomwindow_fov.value * cl.viewzoom * M_PI / 360.0) * (3.0/4.0);
1799                         r_refdef.frustum_x = r_refdef.frustum_y * vid_pixelheight.value * (float)r_refdef.width / (float)r_refdef.height;
1800
1801                         r_refdef.frustum_x *= r_refdef.frustumscale_x;
1802                         r_refdef.frustum_y *= r_refdef.frustumscale_y;
1803
1804                         if(!CL_VM_UpdateView())
1805                                 R_RenderView();
1806                 }
1807         }
1808
1809         if (!r_stereo_sidebyside.integer)
1810         {
1811                 r_refdef.width = vid.width;
1812                 r_refdef.height = vid.height;
1813                 r_refdef.x = 0;
1814                 r_refdef.y = 0;
1815         }
1816
1817         // draw 2D stuff
1818         R_DrawQueue();
1819
1820         R_Mesh_Finish();
1821
1822         if (r_timereport_active)
1823                 R_TimeReport("meshfinish");
1824 }
1825
1826 void SCR_UpdateLoadingScreen (void)
1827 {
1828         float x, y;
1829         cachepic_t *pic;
1830         rmeshstate_t m;
1831         // don't do anything if not initialized yet
1832         if (vid_hidden)
1833                 return;
1834         r_showtrispass = 0;
1835         VID_UpdateGamma(false);
1836         qglViewport(0, 0, vid.width, vid.height);
1837         //qglDisable(GL_SCISSOR_TEST);
1838         //qglDepthMask(1);
1839         qglColorMask(1,1,1,1);
1840         //qglClearColor(0,0,0,0);
1841         //qglClear(GL_COLOR_BUFFER_BIT);
1842         //qglCullFace(GL_FRONT);
1843         //qglDisable(GL_CULL_FACE);
1844         //R_ClearScreen();
1845         R_Textures_Frame();
1846         GL_SetupView_Mode_Ortho(0, 0, vid_conwidth.integer, vid_conheight.integer, -10, 100);
1847         R_Mesh_Start();
1848         R_Mesh_Matrix(&identitymatrix);
1849         // draw the loading plaque
1850         pic = Draw_CachePic("gfx/loading", false);
1851         x = (vid_conwidth.integer - pic->width)/2;
1852         y = (vid_conheight.integer - pic->height)/2;
1853         GL_Color(1,1,1,1);
1854         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1855         GL_DepthTest(false);
1856         memset(&m, 0, sizeof(m));
1857         m.pointer_vertex = varray_vertex3f;
1858         m.pointer_texcoord[0] = varray_texcoord2f[0];
1859         m.tex[0] = R_GetTexture(pic->tex);
1860         R_Mesh_State(&m);
1861         varray_vertex3f[0] = varray_vertex3f[9] = x;
1862         varray_vertex3f[1] = varray_vertex3f[4] = y;
1863         varray_vertex3f[3] = varray_vertex3f[6] = x + pic->width;
1864         varray_vertex3f[7] = varray_vertex3f[10] = y + pic->height;
1865         varray_texcoord2f[0][0] = 0;varray_texcoord2f[0][1] = 0;
1866         varray_texcoord2f[0][2] = 1;varray_texcoord2f[0][3] = 0;
1867         varray_texcoord2f[0][4] = 1;varray_texcoord2f[0][5] = 1;
1868         varray_texcoord2f[0][6] = 0;varray_texcoord2f[0][7] = 1;
1869         GL_LockArrays(0, 4);
1870         R_Mesh_Draw(0, 4, 2, polygonelements);
1871         GL_LockArrays(0, 0);
1872         R_Mesh_Finish();
1873         // refresh
1874         VID_Finish();
1875 }
1876
1877 /*
1878 ==================
1879 SCR_UpdateScreen
1880
1881 This is called every frame, and can also be called explicitly to flush
1882 text to the screen.
1883 ==================
1884 */
1885 void SCR_UpdateScreen (void)
1886 {
1887         if (vid_hidden)
1888                 return;
1889
1890         if (r_textureunits.integer > gl_textureunits)
1891                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1892         if (r_textureunits.integer < 1)
1893                 Cvar_SetValueQuick(&r_textureunits, 1);
1894
1895         if (gl_combine.integer && !gl_combine_extension)
1896                 Cvar_SetValueQuick(&gl_combine, 0);
1897
1898         r_showtrispass = 0;
1899
1900         CHECKGLERROR
1901         qglViewport(0, 0, vid.width, vid.height);
1902         qglDisable(GL_SCISSOR_TEST);
1903         qglDepthMask(1);
1904         qglColorMask(1,1,1,1);
1905         qglClearColor(0,0,0,0);
1906         qglClear(GL_COLOR_BUFFER_BIT);
1907         CHECKGLERROR
1908
1909         if (r_timereport_active)
1910                 R_TimeReport("clear");
1911
1912         if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer || r_stereo_sidebyside.integer)
1913         {
1914                 matrix4x4_t originalmatrix = r_refdef.viewentitymatrix;
1915                 r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[0][1];
1916                 r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[1][1];
1917                 r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * -0.5f * r_refdef.viewentitymatrix.m[2][1];
1918
1919                 if (r_stereo_sidebyside.integer)
1920                         r_stereo_side = 0;
1921
1922                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1923                 {
1924                         r_refdef.colormask[0] = 1;
1925                         r_refdef.colormask[1] = 0;
1926                         r_refdef.colormask[2] = 0;
1927                 }
1928
1929                 SCR_DrawScreen();
1930
1931                 r_refdef.viewentitymatrix.m[0][3] = originalmatrix.m[0][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[0][1];
1932                 r_refdef.viewentitymatrix.m[1][3] = originalmatrix.m[1][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[1][1];
1933                 r_refdef.viewentitymatrix.m[2][3] = originalmatrix.m[2][3] + r_stereo_separation.value * 0.5f * r_refdef.viewentitymatrix.m[2][1];
1934
1935                 if (r_stereo_sidebyside.integer)
1936                         r_stereo_side = 1;
1937
1938                 if (r_stereo_redblue.integer || r_stereo_redgreen.integer || r_stereo_redcyan.integer)
1939                 {
1940                         r_refdef.colormask[0] = 0;
1941                         r_refdef.colormask[1] = r_stereo_redcyan.integer || r_stereo_redgreen.integer;
1942                         r_refdef.colormask[2] = r_stereo_redcyan.integer || r_stereo_redblue.integer;
1943                 }
1944
1945                 SCR_DrawScreen();
1946
1947                 r_refdef.viewentitymatrix = originalmatrix;
1948         }
1949         else
1950                 SCR_DrawScreen();
1951
1952         VID_Finish();
1953         if (r_timereport_active)
1954                 R_TimeReport("finish");
1955 }
1956
1957
1958 //===========================================================================
1959 // dynamic vertex array buffer subsystem
1960 //===========================================================================
1961
1962 // FIXME: someday this should be dynamically allocated and resized?
1963 float varray_vertex3f[65536*3];
1964 float varray_svector3f[65536*3];
1965 float varray_tvector3f[65536*3];
1966 float varray_normal3f[65536*3];
1967 float varray_color4f[65536*4];
1968 float varray_texcoord2f[4][65536*2];
1969 float varray_texcoord3f[4][65536*3];
1970 int earray_element3i[65536];
1971 float varray_vertex3f2[65536*3];
1972
1973 //===========================================================================
1974 // vertex array caching subsystem
1975 //===========================================================================
1976
1977 typedef struct rcachearraylink_s
1978 {
1979         struct rcachearraylink_s *next, *prev;
1980         struct rcachearrayitem_s *data;
1981 }
1982 rcachearraylink_t;
1983
1984 typedef struct rcachearrayitem_s
1985 {
1986         // the original request structure
1987         rcachearrayrequest_t request;
1988         // active
1989         int active;
1990         // offset into r_mesh_rcachedata
1991         int offset;
1992         // for linking this into the sequential list
1993         rcachearraylink_t sequentiallink;
1994         // for linking this into the lookup list
1995         rcachearraylink_t hashlink;
1996 }
1997 rcachearrayitem_t;
1998
1999 #define RCACHEARRAY_HASHSIZE 65536
2000 #define RCACHEARRAY_ITEMS 4096
2001 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
2002
2003 // all active items are linked into this chain in sorted order
2004 static rcachearraylink_t r_mesh_rcachesequentialchain;
2005 // all inactive items are linked into this chain in unknown order
2006 static rcachearraylink_t r_mesh_rcachefreechain;
2007 // all active items are also linked into these chains (using their hashlink)
2008 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
2009
2010 // all items are stored here, whether active or inactive
2011 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
2012
2013 // size of data buffer
2014 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
2015 // data buffer
2016 static unsigned char r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
2017
2018 // current state
2019 static int r_mesh_rcachedata_offset;
2020 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
2021
2022 static void R_Mesh_CacheArray_Startup(void)
2023 {
2024         int i;
2025         rcachearraylink_t *l;
2026         // prepare all the linked lists
2027         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
2028         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
2029         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
2030         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
2031         {
2032                 l = &r_mesh_rcachechain[i];
2033                 l->next = l->prev = l;
2034                 l->data = NULL;
2035         }
2036         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
2037         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
2038         {
2039                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
2040                 l = &r_mesh_rcacheitems[i].sequentiallink;
2041                 l->next = &r_mesh_rcachefreechain;
2042                 l->prev = l->next->prev;
2043                 l->next->prev = l->prev->next = l;
2044         }
2045         // clear other state
2046         r_mesh_rcachedata_offset = 0;
2047         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
2048 }
2049
2050 static void R_Mesh_CacheArray_Shutdown(void)
2051 {
2052 }
2053
2054 /*
2055 static void R_Mesh_CacheArray_ValidateState(int num)
2056 {
2057         rcachearraylink_t *l, *lhead;
2058         lhead = &r_mesh_rcachesequentialchain;
2059         if (r_mesh_rcachesequentialchain_current == lhead)
2060                 return;
2061         for (l = lhead->next;l != lhead;l = l->next)
2062                 if (r_mesh_rcachesequentialchain_current == l)
2063                         return;
2064         Sys_Error("%i", num);
2065 }
2066 */
2067
2068 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
2069 {
2070         rcachearraylink_t *l, *lhead, *lnext;
2071         rcachearrayitem_t *d;
2072         int hashindex, offset, offsetend;
2073
2074         //R_Mesh_CacheArray_ValidateState(3);
2075         // calculate a hashindex to choose a cache chain
2076         r->data = NULL;
2077         hashindex = CRC_Block((unsigned char *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
2078
2079         // is it already cached?
2080         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
2081         {
2082                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
2083                 {
2084                         // we have it cached already
2085                         r->data = r_mesh_rcachedata + l->data->offset;
2086                         return false;
2087                 }
2088         }
2089
2090         // we need to add a new cache item, this means finding a place for the new
2091         // data and making sure we have a free item available, lots of work...
2092
2093         // check if buffer needs to wrap
2094         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
2095         {
2096                 /*
2097                 if (r->data_size * 10 > r_mesh_rcachedata_size)
2098                 {
2099                         // realloc whole cache
2100                 }
2101                 */
2102                 // reset back to start
2103                 r_mesh_rcachedata_offset = 0;
2104                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
2105         }
2106         offset = r_mesh_rcachedata_offset;
2107         r_mesh_rcachedata_offset += r->data_size;
2108         offsetend = r_mesh_rcachedata_offset;
2109         //R_Mesh_CacheArray_ValidateState(4);
2110
2111         /*
2112         {
2113                 int n;
2114                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
2115                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
2116         }
2117         */
2118
2119         // make room for the new data (remove old items)
2120         lhead = &r_mesh_rcachesequentialchain;
2121         l = r_mesh_rcachesequentialchain_current;
2122         if (l == lhead)
2123                 l = l->next;
2124         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
2125         {
2126         //r_mesh_rcachesequentialchain_current = l;
2127         //R_Mesh_CacheArray_ValidateState(8);
2128                 lnext = l->next;
2129                 // if at the end of the chain, wrap around
2130                 if (lnext == lhead)
2131                         lnext = lnext->next;
2132         //r_mesh_rcachesequentialchain_current = lnext;
2133         //R_Mesh_CacheArray_ValidateState(10);
2134
2135                 // unlink from sequential chain
2136                 l->next->prev = l->prev;
2137                 l->prev->next = l->next;
2138         //R_Mesh_CacheArray_ValidateState(11);
2139                 // link into free chain
2140                 l->next = &r_mesh_rcachefreechain;
2141                 l->prev = l->next->prev;
2142                 l->next->prev = l->prev->next = l;
2143         //R_Mesh_CacheArray_ValidateState(12);
2144
2145                 l = &l->data->hashlink;
2146                 // unlink from hash chain
2147                 l->next->prev = l->prev;
2148                 l->prev->next = l->next;
2149
2150                 l = lnext;
2151         //r_mesh_rcachesequentialchain_current = l;
2152         //R_Mesh_CacheArray_ValidateState(9);
2153         }
2154         //r_mesh_rcachesequentialchain_current = l;
2155         //R_Mesh_CacheArray_ValidateState(5);
2156         // gobble an extra item if we have no free items available
2157         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
2158         {
2159                 lnext = l->next;
2160
2161                 // unlink from sequential chain
2162                 l->next->prev = l->prev;
2163                 l->prev->next = l->next;
2164                 // link into free chain
2165                 l->next = &r_mesh_rcachefreechain;
2166                 l->prev = l->next->prev;
2167                 l->next->prev = l->prev->next = l;
2168
2169                 l = &l->data->hashlink;
2170                 // unlink from hash chain
2171                 l->next->prev = l->prev;
2172                 l->prev->next = l->next;
2173
2174                 l = lnext;
2175         }
2176         r_mesh_rcachesequentialchain_current = l;
2177         //R_Mesh_CacheArray_ValidateState(6);
2178
2179         // now take an item from the free chain
2180         l = r_mesh_rcachefreechain.next;
2181         // set it up
2182         d = l->data;
2183         d->request = *r;
2184         d->offset = offset;
2185         // unlink
2186         l->next->prev = l->prev;
2187         l->prev->next = l->next;
2188         // relink to sequential
2189         l->next = r_mesh_rcachesequentialchain_current->prev;
2190         l->prev = l->next->prev;
2191         while (l->next->data && l->data && l->next->data->offset <= d->offset)
2192         {
2193                 //Con_Print(">\n");
2194                 l->next = l->next->next;
2195                 l->prev = l->prev->next;
2196         }
2197         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
2198         {
2199                 //Con_Print("<\n");
2200                 l->prev = l->prev->prev;
2201                 l->next = l->next->prev;
2202         }
2203         l->next->prev = l->prev->next = l;
2204         // also link into hash chain
2205         l = &l->data->hashlink;
2206         l->next = &r_mesh_rcachechain[hashindex];
2207         l->prev = l->next->prev;
2208         l->prev->next = l;
2209         l->next->prev = l->prev->next = l;
2210
2211
2212         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
2213
2214         //R_Mesh_CacheArray_ValidateState(7);
2215         // and finally set the data pointer
2216         r->data = r_mesh_rcachedata + d->offset;
2217         // and tell the caller to fill the array
2218         return true;
2219 }
2220