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