11b89b716c2433e576f2760d68a14928fb1a2633
[xonotic/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_delayfinish = {CVAR_SAVE, "gl_delayfinish", "0"};
11 cvar_t gl_paranoid = {0, "gl_paranoid", "0"};
12 cvar_t gl_printcheckerror = {0, "gl_printcheckerror", "0"};
13
14 cvar_t r_render = {0, "r_render", "1"};
15 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
16 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
17
18 int gl_maxdrawrangeelementsvertices;
19 int gl_maxdrawrangeelementsindices;
20
21 #ifdef DEBUGGL
22 int errornumber = 0;
23
24 void GL_PrintError(int errornumber, char *filename, int linenumber)
25 {
26         switch(errornumber)
27         {
28 #ifdef GL_INVALID_ENUM
29         case GL_INVALID_ENUM:
30                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
31                 break;
32 #endif
33 #ifdef GL_INVALID_VALUE
34         case GL_INVALID_VALUE:
35                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
36                 break;
37 #endif
38 #ifdef GL_INVALID_OPERATION
39         case GL_INVALID_OPERATION:
40                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
41                 break;
42 #endif
43 #ifdef GL_STACK_OVERFLOW
44         case GL_STACK_OVERFLOW:
45                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
46                 break;
47 #endif
48 #ifdef GL_STACK_UNDERFLOW
49         case GL_STACK_UNDERFLOW:
50                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
51                 break;
52 #endif
53 #ifdef GL_OUT_OF_MEMORY
54         case GL_OUT_OF_MEMORY:
55                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
56                 break;
57 #endif
58 #ifdef GL_TABLE_TOO_LARGE
59         case GL_TABLE_TOO_LARGE:
60                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
61                 break;
62 #endif
63         default:
64                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
65                 break;
66         }
67 }
68 #endif
69
70 #define BACKENDACTIVECHECK if (!backendactive) Sys_Error("GL backend function called when backend is not active\n");
71
72 int c_meshs, c_meshelements;
73
74 void SCR_ScreenShot_f (void);
75
76 static matrix4x4_t backend_viewmatrix;
77 static matrix4x4_t backend_modelmatrix;
78 static matrix4x4_t backend_modelviewmatrix;
79 static matrix4x4_t backend_glmodelviewmatrix;
80 static matrix4x4_t backend_projectmatrix;
81
82 static int backendunits, backendactive;
83 static mempool_t *gl_backend_mempool;
84
85 /*
86 note: here's strip order for a terrain row:
87 0--1--2--3--4
88 |\ |\ |\ |\ |
89 | \| \| \| \|
90 A--B--C--D--E
91 clockwise
92
93 A0B, 01B, B1C, 12C, C2D, 23D, D3E, 34E
94
95 *elements++ = i + row;
96 *elements++ = i;
97 *elements++ = i + row + 1;
98 *elements++ = i;
99 *elements++ = i + 1;
100 *elements++ = i + row + 1;
101
102
103 for (y = 0;y < rows - 1;y++)
104 {
105         for (x = 0;x < columns - 1;x++)
106         {
107                 i = y * rows + x;
108                 *elements++ = i + columns;
109                 *elements++ = i;
110                 *elements++ = i + columns + 1;
111                 *elements++ = i;
112                 *elements++ = i + 1;
113                 *elements++ = i + columns + 1;
114         }
115 }
116
117 alternative:
118 0--1--2--3--4
119 | /| /|\ | /|
120 |/ |/ | \|/ |
121 A--B--C--D--E
122 counterclockwise
123
124 for (y = 0;y < rows - 1;y++)
125 {
126         for (x = 0;x < columns - 1;x++)
127         {
128                 i = y * rows + x;
129                 *elements++ = i;
130                 *elements++ = i + columns;
131                 *elements++ = i + columns + 1;
132                 *elements++ = i + columns;
133                 *elements++ = i + columns + 1;
134                 *elements++ = i + 1;
135         }
136 }
137 */
138
139 int polygonelements[768];
140
141 static void R_Mesh_CacheArray_Startup(void);
142 static void R_Mesh_CacheArray_Shutdown(void);
143 void GL_Backend_AllocArrays(void)
144 {
145         if (!gl_backend_mempool)
146                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
147         R_Mesh_CacheArray_Startup();
148 }
149
150 void GL_Backend_FreeArrays(void)
151 {
152         R_Mesh_CacheArray_Shutdown();
153         Mem_FreePool(&gl_backend_mempool);
154 }
155
156 static void gl_backend_start(void)
157 {
158         Con_DPrint("OpenGL Backend started\n");
159         if (qglDrawRangeElements != NULL)
160         {
161                 CHECKGLERROR
162                 qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
163                 CHECKGLERROR
164                 qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
165                 CHECKGLERROR
166                 Con_DPrintf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
167         }
168
169         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
170
171         GL_Backend_AllocArrays();
172
173         backendactive = true;
174 }
175
176 static void gl_backend_shutdown(void)
177 {
178         backendunits = 0;
179         backendactive = false;
180
181         Con_DPrint("OpenGL Backend shutting down\n");
182
183         GL_Backend_FreeArrays();
184 }
185
186 static void gl_backend_newmap(void)
187 {
188 }
189
190 cvar_t scr_zoomwindow = {CVAR_SAVE, "scr_zoomwindow", "0"};
191 cvar_t scr_zoomwindow_viewsizex = {CVAR_SAVE, "scr_zoomwindow_viewsizex", "20"};
192 cvar_t scr_zoomwindow_viewsizey = {CVAR_SAVE, "scr_zoomwindow_viewsizey", "20"};
193 cvar_t scr_zoomwindow_fov = {CVAR_SAVE, "scr_zoomwindow_fov", "20"};
194
195 void gl_backend_init(void)
196 {
197         int i;
198
199         for (i = 0;i < POLYGONELEMENTS_MAXPOINTS - 2;i++)
200         {
201                 polygonelements[i * 3 + 0] = 0;
202                 polygonelements[i * 3 + 1] = i + 1;
203                 polygonelements[i * 3 + 2] = i + 2;
204         }
205
206         Cvar_RegisterVariable(&r_render);
207         Cvar_RegisterVariable(&gl_dither);
208         Cvar_RegisterVariable(&gl_lockarrays);
209         Cvar_RegisterVariable(&gl_delayfinish);
210         Cvar_RegisterVariable(&gl_paranoid);
211         Cvar_RegisterVariable(&gl_printcheckerror);
212 #ifdef NORENDER
213         Cvar_SetValue("r_render", 0);
214 #endif
215
216         Cvar_RegisterVariable(&gl_mesh_drawrangeelements);
217         Cvar_RegisterVariable(&gl_mesh_testarrayelement);
218         Cvar_RegisterVariable(&gl_mesh_testmanualfeeding);
219
220         Cvar_RegisterVariable(&scr_zoomwindow);
221         Cvar_RegisterVariable(&scr_zoomwindow_viewsizex);
222         Cvar_RegisterVariable(&scr_zoomwindow_viewsizey);
223         Cvar_RegisterVariable(&scr_zoomwindow_fov);
224
225         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
226 }
227
228 void GL_SetupView_Orientation_Identity (void)
229 {
230         Matrix4x4_CreateIdentity(&backend_viewmatrix);
231         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
232 }
233
234 void GL_SetupView_Orientation_FromEntity(matrix4x4_t *matrix)
235 {
236         matrix4x4_t tempmatrix, basematrix;
237         Matrix4x4_Invert_Simple(&tempmatrix, matrix);
238         Matrix4x4_CreateRotate(&basematrix, -90, 1, 0, 0);
239         Matrix4x4_ConcatRotate(&basematrix, 90, 0, 0, 1);
240         Matrix4x4_Concat(&backend_viewmatrix, &basematrix, &tempmatrix);
241         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[2], 1, 0, 0);
242         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[0], 0, 1, 0);
243         //Matrix4x4_ConcatRotate(&backend_viewmatrix, -angles[1], 0, 0, 1);
244         //Matrix4x4_ConcatTranslate(&backend_viewmatrix, -origin[0], -origin[1], -origin[2]);
245         memset(&backend_modelmatrix, 0, sizeof(backend_modelmatrix));
246 }
247
248 void GL_SetupView_Mode_Perspective (double fovx, double fovy, double zNear, double zFar)
249 {
250         double xmax, ymax;
251
252         if (!r_render.integer)
253                 return;
254
255         // set up viewpoint
256         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
257         qglLoadIdentity();CHECKGLERROR
258         // pyramid slopes
259         xmax = zNear * tan(fovx * M_PI / 360.0);
260         ymax = zNear * tan(fovy * M_PI / 360.0);
261         // set view pyramid
262         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
263         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
264         GL_SetupView_Orientation_Identity();
265 }
266
267 void GL_SetupView_Mode_PerspectiveInfiniteFarClip (double fovx, double fovy, double zNear)
268 {
269         float nudge, m[16];
270
271         if (!r_render.integer)
272                 return;
273
274         // set up viewpoint
275         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
276         qglLoadIdentity();CHECKGLERROR
277         // set view pyramid
278         nudge = 1.0 - 1.0 / (1<<23);
279         m[ 0] = 1.0 / tan(fovx * M_PI / 360.0);
280         m[ 1] = 0;
281         m[ 2] = 0;
282         m[ 3] = 0;
283         m[ 4] = 0;
284         m[ 5] = 1.0 / tan(fovy * M_PI / 360.0);
285         m[ 6] = 0;
286         m[ 7] = 0;
287         m[ 8] = 0;
288         m[ 9] = 0;
289         m[10] = -nudge;
290         m[11] = -1;
291         m[12] = 0;
292         m[13] = 0;
293         m[14] = -2 * zNear * nudge;
294         m[15] = 0;
295         qglLoadMatrixf(m);
296         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
297         GL_SetupView_Orientation_Identity();
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 }
315
316 void GL_SetupView_Mode_Ortho (double x1, double y1, double x2, double y2, double zNear, double zFar)
317 {
318         if (!r_render.integer)
319                 return;
320
321         // set up viewpoint
322         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
323         qglLoadIdentity();CHECKGLERROR
324         qglOrtho(x1, x2, y2, y1, zNear, zFar);
325         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
326         GL_SetupView_Orientation_Identity();
327 }
328
329 typedef struct gltextureunit_s
330 {
331         int t1d, t2d, t3d, tcubemap;
332         int arrayenabled;
333         int arrayis3d;
334         const void *pointer_texcoord;
335         float rgbscale, alphascale;
336         int combinergb, combinealpha;
337         // FIXME: add more combine stuff
338         matrix4x4_t matrix;
339 }
340 gltextureunit_t;
341
342 static struct
343 {
344         int blendfunc1;
345         int blendfunc2;
346         int blend;
347         GLboolean depthmask;
348         int colormask; // stored as bottom 4 bits: r g b a (3 2 1 0 order)
349         int depthtest;
350         int scissortest;
351         int unit;
352         int clientunit;
353         gltextureunit_t units[MAX_TEXTUREUNITS];
354         float color4f[4];
355         int lockrange_first;
356         int lockrange_count;
357         const void *pointer_vertex;
358         const void *pointer_color;
359 }
360 gl_state;
361
362 void GL_SetupTextureState(void)
363 {
364         int i;
365         gltextureunit_t *unit;
366         CHECKGLERROR
367         gl_state.unit = -1;
368         gl_state.clientunit = -1;
369         for (i = 0;i < backendunits;i++)
370         {
371                 GL_ActiveTexture(i);
372                 GL_ClientActiveTexture(i);
373                 unit = gl_state.units + i;
374                 unit->t1d = 0;
375                 unit->t2d = 0;
376                 unit->t3d = 0;
377                 unit->tcubemap = 0;
378                 unit->arrayenabled = false;
379                 unit->arrayis3d = false;
380                 unit->pointer_texcoord = NULL;
381                 unit->rgbscale = 1;
382                 unit->alphascale = 1;
383                 unit->combinergb = GL_MODULATE;
384                 unit->combinealpha = GL_MODULATE;
385                 unit->matrix = r_identitymatrix;
386
387                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), NULL);CHECKGLERROR
388                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
389
390                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
391                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
392                 if (gl_texture3d)
393                 {
394                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
395                 }
396                 if (gl_texturecubemap)
397                 {
398                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
399                 }
400                 if (gl_combine.integer)
401                 {
402                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
403                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
404                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
405                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
406                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_TEXTURE);CHECKGLERROR // for GL_INTERPOLATE_ARB mode
407                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
408                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
409                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
410                         qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
411                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
412                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
413                         qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
414                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
415                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
416                         qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
417                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
418                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
419                 }
420                 else
421                 {
422                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
423                 }
424         }
425         CHECKGLERROR
426 }
427
428 void GL_Backend_ResetState(void)
429 {
430         memset(&gl_state, 0, sizeof(gl_state));
431         gl_state.depthtest = true;
432         gl_state.blendfunc1 = GL_ONE;
433         gl_state.blendfunc2 = GL_ZERO;
434         gl_state.blend = false;
435         gl_state.depthmask = GL_TRUE;
436         gl_state.colormask = 15;
437         gl_state.color4f[0] = gl_state.color4f[1] = gl_state.color4f[2] = gl_state.color4f[3] = 1;
438         gl_state.lockrange_first = 0;
439         gl_state.lockrange_count = 0;
440         gl_state.pointer_vertex = NULL;
441         gl_state.pointer_color = NULL;
442
443         CHECKGLERROR
444
445         qglColorMask(1, 1, 1, 1);
446         qglEnable(GL_CULL_FACE);CHECKGLERROR
447         qglCullFace(GL_FRONT);CHECKGLERROR
448         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
449         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
450         qglDisable(GL_BLEND);CHECKGLERROR
451         qglDepthMask(gl_state.depthmask);CHECKGLERROR
452
453         qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), NULL);CHECKGLERROR
454         qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
455
456         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), NULL);CHECKGLERROR
457         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
458
459         GL_Color(0, 0, 0, 0);
460         GL_Color(1, 1, 1, 1);
461
462         GL_SetupTextureState();
463 }
464
465 void GL_ActiveTexture(int num)
466 {
467         if (gl_state.unit != num)
468         {
469                 gl_state.unit = num;
470                 if (qglActiveTexture)
471                 {
472                         qglActiveTexture(GL_TEXTURE0_ARB + gl_state.unit);
473                         CHECKGLERROR
474                 }
475         }
476 }
477
478 void GL_ClientActiveTexture(int num)
479 {
480         if (gl_state.clientunit != num)
481         {
482                 gl_state.clientunit = num;
483                 if (qglActiveTexture)
484                 {
485                         qglClientActiveTexture(GL_TEXTURE0_ARB + gl_state.clientunit);
486                         CHECKGLERROR
487                 }
488         }
489 }
490
491 void GL_BlendFunc(int blendfunc1, int blendfunc2)
492 {
493         if (gl_state.blendfunc1 != blendfunc1 || gl_state.blendfunc2 != blendfunc2)
494         {
495                 if (r_showtrispass)
496                         return;
497                 qglBlendFunc(gl_state.blendfunc1 = blendfunc1, gl_state.blendfunc2 = blendfunc2);CHECKGLERROR
498                 if (gl_state.blendfunc2 == GL_ZERO)
499                 {
500                         if (gl_state.blendfunc1 == GL_ONE)
501                         {
502                                 if (gl_state.blend)
503                                 {
504                                         gl_state.blend = 0;
505                                         qglDisable(GL_BLEND);CHECKGLERROR
506                                 }
507                         }
508                         else
509                         {
510                                 if (!gl_state.blend)
511                                 {
512                                         gl_state.blend = 1;
513                                         qglEnable(GL_BLEND);CHECKGLERROR
514                                 }
515                         }
516                 }
517                 else
518                 {
519                         if (!gl_state.blend)
520                         {
521                                 gl_state.blend = 1;
522                                 qglEnable(GL_BLEND);CHECKGLERROR
523                         }
524                 }
525         }
526 }
527
528 void GL_DepthMask(int state)
529 {
530         if (gl_state.depthmask != state)
531         {
532                 if (r_showtrispass)
533                         return;
534                 qglDepthMask(gl_state.depthmask = state);CHECKGLERROR
535         }
536 }
537
538 void GL_DepthTest(int state)
539 {
540         if (gl_state.depthtest != state)
541         {
542                 if (r_showtrispass)
543                         return;
544                 gl_state.depthtest = state;
545                 if (gl_state.depthtest)
546                 {
547                         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
548                 }
549                 else
550                 {
551                         qglDisable(GL_DEPTH_TEST);CHECKGLERROR
552                 }
553         }
554 }
555
556 void GL_ColorMask(int r, int g, int b, int a)
557 {
558         int state = r*8 + g*4 + b*2 + a*1;
559         if (gl_state.colormask != state)
560         {
561                 if (r_showtrispass)
562                         return;
563                 gl_state.colormask = state;
564                 qglColorMask((GLboolean)r, (GLboolean)g, (GLboolean)b, (GLboolean)a);CHECKGLERROR
565         }
566 }
567
568 void GL_Color(float cr, float cg, float cb, float ca)
569 {
570         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)
571         {
572                 if (r_showtrispass)
573                         return;
574                 gl_state.color4f[0] = cr;
575                 gl_state.color4f[1] = cg;
576                 gl_state.color4f[2] = cb;
577                 gl_state.color4f[3] = ca;
578                 CHECKGLERROR
579                 qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
580                 CHECKGLERROR
581         }
582 }
583
584 void GL_ShowTrisColor(float cr, float cg, float cb, float ca)
585 {
586         if (!r_showtrispass)
587                 return;
588         r_showtrispass = false;
589         GL_Color(cr * r_showtris.value, cg * r_showtris.value, cb * r_showtris.value, ca);
590         r_showtrispass = true;
591 }
592
593
594 void GL_LockArrays(int first, int count)
595 {
596         if (gl_state.lockrange_count != count || gl_state.lockrange_first != first)
597         {
598                 if (gl_state.lockrange_count)
599                 {
600                         gl_state.lockrange_count = 0;
601                         CHECKGLERROR
602                         qglUnlockArraysEXT();
603                         CHECKGLERROR
604                 }
605                 if (count && gl_supportslockarrays && gl_lockarrays.integer && r_render.integer)
606                 {
607                         gl_state.lockrange_first = first;
608                         gl_state.lockrange_count = count;
609                         CHECKGLERROR
610                         qglLockArraysEXT(first, count);
611                         CHECKGLERROR
612                 }
613         }
614 }
615
616 void GL_Scissor (int x, int y, int width, int height)
617 {
618         CHECKGLERROR
619         qglScissor(x, vid.realheight - (y + height),width,height);
620         CHECKGLERROR
621 }
622
623 void GL_ScissorTest(int state)
624 {
625         if(gl_state.scissortest == state)
626                 return;
627
628         CHECKGLERROR
629         if((gl_state.scissortest = state))
630                 qglEnable(GL_SCISSOR_TEST);
631         else
632                 qglDisable(GL_SCISSOR_TEST);
633         CHECKGLERROR
634 }
635
636 void GL_Clear(int mask)
637 {
638         if (r_showtrispass)
639                 return;
640         qglClear(mask);CHECKGLERROR
641 }
642
643 void GL_TransformToScreen(const vec4_t in, vec4_t out)
644 {
645         vec4_t temp;
646         float iw;
647         Matrix4x4_Transform4 (&backend_viewmatrix, in, temp);
648         Matrix4x4_Transform4 (&backend_projectmatrix, temp, out);
649         iw = 1.0f / out[3];
650         out[0] = r_view_x + (out[0] * iw + 1.0f) * r_view_width * 0.5f;
651         out[1] = r_view_y + (out[1] * iw + 1.0f) * r_view_height * 0.5f;
652         out[2] = out[2] * iw;
653 }
654
655 // called at beginning of frame
656 void R_Mesh_Start(void)
657 {
658         BACKENDACTIVECHECK
659         CHECKGLERROR
660         GL_Backend_ResetState();
661 }
662
663 int gl_backend_rebindtextures;
664
665 void GL_Backend_RenumberElements(int *out, int count, const int *in, int offset)
666 {
667         int i;
668         if (offset)
669         {
670                 for (i = 0;i < count;i++)
671                         *out++ = *in++ + offset;
672         }
673         else
674                 memcpy(out, in, sizeof(*out) * count);
675 }
676
677 // renders triangles using vertices from the active arrays
678 int paranoidblah = 0;
679 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
680 {
681         int numelements = numtriangles * 3;
682         if (numverts == 0 || numtriangles == 0)
683         {
684                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
685                 return;
686         }
687         CHECKGLERROR
688         if (r_showtrispass)
689         {
690                 R_Mesh_Draw_ShowTris(numverts, numtriangles, elements);
691                 return;
692         }
693         c_meshs++;
694         c_meshelements += numelements;
695         if (gl_paranoid.integer)
696         {
697                 int i, j, size;
698                 const int *p;
699                 if (!qglIsEnabled(GL_VERTEX_ARRAY))
700                         Con_Print("R_Mesh_Draw: vertex array not enabled\n");
701                 for (j = 0, size = numverts * (int)sizeof(float[3]), p = gl_state.pointer_vertex;j < size;j += sizeof(int), p++)
702                         paranoidblah += *p;
703                 if (gl_state.pointer_color)
704                 {
705                         if (!qglIsEnabled(GL_COLOR_ARRAY))
706                                 Con_Print("R_Mesh_Draw: color array set but not enabled\n");
707                         for (j = 0, size = numverts * (int)sizeof(float[4]), p = gl_state.pointer_color;j < size;j += sizeof(int), p++)
708                                 paranoidblah += *p;
709                 }
710                 for (i = 0;i < backendunits;i++)
711                 {
712                         if (gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap || gl_state.units[i].arrayenabled)
713                         {
714                                 if (gl_state.units[i].arrayenabled && !(gl_state.units[i].t1d || gl_state.units[i].t2d || gl_state.units[i].t3d || gl_state.units[i].tcubemap))
715                                         Con_Print("R_Mesh_Draw: array enabled but no texture bound\n");
716                                 GL_ClientActiveTexture(i);
717                                 if (!qglIsEnabled(GL_TEXTURE_COORD_ARRAY))
718                                         Con_Print("R_Mesh_Draw: texcoord array set but not enabled\n");
719                                 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++)
720                                         paranoidblah += *p;
721                         }
722                 }
723                 for (i = 0;i < numtriangles * 3;i++)
724                 {
725                         if (elements[i] < 0 || elements[i] >= numverts)
726                         {
727                                 Con_Printf("R_Mesh_Draw: invalid vertex index %i (outside range 0 - %i) in elements list\n", elements[i], numverts);
728                                 return;
729                         }
730                 }
731                 CHECKGLERROR
732         }
733         if (r_render.integer)
734         {
735                 CHECKGLERROR
736                 if (gl_mesh_testmanualfeeding.integer)
737                 {
738                         int i, j;
739                         const GLfloat *p;
740                         qglBegin(GL_TRIANGLES);
741                         for (i = 0;i < numtriangles * 3;i++)
742                         {
743                                 for (j = 0;j < backendunits;j++)
744                                 {
745                                         if (gl_state.units[j].pointer_texcoord)
746                                         {
747                                                 if (backendunits > 1)
748                                                 {
749                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
750                                                         {
751                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
752                                                                 qglMultiTexCoord3f(GL_TEXTURE0_ARB + j, p[0], p[1], p[2]);
753                                                         }
754                                                         else
755                                                         {
756                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
757                                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, p[0], p[1]);
758                                                         }
759                                                 }
760                                                 else
761                                                 {
762                                                         if (gl_state.units[j].t3d || gl_state.units[j].tcubemap)
763                                                         {
764                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 3;
765                                                                 qglTexCoord3f(p[0], p[1], p[2]);
766                                                         }
767                                                         else
768                                                         {
769                                                                 p = ((const GLfloat *)(gl_state.units[j].pointer_texcoord)) + elements[i] * 2;
770                                                                 qglTexCoord2f(p[0], p[1]);
771                                                         }
772                                                 }
773                                         }
774                                 }
775                                 if (gl_state.pointer_color)
776                                 {
777                                         p = ((const GLfloat *)(gl_state.pointer_color)) + elements[i] * 4;
778                                         qglColor4f(p[0], p[1], p[2], p[3]);
779                                 }
780                                 p = ((const GLfloat *)(gl_state.pointer_vertex)) + elements[i] * 3;
781                                 qglVertex3f(p[0], p[1], p[2]);
782                         }
783                         qglEnd();
784                         CHECKGLERROR
785                 }
786                 else if (gl_mesh_testarrayelement.integer)
787                 {
788                         int i;
789                         qglBegin(GL_TRIANGLES);
790                         for (i = 0;i < numtriangles * 3;i++)
791                         {
792                                 qglArrayElement(elements[i]);
793                         }
794                         qglEnd();
795                         CHECKGLERROR
796                 }
797                 else if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
798                 {
799                         qglDrawRangeElements(GL_TRIANGLES, 0, numverts, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
800                 }
801                 else
802                 {
803                         qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
804                 }
805                 CHECKGLERROR
806         }
807 }
808
809 // restores backend state, used when done with 3D rendering
810 void R_Mesh_Finish(void)
811 {
812         int i;
813         BACKENDACTIVECHECK
814         CHECKGLERROR
815         GL_LockArrays(0, 0);
816         CHECKGLERROR
817
818         for (i = backendunits - 1;i >= 0;i--)
819         {
820                 if (qglActiveTexture)
821                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
822                 if (qglClientActiveTexture)
823                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
824                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
825                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
826                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
827                 if (gl_texture3d)
828                 {
829                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
830                 }
831                 if (gl_texturecubemap)
832                 {
833                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
834                 }
835                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
836                 if (gl_combine.integer)
837                 {
838                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
839                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
840                 }
841         }
842         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
843         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
844
845         qglDisable(GL_BLEND);CHECKGLERROR
846         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
847         qglDepthMask(GL_TRUE);CHECKGLERROR
848         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
849 }
850
851 void R_Mesh_Matrix(const matrix4x4_t *matrix)
852 {
853         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
854         {
855                 backend_modelmatrix = *matrix;
856                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
857                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
858                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
859         }
860 }
861
862 void R_Mesh_State(const rmeshstate_t *m)
863 {
864         int i, combinergb, combinealpha, scale, arrayis3d;
865         gltextureunit_t *unit;
866         const matrix4x4_t *texmatrix;
867         matrix4x4_t tempmatrix;
868         const float *texcoords;
869
870         BACKENDACTIVECHECK
871
872         if (gl_state.pointer_vertex != m->pointer_vertex)
873         {
874                 gl_state.pointer_vertex = m->pointer_vertex;
875                 CHECKGLERROR
876                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), gl_state.pointer_vertex);
877                 CHECKGLERROR
878         }
879
880         if (r_showtrispass)
881                 return;
882
883         if (gl_state.pointer_color != m->pointer_color)
884         {
885                 CHECKGLERROR
886                 if (!gl_state.pointer_color)
887                 {
888                         qglEnableClientState(GL_COLOR_ARRAY);
889                         CHECKGLERROR
890                 }
891                 else if (!m->pointer_color)
892                 {
893                         qglDisableClientState(GL_COLOR_ARRAY);
894                         CHECKGLERROR
895                         // when color array is on the glColor gets trashed, set it again
896                         qglColor4f(gl_state.color4f[0], gl_state.color4f[1], gl_state.color4f[2], gl_state.color4f[3]);
897                         CHECKGLERROR
898                 }
899                 gl_state.pointer_color = m->pointer_color;
900                 qglColorPointer(4, GL_FLOAT, sizeof(float[4]), gl_state.pointer_color);
901                 CHECKGLERROR
902         }
903
904         if (gl_backend_rebindtextures)
905         {
906                 gl_backend_rebindtextures = false;
907                 GL_SetupTextureState();
908         }
909
910         for (i = 0, unit = gl_state.units;i < backendunits;i++, unit++)
911         {
912                 if (unit->t1d != m->tex1d[i])
913                 {
914                         GL_ActiveTexture(i);
915                         if (m->tex1d[i])
916                         {
917                                 if (unit->t1d == 0)
918                                         qglEnable(GL_TEXTURE_1D);CHECKGLERROR
919                         }
920                         else
921                         {
922                                 if (unit->t1d)
923                                         qglDisable(GL_TEXTURE_1D);CHECKGLERROR
924                         }
925                         qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
926                 }
927                 if (unit->t2d != m->tex[i])
928                 {
929                         GL_ActiveTexture(i);
930                         if (m->tex[i])
931                         {
932                                 if (unit->t2d == 0)
933                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
934                         }
935                         else
936                         {
937                                 if (unit->t2d)
938                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
939                         }
940                         qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
941                 }
942                 if (unit->t3d != m->tex3d[i])
943                 {
944                         GL_ActiveTexture(i);
945                         if (m->tex3d[i])
946                         {
947                                 if (unit->t3d == 0)
948                                         qglEnable(GL_TEXTURE_3D);CHECKGLERROR
949                         }
950                         else
951                         {
952                                 if (unit->t3d)
953                                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
954                         }
955                         qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
956                 }
957                 if (unit->tcubemap != m->texcubemap[i])
958                 {
959                         GL_ActiveTexture(i);
960                         if (m->texcubemap[i])
961                         {
962                                 if (unit->tcubemap == 0)
963                                         qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
964                         }
965                         else
966                         {
967                                 if (unit->tcubemap)
968                                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
969                         }
970                         qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
971                 }
972                 combinergb = m->texcombinergb[i];
973                 if (!combinergb)
974                         combinergb = GL_MODULATE;
975                 if (unit->combinergb != combinergb)
976                 {
977                         GL_ActiveTexture(i);
978                         unit->combinergb = combinergb;
979                         if (gl_combine.integer) 
980                         {
981                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
982                         }
983                         else
984                         {
985                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
986                         }
987                 }
988                 combinealpha = m->texcombinealpha[i];
989                 if (!combinealpha)
990                         combinealpha = GL_MODULATE;
991                 if (unit->combinealpha != combinealpha)
992                 {
993                         GL_ActiveTexture(i);
994                         unit->combinealpha = combinealpha;
995                         if (gl_combine.integer)
996                         {
997                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
998                         }
999                 }
1000                 scale = max(m->texrgbscale[i], 1);
1001                 if (unit->rgbscale != scale)
1002                 {
1003                         GL_ActiveTexture(i);
1004                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (unit->rgbscale = scale));CHECKGLERROR
1005                 }
1006                 scale = max(m->texalphascale[i], 1);
1007                 if (unit->alphascale != scale)
1008                 {
1009                         GL_ActiveTexture(i);
1010                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (unit->alphascale = scale));CHECKGLERROR
1011                 }
1012                 arrayis3d = unit->t3d || unit->tcubemap;
1013                 texcoords = m->pointer_texcoord[i];
1014                 if (texcoords && !unit->t1d && !unit->t2d && !unit->t3d && !unit->tcubemap)
1015                         texcoords = NULL;
1016                 if (unit->pointer_texcoord != texcoords || unit->arrayis3d != arrayis3d)
1017                 {
1018                         GL_ClientActiveTexture(i);
1019                         if (texcoords)
1020                         {
1021                                 if (!unit->arrayenabled)
1022                                 {
1023                                         unit->arrayenabled = true;
1024                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1025                                 }
1026                         }
1027                         else
1028                         {
1029                                 if (unit->arrayenabled)
1030                                 {
1031                                         unit->arrayenabled = false;
1032                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1033                                 }
1034                         }
1035                         unit->pointer_texcoord = texcoords;
1036                         unit->arrayis3d = arrayis3d;
1037                         if (unit->arrayis3d)
1038                                 qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), unit->pointer_texcoord);
1039                         else
1040                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), unit->pointer_texcoord);
1041                         CHECKGLERROR
1042                 }
1043                 // if texmatrix is not set (3,3 should always be 1 in a texture matrix) just compare to the identity matrix
1044                 if (m->texmatrix[i].m[3][3])
1045                         texmatrix = &m->texmatrix[i];
1046                 else
1047                         texmatrix = &r_identitymatrix;
1048                 if (memcmp(&unit->matrix, texmatrix, sizeof(matrix4x4_t)))
1049                 {
1050                         unit->matrix = *texmatrix;
1051                         Matrix4x4_Transpose(&tempmatrix, &unit->matrix);
1052                         qglMatrixMode(GL_TEXTURE);
1053                         GL_ActiveTexture(i);
1054                         qglLoadMatrixf(&tempmatrix.m[0][0]);
1055                         qglMatrixMode(GL_MODELVIEW);
1056                 }
1057         }
1058 }
1059
1060 void R_Mesh_Draw_ShowTris(int numverts, int numtriangles, const int *elements)
1061 {
1062         qglBegin(GL_LINES);
1063         for (;numtriangles;numtriangles--, elements += 3)
1064         {
1065                 qglArrayElement(elements[0]);qglArrayElement(elements[1]);
1066                 qglArrayElement(elements[1]);qglArrayElement(elements[2]);
1067                 qglArrayElement(elements[2]);qglArrayElement(elements[0]);
1068         }
1069         qglEnd();
1070         CHECKGLERROR
1071 }
1072
1073 /*
1074 ==============================================================================
1075
1076                                                 SCREEN SHOTS
1077
1078 ==============================================================================
1079 */
1080
1081 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
1082 {
1083         qboolean ret;
1084         qbyte *buffer;
1085
1086         if (!r_render.integer)
1087                 return false;
1088
1089         buffer = Mem_Alloc(tempmempool, width*height*3);
1090         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1091         CHECKGLERROR
1092
1093         if (jpeg)
1094                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
1095         else
1096                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
1097
1098         Mem_Free(buffer);
1099         return ret;
1100 }
1101
1102 //=============================================================================
1103
1104 void R_ClearScreen(void)
1105 {
1106         if (r_render.integer)
1107         {
1108                 // clear to black
1109                 qglClearColor(0,0,0,0);CHECKGLERROR
1110                 qglClearDepth(1);CHECKGLERROR
1111                 if (gl_stencil)
1112                 {
1113                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1114                         // to avoid clamping interfering with strange shadow volume
1115                         // drawing orders
1116                         qglClearStencil(128);CHECKGLERROR
1117                 }
1118                 // clear the screen
1119                 GL_Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));
1120                 // set dithering mode
1121                 if (gl_dither.integer)
1122                 {
1123                         qglEnable(GL_DITHER);CHECKGLERROR
1124                 }
1125                 else
1126                 {
1127                         qglDisable(GL_DITHER);CHECKGLERROR
1128                 }
1129         }
1130 }
1131
1132 /*
1133 ====================
1134 CalcFov
1135 ====================
1136 */
1137 float CalcFov (float fov_x, float width, float height)
1138 {
1139         // calculate vision size and alter by aspect, then convert back to angle
1140         return atan (height / (width / tan(fov_x/360*M_PI))) * 360 / M_PI;
1141 }
1142
1143 /*
1144 ==================
1145 SCR_UpdateScreen
1146
1147 This is called every frame, and can also be called explicitly to flush
1148 text to the screen.
1149 ==================
1150 */
1151 void SCR_UpdateScreen (void)
1152 {
1153         if (gl_delayfinish.integer)
1154         {
1155                 R_Mesh_Finish();
1156                 R_TimeReport("meshfinish");
1157                 VID_Finish();
1158                 R_TimeReport("finish");
1159         }
1160
1161         R_Mesh_Start();
1162
1163         if (r_textureunits.integer > gl_textureunits)
1164                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1165         if (r_textureunits.integer < 1)
1166                 Cvar_SetValueQuick(&r_textureunits, 1);
1167
1168         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1169                 Cvar_SetValueQuick(&gl_combine, 0);
1170
1171 showtris:
1172         R_TimeReport("setup");
1173
1174         R_ClearScreen();
1175
1176         R_TimeReport("clear");
1177
1178         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1179         {
1180                 float size;
1181                 int contents;
1182
1183                 // bound viewsize
1184                 if (scr_viewsize.value < 30)
1185                         Cvar_Set ("viewsize","30");
1186                 if (scr_viewsize.value > 120)
1187                         Cvar_Set ("viewsize","120");
1188                 
1189                 // bound field of view
1190                 if (scr_fov.value < 1)
1191                         Cvar_Set ("fov","1");
1192                 if (scr_fov.value > 170)
1193                         Cvar_Set ("fov","170");
1194         
1195                 // intermission is always full screen
1196                 if (cl.intermission)
1197                 {
1198                         size = 1;
1199                         sb_lines = 0;
1200                 }
1201                 else
1202                 {
1203                         if (scr_viewsize.value >= 120)
1204                                 sb_lines = 0;           // no status bar at all
1205                         else if (scr_viewsize.value >= 110)
1206                                 sb_lines = 24;          // no inventory
1207                         else
1208                                 sb_lines = 24+16+8;
1209                         size = scr_viewsize.value * (1.0 / 100.0);
1210                         size = min(size, 1);
1211                 }
1212         
1213                 r_refdef.width = vid.realwidth * size;
1214                 r_refdef.height = vid.realheight * size;
1215                 r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1216                 r_refdef.y = (vid.realheight - r_refdef.height)/2;
1217         
1218                 // LordHavoc: viewzoom (zoom in for sniper rifles, etc)
1219                 r_refdef.fov_x = scr_fov.value * cl.viewzoom;
1220                 r_refdef.fov_y = CalcFov (r_refdef.fov_x, r_refdef.width, r_refdef.height);
1221         
1222                 if (cl.worldmodel)
1223                 {
1224                         Mod_CheckLoaded(cl.worldmodel);
1225                         contents = CL_PointSuperContents(r_vieworigin);
1226                         if (contents & SUPERCONTENTS_LIQUIDSMASK)
1227                         {
1228                                 r_refdef.fov_x *= (sin(cl.time * 4.7) * 0.015 + 0.985);
1229                                 r_refdef.fov_y *= (sin(cl.time * 3.0) * 0.015 + 0.985);
1230                         }
1231                 }
1232
1233                 R_RenderView();
1234
1235                 if (scr_zoomwindow.integer)
1236                 {
1237                         float sizex = bound(10, scr_zoomwindow_viewsizex.value, 100) / 100.0;
1238                         float sizey = bound(10, scr_zoomwindow_viewsizey.value, 100) / 100.0;
1239                         r_refdef.width = vid.realwidth * sizex;
1240                         r_refdef.height = vid.realheight * sizey;
1241                         r_refdef.x = (vid.realwidth - r_refdef.width)/2;
1242                         r_refdef.y = 0;
1243                         r_refdef.fov_x = scr_zoomwindow_fov.value;
1244                         r_refdef.fov_y = CalcFov(r_refdef.fov_x, r_refdef.width, r_refdef.height);
1245
1246                         R_RenderView();
1247                 }
1248         }
1249
1250         // draw 2D stuff
1251         R_DrawQueue();
1252
1253         if (r_showtrispass)
1254                 r_showtrispass = false;
1255         else if (r_showtris.value > 0)
1256         {
1257                 rmeshstate_t m;
1258                 GL_BlendFunc(GL_ONE, GL_ONE);
1259                 GL_DepthTest(GL_FALSE);
1260                 GL_DepthMask(GL_FALSE);
1261                 memset(&m, 0, sizeof(m));
1262                 R_Mesh_State(&m);
1263                 r_showtrispass = true;
1264                 GL_ShowTrisColor(0.2,0.2,0.2,1);
1265                 goto showtris;
1266         }
1267
1268         if (gl_delayfinish.integer)
1269         {
1270                 // tell driver to commit it's partially full geometry queue to the rendering queue
1271                 // (this doesn't wait for the commands themselves to complete)
1272                 qglFlush();
1273         }
1274         else
1275         {
1276                 R_Mesh_Finish();
1277                 R_TimeReport("meshfinish");
1278                 VID_Finish();
1279                 R_TimeReport("finish");
1280         }
1281 }
1282
1283
1284 //===========================================================================
1285 // dynamic vertex array buffer subsystem
1286 //===========================================================================
1287
1288 float varray_vertex3f[65536*3];
1289 float varray_color4f[65536*4];
1290 float varray_texcoord2f[4][65536*2];
1291 float varray_texcoord3f[4][65536*3];
1292 float varray_normal3f[65536*3];
1293 int earray_element3i[65536];
1294
1295 //===========================================================================
1296 // vertex array caching subsystem
1297 //===========================================================================
1298
1299 typedef struct rcachearraylink_s
1300 {
1301         struct rcachearraylink_s *next, *prev;
1302         struct rcachearrayitem_s *data;
1303 }
1304 rcachearraylink_t;
1305
1306 typedef struct rcachearrayitem_s
1307 {
1308         // the original request structure
1309         rcachearrayrequest_t request;
1310         // active
1311         int active;
1312         // offset into r_mesh_rcachedata
1313         int offset;
1314         // for linking this into the sequential list
1315         rcachearraylink_t sequentiallink;
1316         // for linking this into the lookup list
1317         rcachearraylink_t hashlink;
1318 }
1319 rcachearrayitem_t;
1320
1321 #define RCACHEARRAY_HASHSIZE 65536
1322 #define RCACHEARRAY_ITEMS 4096
1323 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1324
1325 // all active items are linked into this chain in sorted order
1326 static rcachearraylink_t r_mesh_rcachesequentialchain;
1327 // all inactive items are linked into this chain in unknown order
1328 static rcachearraylink_t r_mesh_rcachefreechain;
1329 // all active items are also linked into these chains (using their hashlink)
1330 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1331
1332 // all items are stored here, whether active or inactive
1333 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1334
1335 // size of data buffer
1336 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1337 // data buffer
1338 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1339
1340 // current state
1341 static int r_mesh_rcachedata_offset;
1342 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1343
1344 static void R_Mesh_CacheArray_Startup(void)
1345 {
1346         int i;
1347         rcachearraylink_t *l;
1348         // prepare all the linked lists
1349         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1350         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1351         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1352         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1353         {
1354                 l = &r_mesh_rcachechain[i];
1355                 l->next = l->prev = l;
1356                 l->data = NULL;
1357         }
1358         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
1359         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
1360         {
1361                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
1362                 l = &r_mesh_rcacheitems[i].sequentiallink;
1363                 l->next = &r_mesh_rcachefreechain;
1364                 l->prev = l->next->prev;
1365                 l->next->prev = l->prev->next = l;
1366         }
1367         // clear other state
1368         r_mesh_rcachedata_offset = 0;
1369         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1370 }
1371
1372 static void R_Mesh_CacheArray_Shutdown(void)
1373 {
1374 }
1375
1376 /*
1377 static void R_Mesh_CacheArray_ValidateState(int num)
1378 {
1379         rcachearraylink_t *l, *lhead;
1380         lhead = &r_mesh_rcachesequentialchain;
1381         if (r_mesh_rcachesequentialchain_current == lhead)
1382                 return;
1383         for (l = lhead->next;l != lhead;l = l->next)
1384                 if (r_mesh_rcachesequentialchain_current == l)
1385                         return;
1386         Sys_Error("%i", num);
1387 }
1388 */
1389
1390 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
1391 {
1392         rcachearraylink_t *l, *lhead, *lnext;
1393         rcachearrayitem_t *d;
1394         int hashindex, offset, offsetend;
1395
1396         //R_Mesh_CacheArray_ValidateState(3);
1397         // calculate a hashindex to choose a cache chain
1398         r->data = NULL;
1399         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
1400
1401         // is it already cached?
1402         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
1403         {
1404                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
1405                 {
1406                         // we have it cached already
1407                         r->data = r_mesh_rcachedata + l->data->offset;
1408                         return false;
1409                 }
1410         }
1411
1412         // we need to add a new cache item, this means finding a place for the new
1413         // data and making sure we have a free item available, lots of work...
1414
1415         // check if buffer needs to wrap
1416         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
1417         {
1418                 /*
1419                 if (r->data_size * 10 > r_mesh_rcachedata_size)
1420                 {
1421                         // realloc whole cache
1422                 }
1423                 */
1424                 // reset back to start
1425                 r_mesh_rcachedata_offset = 0;
1426                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1427         }
1428         offset = r_mesh_rcachedata_offset;
1429         r_mesh_rcachedata_offset += r->data_size;
1430         offsetend = r_mesh_rcachedata_offset;
1431         //R_Mesh_CacheArray_ValidateState(4);
1432
1433         /*
1434         {
1435                 int n;
1436                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
1437                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
1438         }
1439         */
1440
1441         // make room for the new data (remove old items)
1442         lhead = &r_mesh_rcachesequentialchain;
1443         l = r_mesh_rcachesequentialchain_current;
1444         if (l == lhead)
1445                 l = l->next;
1446         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
1447         {
1448         //r_mesh_rcachesequentialchain_current = l;
1449         //R_Mesh_CacheArray_ValidateState(8);
1450                 lnext = l->next;
1451                 // if at the end of the chain, wrap around
1452                 if (lnext == lhead)
1453                         lnext = lnext->next;
1454         //r_mesh_rcachesequentialchain_current = lnext;
1455         //R_Mesh_CacheArray_ValidateState(10);
1456
1457                 // unlink from sequential chain
1458                 l->next->prev = l->prev;
1459                 l->prev->next = l->next;
1460         //R_Mesh_CacheArray_ValidateState(11);
1461                 // link into free chain
1462                 l->next = &r_mesh_rcachefreechain;
1463                 l->prev = l->next->prev;
1464                 l->next->prev = l->prev->next = l;
1465         //R_Mesh_CacheArray_ValidateState(12);
1466
1467                 l = &l->data->hashlink;
1468                 // unlink from hash chain
1469                 l->next->prev = l->prev;
1470                 l->prev->next = l->next;
1471
1472                 l = lnext;
1473         //r_mesh_rcachesequentialchain_current = l;
1474         //R_Mesh_CacheArray_ValidateState(9);
1475         }
1476         //r_mesh_rcachesequentialchain_current = l;
1477         //R_Mesh_CacheArray_ValidateState(5);
1478         // gobble an extra item if we have no free items available
1479         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
1480         {
1481                 lnext = l->next;
1482
1483                 // unlink from sequential chain
1484                 l->next->prev = l->prev;
1485                 l->prev->next = l->next;
1486                 // link into free chain
1487                 l->next = &r_mesh_rcachefreechain;
1488                 l->prev = l->next->prev;
1489                 l->next->prev = l->prev->next = l;
1490
1491                 l = &l->data->hashlink;
1492                 // unlink from hash chain
1493                 l->next->prev = l->prev;
1494                 l->prev->next = l->next;
1495
1496                 l = lnext;
1497         }
1498         r_mesh_rcachesequentialchain_current = l;
1499         //R_Mesh_CacheArray_ValidateState(6);
1500
1501         // now take an item from the free chain
1502         l = r_mesh_rcachefreechain.next;
1503         // set it up
1504         d = l->data;
1505         d->request = *r;
1506         d->offset = offset;
1507         // unlink
1508         l->next->prev = l->prev;
1509         l->prev->next = l->next;
1510         // relink to sequential
1511         l->next = r_mesh_rcachesequentialchain_current->prev;
1512         l->prev = l->next->prev;
1513         while (l->next->data && l->data && l->next->data->offset <= d->offset)
1514         {
1515                 //Con_Print(">\n");
1516                 l->next = l->next->next;
1517                 l->prev = l->prev->next;
1518         }
1519         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
1520         {
1521                 //Con_Print("<\n");
1522                 l->prev = l->prev->prev;
1523                 l->next = l->next->prev;
1524         }
1525         l->next->prev = l->prev->next = l;
1526         // also link into hash chain
1527         l = &l->data->hashlink;
1528         l->next = &r_mesh_rcachechain[hashindex];
1529         l->prev = l->next->prev;
1530         l->prev->next = l;
1531         l->next->prev = l->prev->next = l;
1532
1533
1534         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
1535
1536         //R_Mesh_CacheArray_ValidateState(7);
1537         // and finally set the data pointer
1538         r->data = r_mesh_rcachedata + d->offset;
1539         // and tell the caller to fill the array
1540         return true;
1541 }
1542