fixed realtime lighting bugs with gl_mesh_batching 1 (... by not using batching while...
[divverent/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         varray_vertex3f = varray_buf_vertex3f + varray_offset * 3;
856         varray_color4f = varray_buf_color4f + varray_offset * 4;
857         for (i = 0;i < backendunits;i++)
858         {
859                 varray_texcoord3f[i] = varray_buf_texcoord3f[i] + varray_offset * 3;
860                 varray_texcoord2f[i] = varray_buf_texcoord2f[i] + varray_offset * 2;
861         }
862
863         varray_offsetnext = varray_offset + numverts;
864 }
865
866 // renders triangles using vertices from the most recent GetSpace call
867 // (can be multiple Draw calls per GetSpace)
868 void R_Mesh_Draw(int numverts, int numtriangles, const int *elements)
869 {
870         int numelements = numtriangles * 3;
871         if (numtriangles == 0 || numverts == 0)
872         {
873                 Con_Printf("R_Mesh_Draw(%d, %d, %08p);\n", numverts, numtriangles, elements);
874                 return;
875         }
876         c_meshs++;
877         c_meshelements += numelements;
878         CHECKGLERROR
879         if (gl_state.pointervertexcount)
880         {
881 #ifdef MESH_BATCH
882                 if (gl_batchelementcount)
883                         R_Mesh_EndBatch();
884 #endif
885                 if (r_render.integer)
886                 {
887                         GL_LockArrays(0, gl_state.pointervertexcount);
888                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
889                         {
890                                 qglDrawRangeElements(GL_TRIANGLES, 0, gl_state.pointervertexcount, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
891                         }
892                         else
893                         {
894                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
895                         }
896                         GL_LockArrays(0, 0);
897                 }
898         }
899 #ifdef MESH_BATCH
900         else if (gl_mesh_batching.integer)
901         {
902                 if (mesh_maxelements < gl_batchelementcount + numelements)
903                 {
904                         //Con_Printf("R_Mesh_Draw: enlarging elements array\n");
905                         if (gl_batchelementcount)
906                                 R_Mesh_EndBatch();
907                         // round up to a multiple of 1024 and add another 1024 just for good measure
908                         mesh_maxelements = (gl_batchelementcount + numelements + 1024 + 1023) & ~1023;
909                         GL_Backend_AllocElementsArray();
910                 }
911                 if (varray_offset < gl_batchvertexfirst && gl_batchelementcount)
912                         R_Mesh_EndBatch();
913                 if (gl_batchelementcount == 0)
914                 {
915                         gl_batchvertexfirst = varray_offset;
916                         gl_batchvertexcount = 0;
917                 }
918                 if (gl_batchvertexcount < varray_offsetnext - gl_batchvertexfirst)
919                         gl_batchvertexcount = varray_offsetnext - gl_batchvertexfirst;
920                 GL_Backend_RenumberElements(varray_buf_elements3i + gl_batchelementcount, numelements, elements, varray_offset);
921                 //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);
922                 gl_batchelementcount += numelements;
923                 //{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);}
924         }
925 #endif
926         else
927         {
928                 GL_Backend_RenumberElements(varray_buf_elements3i, numelements, elements, varray_offset);
929                 if (r_render.integer)
930                 {
931                         GL_LockArrays(varray_offset, numverts);
932                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
933                         {
934                                 qglDrawRangeElements(GL_TRIANGLES, varray_offset, varray_offset + numverts, numelements, GL_UNSIGNED_INT, varray_buf_elements3i);CHECKGLERROR
935                         }
936                         else
937                         {
938                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, varray_buf_elements3i);CHECKGLERROR
939                         }
940                         GL_LockArrays(0, 0);
941                 }
942         }
943 }
944
945 // renders triangles using vertices from the most recent GetSpace call
946 // (can be multiple Draw calls per GetSpace)
947 void R_Mesh_Draw_NoBatching(int numverts, int numtriangles, const int *elements)
948 {
949         int numelements = numtriangles * 3;
950         if (numtriangles == 0 || numverts == 0)
951         {
952                 Con_Printf("R_Mesh_Draw_NoBatching(%d, %d, %08p);\n", numverts, numtriangles, elements);
953                 return;
954         }
955         c_meshs++;
956         c_meshelements += numelements;
957         CHECKGLERROR
958         if (gl_state.pointervertexcount)
959         {
960                 if (r_render.integer)
961                 {
962                         GL_LockArrays(0, gl_state.pointervertexcount);
963                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
964                         {
965                                 qglDrawRangeElements(GL_TRIANGLES, 0, gl_state.pointervertexcount, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
966                         }
967                         else
968                         {
969                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, elements);CHECKGLERROR
970                         }
971                         GL_LockArrays(0, 0);
972                 }
973         }
974         else
975         {
976                 GL_Backend_RenumberElements(varray_buf_elements3i, numelements, elements, varray_offset);
977                 if (r_render.integer)
978                 {
979                         GL_LockArrays(varray_offset, numverts);
980                         if (gl_mesh_drawrangeelements.integer && qglDrawRangeElements != NULL)
981                         {
982                                 qglDrawRangeElements(GL_TRIANGLES, varray_offset, varray_offset + numverts, numelements, GL_UNSIGNED_INT, varray_buf_elements3i);CHECKGLERROR
983                         }
984                         else
985                         {
986                                 qglDrawElements(GL_TRIANGLES, numelements, GL_UNSIGNED_INT, varray_buf_elements3i);CHECKGLERROR
987                         }
988                         GL_LockArrays(0, 0);
989                 }
990         }
991 }
992
993 // restores backend state, used when done with 3D rendering
994 void R_Mesh_Finish(void)
995 {
996         int i;
997         BACKENDACTIVECHECK
998 #ifdef MESH_BATCH
999         if (gl_batchelementcount)
1000                 R_Mesh_EndBatch();
1001 #endif
1002         GL_LockArrays(0, 0);
1003
1004         for (i = backendunits - 1;i >= 0;i--)
1005         {
1006                 if (qglActiveTexture)
1007                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
1008                 if (qglClientActiveTexture)
1009                         qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
1010                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1011                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1012                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1013                 if (gl_texture3d)
1014                 {
1015                         qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1016                 }
1017                 if (gl_texturecubemap)
1018                 {
1019                         qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1020                 }
1021                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
1022                 if (gl_combine.integer)
1023                 {
1024                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
1025                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
1026                 }
1027         }
1028         qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
1029         qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
1030
1031         qglDisable(GL_BLEND);CHECKGLERROR
1032         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
1033         qglDepthMask(GL_TRUE);CHECKGLERROR
1034         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
1035 }
1036
1037 void R_Mesh_Matrix(const matrix4x4_t *matrix)
1038 {
1039         if (memcmp(matrix, &backend_modelmatrix, sizeof(matrix4x4_t)))
1040         {
1041 #ifdef MESH_BATCH
1042                 if (gl_batchelementcount)
1043                         R_Mesh_EndBatch();
1044 #endif
1045                 backend_modelmatrix = *matrix;
1046                 Matrix4x4_Concat(&backend_modelviewmatrix, &backend_viewmatrix, matrix);
1047                 Matrix4x4_Transpose(&backend_glmodelviewmatrix, &backend_modelviewmatrix);
1048                 qglLoadMatrixf(&backend_glmodelviewmatrix.m[0][0]);
1049         }
1050 }
1051
1052 // sets up the requested state
1053 void R_Mesh_MainState(const rmeshstate_t *m)
1054 {
1055         void *p;
1056         BACKENDACTIVECHECK
1057
1058         if (gl_state.blendfunc1 != m->blendfunc1 || gl_state.blendfunc2 != m->blendfunc2)
1059         {
1060 #ifdef MESH_BATCH
1061                 if (gl_batchelementcount)
1062                         R_Mesh_EndBatch();
1063 #endif
1064                 qglBlendFunc(gl_state.blendfunc1 = m->blendfunc1, gl_state.blendfunc2 = m->blendfunc2);CHECKGLERROR
1065                 if (gl_state.blendfunc2 == GL_ZERO)
1066                 {
1067                         if (gl_state.blendfunc1 == GL_ONE)
1068                         {
1069                                 if (gl_state.blend)
1070                                 {
1071                                         gl_state.blend = 0;
1072                                         qglDisable(GL_BLEND);CHECKGLERROR
1073                                 }
1074                         }
1075                         else
1076                         {
1077                                 if (!gl_state.blend)
1078                                 {
1079                                         gl_state.blend = 1;
1080                                         qglEnable(GL_BLEND);CHECKGLERROR
1081                                 }
1082                         }
1083                 }
1084                 else
1085                 {
1086                         if (!gl_state.blend)
1087                         {
1088                                 gl_state.blend = 1;
1089                                 qglEnable(GL_BLEND);CHECKGLERROR
1090                         }
1091                 }
1092         }
1093         if (gl_state.depthdisable != m->depthdisable)
1094         {
1095 #ifdef MESH_BATCH
1096                 if (gl_batchelementcount)
1097                         R_Mesh_EndBatch();
1098 #endif
1099                 gl_state.depthdisable = m->depthdisable;
1100                 if (gl_state.depthdisable)
1101                         qglDisable(GL_DEPTH_TEST);
1102                 else
1103                         qglEnable(GL_DEPTH_TEST);
1104         }
1105         if (gl_state.depthmask != (m->blendfunc2 == GL_ZERO || m->depthwrite))
1106         {
1107 #ifdef MESH_BATCH
1108                 if (gl_batchelementcount)
1109                         R_Mesh_EndBatch();
1110 #endif
1111                 qglDepthMask(gl_state.depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite));CHECKGLERROR
1112         }
1113
1114         if (gl_state.pointervertexcount != m->pointervertexcount)
1115         {
1116 #ifdef MESH_BATCH
1117                 if (gl_batchelementcount)
1118                         R_Mesh_EndBatch();
1119 #endif
1120                 gl_state.pointervertexcount = m->pointervertexcount;
1121         }
1122
1123         p = gl_state.pointervertexcount ? m->pointer_vertex : NULL;
1124         if (gl_state.pointer_vertex != p)
1125         {
1126 #ifdef MESH_BATCH
1127                 if (gl_batchelementcount)
1128                         R_Mesh_EndBatch();
1129 #endif
1130                 gl_state.pointer_vertex = p;
1131                 qglVertexPointer(3, GL_FLOAT, sizeof(float[3]), p ? p : varray_buf_vertex3f);CHECKGLERROR
1132         }
1133
1134         p = gl_state.pointervertexcount ? m->pointer_color : NULL;
1135         if (gl_state.pointer_color != p)
1136         {
1137 #ifdef MESH_BATCH
1138                 if (gl_batchelementcount)
1139                         R_Mesh_EndBatch();
1140 #endif
1141                 gl_state.pointer_color = p;
1142                 if (p || gl_mesh_floatcolors.integer)
1143                         qglColorPointer(4, GL_FLOAT, sizeof(float[4]), p ? p : varray_buf_color4f);
1144                 else
1145                         qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(GLubyte[4]), p ? p : varray_buf_color4b);
1146                 CHECKGLERROR
1147         }
1148 }
1149
1150 void R_Mesh_TextureState(const rmeshstate_t *m)
1151 {
1152         int i, combinergb, combinealpha;
1153         float scale;
1154         gltextureunit_t *unit;
1155         void *p;
1156
1157         BACKENDACTIVECHECK
1158
1159         if (gl_backend_rebindtextures)
1160         {
1161                 gl_backend_rebindtextures = false;
1162                 GL_SetupTextureState();
1163         }
1164
1165         for (i = 0;i < backendunits;i++)
1166         {
1167                 unit = gl_state.units + i;
1168                 if (unit->t1d != m->tex1d[i] || unit->t2d != m->tex[i] || unit->t3d != m->tex3d[i] || unit->tcubemap != m->texcubemap[i])
1169                 {
1170                         if (m->tex3d[i] || m->texcubemap[i])
1171                         {
1172                                 if (!unit->arrayis3d)
1173                                 {
1174 #ifdef MESH_BATCH
1175                                         if (gl_batchelementcount)
1176                                                 R_Mesh_EndBatch();
1177 #endif
1178                                         unit->arrayis3d = true;
1179                                         if (gl_state.clientunit != i)
1180                                         {
1181                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1182                                         }
1183                                         qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), varray_buf_texcoord3f[i]);
1184                                 }
1185                                 if (!unit->arrayenabled)
1186                                 {
1187 #ifdef MESH_BATCH
1188                                         if (gl_batchelementcount)
1189                                                 R_Mesh_EndBatch();
1190 #endif
1191                                         unit->arrayenabled = true;
1192                                         if (gl_state.clientunit != i)
1193                                         {
1194                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1195                                         }
1196                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1197                                 }
1198                         }
1199                         else if (m->tex1d[i] || m->tex[i])
1200                         {
1201                                 if (unit->arrayis3d)
1202                                 {
1203 #ifdef MESH_BATCH
1204                                         if (gl_batchelementcount)
1205                                                 R_Mesh_EndBatch();
1206 #endif
1207                                         unit->arrayis3d = false;
1208                                         if (gl_state.clientunit != i)
1209                                         {
1210                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1211                                         }
1212                                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), varray_buf_texcoord2f[i]);
1213                                 }
1214                                 if (!unit->arrayenabled)
1215                                 {
1216 #ifdef MESH_BATCH
1217                                         if (gl_batchelementcount)
1218                                                 R_Mesh_EndBatch();
1219 #endif
1220                                         unit->arrayenabled = true;
1221                                         if (gl_state.clientunit != i)
1222                                         {
1223                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1224                                         }
1225                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1226                                 }
1227                         }
1228                         else
1229                         {
1230                                 if (unit->arrayenabled)
1231                                 {
1232 #ifdef MESH_BATCH
1233                                         if (gl_batchelementcount)
1234                                                 R_Mesh_EndBatch();
1235 #endif
1236                                         unit->arrayenabled = false;
1237                                         if (gl_state.clientunit != i)
1238                                         {
1239                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1240                                         }
1241                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
1242                                 }
1243                         }
1244                         if (unit->t1d != m->tex1d[i])
1245                         {
1246 #ifdef MESH_BATCH
1247                                 if (gl_batchelementcount)
1248                                         R_Mesh_EndBatch();
1249 #endif
1250                                 if (gl_state.unit != i)
1251                                 {
1252                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1253                                 }
1254                                 if (m->tex1d[i])
1255                                 {
1256                                         if (unit->t1d == 0)
1257                                                 qglEnable(GL_TEXTURE_1D);CHECKGLERROR
1258                                 }
1259                                 else
1260                                 {
1261                                         if (unit->t1d)
1262                                                 qglDisable(GL_TEXTURE_1D);CHECKGLERROR
1263                                 }
1264                                 qglBindTexture(GL_TEXTURE_1D, (unit->t1d = m->tex1d[i]));CHECKGLERROR
1265                         }
1266                         if (unit->t2d != m->tex[i])
1267                         {
1268 #ifdef MESH_BATCH
1269                                 if (gl_batchelementcount)
1270                                         R_Mesh_EndBatch();
1271 #endif
1272                                 if (gl_state.unit != i)
1273                                 {
1274                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1275                                 }
1276                                 if (m->tex[i])
1277                                 {
1278                                         if (unit->t2d == 0)
1279                                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
1280                                 }
1281                                 else
1282                                 {
1283                                         if (unit->t2d)
1284                                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
1285                                 }
1286                                 qglBindTexture(GL_TEXTURE_2D, (unit->t2d = m->tex[i]));CHECKGLERROR
1287                         }
1288                         if (unit->t3d != m->tex3d[i])
1289                         {
1290 #ifdef MESH_BATCH
1291                                 if (gl_batchelementcount)
1292                                         R_Mesh_EndBatch();
1293 #endif
1294                                 if (gl_state.unit != i)
1295                                 {
1296                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1297                                 }
1298                                 if (m->tex3d[i])
1299                                 {
1300                                         if (unit->t3d == 0)
1301                                                 qglEnable(GL_TEXTURE_3D);CHECKGLERROR
1302                                 }
1303                                 else
1304                                 {
1305                                         if (unit->t3d)
1306                                                 qglDisable(GL_TEXTURE_3D);CHECKGLERROR
1307                                 }
1308                                 qglBindTexture(GL_TEXTURE_3D, (unit->t3d = m->tex3d[i]));CHECKGLERROR
1309                         }
1310                         if (unit->tcubemap != m->texcubemap[i])
1311                         {
1312 #ifdef MESH_BATCH
1313                                 if (gl_batchelementcount)
1314                                         R_Mesh_EndBatch();
1315 #endif
1316                                 if (gl_state.unit != i)
1317                                 {
1318                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1319                                 }
1320                                 if (m->texcubemap[i])
1321                                 {
1322                                         if (unit->tcubemap == 0)
1323                                                 qglEnable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1324                                 }
1325                                 else
1326                                 {
1327                                         if (unit->tcubemap)
1328                                                 qglDisable(GL_TEXTURE_CUBE_MAP_ARB);CHECKGLERROR
1329                                 }
1330                                 qglBindTexture(GL_TEXTURE_CUBE_MAP_ARB, (unit->tcubemap = m->texcubemap[i]));CHECKGLERROR
1331                         }
1332                 }
1333                 combinergb = m->texcombinergb[i];
1334                 if (!combinergb)
1335                         combinergb = GL_MODULATE;
1336                 if (unit->combinergb != combinergb)
1337                 {
1338 #ifdef MESH_BATCH
1339                         if (gl_batchelementcount)
1340                                 R_Mesh_EndBatch();
1341 #endif
1342                         if (gl_state.unit != i)
1343                         {
1344                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1345                         }
1346                         unit->combinergb = combinergb;
1347                         if (gl_combine.integer)
1348                         {
1349                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, unit->combinergb);CHECKGLERROR
1350                         }
1351                         else
1352                         {
1353                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, unit->combinergb);CHECKGLERROR
1354                         }
1355                 }
1356                 combinealpha = m->texcombinealpha[i];
1357                 if (!combinealpha)
1358                         combinealpha = GL_MODULATE;
1359                 if (unit->combinealpha != combinealpha)
1360                 {
1361 #ifdef MESH_BATCH
1362                         if (gl_batchelementcount)
1363                                 R_Mesh_EndBatch();
1364 #endif
1365                         if (gl_state.unit != i)
1366                         {
1367                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1368                         }
1369                         unit->combinealpha = combinealpha;
1370                         if (gl_combine.integer)
1371                         {
1372                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, unit->combinealpha);CHECKGLERROR
1373                         }
1374                 }
1375                 scale = max(m->texrgbscale[i], 1);
1376                 if (gl_state.units[i].rgbscale != scale)
1377                 {
1378 #ifdef MESH_BATCH
1379                         if (gl_batchelementcount)
1380                                 R_Mesh_EndBatch();
1381 #endif
1382                         if (gl_state.unit != i)
1383                         {
1384                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1385                         }
1386                         qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.units[i].rgbscale = scale));CHECKGLERROR
1387                 }
1388                 scale = max(m->texalphascale[i], 1);
1389                 if (gl_state.units[i].alphascale != scale)
1390                 {
1391 #ifdef MESH_BATCH
1392                         if (gl_batchelementcount)
1393                                 R_Mesh_EndBatch();
1394 #endif
1395                         if (gl_state.unit != i)
1396                         {
1397                                 qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
1398                         }
1399                         qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, (gl_state.units[i].alphascale = scale));CHECKGLERROR
1400                 }
1401                 if (unit->arrayenabled)
1402                 {
1403                         p = gl_state.pointervertexcount ? m->pointer_texcoord[i] : NULL;
1404                         if (unit->pointer_texcoord != p)
1405                         {
1406 #ifdef MESH_BATCH
1407                                 if (gl_batchelementcount)
1408                                         R_Mesh_EndBatch();
1409 #endif
1410                                 unit->pointer_texcoord = p;
1411                                 if (gl_state.clientunit != i)
1412                                 {
1413                                         qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
1414                                 }
1415                                 if (unit->arrayis3d)
1416                                         qglTexCoordPointer(3, GL_FLOAT, sizeof(float[3]), p ? p : varray_buf_texcoord3f[i]);
1417                                 else
1418                                         qglTexCoordPointer(2, GL_FLOAT, sizeof(float[2]), p ? p : varray_buf_texcoord2f[i]);
1419                                 CHECKGLERROR
1420                         }
1421                 }
1422         }
1423 }
1424
1425 void R_Mesh_State(const rmeshstate_t *m)
1426 {
1427         R_Mesh_MainState(m);
1428         R_Mesh_TextureState(m);
1429 }
1430
1431 /*
1432 ==============================================================================
1433
1434                                                 SCREEN SHOTS
1435
1436 ==============================================================================
1437 */
1438
1439 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height, qboolean jpeg)
1440 {
1441         qboolean ret;
1442         int i, j;
1443         qbyte *buffer;
1444
1445         if (!r_render.integer)
1446                 return false;
1447
1448         buffer = Mem_Alloc(tempmempool, width*height*3);
1449         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1450         CHECKGLERROR
1451
1452         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
1453         if (v_hwgamma.integer)
1454         {
1455                 for (i = 0;i < width * height * 3;i++)
1456                 {
1457                         j = buffer[i] << v_overbrightbits.integer;
1458                         buffer[i] = (qbyte) (bound(0, j, 255));
1459                 }
1460         }
1461
1462         if (jpeg)
1463                 ret = JPEG_SaveImage_preflipped (filename, width, height, buffer);
1464         else
1465                 ret = Image_WriteTGARGB_preflipped (filename, width, height, buffer);
1466
1467         Mem_Free(buffer);
1468         return ret;
1469 }
1470
1471 //=============================================================================
1472
1473 void R_ClearScreen(void)
1474 {
1475         if (r_render.integer)
1476         {
1477                 // clear to black
1478                 qglClearColor(0,0,0,0);CHECKGLERROR
1479                 qglClearDepth(1);CHECKGLERROR
1480                 if (gl_stencil)
1481                 {
1482                         // LordHavoc: we use a stencil centered around 128 instead of 0,
1483                         // to avoid clamping interfering with strange shadow volume
1484                         // drawing orders
1485                         qglClearStencil(128);CHECKGLERROR
1486                 }
1487                 // clear the screen
1488                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | (gl_stencil ? GL_STENCIL_BUFFER_BIT : 0));CHECKGLERROR
1489                 // set dithering mode
1490                 if (gl_dither.integer)
1491                 {
1492                         qglEnable(GL_DITHER);CHECKGLERROR
1493                 }
1494                 else
1495                 {
1496                         qglDisable(GL_DITHER);CHECKGLERROR
1497                 }
1498         }
1499 }
1500
1501 /*
1502 ==================
1503 SCR_UpdateScreen
1504
1505 This is called every frame, and can also be called explicitly to flush
1506 text to the screen.
1507 ==================
1508 */
1509 void SCR_UpdateScreen (void)
1510 {
1511         if (gl_delayfinish.integer)
1512         {
1513                 VID_Finish ();
1514
1515                 R_TimeReport("finish");
1516         }
1517
1518         if (r_textureunits.integer > gl_textureunits)
1519                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1520         if (r_textureunits.integer < 1)
1521                 Cvar_SetValueQuick(&r_textureunits, 1);
1522
1523         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1524                 Cvar_SetValueQuick(&gl_combine, 0);
1525
1526         // lighting scale
1527         r_colorscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1528
1529         // lightmaps only
1530         r_lightmapscalebit = v_overbrightbits.integer;
1531         if (gl_combine.integer && r_textureunits.integer > 1)
1532                 r_lightmapscalebit += 2;
1533
1534         R_TimeReport("setup");
1535
1536         R_ClearScreen();
1537
1538         R_TimeReport("clear");
1539
1540         if (scr_conlines < vid.conheight && cls.signon == SIGNONS)
1541                 R_RenderView();
1542
1543         // draw 2D stuff
1544         R_DrawQueue();
1545
1546         if (gl_delayfinish.integer)
1547         {
1548                 // tell driver to commit it's partially full geometry queue to the rendering queue
1549                 // (this doesn't wait for the commands themselves to complete)
1550                 qglFlush();
1551         }
1552         else
1553         {
1554                 VID_Finish ();
1555
1556                 R_TimeReport("finish");
1557         }
1558 }
1559
1560 // utility functions
1561
1562 void R_Mesh_CopyVertex3f(const float *vertex3f, int numverts)
1563 {
1564 #ifdef MESH_VAR
1565         if (mesh_var)
1566         {
1567                 float *out = varray_vertex3f;
1568                 while (--numverts)
1569                 {
1570                         *out++ = *vertex3f++;
1571                         *out++ = *vertex3f++;
1572                         *out++ = *vertex3f++;
1573                 }
1574         }
1575         else
1576 #endif
1577                 memcpy(varray_vertex3f, vertex3f, numverts * sizeof(float[3]));
1578 }
1579
1580 void R_Mesh_CopyTexCoord2f(int tmu, const float *texcoord2f, int numverts)
1581 {
1582 #ifdef MESH_VAR
1583         if (mesh_var)
1584         {
1585                 float *out = varray_texcoord2f[tmu];
1586                 while (--numverts)
1587                 {
1588                         *out++ = *texcoord2f++;
1589                         *out++ = *texcoord2f++;
1590                 }
1591         }
1592         else
1593 #endif
1594                 memcpy(varray_texcoord2f[tmu], texcoord2f, numverts * sizeof(float[2]));
1595 }
1596
1597 void R_Mesh_CopyColor4f(const float *color4f, int numverts)
1598 {
1599 #ifdef MESH_VAR
1600         if (mesh_var)
1601         {
1602                 float *out = varray_color4f;
1603                 while (--numverts)
1604                 {
1605                         *out++ = *color4f++;
1606                         *out++ = *color4f++;
1607                         *out++ = *color4f++;
1608                         *out++ = *color4f++;
1609                 }
1610         }
1611         else
1612 #endif
1613                 memcpy(varray_color4f, color4f, numverts * sizeof(float[4]));
1614 }
1615
1616 //===========================================================================
1617 // vertex array caching subsystem
1618 //===========================================================================
1619
1620 typedef struct rcachearraylink_s
1621 {
1622         struct rcachearraylink_s *next, *prev;
1623         struct rcachearrayitem_s *data;
1624 }
1625 rcachearraylink_t;
1626
1627 typedef struct rcachearrayitem_s
1628 {
1629         // the original request structure
1630         rcachearrayrequest_t request;
1631         // active
1632         int active;
1633         // offset into r_mesh_rcachedata
1634         int offset;
1635         // for linking this into the sequential list
1636         rcachearraylink_t sequentiallink;
1637         // for linking this into the lookup list
1638         rcachearraylink_t hashlink;
1639 }
1640 rcachearrayitem_t;
1641
1642 #define RCACHEARRAY_HASHSIZE 65536
1643 #define RCACHEARRAY_ITEMS 4096
1644 #define RCACHEARRAY_DEFAULTSIZE (4 << 20)
1645
1646 // all active items are linked into this chain in sorted order
1647 static rcachearraylink_t r_mesh_rcachesequentialchain;
1648 // all inactive items are linked into this chain in unknown order
1649 static rcachearraylink_t r_mesh_rcachefreechain;
1650 // all active items are also linked into these chains (using their hashlink)
1651 static rcachearraylink_t r_mesh_rcachechain[RCACHEARRAY_HASHSIZE];
1652
1653 // all items are stored here, whether active or inactive
1654 static rcachearrayitem_t r_mesh_rcacheitems[RCACHEARRAY_ITEMS];
1655
1656 // size of data buffer
1657 static int r_mesh_rcachedata_size = RCACHEARRAY_DEFAULTSIZE;
1658 // data buffer
1659 static qbyte r_mesh_rcachedata[RCACHEARRAY_DEFAULTSIZE];
1660
1661 // current state
1662 static int r_mesh_rcachedata_offset;
1663 static rcachearraylink_t *r_mesh_rcachesequentialchain_current;
1664
1665 static void R_Mesh_CacheArray_Startup(void)
1666 {
1667         int i;
1668         rcachearraylink_t *l;
1669         // prepare all the linked lists
1670         l = &r_mesh_rcachesequentialchain;l->next = l->prev = l;l->data = NULL;
1671         l = &r_mesh_rcachefreechain;l->next = l->prev = l;l->data = NULL;
1672         memset(&r_mesh_rcachechain, 0, sizeof(r_mesh_rcachechain));
1673         for (i = 0;i < RCACHEARRAY_HASHSIZE;i++)
1674         {
1675                 l = &r_mesh_rcachechain[i];
1676                 l->next = l->prev = l;
1677                 l->data = NULL;
1678         }
1679         memset(&r_mesh_rcacheitems, 0, sizeof(r_mesh_rcacheitems));
1680         for (i = 0;i < RCACHEARRAY_ITEMS;i++)
1681         {
1682                 r_mesh_rcacheitems[i].hashlink.data = r_mesh_rcacheitems[i].sequentiallink.data = &r_mesh_rcacheitems[i];
1683                 l = &r_mesh_rcacheitems[i].sequentiallink;
1684                 l->next = &r_mesh_rcachefreechain;
1685                 l->prev = l->next->prev;
1686                 l->next->prev = l->prev->next = l;
1687         }
1688         // clear other state
1689         r_mesh_rcachedata_offset = 0;
1690         r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1691 }
1692
1693 static void R_Mesh_CacheArray_Shutdown(void)
1694 {
1695 }
1696
1697 /*
1698 static void R_Mesh_CacheArray_ValidateState(int num)
1699 {
1700         rcachearraylink_t *l, *lhead;
1701         lhead = &r_mesh_rcachesequentialchain;
1702         if (r_mesh_rcachesequentialchain_current == lhead)
1703                 return;
1704         for (l = lhead->next;l != lhead;l = l->next)
1705                 if (r_mesh_rcachesequentialchain_current == l)
1706                         return;
1707         Sys_Error("%i", num);
1708 }
1709 */
1710
1711 int R_Mesh_CacheArray(rcachearrayrequest_t *r)
1712 {
1713         rcachearraylink_t *l, *lhead, *lnext;
1714         rcachearrayitem_t *d;
1715         int hashindex, offset, offsetend;
1716
1717         //R_Mesh_CacheArray_ValidateState(3);
1718         // calculate a hashindex to choose a cache chain
1719         r->data = NULL;
1720         hashindex = CRC_Block((void *)r, sizeof(*r)) % RCACHEARRAY_HASHSIZE;
1721
1722         // is it already cached?
1723         for (lhead = &r_mesh_rcachechain[hashindex], l = lhead->next;l != lhead;l = l->next)
1724         {
1725                 if (!memcmp(&l->data->request, r, sizeof(l->data->request)))
1726                 {
1727                         // we have it cached already
1728                         r->data = r_mesh_rcachedata + l->data->offset;
1729                         return false;
1730                 }
1731         }
1732
1733         // we need to add a new cache item, this means finding a place for the new
1734         // data and making sure we have a free item available, lots of work...
1735
1736         // check if buffer needs to wrap
1737         if (r_mesh_rcachedata_offset + r->data_size > r_mesh_rcachedata_size)
1738         {
1739                 /*
1740                 if (r->data_size * 10 > r_mesh_rcachedata_size)
1741                 {
1742                         // realloc whole cache
1743                 }
1744                 */
1745                 // reset back to start
1746                 r_mesh_rcachedata_offset = 0;
1747                 r_mesh_rcachesequentialchain_current = &r_mesh_rcachesequentialchain;
1748         }
1749         offset = r_mesh_rcachedata_offset;
1750         r_mesh_rcachedata_offset += r->data_size;
1751         offsetend = r_mesh_rcachedata_offset;
1752         //R_Mesh_CacheArray_ValidateState(4);
1753
1754         /*
1755         {
1756                 int n;
1757                 for (lhead = &r_mesh_rcachesequentialchain, l = lhead->next, n = 0;l != lhead;l = l->next, n++);
1758                 Con_Printf("R_Mesh_CacheArray: new data range %i:%i, %i items are already linked\n", offset, offsetend, n);
1759         }
1760         */
1761
1762         // make room for the new data (remove old items)
1763         lhead = &r_mesh_rcachesequentialchain;
1764         l = r_mesh_rcachesequentialchain_current;
1765         if (l == lhead)
1766                 l = l->next;
1767         while (l != lhead && l->data->offset < offsetend && l->data->offset + l->data->request.data_size > offset)
1768         {
1769         //r_mesh_rcachesequentialchain_current = l;
1770         //R_Mesh_CacheArray_ValidateState(8);
1771                 lnext = l->next;
1772                 // if at the end of the chain, wrap around
1773                 if (lnext == lhead)
1774                         lnext = lnext->next;
1775         //r_mesh_rcachesequentialchain_current = lnext;
1776         //R_Mesh_CacheArray_ValidateState(10);
1777
1778                 // unlink from sequential chain
1779                 l->next->prev = l->prev;
1780                 l->prev->next = l->next;
1781         //R_Mesh_CacheArray_ValidateState(11);
1782                 // link into free chain
1783                 l->next = &r_mesh_rcachefreechain;
1784                 l->prev = l->next->prev;
1785                 l->next->prev = l->prev->next = l;
1786         //R_Mesh_CacheArray_ValidateState(12);
1787
1788                 l = &l->data->hashlink;
1789                 // unlink from hash chain
1790                 l->next->prev = l->prev;
1791                 l->prev->next = l->next;
1792
1793                 l = lnext;
1794         //r_mesh_rcachesequentialchain_current = l;
1795         //R_Mesh_CacheArray_ValidateState(9);
1796         }
1797         //r_mesh_rcachesequentialchain_current = l;
1798         //R_Mesh_CacheArray_ValidateState(5);
1799         // gobble an extra item if we have no free items available
1800         if (r_mesh_rcachefreechain.next == &r_mesh_rcachefreechain)
1801         {
1802                 lnext = l->next;
1803
1804                 // unlink from sequential chain
1805                 l->next->prev = l->prev;
1806                 l->prev->next = l->next;
1807                 // link into free chain
1808                 l->next = &r_mesh_rcachefreechain;
1809                 l->prev = l->next->prev;
1810                 l->next->prev = l->prev->next = l;
1811
1812                 l = &l->data->hashlink;
1813                 // unlink from hash chain
1814                 l->next->prev = l->prev;
1815                 l->prev->next = l->next;
1816
1817                 l = lnext;
1818         }
1819         r_mesh_rcachesequentialchain_current = l;
1820         //R_Mesh_CacheArray_ValidateState(6);
1821
1822         // now take an item from the free chain
1823         l = r_mesh_rcachefreechain.next;
1824         // set it up
1825         d = l->data;
1826         d->request = *r;
1827         d->offset = offset;
1828         // unlink
1829         l->next->prev = l->prev;
1830         l->prev->next = l->next;
1831         // relink to sequential
1832         l->next = r_mesh_rcachesequentialchain_current->prev;
1833         l->prev = l->next->prev;
1834         while (l->next->data && l->data && l->next->data->offset <= d->offset)
1835         {
1836                 //Con_Printf(">\n");
1837                 l->next = l->next->next;
1838                 l->prev = l->prev->next;
1839         }
1840         while (l->prev->data && l->data && l->prev->data->offset >= d->offset)
1841         {
1842                 //Con_Printf("<\n");
1843                 l->prev = l->prev->prev;
1844                 l->next = l->next->prev;
1845         }
1846         l->next->prev = l->prev->next = l;
1847         // also link into hash chain
1848         l = &l->data->hashlink;
1849         l->next = &r_mesh_rcachechain[hashindex];
1850         l->prev = l->next->prev;
1851         l->prev->next = l;
1852         l->next->prev = l->prev->next = l;
1853
1854
1855         //r_mesh_rcachesequentialchain_current = d->sequentiallink.next;
1856
1857         //R_Mesh_CacheArray_ValidateState(7);
1858         // and finally set the data pointer
1859         r->data = r_mesh_rcachedata + d->offset;
1860         // and tell the caller to fill the array
1861         return true;
1862 }
1863