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