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