make sure zFar is at least 64 units to avoid feeding a bogus value to glFrustum
[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_floatcolors = {0, "gl_mesh_floatcolors", "1"};
6 cvar_t gl_mesh_drawmode = {CVAR_SAVE, "gl_mesh_drawmode", "3"};
7
8 cvar_t r_render = {0, "r_render", "1"};
9 cvar_t gl_dither = {CVAR_SAVE, "gl_dither", "1"}; // whether or not to use dithering
10 cvar_t gl_lockarrays = {0, "gl_lockarrays", "1"};
11
12 // this is used to increase gl_mesh_maxtriangles automatically if a mesh was
13 // too large for the buffers in the previous frame
14 int overflowedverts = 0;
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_mesh_farclip;
69
70 static float viewdist;
71 // sign bits (true if negative) for vpn[] entries, so quick integer compares can be used instead of float compares
72 static int vpnbit0, vpnbit1, vpnbit2;
73
74 int c_meshs, c_meshtris;
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_verts; // always max_meshs * 3
84
85 typedef struct buf_mesh_s
86 {
87         int depthmask;
88         int depthtest;
89         int blendfunc1, blendfunc2;
90         int textures[MAX_TEXTUREUNITS];
91         int texturergbscale[MAX_TEXTUREUNITS];
92         int firsttriangle;
93         int triangles;
94         int firstvert;
95         int verts;
96         matrix4x4_t matrix;
97         struct buf_mesh_s *chain;
98 }
99 buf_mesh_t;
100
101 typedef struct buf_tri_s
102 {
103         int index[3];
104 }
105 buf_tri_t;
106
107 typedef struct
108 {
109         float v[4];
110 }
111 buf_vertex_t;
112
113 typedef struct
114 {
115         float c[4];
116 }
117 buf_fcolor_t;
118
119 typedef struct
120 {
121         qbyte c[4];
122 }
123 buf_bcolor_t;
124
125 typedef struct
126 {
127         float t[2];
128 }
129 buf_texcoord_t;
130
131 static int currentmesh, currenttriangle, currentvertex, backendunits, backendactive;
132 static buf_mesh_t *buf_mesh;
133 static buf_tri_t *buf_tri;
134 static buf_vertex_t *buf_vertex;
135 static buf_fcolor_t *buf_fcolor;
136 static buf_bcolor_t *buf_bcolor;
137 static buf_texcoord_t *buf_texcoord[MAX_TEXTUREUNITS];
138
139 static mempool_t *gl_backend_mempool;
140 static int resizingbuffers = false;
141
142 static void gl_backend_start(void)
143 {
144         int i;
145
146         qglGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &gl_maxdrawrangeelementsvertices);
147         qglGetIntegerv(GL_MAX_ELEMENTS_INDICES, &gl_maxdrawrangeelementsindices);
148
149         Con_Printf("OpenGL Backend started with gl_mesh_maxtriangles %i\n", gl_mesh_maxtriangles.integer);
150         if (qglDrawRangeElements != NULL)
151                 Con_Printf("glDrawRangeElements detected (max vertices %i, max indices %i)\n", gl_maxdrawrangeelementsvertices, gl_maxdrawrangeelementsindices);
152         if (strstr(gl_renderer, "3Dfx"))
153         {
154                 Con_Printf("3Dfx driver detected, forcing gl_mesh_floatcolors to 0 to prevent crashs\n");
155                 Cvar_SetValueQuick(&gl_mesh_floatcolors, 0);
156         }
157         Con_Printf("\n");
158
159         max_verts = max_meshs * 3;
160
161         if (!gl_backend_mempool)
162                 gl_backend_mempool = Mem_AllocPool("GL_Backend");
163
164 #define BACKENDALLOC(var, count, sizeofstruct, varname)\
165         {\
166                 var = Mem_Alloc(gl_backend_mempool, count * sizeof(sizeofstruct));\
167                 if (var == NULL)\
168                         Sys_Error("gl_backend_start: unable to allocate memory for %s (%d bytes)\n", (varname), count * sizeof(sizeofstruct));\
169                 memset(var, 0, count * sizeof(sizeofstruct));\
170         }
171
172         BACKENDALLOC(buf_mesh, max_meshs, buf_mesh_t, "buf_mesh")
173         BACKENDALLOC(buf_tri, max_meshs, buf_tri_t, "buf_tri")
174         BACKENDALLOC(buf_vertex, max_verts, buf_vertex_t, "buf_vertex")
175         BACKENDALLOC(buf_fcolor, max_verts, buf_fcolor_t, "buf_fcolor")
176         BACKENDALLOC(buf_bcolor, max_verts, buf_bcolor_t, "buf_bcolor")
177
178         for (i = 0;i < MAX_TEXTUREUNITS;i++)
179         {
180                 // only allocate as many texcoord arrays as we need
181                 if (i < gl_textureunits)
182                 {
183                         BACKENDALLOC(buf_texcoord[i], max_verts, buf_texcoord_t, va("buf_texcoord[%d]", i))
184                 }
185                 else
186                 {
187                         buf_texcoord[i] = NULL;
188                 }
189         }
190         backendunits = min(MAX_TEXTUREUNITS, gl_textureunits);
191         backendactive = true;
192 }
193
194 static void gl_backend_shutdown(void)
195 {
196         Con_Printf("OpenGL Backend shutting down\n");
197
198         if (resizingbuffers)
199                 Mem_EmptyPool(gl_backend_mempool);
200         else
201                 Mem_FreePool(&gl_backend_mempool);
202
203         backendunits = 0;
204         backendactive = false;
205 }
206
207 static void gl_backend_bufferchanges(int init)
208 {
209         if (overflowedverts > gl_mesh_maxtriangles.integer * 3)
210                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, (int) ((overflowedverts + 2) / 3));
211         overflowedverts = 0;
212
213         if (gl_mesh_drawmode.integer < 0)
214                 Cvar_SetValueQuick(&gl_mesh_drawmode, 0);
215         if (gl_mesh_drawmode.integer > 3)
216                 Cvar_SetValueQuick(&gl_mesh_drawmode, 3);
217
218         if (gl_mesh_drawmode.integer >= 3 && qglDrawRangeElements == NULL)
219         {
220                 // change drawmode 3 to 2 if 3 won't work at all
221                 Cvar_SetValueQuick(&gl_mesh_drawmode, 2);
222         }
223
224         // 21760 is (65536 / 3) rounded off to a multiple of 128
225         if (gl_mesh_maxtriangles.integer < 1024)
226                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 1024);
227         if (gl_mesh_maxtriangles.integer > 21760)
228                 Cvar_SetValueQuick(&gl_mesh_maxtriangles, 21760);
229
230         if (max_meshs != gl_mesh_maxtriangles.integer)
231         {
232                 max_meshs = gl_mesh_maxtriangles.integer;
233
234                 if (!init)
235                 {
236                         resizingbuffers = true;
237                         gl_backend_shutdown();
238                         gl_backend_start();
239                         resizingbuffers = false;
240                 }
241         }
242 }
243
244 static void gl_backend_newmap(void)
245 {
246 }
247
248 void gl_backend_init(void)
249 {
250         Cvar_RegisterVariable(&r_render);
251         Cvar_RegisterVariable(&gl_dither);
252         Cvar_RegisterVariable(&gl_lockarrays);
253 #ifdef NORENDER
254         Cvar_SetValue("r_render", 0);
255 #endif
256
257         Cvar_RegisterVariable(&gl_mesh_maxtriangles);
258         Cvar_RegisterVariable(&gl_mesh_floatcolors);
259         Cvar_RegisterVariable(&gl_mesh_drawmode);
260         R_RegisterModule("GL_Backend", gl_backend_start, gl_backend_shutdown, gl_backend_newmap);
261         gl_backend_bufferchanges(true);
262 }
263
264 int arraylocked = false;
265
266 void GL_LockArray(int first, int count)
267 {
268         if (!arraylocked && gl_supportslockarrays && gl_lockarrays.integer && gl_mesh_drawmode.integer > 0)
269         {
270                 qglLockArraysEXT(first, count);
271                 CHECKGLERROR
272                 arraylocked = true;
273         }
274 }
275
276 void GL_UnlockArray(void)
277 {
278         if (arraylocked)
279         {
280                 qglUnlockArraysEXT();
281                 CHECKGLERROR
282                 arraylocked = false;
283         }
284 }
285
286 /*
287 =============
288 GL_SetupFrame
289 =============
290 */
291 static void GL_SetupFrame (void)
292 {
293         double xmax, ymax;
294         double fovx, fovy, zNear, zFar, aspect;
295
296         if (!r_render.integer)
297                 return;
298
299         qglDepthFunc (GL_LEQUAL);CHECKGLERROR
300
301         // set up viewpoint
302         qglMatrixMode(GL_PROJECTION);CHECKGLERROR
303         qglLoadIdentity ();CHECKGLERROR
304
305         // y is weird beause OpenGL is bottom to top, we use top to bottom
306         qglViewport(r_refdef.x, vid.realheight - (r_refdef.y + r_refdef.height), r_refdef.width, r_refdef.height);CHECKGLERROR
307
308         // depth range
309         zNear = 1.0;
310         zFar = r_mesh_farclip;
311         if (zFar < 64)
312                 zFar = 64;
313
314         // fov angles
315         fovx = r_refdef.fov_x;
316         fovy = r_refdef.fov_y;
317         aspect = r_refdef.width / r_refdef.height;
318
319         // pyramid slopes
320         xmax = zNear * tan(fovx * M_PI / 360.0) * aspect;
321         ymax = zNear * tan(fovy * M_PI / 360.0);
322
323         // set view pyramid
324         qglFrustum(-xmax, xmax, -ymax, ymax, zNear, zFar);CHECKGLERROR
325
326         qglMatrixMode(GL_MODELVIEW);CHECKGLERROR
327         qglLoadIdentity ();CHECKGLERROR
328
329         // put Z going up
330         qglRotatef (-90,  1, 0, 0);CHECKGLERROR
331         qglRotatef (90,  0, 0, 1);CHECKGLERROR
332         // camera rotation
333         qglRotatef (-r_refdef.viewangles[2],  1, 0, 0);CHECKGLERROR
334         qglRotatef (-r_refdef.viewangles[0],  0, 1, 0);CHECKGLERROR
335         qglRotatef (-r_refdef.viewangles[1],  0, 0, 1);CHECKGLERROR
336         // camera location
337         qglTranslatef (-r_refdef.vieworg[0],  -r_refdef.vieworg[1],  -r_refdef.vieworg[2]);CHECKGLERROR
338 }
339
340 static struct
341 {
342         int blendfunc1;
343         int blendfunc2;
344         int blend;
345         GLboolean depthmask;
346         int depthtest;
347         int unit;
348         int clientunit;
349         int texture[MAX_TEXTUREUNITS];
350         float texturergbscale[MAX_TEXTUREUNITS];
351 }
352 gl_state;
353
354 void GL_SetupTextureState(void)
355 {
356         int i;
357         if (backendunits > 1)
358         {
359                 for (i = 0;i < backendunits;i++)
360                 {
361                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
362                         qglBindTexture(GL_TEXTURE_2D, gl_state.texture[i]);CHECKGLERROR
363                         if (gl_combine.integer)
364                         {
365                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);CHECKGLERROR
366                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);CHECKGLERROR
367                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_TEXTURE);CHECKGLERROR
368                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
369                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB_ARB, GL_CONSTANT_ARB);CHECKGLERROR
370                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
371                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB_ARB, GL_SRC_COLOR);CHECKGLERROR
372                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB_ARB, GL_SRC_ALPHA);CHECKGLERROR
373                                 qglTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);CHECKGLERROR
374                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_TEXTURE);CHECKGLERROR
375                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_PREVIOUS_ARB);CHECKGLERROR
376                                 qglTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_ALPHA_ARB, GL_CONSTANT_ARB);CHECKGLERROR
377                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
378                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
379                                 qglTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_ALPHA_ARB, GL_SRC_ALPHA);CHECKGLERROR
380                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, gl_state.texturergbscale[i]);CHECKGLERROR
381                                 qglTexEnvi(GL_TEXTURE_ENV, GL_ALPHA_SCALE, 1);CHECKGLERROR
382                         }
383                         else
384                         {
385                                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
386                         }
387                         if (gl_state.texture[i])
388                         {
389                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
390                         }
391                         else
392                         {
393                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
394                         }
395                         if (gl_mesh_drawmode.integer > 0)
396                         {
397                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
398                                 qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[i]);CHECKGLERROR
399                                 if (gl_state.texture[i])
400                                 {
401                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
402                                 }
403                                 else
404                                 {
405                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
406                                 }
407                         }
408                 }
409         }
410         else
411         {
412                 qglBindTexture(GL_TEXTURE_2D, gl_state.texture[0]);CHECKGLERROR
413                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
414                 if (gl_state.texture[0])
415                 {
416                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
417                 }
418                 else
419                 {
420                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
421                 }
422                 if (gl_mesh_drawmode.integer > 0)
423                 {
424                         qglTexCoordPointer(2, GL_FLOAT, sizeof(buf_texcoord_t), buf_texcoord[0]);CHECKGLERROR
425                         if (gl_state.texture[0])
426                         {
427                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
428                         }
429                         else
430                         {
431                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
432                         }
433                 }
434         }
435 }
436
437 // called at beginning of frame
438 int usedarrays;
439 void R_Mesh_Start(float farclip)
440 {
441         int i;
442         if (!backendactive)
443                 Sys_Error("R_Mesh_Clear: called when backend is not active\n");
444
445         CHECKGLERROR
446
447         gl_backend_bufferchanges(false);
448
449         currentmesh = 0;
450         currenttriangle = 0;
451         currentvertex = 0;
452         r_mesh_farclip = farclip;
453         viewdist = DotProduct(r_origin, vpn);
454         vpnbit0 = vpn[0] < 0;
455         vpnbit1 = vpn[1] < 0;
456         vpnbit2 = vpn[2] < 0;
457
458         c_meshs = 0;
459         c_meshtris = 0;
460
461         GL_SetupFrame();
462
463         gl_state.unit = 0;
464         gl_state.clientunit = 0;
465
466         for (i = 0;i < backendunits;i++)
467         {
468                 gl_state.texture[i] = 0;
469                 gl_state.texturergbscale[i] = 1;
470         }
471
472         qglEnable(GL_CULL_FACE);CHECKGLERROR
473         qglCullFace(GL_FRONT);CHECKGLERROR
474
475         gl_state.depthtest = true;
476         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
477
478         gl_state.blendfunc1 = GL_ONE;
479         gl_state.blendfunc2 = GL_ZERO;
480         qglBlendFunc(gl_state.blendfunc1, gl_state.blendfunc2);CHECKGLERROR
481
482         gl_state.blend = 0;
483         qglDisable(GL_BLEND);CHECKGLERROR
484
485         gl_state.depthmask = GL_TRUE;
486         qglDepthMask(gl_state.depthmask);CHECKGLERROR
487
488         usedarrays = false;
489         if (gl_mesh_drawmode.integer > 0)
490         {
491                 usedarrays = true;
492                 qglVertexPointer(3, GL_FLOAT, sizeof(buf_vertex_t), &buf_vertex[0].v[0]);CHECKGLERROR
493                 qglEnableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
494                 if (gl_mesh_floatcolors.integer)
495                 {
496                         qglColorPointer(4, GL_FLOAT, sizeof(buf_fcolor_t), &buf_fcolor[0].c[0]);CHECKGLERROR
497                 }
498                 else
499                 {
500                         qglColorPointer(4, GL_UNSIGNED_BYTE, sizeof(buf_bcolor_t), &buf_bcolor[0].c[0]);CHECKGLERROR
501                 }
502                 qglEnableClientState(GL_COLOR_ARRAY);CHECKGLERROR
503         }
504
505         GL_SetupTextureState();
506 }
507
508 int gl_backend_rebindtextures;
509
510 void GL_ConvertColorsFloatToByte(void)
511 {
512         int i, k, total;
513         // LordHavoc: to avoid problems with aliasing (treating memory as two
514         // different types - exactly what this is doing), these must be volatile
515         // (or a union)
516         volatile int *icolor;
517         volatile float *fcolor;
518         qbyte *bcolor;
519
520         total = currentvertex * 4;
521
522         // shift float to have 8bit fraction at base of number
523         fcolor = &buf_fcolor->c[0];
524         for (i = 0;i < total;)
525         {
526                 fcolor[i    ] += 32768.0f;
527                 fcolor[i + 1] += 32768.0f;
528                 fcolor[i + 2] += 32768.0f;
529                 fcolor[i + 3] += 32768.0f;
530                 i += 4;
531         }
532
533         // then read as integer and kill float bits...
534         icolor = (int *)&buf_fcolor->c[0];
535         bcolor = &buf_bcolor->c[0];
536         for (i = 0;i < total;)
537         {
538                 k = icolor[i    ] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i    ] = (qbyte) k;
539                 k = icolor[i + 1] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 1] = (qbyte) k;
540                 k = icolor[i + 2] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 2] = (qbyte) k;
541                 k = icolor[i + 3] & 0x7FFFFF;if (k > 255) k = 255;bcolor[i + 3] = (qbyte) k;
542                 i += 4;
543         }
544 }
545
546 void GL_MeshState(buf_mesh_t *mesh)
547 {
548         int i;
549         if (backendunits > 1)
550         {
551                 for (i = 0;i < backendunits;i++)
552                 {
553                         if (gl_state.texture[i] != mesh->textures[i])
554                         {
555                                 if (gl_state.unit != i)
556                                 {
557                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
558                                 }
559                                 if (gl_state.texture[i] == 0)
560                                 {
561                                         qglEnable(GL_TEXTURE_2D);CHECKGLERROR
562                                         // have to disable texcoord array on disabled texture
563                                         // units due to NVIDIA driver bug with
564                                         // compiled_vertex_array
565                                         if (gl_state.clientunit != i)
566                                         {
567                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
568                                         }
569                                         qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
570                                 }
571                                 qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[i] = mesh->textures[i]));CHECKGLERROR
572                                 if (gl_state.texture[i] == 0)
573                                 {
574                                         qglDisable(GL_TEXTURE_2D);CHECKGLERROR
575                                         // have to disable texcoord array on disabled texture
576                                         // units due to NVIDIA driver bug with
577                                         // compiled_vertex_array
578                                         if (gl_state.clientunit != i)
579                                         {
580                                                 qglClientActiveTexture(GL_TEXTURE0_ARB + (gl_state.clientunit = i));CHECKGLERROR
581                                         }
582                                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
583                                 }
584                         }
585                         if (gl_state.texturergbscale[i] != mesh->texturergbscale[i])
586                         {
587                                 if (gl_state.unit != i)
588                                 {
589                                         qglActiveTexture(GL_TEXTURE0_ARB + (gl_state.unit = i));CHECKGLERROR
590                                 }
591                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, (gl_state.texturergbscale[i] = mesh->texturergbscale[i]));CHECKGLERROR
592                         }
593                 }
594         }
595         else
596         {
597                 if (gl_state.texture[0] != mesh->textures[0])
598                 {
599                         if (gl_state.texture[0] == 0)
600                         {
601                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
602                                 qglEnableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
603                         }
604                         qglBindTexture(GL_TEXTURE_2D, (gl_state.texture[0] = mesh->textures[0]));CHECKGLERROR
605                         if (gl_state.texture[0] == 0)
606                         {
607                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
608                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
609                         }
610                 }
611         }
612         if (gl_state.blendfunc1 != mesh->blendfunc1 || gl_state.blendfunc2 != mesh->blendfunc2)
613         {
614                 qglBlendFunc(gl_state.blendfunc1 = mesh->blendfunc1, gl_state.blendfunc2 = mesh->blendfunc2);CHECKGLERROR
615                 if (gl_state.blendfunc2 == GL_ZERO)
616                 {
617                         if (gl_state.blendfunc1 == GL_ONE)
618                         {
619                                 if (gl_state.blend)
620                                 {
621                                         gl_state.blend = 0;
622                                         qglDisable(GL_BLEND);CHECKGLERROR
623                                 }
624                         }
625                         else
626                         {
627                                 if (!gl_state.blend)
628                                 {
629                                         gl_state.blend = 1;
630                                         qglEnable(GL_BLEND);CHECKGLERROR
631                                 }
632                         }
633                 }
634                 else
635                 {
636                         if (!gl_state.blend)
637                         {
638                                 gl_state.blend = 1;
639                                 qglEnable(GL_BLEND);CHECKGLERROR
640                         }
641                 }
642         }
643         if (gl_state.depthtest != mesh->depthtest)
644         {
645                 gl_state.depthtest = mesh->depthtest;
646                 if (gl_state.depthtest)
647                         qglEnable(GL_DEPTH_TEST);
648                 else
649                         qglDisable(GL_DEPTH_TEST);
650         }
651         if (gl_state.depthmask != mesh->depthmask)
652         {
653                 qglDepthMask(gl_state.depthmask = mesh->depthmask);CHECKGLERROR
654         }
655 }
656
657 void GL_DrawRangeElements(int firstvert, int endvert, int indexcount, GLuint *index)
658 {
659         unsigned int i, j, in;
660         if (gl_mesh_drawmode.integer >= 3/* && (endvert - firstvert) <= gl_maxdrawrangeelementsvertices && (indexcount) <= gl_maxdrawrangeelementsindices*/)
661         {
662                 // GL 1.2 or GL 1.1 with extension
663                 qglDrawRangeElements(GL_TRIANGLES, firstvert, endvert, indexcount, GL_UNSIGNED_INT, index);
664         }
665         else if (gl_mesh_drawmode.integer >= 2)
666         {
667                 // GL 1.1
668                 qglDrawElements(GL_TRIANGLES, indexcount, GL_UNSIGNED_INT, index);
669         }
670         else if (gl_mesh_drawmode.integer >= 1)
671         {
672                 // GL 1.1
673                 // feed it manually using glArrayElement
674                 qglBegin(GL_TRIANGLES);
675                 for (i = 0;i < indexcount;i++)
676                         qglArrayElement(index[i]);
677                 qglEnd();
678         }
679         else
680         {
681                 // GL 1.1 but not using vertex arrays - 3dfx glquake minigl driver
682                 // feed it manually
683                 qglBegin(GL_TRIANGLES);
684                 if (gl_state.texture[1]) // if the mesh uses multiple textures
685                 {
686                         // the minigl doesn't have this (because it does not have ARB_multitexture)
687                         for (i = 0;i < indexcount;i++)
688                         {
689                                 in = index[i];
690                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
691                                 for (j = 0;j < backendunits;j++)
692                                         if (gl_state.texture[j])
693                                                 qglMultiTexCoord2f(GL_TEXTURE0_ARB + j, buf_texcoord[j][in].t[0], buf_texcoord[j][in].t[1]);
694                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
695                         }
696                 }
697                 else
698                 {
699                         for (i = 0;i < indexcount;i++)
700                         {
701                                 in = index[i];
702                                 qglColor4ub(buf_bcolor[in].c[0], buf_bcolor[in].c[1], buf_bcolor[in].c[2], buf_bcolor[in].c[3]);
703                                 if (gl_state.texture[0])
704                                         qglTexCoord2f(buf_texcoord[0][in].t[0], buf_texcoord[0][in].t[1]);
705                                 qglVertex3f(buf_vertex[in].v[0], buf_vertex[in].v[1], buf_vertex[in].v[2]);
706                         }
707                 }
708                 qglEnd();
709         }
710 }
711
712 // renders mesh buffers, called to flush buffers when full
713 void R_Mesh_Render(void)
714 {
715         int i, k;
716         float *v, tempv[4], m[12];
717         buf_mesh_t *mesh;
718
719         if (!backendactive)
720                 Sys_Error("R_Mesh_Render: called when backend is not active\n");
721
722         if (!currentmesh)
723                 return;
724
725         if (!r_render.integer)
726         {
727                 currentmesh = 0;
728                 currenttriangle = 0;
729                 currentvertex = 0;
730                 return;
731         }
732
733         CHECKGLERROR
734
735         // drawmode 0 always uses byte colors
736         if (!gl_mesh_floatcolors.integer || gl_mesh_drawmode.integer <= 0)
737                 GL_ConvertColorsFloatToByte();
738
739         if (gl_backend_rebindtextures)
740         {
741                 gl_backend_rebindtextures = false;
742                 GL_SetupTextureState();
743         }
744
745         GL_MeshState(buf_mesh);
746         for (k = 0, mesh = buf_mesh;k < currentmesh;k++, mesh++)
747         {
748                 m[0] = mesh->matrix.m[0][0];
749                 m[1] = mesh->matrix.m[0][1];
750                 m[2] = mesh->matrix.m[0][2];
751                 m[3] = mesh->matrix.m[0][3];
752                 m[4] = mesh->matrix.m[1][0];
753                 m[5] = mesh->matrix.m[1][1];
754                 m[6] = mesh->matrix.m[1][2];
755                 m[7] = mesh->matrix.m[1][3];
756                 m[8] = mesh->matrix.m[2][0];
757                 m[9] = mesh->matrix.m[2][1];
758                 m[10] = mesh->matrix.m[2][2];
759                 m[11] = mesh->matrix.m[2][3];
760                 for (i = 0, v = buf_vertex[mesh->firstvert].v;i < mesh->verts;i++, v += 4)
761                 {
762                         VectorCopy(v, tempv);
763                         //Matrix4x4_Transform(&mesh->matrix, tempv, v);
764                         v[0] = tempv[0] * m[0] + tempv[1] * m[1] + tempv[2] * m[2] + m[3];
765                         v[1] = tempv[0] * m[4] + tempv[1] * m[5] + tempv[2] * m[6] + m[7];
766                         v[2] = tempv[0] * m[8] + tempv[1] * m[9] + tempv[2] * m[10] + m[11];
767                 }
768         }
769         GL_LockArray(0, currentvertex);
770         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
771
772         if (currentmesh >= 2)
773         {
774                 for (k = 1, mesh = buf_mesh + k;k < currentmesh;k++, mesh++)
775                 {
776                         GL_MeshState(mesh);
777                         GL_DrawRangeElements(mesh->firstvert, mesh->firstvert + mesh->verts, mesh->triangles * 3, buf_tri[mesh->firsttriangle].index);CHECKGLERROR
778                 }
779         }
780
781         currentmesh = 0;
782         currenttriangle = 0;
783         currentvertex = 0;
784
785         GL_UnlockArray();CHECKGLERROR
786 }
787
788 // restores backend state, used when done with 3D rendering
789 void R_Mesh_Finish(void)
790 {
791         int i;
792         // flush any queued meshs
793         if (currentmesh)
794                 R_Mesh_Render();
795
796         if (backendunits > 1)
797         {
798                 for (i = backendunits - 1;i >= 0;i--)
799                 {
800                         qglActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
801                         qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
802                         if (gl_combine.integer)
803                         {
804                                 qglTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 1);CHECKGLERROR
805                         }
806                         if (i > 0)
807                         {
808                                 qglDisable(GL_TEXTURE_2D);CHECKGLERROR
809                         }
810                         else
811                         {
812                                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
813                         }
814                         qglBindTexture(GL_TEXTURE_2D, 0);CHECKGLERROR
815
816                         if (usedarrays)
817                         {
818                                 qglClientActiveTexture(GL_TEXTURE0_ARB + i);CHECKGLERROR
819                                 qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
820                         }
821                 }
822         }
823         else
824         {
825                 qglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);CHECKGLERROR
826                 qglEnable(GL_TEXTURE_2D);CHECKGLERROR
827                 if (usedarrays)
828                 {
829                         qglDisableClientState(GL_TEXTURE_COORD_ARRAY);CHECKGLERROR
830                 }
831         }
832         if (usedarrays)
833         {
834                 qglDisableClientState(GL_COLOR_ARRAY);CHECKGLERROR
835                 qglDisableClientState(GL_VERTEX_ARRAY);CHECKGLERROR
836         }
837
838         qglDisable(GL_BLEND);CHECKGLERROR
839         qglEnable(GL_DEPTH_TEST);CHECKGLERROR
840         qglDepthMask(GL_TRUE);CHECKGLERROR
841         qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);CHECKGLERROR
842 }
843
844 void R_Mesh_ClearDepth(void)
845 {
846         if (currentmesh)
847                 R_Mesh_Render();
848         R_Mesh_Finish();
849         qglClear(GL_DEPTH_BUFFER_BIT);
850         R_Mesh_Start(r_mesh_farclip);
851 }
852
853 // allocates space in geometry buffers, and fills in pointers to the buffers in passsed struct
854 // (this is used for very high speed rendering, no copying)
855 int R_Mesh_Draw_GetBuffer(rmeshbufferinfo_t *m, int wantoverbright)
856 {
857         // these are static because gcc runs out of virtual registers otherwise
858         int i, j, overbright;
859         float scaler;
860         buf_mesh_t *mesh;
861
862         if (!backendactive)
863                 Sys_Error("R_Mesh_Draw_GetBuffer: called when backend is not active\n");
864
865         if (!m->numtriangles
866          || !m->numverts)
867                 Host_Error("R_Mesh_Draw_GetBuffer: no triangles or verts\n");
868
869         // LordHavoc: removed this error condition because with floatcolors 0,
870         // the 3DFX driver works with very large meshs
871         // FIXME: we can work around this by falling back on non-array renderer if buffers are too big
872         //if (m->numtriangles > 1024 || m->numverts > 3072)
873         //{
874         //      Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for 3DFX drivers, rejected\n");
875         //      return false;
876         //}
877
878         i = max(m->numtriangles * 3, m->numverts);
879         if (overflowedverts < i)
880                 overflowedverts = i;
881
882         if (m->numtriangles > max_meshs || m->numverts > max_verts)
883         {
884                 Con_Printf("R_Mesh_Draw_GetBuffer: mesh too big for current gl_mesh_maxtriangles setting, increasing limits\n");
885                 return false;
886         }
887
888         if (currentmesh)
889         {
890                 R_Mesh_Render();
891                 Con_Printf("mesh queue not empty, flushing.\n");
892         }
893
894         c_meshs++;
895         c_meshtris += m->numtriangles;
896         m->index = &buf_tri[currenttriangle].index[0];
897         m->vertex = &buf_vertex[currentvertex].v[0];
898         m->color = &buf_fcolor[currentvertex].c[0];
899         for (i = 0;i < backendunits;i++)
900                 m->texcoords[i] = &buf_texcoord[i][currentvertex].t[0];
901
902         // opaque meshs are rendered directly
903         mesh = &buf_mesh[currentmesh++];
904         mesh->firsttriangle = currenttriangle;
905         mesh->firstvert = currentvertex;
906         currenttriangle += m->numtriangles;
907         currentvertex += m->numverts;
908
909         mesh->blendfunc1 = m->blendfunc1;
910         mesh->blendfunc2 = m->blendfunc2;
911         mesh->depthmask = (m->blendfunc2 == GL_ZERO || m->depthwrite);
912         mesh->depthtest = !m->depthdisable;
913         mesh->triangles = m->numtriangles;
914         mesh->verts = m->numverts;
915         mesh->matrix = m->matrix; // this copies the struct
916
917         overbright = false;
918         scaler = 1;
919         if (m->blendfunc1 == GL_DST_COLOR)
920         {
921                 // check if it is a 2x modulate with framebuffer
922                 if (m->blendfunc2 == GL_SRC_COLOR)
923                         scaler *= 0.5f;
924         }
925         else if (m->blendfunc2 != GL_SRC_COLOR)
926         {
927                 if (m->tex[0])
928                 {
929                         overbright = wantoverbright && gl_combine.integer;
930                         if (overbright)
931                                 scaler *= 0.25f;
932                 }
933                 scaler *= overbrightscale;
934         }
935         m->colorscale = scaler;
936
937         j = -1;
938         for (i = 0;i < MAX_TEXTUREUNITS;i++)
939         {
940                 if ((mesh->textures[i] = m->tex[i]))
941                 {
942                         j = i;
943                         if (i >= backendunits)
944                                 Sys_Error("R_Mesh_Draw_GetBuffer: texture %i supplied when there are only %i texture units\n", j + 1, backendunits);
945                 }
946                 mesh->texturergbscale[i] = m->texrgbscale[i];
947                 if (mesh->texturergbscale[i] != 1 && mesh->texturergbscale[i] != 2 && mesh->texturergbscale[i] != 4)
948                         mesh->texturergbscale[i] = 1;
949         }
950         if (overbright && j >= 0)
951                 mesh->texturergbscale[j] = 4;
952
953         return true;
954 }
955
956 /*
957 ==============================================================================
958
959                                                 SCREEN SHOTS
960
961 ==============================================================================
962 */
963
964 qboolean SCR_ScreenShot(char *filename, int x, int y, int width, int height)
965 {
966         qboolean ret;
967         int i;
968         qbyte *buffer;
969
970         if (!r_render.integer)
971                 return false;
972
973         buffer = Mem_Alloc(tempmempool, width*height*3);
974         qglReadPixels (x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
975         CHECKGLERROR
976
977         // LordHavoc: compensate for v_overbrightbits when using hardware gamma
978         if (v_hwgamma.integer)
979                 for (i = 0;i < width * height * 3;i++)
980                         buffer[i] <<= v_overbrightbits.integer;
981
982         ret = Image_WriteTGARGB_preflipped(filename, width, height, buffer);
983
984         Mem_Free(buffer);
985         return ret;
986 }
987
988 //=============================================================================
989
990 void R_ClearScreen(void)
991 {
992         if (r_render.integer)
993         {
994                 // clear to black
995                 qglClearColor(0,0,0,0);CHECKGLERROR
996                 // clear the screen
997                 qglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);CHECKGLERROR
998                 // set dithering mode
999                 if (gl_dither.integer)
1000                 {
1001                         qglEnable(GL_DITHER);CHECKGLERROR
1002                 }
1003                 else
1004                 {
1005                         qglDisable(GL_DITHER);CHECKGLERROR
1006                 }
1007         }
1008 }
1009
1010 /*
1011 ==================
1012 SCR_UpdateScreen
1013
1014 This is called every frame, and can also be called explicitly to flush
1015 text to the screen.
1016 ==================
1017 */
1018 void SCR_UpdateScreen (void)
1019 {
1020         VID_Finish ();
1021
1022         R_TimeReport("finish");
1023
1024         if (r_textureunits.integer > gl_textureunits)
1025                 Cvar_SetValueQuick(&r_textureunits, gl_textureunits);
1026         if (r_textureunits.integer < 1)
1027                 Cvar_SetValueQuick(&r_textureunits, 1);
1028
1029         if (gl_combine.integer && (!gl_combine_extension || r_textureunits.integer < 2))
1030                 Cvar_SetValueQuick(&gl_combine, 0);
1031
1032         // lighting scale
1033         overbrightscale = 1.0f / (float) (1 << v_overbrightbits.integer);
1034
1035         // lightmaps only
1036         lightscalebit = v_overbrightbits.integer;
1037         if (gl_combine.integer && r_textureunits.integer > 1)
1038                 lightscalebit += 2;
1039         lightscale = 1.0f / (float) (1 << lightscalebit);
1040
1041         R_TimeReport("setup");
1042
1043         R_ClearScreen();
1044
1045         R_TimeReport("clear");
1046
1047         if (scr_conlines < vid.conheight)
1048                 R_RenderView();
1049
1050         // draw 2D stuff
1051         R_DrawQueue();
1052
1053         // tell driver to commit it's partially full geometry queue to the rendering queue
1054         // (this doesn't wait for the commands themselves to complete)
1055         qglFlush();
1056 }
1057