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