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