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