use volatile on icolor and fcolor pointers in GL_ConvertColorsFloatToByte to avoid...
[divverent/darkplaces.git] / gl_backend.c
1
2 #include "quakedef.h"
3
4 //cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "21760"};
5 cvar_t gl_mesh_maxtriangles = {0, "gl_mesh_maxtriangles", "1024"};
6 //cvar_t gl_mesh_batchtriangles = {0, "gl_mesh_batchtriangles", "1024"};
7 cvar_t gl_mesh_batchtriangles = {0, "gl_mesh_batchtriangles", "0"};
8 cvar_t gl_mesh_transtriangles = {0, "gl_mesh_transtriangles", "16384"};
9 cvar_t gl_mesh_floatcolors = {0, "gl_mesh_floatcolors", "0"};
10 cvar_t gl_mesh_drawmode = {CVAR_SAVE, "gl_mesh_drawmode", "3"};
11
12 cvar_t r_render = {0, "r_render", "1"};
13 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
14 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
15
16 int gl_maxdrawrangeelementsvertices;
17 int gl_maxdrawrangeelementsindices;
18
19 #ifdef DEBUGGL
20 int errornumber = 0;
21
22 void GL_PrintError(int errornumber, char *filename, int linenumber)
23 {
24         switch(errornumber)
25         {
26 #ifdef GL_INVALID_ENUM
27         case GL_INVALID_ENUM:
28                 Con_Printf("GL_INVALID_ENUM at %s:%i\n", filename, linenumber);
29                 break;
30 #endif
31 #ifdef GL_INVALID_VALUE
32         case GL_INVALID_VALUE:
33                 Con_Printf("GL_INVALID_VALUE at %s:%i\n", filename, linenumber);
34                 break;
35 #endif
36 #ifdef GL_INVALID_OPERATION
37         case GL_INVALID_OPERATION:
38                 Con_Printf("GL_INVALID_OPERATION at %s:%i\n", filename, linenumber);
39                 break;
40 #endif
41 #ifdef GL_STACK_OVERFLOW
42         case GL_STACK_OVERFLOW:
43                 Con_Printf("GL_STACK_OVERFLOW at %s:%i\n", filename, linenumber);
44                 break;
45 #endif
46 #ifdef GL_STACK_UNDERFLOW
47         case GL_STACK_UNDERFLOW:
48                 Con_Printf("GL_STACK_UNDERFLOW at %s:%i\n", filename, linenumber);
49                 break;
50 #endif
51 #ifdef GL_OUT_OF_MEMORY
52         case GL_OUT_OF_MEMORY:
53                 Con_Printf("GL_OUT_OF_MEMORY at %s:%i\n", filename, linenumber);
54                 break;
55 #endif
56 #ifdef GL_TABLE_TOO_LARGE
57     case GL_TABLE_TOO_LARGE:
58                 Con_Printf("GL_TABLE_TOO_LARGE at %s:%i\n", filename, linenumber);
59                 break;
60 #endif
61         default:
62                 Con_Printf("GL UNKNOWN (%i) at %s:%i\n", errornumber, filename, linenumber);
63                 break;
64         }
65 }
66 #endif
67
68 float r_farclip, r_newfarclip;
69
70 int polyindexarray[768];
71
72 static float viewdist;
73
74 int c_meshs, c_meshtris, c_transmeshs, c_transtris;
75
76 int                     lightscalebit;
77 float           lightscale;
78 float           overbrightscale;
79
80 void SCR_ScreenShot_f (void);
81
82 static int max_meshs;
83 static int max_transmeshs;
84 static int max_batch;
85 static int max_verts; // always max_meshs * 3
86 static int max_transverts; // always max_transmeshs * 3
87 #define TRANSDEPTHRES 4096
88
89 typedef struct buf_mesh_s
90 {
91         int depthmask;
92         int depthtest;
93         int blendfunc1, blendfunc2;
94         int textures[MAX_TEXTUREUNITS];
95         int texturergbscale[MAX_TEXTUREUNITS];
96         int firsttriangle;
97         int triangles;
98         int firstvert;
99         int verts;
100         struct buf_mesh_s *chain;
101         struct buf_transtri_s *transchain;
102 }
103 buf_mesh_t;
104
105 typedef struct buf_transtri_s
106 {
107         struct buf_transtri_s *next;
108         struct buf_transtri_s *meshsortchain;
109         buf_mesh_t *mesh;
110         int index[3];
111 }
112 buf_transtri_t;
113
114 typedef struct buf_tri_s
115 {
116         int index[3];
117 }
118 buf_tri_t;
119
120 typedef struct
121 {
122         float v[4];
123 }
124 buf_vertex_t;
125
126 typedef struct
127 {
128         float c[4];
129 }
130 buf_fcolor_t;
131
132 typedef struct
133 {
134         qbyte c[4];
135 }
136 buf_bcolor_t;
137
138 typedef struct
139 {
140         float t[2];
141 }
142 buf_texcoord_t;
143
144 static float meshfarclip;
145 static int currentmesh, currenttriangle, currentvertex, backendunits, backendactive, transranout;
146 static buf_mesh_t *buf_mesh;
147 static buf_tri_t *buf_tri;
148 static buf_vertex_t *buf_vertex;
149 static buf_fcolor_t *buf_fcolor;
150 static buf_bcolor_t *buf_bcolor;
151 static buf_texcoord_t *buf_texcoord[MAX_TEXTUREUNITS];
152
153 static int currenttransmesh, currenttransvertex, currenttranstriangle;
154 static buf_mesh_t *buf_transmesh;
155 static buf_transtri_t *buf_sorttranstri;
156 static buf_transtri_t **buf_sorttranstri_list;
157 static buf_tri_t *buf_transtri;
158 static buf_vertex_t *buf_transvertex;
159 static buf_fcolor_t *buf_transfcolor;
160 static buf_texcoord_t *buf_transtexcoord[MAX_TEXTUREUNITS];
161
162 static mempool_t *gl_backend_mempool;
163 static int resizingbuffers = false;
164
165 static void gl_backend_start(void)
166 {
167         int i;
168
169         max_verts = max_meshs * 3;
170         max_transverts = max_transmeshs * 3;
171
172         if (!gl_backend_mempool)
173                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
174
175 #define BACKENDALLOC(var, count, sizeofstruct, varname)\
176         {\
177                 var = Mem_Alloc(gl_backend_mempool, count * sizeof(sizeofstruct));\
178                 if (var == NULL)\
179                         Sys_Error("gl_backend_start: unable to allocate memory for %s (%d bytes)\n", (varname), count * sizeof(sizeofstruct));\
180                 memset(var, 0, count * sizeof(sizeofstruct));\
181         }
182
183         BACKENDALLOC(buf_mesh, max_meshs, buf_mesh_t, "buf_mesh")
184         BACKENDALLOC(buf_tri, max_meshs, buf_tri_t, "buf_tri")
185         BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t, "buf_vertex")
186         BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t, "buf_fcolor")
187         BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t, "buf_bcolor")
188
189         BACKENDALLOC(buf_transmesh, max_transmeshs, buf_mesh_t, "buf_transmesh")
190         BACKENDALLOC(buf_sorttranstri, max_transmeshs, buf_transtri_t, "buf_sorttranstri")
191         BACKENDALLOC(buf_sorttranstri_list, TRANSDEPTHRES, buf_transtri_t *, "buf_sorttranstri_list")
192         BACKENDALLOC(buf_transtri, max_transmeshs, buf_tri_t, "buf_transtri")
193         BACKENDALLOC(buf_transvertex, max_transverts, buf_vertex_t, "buf_vertex")
194         BACKENDALLOC(buf_transfcolor, max_transverts, buf_fcolor_t, "buf_fcolor")
195
196         for (i = 0;i < MAX_TEXTUREUNITS;i++)
197         {
198                 // only allocate as many texcoord arrays as we need
199                 if (i < gl_textureunits)
200                 {
201                         BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t, va("buf_texcoord[%d]", i))
202                         BACKENDALLOC(buf_transtexcoord[i], max_transverts, buf_texcoord_t, va("buf_transtexcoord[%d]", i))
203                 }
204                 else
205                 {
206                         buf_texcoord[i] = NULL;
207                         buf_transtexcoord[i] = NULL;
208                 }
209         }
210         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
211         backendactive = true;
212 }
213
214 static void gl_backend_shutdown(void)
215 {
216         if (resizingbuffers)
217                 Mem_EmptyPool(gl_backend_mempool);
218         else
219                 Mem_FreePool(&gl_backend_mempool);
220
221         backendunits = 0;
222         backendactive = false;
223 }
224
225 static void gl_backend_bufferchanges(int init)
226 {
227         if (gl_mesh_drawmode.integer == 3 && qglDrawRangeElements != NULL)
228         {
229                 if (gl_mesh_maxtriangles.integer * 3 > gl_maxdrawrangeelementsindices)
230                         Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) (gl_maxdrawrangeelementsindices / 3));
231                 if (gl_mesh_maxtriangles.integer * 3 > gl_maxdrawrangeelementsvertices)
232                         Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) (gl_maxdrawrangeelementsvertices / 3));
233         }
234
235         // 21760 is (65536 / 3) rounded off to a multiple of 128
236         if (gl_mesh_maxtriangles.integer < 1024)
237                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
238         if (gl_mesh_maxtriangles.integer > 21760)
239                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
240
241         if (gl_mesh_transtriangles.integer < 1024)
242                 Cvar_SetValueQuick(&gl_mesh_transtriangles, 1024);
243         if (gl_mesh_transtriangles.integer > 65536)
244                 Cvar_SetValueQuick(&gl_mesh_transtriangles, 65536);
245
246         if (gl_mesh_batchtriangles.integer < 0)
247                 Cvar_SetValueQuick(&gl_mesh_batchtriangles, 0);
248         if (gl_mesh_batchtriangles.integer > gl_mesh_maxtriangles.integer)
249                 Cvar_SetValueQuick(&gl_mesh_batchtriangles, gl_mesh_maxtriangles.integer);
250
251         max_batch = gl_mesh_batchtriangles.integer;
252
253         if (max_meshs != gl_mesh_maxtriangles.integer || max_transmeshs != gl_mesh_transtriangles.integer)
254         {
255                 max_meshs = gl_mesh_maxtriangles.integer;
256                 max_transmeshs = gl_mesh_transtriangles.integer;
257
258                 if (!init)
259                 {
260                         resizingbuffers = true;
261                         gl_backend_shutdown();
262                         gl_backend_start();
263                         resizingbuffers = false;
264                 }
265         }
266 }
267
268 static void gl_backend_newmap(void)
269 {
270         r_farclip = r_newfarclip = 2048.0f;
271 }
272
273 void gl_backend_init(void)
274 {
275         int i;
276
277         Cvar_RegisterVariable(&r_render);
278         Cvar_RegisterVariable(&gl_dither);
279         Cvar_RegisterVariable(&gl_lockarrays);
280 #ifdef NORENDER
281         Cvar_SetValue("r_render", 0);
282 #endif
283
284         Cvar_RegisterVariable(&gl_mesh_maxtriangles);
285         Cvar_RegisterVariable(&gl_mesh_transtriangles);
286         Cvar_RegisterVariable(&gl_mesh_batchtriangles);
287         Cvar_RegisterVariable(&gl_mesh_floatcolors);
288         Cvar_RegisterVariable(&gl_mesh_drawmode);
289         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
290         gl_backend_bufferchanges(true);
291         for (i = 0;i < 256;i++)
292         {
293                 polyindexarray[i*3+0] = 0;
294                 polyindexarray[i*3+1] = i + 1;
295                 polyindexarray[i*3+2] = i + 2;
296         }
297 }
298
299 int arraylocked = false;
300
301 void GL_LockArray(int first, int count)
302 {
303         if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer != 0)
304         {
305                 qglLockArraysEXT(first, count);
306                 CHECKGLERROR
307                 arraylocked = true;
308         }
309 }
310
311 void GL_UnlockArray(void)
312 {
313         if (arraylocked)
314         {
315                 qglUnlockArraysEXT();
316                 CHECKGLERROR
317                 arraylocked = false;
318         }
319 }
320
321 //static float gldepthmin, gldepthmax;
322
323 /*
324 =============
325 GL_SetupFrame
326 =============
327 */
328 static void GL_SetupFrame (void)
329 {
330         double xmax, ymax;
331         double fovx, fovy, zNear, zFar, aspect;
332
333         // update farclip based on previous frame
334         r_farclip = r_newfarclip;
335
336         if (!r_render.integer)
337                 return;
338
339 //      qglClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // LordHavoc: moved to SCR_UpdateScreen
340 //      gldepthmin = 0;
341 //      gldepthmax = 1;
342         qglDepthFunc (GL_LEQUAL);CHECKGLERROR
343
344 //      qglDepthRange (gldepthmin, gldepthmax);CHECKGLERROR
345
346         // set up viewpoint
347         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
348         qglLoadIdentity ();CHECKGLERROR
349
350         // y is weird beause OpenGL is bottom to top, we use top to bottom
351         qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
352
353         // depth range
354         zNear = 1.0;
355         zFar = r_farclip;
356
357         // fov angles
358         fovx = r_refdef.fov_x;
359         fovy = r_refdef.fov_y;
360         aspect = r_refdef.width / r_refdef.height;
361
362         // pyramid slopes
363         xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
364         ymax = zNear * tan(fovy * M_PI / 360.0);
365
366         // set view pyramid
367         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
368
369 //      qglCullFace(GL_FRONT);CHECKGLERROR
370
371         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
372         qglLoadIdentity ();CHECKGLERROR
373
374         // put Z going up
375         qglRotatef (-90,  1, 0, 0);CHECKGLERROR
376         qglRotatef (90,  0, 0, 1);CHECKGLERROR
377         // camera rotation
378         qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
379         qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
380         qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
381         // camera location
382         qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
383
384 //      qglGetFloatv (GL_MODELVIEW_MATRIX, r_world_matrix);
385
386         //
387         // set drawing parms
388         //
389 //      if (gl_cull.integer)
390 //      {
391 //              qglEnable(GL_CULL_FACE);CHECKGLERROR
392 //      }
393 //      else
394 //      {
395 //              qglDisable(GL_CULL_FACE);CHECKGLERROR
396 //      }
397
398 //      qglEnable(GL_BLEND);CHECKGLERROR
399 //      qglEnable(GL_DEPTH_TEST);CHECKGLERROR
400 //      qglDepthMask(1);CHECKGLERROR
401 }
402
403 static int mesh_blendfunc1;
404 static int mesh_blendfunc2;
405 static int mesh_blend;
406 static GLboolean mesh_depthmask;
407 static int mesh_depthtest;
408 static int mesh_unit;
409 static int mesh_clientunit;
410 static int mesh_texture[MAX_TEXTUREUNITS];
411 static float mesh_texturergbscale[MAX_TEXTUREUNITS];
412
413 void GL_SetupTextureState(void)
414 {
415         int i;
416         if (backendunits > 1)
417         {
418                 for (i = 0;i < backendunits;i++)
419                 {
420                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
421                         qglBindTexture(GL_TEXTURE_2D, mesh_texture[i]);CHECKGLERROR
422                         if (gl_combine.integer)
423                         {
424                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
425                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
426                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
427                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
428                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
429                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
430                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
431                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
432                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
433                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
434                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
435                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
436                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
437                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
438                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
439                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, mesh_texturergbscale[i]);CHECKGLERROR
440                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
441                         }
442                         else
443                         {
444                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
445                         }
446                         if (mesh_texture[i])
447                         {
448                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
449                         }
450                         else
451                         {
452                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
453                         }
454                         if (gl_mesh_drawmode.integer != 0)
455                         {
456                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
457                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
458                                 if (mesh_texture[i])
459                                 {
460                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
461                                 }
462                                 else
463                                 {
464                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
465                                 }
466                         }
467                 }
468         }
469         else
470         {
471                 qglBindTexture(GL_TEXTURE_2D, mesh_texture[0]);CHECKGLERROR
472                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
473                 if (mesh_texture[0])
474                 {
475                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
476                 }
477                 else
478                 {
479                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
480                 }
481                 if (gl_mesh_drawmode.integer != 0)
482                 {
483                         qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
484                         if (mesh_texture[0])
485                         {
486                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
487                         }
488                         else
489                         {
490                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
491                         }
492                 }
493         }
494 }
495
496 // called at beginning of frame
497 int usedarrays;
498 void R_Mesh_Start(void)
499 {
500         int i;
501         if (!backendactive)
502                 Sys_Error("R_Mesh_Clear: called when backend is not active\n");
503
504         CHECKGLERROR
505
506         gl_backend_bufferchanges(false);
507
508         currentmesh = 0;
509         currenttriangle = 0;
510         currentvertex = 0;
511         currenttransmesh = 0;
512         currenttranstriangle = 0;
513         currenttransvertex = 0;
514         meshfarclip = 0;
515         transranout = false;
516         viewdist = DotProduct(r_origin, vpn);
517
518         c_meshs = 0;
519         c_meshtris = 0;
520         c_transmeshs = 0;
521         c_transtris = 0;
522
523         GL_SetupFrame();
524
525         mesh_unit = 0;
526         mesh_clientunit = 0;
527
528         for (i = 0;i < backendunits;i++)
529         {
530                 mesh_texture[i] = 0;
531                 mesh_texturergbscale[i] = 1;
532         }
533
534         qglEnable(GL_CULL_FACE);CHECKGLERROR
535         qglCullFace(GL_FRONT);CHECKGLERROR
536
537         mesh_depthtest = true;
538         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
539
540         mesh_blendfunc1 = GL_ONE;
541         mesh_blendfunc2 = GL_ZERO;
542         qglBlendFunc(mesh_blendfunc1, mesh_blendfunc2);CHECKGLERROR
543
544         mesh_blend = 0;
545         qglDisable(GL_BLEND);CHECKGLERROR
546
547         mesh_depthmask = GL_TRUE;
548         qglDepthMask(mesh_depthmask);CHECKGLERROR
549
550         usedarrays = false;
551         if (gl_mesh_drawmode.integer != 0)
552         {
553                 usedarrays = true;
554                 qglVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), &buf_vertex[0].v[0]);CHECKGLERROR
555                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
556                 if (gl_mesh_floatcolors.integer)
557                 {
558                         qglColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), &buf_fcolor[0].c[0]);CHECKGLERROR
559                 }
560                 else
561                 {
562                         qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), &buf_bcolor[0].c[0]);CHECKGLERROR
563                 }
564                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
565         }
566
567         GL_SetupTextureState();
568 }
569
570 int gl_backend_rebindtextures;
571
572 void GL_UpdateFarclip(void)
573 {
574         int i;
575         float farclip;
576
577         // push out farclip based on vertices
578         // FIXME: wouldn't this be slow when using matrix transforms?
579         for (i = 0;i < currentvertex;i++)
580         {
581                 farclip = DotProduct(buf_vertex[i].v, vpn);
582                 if (meshfarclip < farclip)
583                         meshfarclip = farclip;
584         }
585
586         farclip = meshfarclip + 256.0f - viewdist; // + 256 just to be safe
587
588         // push out farclip for next frame
589         if (farclip > r_newfarclip)
590                 r_newfarclip = ceil((farclip + 255) / 256) * 256 + 256;
591 }
592
593 void GL_ConvertColorsFloatToByte(void)
594 {
595         int i, k, total;
596         // LordHavoc: to avoid problems with aliasing (treating memory as two
597         // different types - exactly what this is doing), these must be volatile
598         // (or a union)
599         volatile int *icolor;
600         volatile float *fcolor;
601         qbyte *bcolor;
602
603         total = currentvertex * 4;
604
605         // shift float to have 8bit fraction at base of number
606         fcolor = &buf_fcolor->c[0];
607         for (i = 0;i < total;)
608         {
609                 fcolor[i    ] += 32768.0f;
610                 fcolor[i + 1] += 32768.0f;
611                 fcolor[i + 2] += 32768.0f;
612                 fcolor[i + 3] += 32768.0f;
613                 i += 4;
614         }
615
616         // then read as integer and kill float bits...
617         icolor = (int *)&buf_fcolor->c[0];
618         bcolor = &buf_bcolor->c[0];
619         for (i = 0;i < total;)
620         {
621                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
622                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
623                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
624                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
625                 i += 4;
626         }
627 }
628
629 void GL_MeshState(buf_mesh_t *mesh)
630 {
631         int i;
632         if (backendunits > 1)
633         {
634                 for (i = 0;i < backendunits;i++)
635                 {
636                         if (mesh_texture[i] != mesh->textures[i])
637                         {
638                                 if (mesh_unit != i)
639                                 {
640                                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
641                                 }
642                                 if (mesh_texture[i] == 0)
643                                 {
644                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
645                                         // have to disable texcoord array on disabled texture
646                                         // units due to NVIDIA driver bug with
647                                         // compiled_vertex_array
648                                         if (mesh_clientunit != i)
649                                         {
650                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
651                                         }
652                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
653                                 }
654                                 qglBindTexture(GL_TEXTURE_2D, (mesh_texture[i] = mesh->textures[i]));CHECKGLERROR
655                                 if (mesh_texture[i] == 0)
656                                 {
657                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
658                                         // have to disable texcoord array on disabled texture
659                                         // units due to NVIDIA driver bug with
660                                         // compiled_vertex_array
661                                         if (mesh_clientunit != i)
662                                         {
663                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (mesh_clientunit = i));CHECKGLERROR
664                                         }
665                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
666                                 }
667                         }
668                         if (mesh_texturergbscale[i] != mesh->texturergbscale[i])
669                         {
670                                 if (mesh_unit != i)
671                                 {
672                                         qglActiveTexture(GL_TEXTURE0_ARB + (mesh_unit = i));CHECKGLERROR
673                                 }
674                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (mesh_texturergbscale[i] = mesh->texturergbscale[i]));CHECKGLERROR
675                         }
676                 }
677         }
678         else
679         {
680                 if (mesh_texture[0] != mesh->textures[0])
681                 {
682                         if (mesh_texture[0] == 0)
683                         {
684                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
685                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
686                         }
687                         qglBindTexture(GL_TEXTURE_2D, (mesh_texture[0] = mesh->textures[0]));CHECKGLERROR
688                         if (mesh_texture[0] == 0)
689                         {
690                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
691                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
692                         }
693                 }
694         }
695         if (mesh_blendfunc1 != mesh->blendfunc1 || mesh_blendfunc2 != mesh->blendfunc2)
696         {
697                 qglBlendFunc(mesh_blendfunc1 = mesh->blendfunc1, mesh_blendfunc2 = mesh->blendfunc2);CHECKGLERROR
698                 if (mesh_blendfunc2 == GL_ZERO)
699                 {
700                         if (mesh_blendfunc1 == GL_ONE)
701                         {
702                                 if (mesh_blend)
703                                 {
704                                         mesh_blend = 0;
705                                         qglDisable(GL_BLEND);CHECKGLERROR
706                                 }
707                         }
708                         else
709                         {
710                                 if (!mesh_blend)
711                                 {
712                                         mesh_blend = 1;
713                                         qglEnable(GL_BLEND);CHECKGLERROR
714                                 }
715                         }
716                 }
717                 else
718                 {
719                         if (!mesh_blend)
720                         {
721                                 mesh_blend = 1;
722                                 qglEnable(GL_BLEND);CHECKGLERROR
723                         }
724                 }
725         }
726         if (mesh_depthtest != mesh->depthtest)
727         {
728                 mesh_depthtest = mesh->depthtest;
729                 if (mesh_depthtest)
730                         qglEnable(GL_DEPTH_TEST);
731                 else
732                         qglDisable(GL_DEPTH_TEST);
733         }
734         if (mesh_depthmask != mesh->depthmask)
735         {
736                 qglDepthMask(mesh_depthmask = mesh->depthmask);CHECKGLERROR
737         }
738 }
739
740 void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, GLuint *index)
741 {
742         unsigned int i, j, in;
743         if (gl_mesh_drawmode.integer == 3 && qglDrawRangeElements == NULL)
744                 Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
745
746         if (gl_mesh_drawmode.integer == 3)
747         {
748                 // GL 1.2 or GL 1.1 with extension
749                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, index);
750         }
751         else if (gl_mesh_drawmode.integer == 2)
752         {
753                 // GL 1.1
754                 qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);
755         }
756         else if (gl_mesh_drawmode.integer == 1)
757         {
758                 // GL 1.1
759                 // feed it manually using glArrayElement
760                 qglBegin(GL_TRIANGLES);
761                 for (i = 0;i < indexcount;i++)
762                         qglArrayElement(index[i]);
763                 qglEnd();
764         }
765         else
766         {
767                 // GL 1.1 but not using vertex arrays - 3dfx glquake minigl driver
768                 // feed it manually
769                 if (gl_mesh_drawmode.integer != 0)
770                         Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
771                 qglBegin(GL_TRIANGLES);
772                 if (r_multitexture.integer)
773                 {
774                         // the minigl doesn't have this (because it does not have ARB_multitexture)
775                         for (i = 0;i < indexcount;i++)
776                         {
777                                 in = index[i];
778                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
779                                 for (j = 0;j < backendunits;j++)
780                                         if (mesh_texture[j])
781                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, buf_texcoord[j][in].t[0], buf_texcoord[j][in].t[1]);
782                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
783                         }
784                 }
785                 else
786                 {
787                         for (i = 0;i < indexcount;i++)
788                         {
789                                 in = index[i];
790                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
791                                 if (mesh_texture[0])
792                                         qglTexCoord2f(buf_texcoord[0][in].t[0], buf_texcoord[0][in].t[1]);
793                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
794                         }
795                 }
796                 qglEnd();
797         }
798         /*
799         if (qglDrawRangeElements)
800                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, index);
801         else
802         {
803         }
804         #ifdef WIN32
805         // FIXME: dynamic link to GL so we can get DrawRangeElements on WIN32
806         qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);CHECKGLERROR
807         #else
808         qglDrawRangeElements(GL_TRIANGLES, firstvert, firstvert + mesh->verts, indexcount, GL_UNSIGNED_INT, index);CHECKGLERROR
809         #endif
810         */
811 }
812
813 // renders mesh buffers, called to flush buffers when full
814 void R_Mesh_Render(void)
815 {
816         int i;
817         int k;
818         int indexcount;
819         int firstvert;
820         buf_mesh_t *mesh;
821         unsigned int *index;
822
823         if (!backendactive)
824                 Sys_Error("R_Mesh_Render: called when backend is not active\n");
825
826         if (!currentmesh)
827                 return;
828
829         CHECKGLERROR
830
831         GL_UpdateFarclip();
832
833         if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer == 0)
834                 GL_ConvertColorsFloatToByte();
835
836         // lock the arrays now that they will have no further modifications
837         //GL_LockArray(0, currentvertex);CHECKGLERROR
838         if (gl_backend_rebindtextures)
839         {
840                 gl_backend_rebindtextures = false;
841                 GL_SetupTextureState();
842         }
843
844         GL_MeshState(buf_mesh);
845         GL_LockArray(0, currentvertex);
846         GL_DrawRangeElements(buf_mesh->firstvert, buf_mesh->firstvert + buf_mesh->verts, buf_mesh->triangles * 3, (unsigned int *)&buf_tri[buf_mesh->firsttriangle].index[0]);CHECKGLERROR
847
848         if (currentmesh >= 2)
849         {
850                 for (k = 1, mesh = buf_mesh + k;k < currentmesh;k++, mesh++)
851                 {
852                         GL_MeshState(mesh);
853
854                         firstvert = mesh->firstvert;
855                         indexcount = mesh->triangles * 3;
856                         index = (unsigned int *)&buf_tri[mesh->firsttriangle].index[0];
857
858                         // if not using batching, skip the index adjustment
859                         if (firstvert != 0)
860                                 for (i = 0;i < indexcount;i++)
861                                         index[i] += firstvert;
862
863                         GL_DrawRangeElements(firstvert, firstvert + mesh->verts, indexcount, index);CHECKGLERROR
864                 }
865         }
866
867         currentmesh = 0;
868         currenttriangle = 0;
869         currentvertex = 0;
870
871         GL_UnlockArray();CHECKGLERROR
872 }
873
874 // restores backend state, used when done with 3D rendering
875 void R_Mesh_Finish(void)
876 {
877         int i;
878         // flush any queued meshs
879         R_Mesh_Render();
880
881         if (backendunits > 1)
882         {
883                 for (i = backendunits - 1;i >= 0;i--)
884                 {
885                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
886                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
887                         if (gl_combine.integer)
888                         {
889                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
890                         }
891                         if (i > 0)
892                         {
893                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
894                         }
895                         else
896                         {
897                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
898                         }
899                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
900
901                         if (usedarrays)
902                         {
903                                 qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
904                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
905                         }
906                 }
907         }
908         else
909         {
910                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
911                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
912                 if (usedarrays)
913                 {
914                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
915                 }
916         }
917         if (usedarrays)
918         {
919                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
920                 qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
921         }
922
923         qglDisable(GL_BLEND);CHECKGLERROR
924         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
925         qglDepthMask(GL_TRUE);CHECKGLERROR
926         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
927 }
928
929 void R_Mesh_ClearDepth(void)
930 {
931         R_Mesh_AddTransparent();
932         R_Mesh_Finish();
933         qglClear(GL_DEPTH_BUFFER_BIT);
934         R_Mesh_Start();
935 }
936
937 void R_Mesh_AddTransparent(void)
938 {
939         int i, j, k, *index;
940         float viewdistcompare, centerscaler, dist1, dist2, dist3, center, maxdist;
941         buf_vertex_t *vert1, *vert2, *vert3;
942         buf_transtri_t *tri;
943         buf_mesh_t *mesh, *transmesh;
944
945         if (!currenttransmesh)
946                 return;
947
948         // convert index data to transtris for sorting
949         for (j = 0;j < currenttransmesh;j++)
950         {
951                 mesh = buf_transmesh + j;
952                 k = mesh->firsttriangle;
953                 index = &buf_transtri[k].index[0];
954                 for (i = 0;i < mesh->triangles;i++)
955                 {
956                         tri = &buf_sorttranstri[k++];
957                         tri->mesh = mesh;
958                         tri->index[0] = *index++;
959                         tri->index[1] = *index++;
960                         tri->index[2] = *index++;
961                 }
962         }
963
964         // map farclip to 0-4095 list range
965         centerscaler = (TRANSDEPTHRES / r_farclip) * (1.0f / 3.0f);
966         viewdistcompare = viewdist + 4.0f;
967
968         memset(buf_sorttranstri_list, 0, TRANSDEPTHRES * sizeof(buf_transtri_t *));
969
970         k = 0;
971         for (j = 0;j < currenttranstriangle;j++)
972         {
973                 tri = &buf_sorttranstri[j];
974                 i = tri->mesh->firstvert;
975
976                 vert1 = &buf_transvertex[tri->index[0] + i];
977                 vert2 = &buf_transvertex[tri->index[1] + i];
978                 vert3 = &buf_transvertex[tri->index[2] + i];
979
980                 dist1 = DotProduct(vert1->v, vpn);
981                 dist2 = DotProduct(vert2->v, vpn);
982                 dist3 = DotProduct(vert3->v, vpn);
983
984                 maxdist = max(dist1, max(dist2, dist3));
985                 if (maxdist < viewdistcompare)
986                         continue;
987
988                 center = (dist1 + dist2 + dist3) * centerscaler - viewdist;
989 #if SLOWMATH
990                 i = (int) center;
991                 i = bound(0, i, (TRANSDEPTHRES - 1));
992 #else
993                 if (center < 0.0f)
994                         center = 0.0f;
995                 center += 8388608.0f;
996                 i = *((int *)&center) & 0x7FFFFF;
997                 i = min(i, (TRANSDEPTHRES - 1));
998 #endif
999                 tri->next = buf_sorttranstri_list[i];
1000                 buf_sorttranstri_list[i] = tri;
1001                 k++;
1002         }
1003
1004         for (i = 0;i < currenttransmesh;i++)
1005                 buf_transmesh[i].transchain = NULL;
1006         transmesh = NULL;
1007         for (j = 0;j < TRANSDEPTHRES;j++)
1008         {
1009                 if ((tri = buf_sorttranstri_list[j]))
1010                 {
1011                         for (;tri;tri = tri->next)
1012                         {
1013                                 if (!tri->mesh->transchain)
1014                                 {
1015                                         tri->mesh->chain = transmesh;
1016                                         transmesh = tri->mesh;
1017                                 }
1018                                 tri->meshsortchain = tri->mesh->transchain;
1019                                 tri->mesh->transchain = tri;
1020                         }
1021                 }
1022         }
1023
1024         for (;transmesh;transmesh = transmesh->chain)
1025         {
1026                 if (currentmesh >= max_meshs || currenttriangle + transmesh->triangles > max_batch || currenttriangle + transmesh->triangles > 1024 || currentvertex + transmesh->verts > max_verts)
1027                         R_Mesh_Render();
1028
1029                 mesh = &buf_mesh[currentmesh++];
1030                 *mesh = *transmesh; // copy mesh properties
1031
1032                 mesh->firstvert = currentvertex;
1033                 memcpy(&buf_vertex[currentvertex], &buf_transvertex[transmesh->firstvert], transmesh->verts * sizeof(buf_vertex_t));
1034                 memcpy(&buf_fcolor[currentvertex], &buf_transfcolor[transmesh->firstvert], transmesh->verts * sizeof(buf_fcolor_t));
1035                 for (i = 0;i < backendunits && transmesh->textures[i];i++)
1036                         memcpy(&buf_texcoord[i][currentvertex], &buf_transtexcoord[i][transmesh->firstvert], transmesh->verts * sizeof(buf_texcoord_t));
1037                 currentvertex += mesh->verts;
1038
1039                 mesh->firsttriangle = currenttriangle;
1040                 for (tri = transmesh->transchain;tri;tri = tri->meshsortchain)
1041                 {
1042                         buf_tri[currenttriangle].index[0] = tri->index[0];
1043                         buf_tri[currenttriangle].index[1] = tri->index[1];
1044                         buf_tri[currenttriangle].index[2] = tri->index[2];
1045                         currenttriangle++;
1046                 }
1047                 mesh->triangles = currenttriangle - mesh->firsttriangle;
1048         }
1049
1050         currenttransmesh = 0;
1051         currenttranstriangle = 0;
1052         currenttransvertex = 0;
1053 }
1054
1055 void R_Mesh_Draw(const rmeshinfo_t *m)
1056 {
1057         // these are static because gcc runs out of virtual registers otherwise
1058         static int i, j, overbright, *index;
1059         static float *in, scaler;
1060         static float cr, cg, cb, ca;
1061         static buf_mesh_t *mesh;
1062         static buf_vertex_t *vert;
1063         static buf_fcolor_t *fcolor;
1064         static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
1065
1066         if (!backendactive)
1067                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1068
1069         if (m->index == NULL
1070          || !m->numtriangles
1071          || m->vertex == NULL
1072          || !m->numverts)
1073                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1074
1075         // ignore meaningless alpha meshs
1076         if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
1077         {
1078                 if (m->color)
1079                 {
1080                         for (i = 0, in = m->color + 3;i < m->numverts;i++, (int)in += m->colorstep)
1081                                 if (*in >= 0.01f)
1082                                         break;
1083                         if (i == m->numverts)
1084                                 return;
1085                 }
1086                 else if (m->ca < 0.01f)
1087                         return;
1088         }
1089
1090         if (!backendactive)
1091                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1092
1093 #ifdef DEBUGGL
1094         for (i = 0;i < m->numtriangles * 3;i++)
1095                 if ((unsigned int) m->index[i] >= (unsigned int) m->numverts)
1096                         Host_Error("R_Mesh_Draw: invalid index (%i of %i verts)\n", m->index, m->numverts);
1097 #endif
1098
1099         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
1100         if (m->numtriangles > 1024 || m->numverts > 3072)
1101         {
1102                 Con_Printf("R_Mesh_Draw: mesh too big for 3DFX drivers, rejected\n");
1103                 return;
1104         }
1105
1106         if (m->numtriangles > max_meshs || m->numverts > max_verts)
1107         {
1108                 Con_Printf("R_Mesh_Draw: mesh too big for current gl_mesh_maxtriangles setting, rejected\n");
1109                 return;
1110         }
1111
1112
1113         if (m->transparent)
1114         {
1115                 if (currenttransmesh >= max_transmeshs || (currenttranstriangle + m->numtriangles) > max_transmeshs || (currenttransvertex + m->numverts) > max_transverts)
1116                 {
1117                         if (!transranout)
1118                         {
1119                                 Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
1120                                 transranout = true;
1121                         }
1122                         return;
1123                 }
1124
1125                 c_transmeshs++;
1126                 c_transtris += m->numtriangles;
1127                 vert = &buf_transvertex[currenttransvertex];
1128                 fcolor = &buf_transfcolor[currenttransvertex];
1129                 for (i = 0;i < backendunits;i++)
1130                         texcoord[i] = &buf_transtexcoord[i][currenttransvertex];
1131
1132                 // transmesh is only for storage of transparent meshs until they
1133                 // are inserted into the main mesh array
1134                 mesh = &buf_transmesh[currenttransmesh++];
1135                 mesh->firsttriangle = currenttranstriangle;
1136                 mesh->firstvert = currenttransvertex;
1137                 index = &buf_transtri[currenttranstriangle].index[0];
1138
1139                 currenttranstriangle += m->numtriangles;
1140                 currenttransvertex += m->numverts;
1141         }
1142         else
1143         {
1144                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1145                         R_Mesh_Render();
1146
1147                 c_meshs++;
1148                 c_meshtris += m->numtriangles;
1149                 vert = &buf_vertex[currentvertex];
1150                 fcolor = &buf_fcolor[currentvertex];
1151                 for (i = 0;i < backendunits;i++)
1152                         texcoord[i] = &buf_texcoord[i][currentvertex];
1153
1154                 // opaque meshs are rendered directly
1155                 mesh = &buf_mesh[currentmesh++];
1156                 mesh->firsttriangle = currenttriangle;
1157                 mesh->firstvert = currentvertex;
1158                 index = &buf_tri[currenttriangle].index[0];
1159
1160                 currenttriangle += m->numtriangles;
1161                 currentvertex += m->numverts;
1162         }
1163
1164         // code shared for transparent and opaque meshs
1165         memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
1166         mesh->blendfunc1 = m->blendfunc1;
1167         mesh->blendfunc2 = m->blendfunc2;
1168         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1169         mesh->depthtest = !m->depthdisable;
1170         mesh->triangles = m->numtriangles;
1171         mesh->verts = m->numverts;
1172
1173         overbright = false;
1174         scaler = 1;
1175         if (m->blendfunc2 == GL_SRC_COLOR)
1176         {
1177                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1178                         scaler *= 0.5f;
1179         }
1180         else
1181         {
1182                 if (m->tex[0])
1183                 {
1184                         overbright = gl_combine.integer;
1185                         if (overbright)
1186                                 scaler *= 0.25f;
1187                 }
1188                 scaler *= overbrightscale;
1189         }
1190
1191
1192         j = -1;
1193         for (i = 0;i < backendunits;i++)
1194         {
1195                 if ((mesh->textures[i] = m->tex[i]))
1196                         j = i;
1197                 mesh->texturergbscale[i] = m->texrgbscale[i];
1198                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1199                         mesh->texturergbscale[i] = 1;
1200         }
1201         if (overbright && j >= 0)
1202                 mesh->texturergbscale[j] = 4;
1203
1204         if (m->vertexstep != sizeof(buf_vertex_t))
1205         {
1206                 for (i = 0, in = m->vertex;i < m->numverts;i++, (int)in += m->vertexstep)
1207                 {
1208                         vert[i].v[0] = in[0];
1209                         vert[i].v[1] = in[1];
1210                         vert[i].v[2] = in[2];
1211                 }
1212         }
1213         else
1214                 memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
1215
1216         if (m->color)
1217         {
1218                 for (i = 0, in = m->color;i < m->numverts;i++, (int)in += m->colorstep)
1219                 {
1220                         fcolor[i].c[0] = in[0] * scaler;
1221                         fcolor[i].c[1] = in[1] * scaler;
1222                         fcolor[i].c[2] = in[2] * scaler;
1223                         fcolor[i].c[3] = in[3];
1224                 }
1225         }
1226         else
1227         {
1228                 cr = m->cr * scaler;
1229                 cg = m->cg * scaler;
1230                 cb = m->cb * scaler;
1231                 ca = m->ca;
1232                 for (i = 0;i < m->numverts;i++)
1233                 {
1234                         fcolor[i].c[0] = cr;
1235                         fcolor[i].c[1] = cg;
1236                         fcolor[i].c[2] = cb;
1237                         fcolor[i].c[3] = ca;
1238                 }
1239         }
1240
1241         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1242         {
1243                 if (j >= backendunits)
1244                         Sys_Error("R_Mesh_Draw: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1245                 if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
1246                 {
1247                         for (i = 0, in = m->texcoords[j];i < m->numverts;i++, (int)in += m->texcoordstep[j])
1248                         {
1249                                 texcoord[j][i].t[0] = in[0];
1250                                 texcoord[j][i].t[1] = in[1];
1251                         }
1252                 }
1253                 else
1254                         memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
1255         }
1256         #if 0
1257         for (;j < backendunits;j++)
1258                 memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
1259         #endif
1260
1261         if (currenttriangle >= max_batch)
1262                 R_Mesh_Render();
1263 }
1264
1265 void R_Mesh_Draw_NativeOnly(const rmeshinfo_t *m)
1266 {
1267         // these are static because gcc runs out of virtual registers otherwise
1268         static int i, j, overbright, *index;
1269         static float *in, scaler;
1270         static buf_mesh_t *mesh;
1271         static buf_vertex_t *vert;
1272         static buf_fcolor_t *fcolor;
1273         static buf_texcoord_t *texcoord[MAX_TEXTUREUNITS];
1274
1275         if (!backendactive)
1276                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1277
1278         if (m->index == NULL
1279          || !m->numtriangles
1280          || m->vertex == NULL
1281          || !m->numverts)
1282                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1283
1284         // ignore meaningless alpha meshs
1285         if (!m->depthwrite && m->blendfunc1 == GL_SRC_ALPHA && (m->blendfunc2 == GL_ONE || m->blendfunc2 == GL_ONE_MINUS_SRC_ALPHA))
1286         {
1287                 if (m->color)
1288                 {
1289                         for (i = 0, in = m->color + 3;i < m->numverts;i++, (int)in += m->colorstep)
1290                                 if (*in >= 0.01f)
1291                                         break;
1292                         if (i == m->numverts)
1293                                 return;
1294                 }
1295                 else if (m->ca < 0.01f)
1296                         return;
1297         }
1298
1299         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
1300         if (m->numtriangles > 1024 || m->numverts > 3072)
1301         {
1302                 Con_Printf("R_Mesh_Draw_NativeOnly: mesh too big for 3DFX drivers, rejected\n");
1303                 return;
1304         }
1305
1306         if (m->numtriangles > max_meshs || m->numverts > max_verts)
1307         {
1308                 Con_Printf("R_Mesh_Draw_NativeOnly: mesh too big for current gl_mesh_maxtriangles setting, rejected\n");
1309                 return;
1310         }
1311
1312
1313         if (m->transparent)
1314         {
1315                 if (currenttransmesh >= max_transmeshs || (currenttranstriangle + m->numtriangles) > max_transmeshs || (currenttransvertex + m->numverts) > max_transverts)
1316                 {
1317                         if (!transranout)
1318                         {
1319                                 Con_Printf("R_Mesh_Draw_NativeOnly: ran out of room for transparent meshs\n");
1320                                 transranout = true;
1321                         }
1322                         return;
1323                 }
1324
1325                 c_transmeshs++;
1326                 c_transtris += m->numtriangles;
1327                 vert = &buf_transvertex[currenttransvertex];
1328                 fcolor = &buf_transfcolor[currenttransvertex];
1329                 for (i = 0;i < backendunits;i++)
1330                         texcoord[i] = &buf_transtexcoord[i][currenttransvertex];
1331
1332                 // transmesh is only for storage of transparent meshs until they
1333                 // are inserted into the main mesh array
1334                 mesh = &buf_transmesh[currenttransmesh++];
1335                 mesh->firsttriangle = currenttranstriangle;
1336                 mesh->firstvert = currenttransvertex;
1337                 index = &buf_transtri[currenttranstriangle].index[0];
1338                 currenttranstriangle += m->numtriangles;
1339                 currenttransvertex += m->numverts;
1340         }
1341         else
1342         {
1343                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1344                         R_Mesh_Render();
1345
1346                 c_meshs++;
1347                 c_meshtris += m->numtriangles;
1348                 vert = &buf_vertex[currentvertex];
1349                 fcolor = &buf_fcolor[currentvertex];
1350                 for (i = 0;i < backendunits;i++)
1351                         texcoord[i] = &buf_texcoord[i][currentvertex];
1352
1353                 // opaque meshs are rendered directly
1354                 mesh = &buf_mesh[currentmesh++];
1355                 mesh->firsttriangle = currenttriangle;
1356                 mesh->firstvert = currentvertex;
1357                 index = &buf_tri[currenttriangle].index[0];
1358                 currenttriangle += m->numtriangles;
1359                 currentvertex += m->numverts;
1360         }
1361
1362         // code shared for transparent and opaque meshs
1363         memcpy(index, m->index, sizeof(int[3]) * m->numtriangles);
1364         mesh->blendfunc1 = m->blendfunc1;
1365         mesh->blendfunc2 = m->blendfunc2;
1366         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1367         mesh->depthtest = !m->depthdisable;
1368         mesh->triangles = m->numtriangles;
1369         mesh->verts = m->numverts;
1370
1371         overbright = false;
1372         scaler = 1;
1373         if (m->blendfunc2 == GL_SRC_COLOR)
1374         {
1375                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1376                         scaler *= 0.5f;
1377         }
1378         else
1379         {
1380                 if (m->tex[0])
1381                 {
1382                         overbright = gl_combine.integer;
1383                         if (overbright)
1384                                 scaler *= 0.25f;
1385                 }
1386                 scaler *= overbrightscale;
1387         }
1388
1389         j = -1;
1390         for (i = 0;i < backendunits;i++)
1391         {
1392                 if ((mesh->textures[i] = m->tex[i]))
1393                         j = i;
1394                 mesh->texturergbscale[i] = m->texrgbscale[i];
1395                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1396                         mesh->texturergbscale[i] = 1;
1397         }
1398         if (overbright && j >= 0)
1399                 mesh->texturergbscale[j] = 4;
1400
1401         if (m->vertexstep != sizeof(buf_vertex_t))
1402                 Host_Error("R_Mesh_Draw_NativeOnly: unsupported vertexstep\n");
1403         if (m->colorstep != sizeof(buf_fcolor_t))
1404                 Host_Error("R_Mesh_Draw_NativeOnly: unsupported colorstep\n");
1405         if (m->color == NULL)
1406                 Host_Error("R_Mesh_Draw_NativeOnly: must provide color array\n");
1407         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1408         {
1409                 if (j >= backendunits)
1410                         Sys_Error("R_Mesh_Draw_NativeOnly: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1411                 if (m->texcoordstep[j] != sizeof(buf_texcoord_t))
1412                         Host_Error("R_Mesh_Draw_NativeOnly: unsupported texcoordstep\n");
1413         }
1414
1415         memcpy(vert, m->vertex, m->numverts * sizeof(buf_vertex_t));
1416         for (j = 0;j < MAX_TEXTUREUNITS && m->tex[j];j++)
1417                 memcpy(&texcoord[j][0].t[0], m->texcoords[j], m->numverts * sizeof(buf_texcoord_t));
1418         #if 0
1419         for (;j < backendunits;j++)
1420                 memset(&texcoord[j][0].t[0], 0, m->numverts * sizeof(buf_texcoord_t));
1421         #endif
1422
1423         memcpy(fcolor, m->color, m->numverts * sizeof(buf_fcolor_t));
1424
1425         // do this as a second step because memcpy preloaded the cache, which we can't easily do
1426         if (scaler != 1)
1427         {
1428                 for (i = 0;i < m->numverts;i++)
1429                 {
1430                         fcolor[i].c[0] *= scaler;
1431                         fcolor[i].c[1] *= scaler;
1432                         fcolor[i].c[2] *= scaler;
1433                 }
1434         }
1435
1436         if (currenttriangle >= max_batch)
1437                 R_Mesh_Render();
1438 }
1439
1440 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
1441 // (this is used for very high speed rendering, no copying)
1442 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m)
1443 {
1444         // these are static because gcc runs out of virtual registers otherwise
1445         int i, j, overbright;
1446         float scaler;
1447         buf_mesh_t *mesh;
1448
1449         if (!backendactive)
1450                 Sys_Error("R_Mesh_Draw: called when backend is not active\n");
1451
1452         if (!m->numtriangles
1453          || !m->numverts)
1454                 Host_Error("R_Mesh_Draw: no triangles or verts\n");
1455
1456         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
1457         if (m->numtriangles > 1024 || m->numverts > 3072)
1458         {
1459                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for 3DFX drivers, rejected\n");
1460                 return false;
1461         }
1462
1463         if (m->numtriangles > max_meshs || m->numverts > max_verts)
1464         {
1465                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for current gl_mesh_maxtriangles setting, rejected\n");
1466                 return false;
1467         }
1468
1469
1470         if (m->transparent)
1471         {
1472                 if (currenttransmesh >= max_transmeshs || (currenttranstriangle + m->numtriangles) > max_transmeshs || (currenttransvertex + m->numverts) > max_transverts)
1473                 {
1474                         if (!transranout)
1475                         {
1476                                 Con_Printf("R_Mesh_Draw: ran out of room for transparent meshs\n");
1477                                 transranout = true;
1478                         }
1479                         return false;
1480                 }
1481
1482                 c_transmeshs++;
1483                 c_transtris += m->numtriangles;
1484                 m->index = &buf_transtri[currenttranstriangle].index[0];
1485                 m->vertex = &buf_transvertex[currenttransvertex].v[0];
1486                 m->color = &buf_transfcolor[currenttransvertex].c[0];
1487                 for (i = 0;i < backendunits;i++)
1488                         m->texcoords[i] = &buf_transtexcoord[i][currenttransvertex].t[0];
1489
1490                 // transmesh is only for storage of transparent meshs until they
1491                 // are inserted into the main mesh array
1492                 mesh = &buf_transmesh[currenttransmesh++];
1493                 mesh->firsttriangle = currenttranstriangle;
1494                 mesh->firstvert = currenttransvertex;
1495                 currenttranstriangle += m->numtriangles;
1496                 currenttransvertex += m->numverts;
1497         }
1498         else
1499         {
1500                 if (currentmesh >= max_meshs || (currenttriangle + m->numtriangles) > max_batch || (currentvertex + m->numverts) > max_verts)
1501                         R_Mesh_Render();
1502
1503                 c_meshs++;
1504                 c_meshtris += m->numtriangles;
1505                 m->index = &buf_tri[currenttriangle].index[0];
1506                 m->vertex = &buf_vertex[currentvertex].v[0];
1507                 m->color = &buf_fcolor[currentvertex].c[0];
1508                 for (i = 0;i < backendunits;i++)
1509                         m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
1510
1511                 // opaque meshs are rendered directly
1512                 mesh = &buf_mesh[currentmesh++];
1513                 mesh->firsttriangle = currenttriangle;
1514                 mesh->firstvert = currentvertex;
1515                 currenttriangle += m->numtriangles;
1516                 currentvertex += m->numverts;
1517         }
1518
1519         // code shared for transparent and opaque meshs
1520         mesh->blendfunc1 = m->blendfunc1;
1521         mesh->blendfunc2 = m->blendfunc2;
1522         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
1523         mesh->depthtest = !m->depthdisable;
1524         mesh->triangles = m->numtriangles;
1525         mesh->verts = m->numverts;
1526
1527         overbright = false;
1528         scaler = 1;
1529         if (m->blendfunc2 == GL_SRC_COLOR)
1530         {
1531                 if (m->blendfunc1 == GL_DST_COLOR) // 2x modulate with framebuffer
1532                         scaler *= 0.5f;
1533         }
1534         else
1535         {
1536                 if (m->tex[0])
1537                 {
1538                         overbright = gl_combine.integer;
1539                         if (overbright)
1540                                 scaler *= 0.25f;
1541                 }
1542                 scaler *= overbrightscale;
1543         }
1544         m->colorscale = scaler;
1545
1546         j = -1;
1547         for (i = 0;i < MAX_TEXTUREUNITS;i++)
1548         {
1549                 if ((mesh->textures[i] = m->tex[i]))
1550                 {
1551                         j = i;
1552                         if (i >= backendunits)
1553                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
1554                 }
1555                 mesh->texturergbscale[i] = m->texrgbscale[i];
1556                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
1557                         mesh->texturergbscale[i] = 1;
1558         }
1559         if (overbright && j >= 0)
1560                 mesh->texturergbscale[j] = 4;
1561
1562         return true;
1563 }
1564
1565 void R_Mesh_DrawPolygon(rmeshinfo_t *m, int numverts)
1566 {
1567         m->index = polyindexarray;
1568         m->numverts = numverts;
1569         m->numtriangles = numverts - 2;
1570         if (m->numtriangles < 1)
1571         {
1572                 Con_Printf("R_Mesh_DrawPolygon: invalid vertex count\n");
1573                 return;
1574         }
1575         if (m->numtriangles >= 256)
1576         {
1577                 Con_Printf("R_Mesh_DrawPolygon: only up to 256 triangles (258 verts) supported\n");
1578                 return;
1579         }
1580         R_Mesh_Draw(m);
1581 }
1582
1583 /*
1584 ==============================================================================
1585
1586                                                 SCREEN SHOTS
1587
1588 ==============================================================================
1589 */
1590
1591 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
1592 {
1593         qboolean ret;
1594         int i;
1595         qbyte *buffer;
1596
1597         if (!r_render.integer)
1598                 return false;
1599
1600         buffer = Mem_Alloc(tempmempool, width*height*3);
1601         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
1602         CHECKGLERROR
1603
1604         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
1605         if (v_hwgamma.integer)
1606                 for (i = 0;i < width * height * 3;i++)
1607                         buffer[i] <<= v_overbrightbits.integer;
1608
1609         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
1610
1611         Mem_Free(buffer);
1612         return ret;
1613 }
1614
1615 //=============================================================================
1616
1617 void R_ClearScreen(void)
1618 {
1619         if (r_render.integer)
1620         {
1621                 // clear to black
1622                 qglClearColor(0,0,0,0);CHECKGLERROR
1623                 // clear the screen
1624                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
1625                 // set dithering mode
1626                 if (gl_dither.integer)
1627                 {
1628                         qglEnable(GL_DITHER);CHECKGLERROR
1629                 }
1630                 else
1631                 {
1632                         qglDisable(GL_DITHER);CHECKGLERROR
1633                 }
1634         }
1635 }
1636
1637 /*
1638 ==================
1639 SCR_UpdateScreen
1640
1641 This is called every frame, and can also be called explicitly to flush
1642 text to the screen.
1643 ==================
1644 */
1645 void SCR_UpdateScreen (void)
1646 {
1647         //Mem_CheckSentinelsGlobal();
1648         //R_TimeReport("memtest");
1649
1650         VID_Finish ();
1651
1652         R_TimeReport("finish");
1653
1654         if (gl_combine.integer && !gl_combine_extension)
1655                 Cvar_SetValue("gl_combine", 0);
1656
1657         lightscalebit = v_overbrightbits.integer;
1658         if (gl_combine.integer && r_multitexture.integer)
1659                 lightscalebit += 2;
1660
1661         lightscale = 1.0f / (float) (1 << lightscalebit);
1662         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1663
1664         R_TimeReport("setup");
1665
1666         R_ClearScreen();
1667
1668         R_TimeReport("clear");
1669
1670         if (scr_conlines < vid.conheight)
1671                 R_RenderView();
1672
1673         // draw 2D stuff
1674         R_DrawQueue();
1675
1676         // tell driver to commit it's partially full geometry queue to the rendering queue
1677         // (this doesn't wait for the commands themselves to complete)
1678         qglFlush();
1679 }