clean up, r_farclip cvar, lit particles (optional), stuff
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23
24 extern int                     skytexturenum;
25
26 int             lightmap_textures;
27
28 signed blocklights[18*18*3]; // LordHavoc: *3 for colored lighting
29
30 // LordHavoc: skinny but tall lightmaps for quicker subimage uploads
31 #define BLOCK_WIDTH             128
32 #define BLOCK_HEIGHT    128
33 // LordHavoc: increased lightmap limit from 64 to 1024
34 #define MAX_LIGHTMAPS   1024
35 #define LIGHTMAPSIZE    (BLOCK_WIDTH*BLOCK_HEIGHT*3)
36
37 int                     active_lightmaps;
38
39 short allocated[MAX_LIGHTMAPS][BLOCK_WIDTH];
40
41 byte *lightmaps[MAX_LIGHTMAPS];
42 short lightmapupdate[MAX_LIGHTMAPS][2];
43
44 int lightmapalign, lightmapalignmask; // LordHavoc: NVIDIA's broken subimage fix, see BuildLightmaps for notes
45 cvar_t gl_lightmapalign = {"gl_lightmapalign", "4"};
46 cvar_t gl_lightmaprgba = {"gl_lightmaprgba", "1"};
47 cvar_t gl_nosubimagefragments = {"gl_nosubimagefragments", "0"};
48 cvar_t gl_nosubimage = {"gl_nosubimage", "0"};
49
50 qboolean lightmaprgba, nosubimagefragments, nosubimage;
51 int lightmapbytes;
52
53 qboolean skyisvisible;
54 extern qboolean gl_arrays;
55
56 void glrsurf_init()
57 {
58         int i;
59         for (i = 0;i < MAX_LIGHTMAPS;i++)
60                 lightmaps[i] = NULL;
61         Cvar_RegisterVariable(&gl_lightmapalign);
62         Cvar_RegisterVariable(&gl_lightmaprgba);
63         Cvar_RegisterVariable(&gl_nosubimagefragments);
64         Cvar_RegisterVariable(&gl_nosubimage);
65         // check if it's the glquake minigl driver
66         if (strncasecmp(gl_vendor,"3Dfx",4)==0)
67         if (!gl_arrays)
68         {
69                 Cvar_SetValue("gl_nosubimagefragments", 1);
70 //              Cvar_SetValue("gl_nosubimage", 1);
71                 Cvar_SetValue("gl_lightmode", 0);
72         }
73 }
74
75 int dlightdivtable[8192];
76 int dlightdivtableinitialized = 0;
77
78 /*
79 ===============
80 R_AddDynamicLights
81 ===============
82 */
83 void R_AddDynamicLights (msurface_t *surf)
84 {
85         int                     sdtable[18], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, red, green, blue, j;
86         unsigned        *bl;
87         float           dist, f;
88         vec3_t          impact, local;
89         // use 64bit integer...  shame it's not very standardized...
90 #if _MSC_VER || __BORLANDC__
91         __int64         k; // MSVC
92 #else
93         long long       k; // GCC
94 #endif
95
96         if (!dlightdivtableinitialized)
97         {
98                 dlightdivtable[0] = 1048576 >> 7;
99                 for (s = 1;s < 8192;s++)
100                         dlightdivtable[s] = 1048576 / (s << 7);
101                 dlightdivtableinitialized = 1;
102         }
103
104         smax = (surf->extents[0]>>4)+1;
105         tmax = (surf->extents[1]>>4)+1;
106
107         for (lnum=0 ; lnum<MAX_DLIGHTS ; lnum++)
108         {
109                 if ( !(surf->dlightbits[lnum >> 5] & (1<<(lnum&31)) ) )
110                         continue;               // not lit by this light
111
112                 VectorSubtract(cl_dlights[lnum].origin, currententity->origin, local);
113                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
114                 for (i=0 ; i<3 ; i++)
115                         impact[i] = cl_dlights[lnum].origin[i] - surf->plane->normal[i]*dist;
116
117                 f = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
118                 i = f;
119
120                 // reduce calculations
121                 t = dist*dist;
122                 for (s = 0;s < smax;s++, i -= 16)
123                         sdtable[s] = i*i + t;
124
125                 f = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
126                 i = f;
127
128                 maxdist = (int) (cl_dlights[lnum].radius*cl_dlights[lnum].radius); // for comparisons to minimum acceptable light
129                 // clamp radius to avoid exceeding 8192 entry division table
130                 if (maxdist > 1048576)
131                         maxdist = 1048576;
132                 maxdist3 = maxdist - (int) (dist*dist);
133                 // convert to 8.8 blocklights format
134                 if (!cl_dlights[lnum].dark)
135                 {
136                         f = cl_dlights[lnum].color[0] * maxdist;red = f;
137                         f = cl_dlights[lnum].color[1] * maxdist;green = f;
138                         f = cl_dlights[lnum].color[2] * maxdist;blue = f;
139                 }
140                 else // negate for darklight
141                 {
142                         f = cl_dlights[lnum].color[0] * -maxdist;red = f;
143                         f = cl_dlights[lnum].color[1] * -maxdist;green = f;
144                         f = cl_dlights[lnum].color[2] * -maxdist;blue = f;
145                 }
146                 bl = blocklights;
147                 for (t = 0;t < tmax;t++,i -= 16)
148                 {
149                         td = i*i;
150                         if (td < maxdist3) // make sure some part of it is visible on this line
151                         {
152                                 maxdist2 = maxdist - td;
153                                 for (s = 0;s < smax;s++)
154                                 {
155                                         if (sdtable[s] < maxdist2)
156                                         {
157                                                 j = dlightdivtable[(sdtable[s]+td) >> 7];
158                                                 k = (red   * j) >> 8;bl[0] += k;
159                                                 k = (green * j) >> 8;bl[1] += k;
160                                                 k = (blue  * j) >> 8;bl[2] += k;
161                                         }
162                                         bl += 3;
163                                 }
164                         }
165                         else
166                                 bl+=smax*3; // skip line
167                 }
168         }
169 }
170
171 extern qboolean lighthalf;
172 /*
173 ===============
174 R_BuildLightMap
175
176 Combine and scale multiple lightmaps into the 8.8 format in blocklights
177 ===============
178 */
179 void R_BuildLightMap (msurface_t *surf, byte *dest, int stride)
180 {
181         int                     smax, tmax;
182         int                     t;
183         int                     i, j, size;
184         byte            *lightmap;
185         int                     scale;
186         int                     maps;
187         int                     *bl;
188
189         surf->cached_dlight = (surf->dlightframe == r_framecount);
190         surf->cached_lighthalf = lighthalf;
191
192         smax = (surf->extents[0]>>4)+1;
193         tmax = (surf->extents[1]>>4)+1;
194         size = smax*tmax;
195         lightmap = surf->samples;
196
197 // set to full bright if no light data
198         if (currententity->effects & EF_FULLBRIGHT || !cl.worldmodel->lightdata)
199         {
200                 bl = blocklights;
201                 for (i=0 ; i<size ; i++)
202                 {
203                         *bl++ = 255*256;
204                         *bl++ = 255*256;
205                         *bl++ = 255*256;
206                 }
207         }
208         else
209         {
210 // clear to no light
211                 bl = blocklights;
212                 for (i=0 ; i<size ; i++)
213                 {
214                         *bl++ = 0;
215                         *bl++ = 0;
216                         *bl++ = 0;
217                 }
218
219 // add all the lightmaps
220                 if (lightmap)
221                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++)
222                         {
223                                 scale = d_lightstylevalue[surf->styles[maps]];
224                                 surf->cached_light[maps] = scale;       // 8.8 fraction
225                                 bl = blocklights;
226                                 for (i=0 ; i<size ; i++)
227                                 {
228                                         *bl++ += *lightmap++ * scale;
229                                         *bl++ += *lightmap++ * scale;
230                                         *bl++ += *lightmap++ * scale;
231                                 }
232                         }
233
234 // add all the dynamic lights
235                 if (surf->dlightframe == r_framecount)
236                         R_AddDynamicLights (surf);
237         }
238         stride -= (smax*lightmapbytes);
239         bl = blocklights;
240         if (lighthalf)
241         {
242                 // LordHavoc: I shift down by 8 unlike GLQuake's 7,
243                 // the image is brightened as a processing pass
244                 if (lightmaprgba)
245                 {
246                         for (i=0 ; i<tmax ; i++, dest += stride)
247                         {
248                                 for (j=0 ; j<smax ; j++)
249                                 {
250                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
251                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
252                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
253                                         *dest++ = 255;
254                                 }
255                         }
256                 }
257                 else
258                 {
259                         for (i=0 ; i<tmax ; i++, dest += stride)
260                         {
261                                 for (j=0 ; j<smax ; j++)
262                                 {
263                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
264                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
265                                         t = *bl++ >> 8;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
266                                 }
267                         }
268                 }
269         }
270         else
271         {
272                 if (lightmaprgba)
273                 {
274                         for (i=0 ; i<tmax ; i++, dest += stride)
275                         {
276                                 for (j=0 ; j<smax ; j++)
277                                 {
278                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
279                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
280                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
281                                         *dest++ = 255;
282                                 }
283                         }
284                 }
285                 else
286                 {
287                         for (i=0 ; i<tmax ; i++, dest += stride)
288                         {
289                                 for (j=0 ; j<smax ; j++)
290                                 {
291                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
292                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
293                                         t = *bl++ >> 7;if (t > 255) t = 255;else if (t < 0) t = 0;*dest++ = t;
294                                 }
295                         }
296                 }
297         }
298 }
299
300 byte templight[32*32*4];
301
302 void R_UpdateLightmap(msurface_t *s, int lnum)
303 {
304         int smax, tmax;
305         // upload the new lightmap texture fragment
306         glBindTexture(GL_TEXTURE_2D, lightmap_textures + lnum);
307         if (nosubimage || nosubimagefragments)
308         {
309                 if (lightmapupdate[lnum][0] > s->light_t)
310                         lightmapupdate[lnum][0] = s->light_t;
311                 if (lightmapupdate[lnum][1] < (s->light_t + ((s->extents[1]>>4)+1)))
312                         lightmapupdate[lnum][1] = (s->light_t + ((s->extents[1]>>4)+1));
313                 if (lightmaprgba)
314                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 4, BLOCK_WIDTH * 4);
315                 else
316                         R_BuildLightMap (s, lightmaps[s->lightmaptexturenum] + (s->light_t * BLOCK_WIDTH + s->light_s) * 3, BLOCK_WIDTH * 3);
317         }
318         else
319         {
320                 smax = ((s->extents[0]>>4)+lightmapalign) & lightmapalignmask;
321                 tmax = (s->extents[1]>>4)+1;
322                 if (lightmaprgba)
323                 {
324                         R_BuildLightMap (s, templight, smax * 4);
325                         glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
326                 }
327                 else
328                 {
329                         R_BuildLightMap (s, templight, smax * 3);
330                         glTexSubImage2D(GL_TEXTURE_2D, 0, s->light_s, s->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
331                 }
332         }
333 }
334
335
336 /*
337 ===============
338 R_TextureAnimation
339
340 Returns the proper texture for a given time and base texture
341 ===============
342 */
343 texture_t *R_TextureAnimation (texture_t *base)
344 {
345         texture_t *original;
346         int             relative;
347         int             count;
348
349         if (currententity->frame)
350         {
351                 if (base->alternate_anims)
352                         base = base->alternate_anims;
353         }
354         
355         if (!base->anim_total)
356                 return base;
357
358         original = base;
359
360         relative = (int)(cl.time*10) % base->anim_total;
361
362         count = 0;      
363         while (base->anim_min > relative || base->anim_max <= relative)
364         {
365                 base = base->anim_next;
366                 if (!base)
367                 {
368                         Con_Printf("R_TextureAnimation: broken cycle");
369                         return original;
370                 }
371                 if (++count > 100)
372                 {
373                         Con_Printf("R_TextureAnimation: infinite cycle");
374                         return original;
375                 }
376         }
377
378         return base;
379 }
380
381
382 /*
383 =============================================================
384
385         BRUSH MODELS
386
387 =============================================================
388 */
389
390
391 extern  int             solidskytexture;
392 extern  int             alphaskytexture;
393 extern  float   speedscale;             // for top sky and bottom sky
394
395 qboolean mtexenabled = false;
396
397 extern char skyname[];
398
399 void R_DynamicLightPoint(vec3_t color, vec3_t org, int *dlightbits);
400 //extern cvar_t r_dynamicwater;
401 extern int r_dlightframecount;
402 float   turbsin[256] =
403 {
404         #include "gl_warp_sin.h"
405 };
406 #define TURBSCALE (256.0 / (2 * M_PI))
407
408
409 void UploadLightmaps()
410 {
411         int i;
412         if (nosubimage || nosubimagefragments)
413         {
414                 for (i = 0;i < MAX_LIGHTMAPS;i++)
415                 {
416                         if (lightmapupdate[i][0] < lightmapupdate[i][1])
417                         {
418                                 glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
419                                 if (nosubimage)
420                                 {
421                                         if (lightmaprgba)
422                                                 glTexImage2D(GL_TEXTURE_2D, 0, 4, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
423                                         else
424                                                 glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
425                                 }
426                                 else
427                                 {
428                                         if (lightmaprgba)
429                                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 4 * lightmapupdate[i][0]));
430                                         else
431                                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, lightmapupdate[i][0], BLOCK_WIDTH, lightmapupdate[i][1] - lightmapupdate[i][0], GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i] + (BLOCK_WIDTH * 3 * lightmapupdate[i][0]));
432                                 }
433                         }
434                         lightmapupdate[i][0] = BLOCK_HEIGHT;
435                         lightmapupdate[i][1] = 0;
436                 }
437         }
438 }
439
440 /*
441 ================
442 DrawTextureChains
443 ================
444 */
445 extern qboolean hlbsp;
446 extern void R_Sky();
447 extern char skyname[];
448 void DrawTextureChains (void)
449 {
450         int             i, j, maps;
451         msurface_t      *s;
452         texture_t       *t;
453         glpoly_t        *p;
454         float           *v;
455         float           os = turbsin[(int)(realtime * TURBSCALE) & 255], ot = turbsin[(int)(realtime * TURBSCALE + 96.0) & 255];
456
457         // first the sky
458         skypolyclear();
459         for (j = 0;j < cl.worldmodel->numtextures;j++)
460         {
461                 if (!cl.worldmodel->textures[j] || !(s = cl.worldmodel->textures[j]->texturechain))
462                         continue;
463                 // LordHavoc: decide the render type only once, because the surface properties were determined by texture anyway
464                 // subdivided water surface warp
465                 if (s->flags & SURF_DRAWSKY)
466                 {
467                         cl.worldmodel->textures[j]->texturechain = NULL;
468                         t = R_TextureAnimation (cl.worldmodel->textures[j]);
469                         skyisvisible = true;
470                         if (!hlbsp) // LordHavoc: HalfLife maps have freaky skypolys...
471                         {
472                                 for (;s;s = s->texturechain)
473                                 {
474                                         for (p=s->polys ; p ; p=p->next)
475                                         {
476                                                 if (currentskypoly < MAX_SKYPOLYS && currentskyvert + p->numverts <= MAX_SKYVERTS)
477                                                 {
478                                                         skypoly[currentskypoly].firstvert = currentskyvert;
479                                                         skypoly[currentskypoly++].verts = p->numverts;
480                                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
481                                                         {
482                                                                 skyvert[currentskyvert].v[0] = v[0];
483                                                                 skyvert[currentskyvert].v[1] = v[1];
484                                                                 skyvert[currentskyvert++].v[2] = v[2];
485                                                         }
486                                                 }
487                                         }
488                                 }
489                         }
490                 }
491         }
492         skypolyrender(); // fogged sky polys, affects depth
493
494         if (skyname[0] && skyisvisible && !fogenabled)
495                 R_Sky(); // does not affect depth, draws over the sky polys
496
497         // then walls
498         wallpolyclear();
499         for (j = 0;j < cl.worldmodel->numtextures;j++)
500         {
501                 if (!cl.worldmodel->textures[j] || !(s = cl.worldmodel->textures[j]->texturechain))
502                         continue;
503                 if (!(s->flags & SURF_DRAWTURB))
504                 {
505                         cl.worldmodel->textures[j]->texturechain = NULL;
506                         t = R_TextureAnimation (cl.worldmodel->textures[j]);
507                         for (;s;s = s->texturechain)
508                         {
509                                 if (currentwallpoly < MAX_WALLPOLYS && currentwallvert < MAX_WALLVERTS && (currentwallvert + s->polys->numverts) <= MAX_WALLVERTS)
510                                 {
511                                         // check for lightmap modification
512                                         if (r_dynamic.value)
513                                         {
514                                                 if (s->dlightframe == r_framecount || s->cached_dlight || lighthalf != s->cached_lighthalf) // dynamic this frame or previously, or lighthalf changed
515                                                         R_UpdateLightmap(s, s->lightmaptexturenum);
516                                                 else
517                                                         for (maps = 0 ; maps < MAXLIGHTMAPS && s->styles[maps] != 255 ; maps++)
518                                                                 if (d_lightstylevalue[s->styles[maps]] != s->cached_light[maps])
519                                                                 {
520                                                                         R_UpdateLightmap(s, s->lightmaptexturenum);
521                                                                         break;
522                                                                 }
523                                         }
524                                         wallpoly[currentwallpoly].texnum = (unsigned short) t->gl_texturenum;
525                                         wallpoly[currentwallpoly].lighttexnum = (unsigned short) lightmap_textures + s->lightmaptexturenum;
526                                         wallpoly[currentwallpoly].glowtexnum = (unsigned short) t->gl_glowtexturenum;
527                                         wallpoly[currentwallpoly].firstvert = currentwallvert;
528                                         wallpoly[currentwallpoly++].verts = s->polys->numverts;
529                                         for (i = 0,v = s->polys->verts[0];i<s->polys->numverts;i++, v += VERTEXSIZE)
530                                         {
531                                                 wallvert[currentwallvert].vert[0] = v[0];
532                                                 wallvert[currentwallvert].vert[1] = v[1];
533                                                 wallvert[currentwallvert].vert[2] = v[2];
534                                                 wallvert[currentwallvert].s = v[3];
535                                                 wallvert[currentwallvert].t = v[4];
536                                                 wallvert[currentwallvert].u = v[5];
537                                                 wallvert[currentwallvert++].v = v[6];
538                                         }
539                                 }
540                         }
541                 }
542         }
543         UploadLightmaps();
544         wallpolyrender();
545
546         // then water (water gets diverted to transpoly list)
547         for (j = 0;j < cl.worldmodel->numtextures;j++)
548         {
549                 if (!cl.worldmodel->textures[j] || !(s = cl.worldmodel->textures[j]->texturechain))
550                         continue;
551                 cl.worldmodel->textures[j]->texturechain = NULL;
552                 t = R_TextureAnimation (cl.worldmodel->textures[j]);
553                 // LordHavoc: decide the render type only once, because the surface properties were determined by texture anyway
554                 // subdivided water surface warp
555                 if (s->flags & SURF_DRAWTURB)
556                 {
557                         int light, alpha, r = 0, g = 0, b = 0;
558                         vec3_t nv, shadecolor;
559                         alpha = s->flags & SURF_DRAWNOALPHA ? 255 : r_wateralpha.value*255.0f;
560                         light = false;
561                         if (s->flags & SURF_DRAWFULLBRIGHT)
562                                 r = g = b = lighthalf ? 128 : 255;
563                         else if (s->dlightframe == r_dlightframecount && r_dynamic.value)
564                                 light = true;
565                         else
566                                 r = g = b = lighthalf ? 64 : 128;
567                         if (r_waterripple.value)
568                         {
569                                 if (lighthalf)
570                                 {
571                                         if (light)
572                                         {
573                                                 for (;s;s = s->texturechain)
574                                                 {
575                                                         for (p=s->polys ; p ; p=p->next)
576                                                         {
577                                                                 // FIXME: could be a transparent water texture
578                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
579                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
580                                                                 {
581                                                                         nv[0] = v[0];
582                                                                         nv[1] = v[1];
583                                                                         nv[2] = v[2] + r_waterripple.value * turbsin[(int)((v[3]*0.125f+realtime) * TURBSCALE) & 255] * turbsin[(int)((v[4]*0.125f+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
584                                                                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
585                                                                         R_DynamicLightPoint(shadecolor, nv, s->dlightbits);
586                                                                         transpolyvert(nv[0], nv[1], nv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), (int) shadecolor[0] >> 1,(int) shadecolor[1] >> 1,(int) shadecolor[2] >> 1,alpha);
587                                                                 }
588                                                                 transpolyend();
589                                                         }
590                                                 }
591                                         }
592                                         else
593                                         {
594                                                 for (;s;s = s->texturechain)
595                                                 {
596                                                         for (p=s->polys ; p ; p=p->next)
597                                                         {
598                                                                 // FIXME: could be a transparent water texture
599                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
600                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
601                                                                 {
602                                                                         nv[0] = v[0];
603                                                                         nv[1] = v[1];
604                                                                         nv[2] = v[2] + r_waterripple.value * turbsin[(int)((v[3]*0.125f+realtime) * TURBSCALE) & 255] * turbsin[(int)((v[4]*0.125f+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
605                                                                         transpolyvert(nv[0], nv[1], nv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), r,g,b,alpha);
606                                                                 }
607                                                                 transpolyend();
608                                                         }
609                                                 }
610                                         }
611                                 }
612                                 else
613                                 {
614                                         if (light)
615                                         {
616                                                 for (;s;s = s->texturechain)
617                                                 {
618                                                         for (p=s->polys ; p ; p=p->next)
619                                                         {
620                                                                 // FIXME: could be a transparent water texture
621                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
622                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
623                                                                 {
624                                                                         nv[0] = v[0];
625                                                                         nv[1] = v[1];
626                                                                         nv[2] = v[2] + r_waterripple.value * turbsin[(int)((v[3]*0.125f+realtime) * TURBSCALE) & 255] * turbsin[(int)((v[4]*0.125f+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
627                                                                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
628                                                                         R_DynamicLightPoint(shadecolor, nv, s->dlightbits);
629                                                                         transpolyvert(nv[0], nv[1], nv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), shadecolor[0],shadecolor[1],shadecolor[2],alpha);
630                                                                 }
631                                                                 transpolyend();
632                                                         }
633                                                 }
634                                         }
635                                         else
636                                         {
637                                                 for (;s;s = s->texturechain)
638                                                 {
639                                                         for (p=s->polys ; p ; p=p->next)
640                                                         {
641                                                                 // FIXME: could be a transparent water texture
642                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
643                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
644                                                                 {
645                                                                         nv[0] = v[0];
646                                                                         nv[1] = v[1];
647                                                                         nv[2] = v[2] + r_waterripple.value * turbsin[(int)((v[3]*0.125f+realtime) * TURBSCALE) & 255] * turbsin[(int)((v[4]*0.125f+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
648                                                                         transpolyvert(nv[0], nv[1], nv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), r,g,b,alpha);
649                                                                 }
650                                                                 transpolyend();
651                                                         }
652                                                 }
653                                         }
654                                 }
655                         }
656                         else
657                         {
658                                 if (lighthalf)
659                                 {
660                                         if (light)
661                                         {
662                                                 for (;s;s = s->texturechain)
663                                                 {
664                                                         for (p=s->polys ; p ; p=p->next)
665                                                         {
666                                                                 // FIXME: could be a transparent water texture
667                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
668                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
669                                                                 {
670                                                                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
671                                                                         R_DynamicLightPoint(shadecolor, v, s->dlightbits);
672                                                                         transpolyvert(v[0], v[1], v[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), (int) shadecolor[0] >> 1,(int) shadecolor[1] >> 1,(int) shadecolor[2] >> 1,alpha);
673                                                                 }
674                                                                 transpolyend();
675                                                         }
676                                                 }
677                                         }
678                                         else
679                                         {
680                                                 for (;s;s = s->texturechain)
681                                                 {
682                                                         for (p=s->polys ; p ; p=p->next)
683                                                         {
684                                                                 // FIXME: could be a transparent water texture
685                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
686                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
687                                                                 {
688                                                                         transpolyvert(v[0], v[1], v[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), r,g,b,alpha);
689                                                                 }
690                                                                 transpolyend();
691                                                         }
692                                                 }
693                                         }
694                                 }
695                                 else
696                                 {
697                                         if (light)
698                                         {
699                                                 for (;s;s = s->texturechain)
700                                                 {
701                                                         for (p=s->polys ; p ; p=p->next)
702                                                         {
703                                                                 // FIXME: could be a transparent water texture
704                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
705                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
706                                                                 {
707                                                                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
708                                                                         R_DynamicLightPoint(shadecolor, v, s->dlightbits);
709                                                                         transpolyvert(v[0], v[1], v[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), shadecolor[0],shadecolor[1],shadecolor[2],alpha);
710                                                                 }
711                                                                 transpolyend();
712                                                         }
713                                                 }
714                                         }
715                                         else
716                                         {
717                                                 for (;s;s = s->texturechain)
718                                                 {
719                                                         for (p=s->polys ; p ; p=p->next)
720                                                         {
721                                                                 // FIXME: could be a transparent water texture
722                                                                 transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, TPOLYTYPE_ALPHA);
723                                                                 for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
724                                                                 {
725                                                                         transpolyvert(v[0], v[1], v[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), r,g,b,alpha);
726                                                                 }
727                                                                 transpolyend();
728                                                         }
729                                                 }
730                                         }
731                                 }
732                         }
733                 }
734         }
735 }
736
737 // LordHavoc: transparent brush models
738 extern int r_dlightframecount;
739 extern float modelalpha;
740 extern vec3_t shadecolor;
741 //qboolean R_CullBox (vec3_t mins, vec3_t maxs);
742 void R_DynamicLightPoint(vec3_t color, vec3_t org, int *dlightbits);
743 void R_DynamicLightPointNoMask(vec3_t color, vec3_t org);
744 void EmitWaterPolys (msurface_t *fa);
745 void R_MarkLights (vec3_t lightorigin, dlight_t *light, int bit, int bitindex, mnode_t *node);
746
747 /*
748 =================
749 R_DrawBrushModel
750 =================
751 */
752 void R_DrawBrushModel (entity_t *e)
753 {
754         int                     i, j, k, smax, tmax, size3, maps;
755         vec3_t          mins, maxs, nv;
756         msurface_t      *s;
757         mplane_t        *pplane;
758         model_t         *clmodel;
759         qboolean        rotated, vertexlit = false;
760         float           dot, *v, scale;
761         texture_t       *t;
762         byte            *lm;
763         float           os = turbsin[(int)(realtime * TURBSCALE) & 255], ot = turbsin[(int)(realtime * TURBSCALE + 96.0) & 255];
764
765         currententity = e;
766
767         clmodel = e->model;
768
769         if (e->angles[0] || e->angles[1] || e->angles[2])
770         {
771                 rotated = true;
772                 for (i=0 ; i<3 ; i++)
773                 {
774                         mins[i] = e->origin[i] - clmodel->radius;
775                         maxs[i] = e->origin[i] + clmodel->radius;
776                 }
777         }
778         else
779         {
780                 rotated = false;
781                 VectorAdd (e->origin, clmodel->mins, mins);
782                 VectorAdd (e->origin, clmodel->maxs, maxs);
783         }
784
785         if (R_CullBox (mins, maxs))
786                 return;
787
788         VectorSubtract (r_refdef.vieworg, e->origin, modelorg);
789         if (rotated)
790         {
791                 vec3_t  temp;
792                 vec3_t  forward, right, up;
793
794                 VectorCopy (modelorg, temp);
795                 AngleVectors (e->angles, forward, right, up);
796                 modelorg[0] = DotProduct (temp, forward);
797                 modelorg[1] = -DotProduct (temp, right);
798                 modelorg[2] = DotProduct (temp, up);
799         }
800
801         s = &clmodel->surfaces[clmodel->firstmodelsurface];
802
803 // calculate dynamic lighting for bmodel if it's not an
804 // instanced model
805         if (modelalpha == 1 && clmodel->firstmodelsurface != 0 && !(currententity->effects & EF_FULLBRIGHT) && currententity->colormod[0] == 1 && currententity->colormod[2] == 1 && currententity->colormod[2] == 1)
806         {
807 //              if (!gl_flashblend.value)
808 //              {
809                         vec3_t org;
810                         for (k=0 ; k<MAX_DLIGHTS ; k++)
811                         {
812                                 if ((cl_dlights[k].die < cl.time) || (!cl_dlights[k].radius))
813                                         continue;
814
815                                 VectorSubtract(cl_dlights[k].origin, currententity->origin, org);
816                                 R_MarkLights (org, &cl_dlights[k], 1<<(k&31), k >> 5, clmodel->nodes + clmodel->hulls[0].firstclipnode);
817                         }
818 //              }
819         }
820         else
821                 vertexlit = true;
822
823 e->angles[0] = -e->angles[0];   // stupid quake bug
824         softwaretransformforentity (e);
825 e->angles[0] = -e->angles[0];   // stupid quake bug
826
827         // draw texture
828         for (j = 0;j < clmodel->nummodelsurfaces;j++, s++)
829         {
830         // find which side of the node we are on
831                 pplane = s->plane;
832
833                 dot = DotProduct (modelorg, pplane->normal) - pplane->dist;
834
835         // draw the polygon
836                 if (((s->flags & SURF_PLANEBACK) && (dot < -BACKFACE_EPSILON)) ||
837                         (!(s->flags & SURF_PLANEBACK) && (dot > BACKFACE_EPSILON)))
838                 {
839                         if (s->flags & SURF_DRAWSKY)
840                                 continue;
841                         if (s->flags & SURF_DRAWTURB)
842                         {
843                                 glpoly_t        *p;
844                                 int                     light, alpha, r = 0, g = 0, b = 0;
845                                 vec3_t          shadecolor;
846
847                                 if (s->flags & SURF_DRAWNOALPHA)
848                                         alpha = modelalpha*255.0f;
849                                 else
850                                         alpha = r_wateralpha.value*modelalpha*255.0f;
851                                 light = false;
852                                 if (s->flags & SURF_DRAWFULLBRIGHT || currententity->effects & EF_FULLBRIGHT)
853                                 {
854                                         if (lighthalf)
855                                         {
856                                                 r = 128.0f * currententity->colormod[0];
857                                                 g = 128.0f * currententity->colormod[1];
858                                                 b = 128.0f * currententity->colormod[2];
859                                         }
860                                         else
861                                         {
862                                                 r = 255.0f * currententity->colormod[0];
863                                                 g = 255.0f * currententity->colormod[1];
864                                                 b = 255.0f * currententity->colormod[2];
865                                         }
866                                 }
867                                 else if (s->dlightframe == r_dlightframecount && r_dynamic.value)
868                                         light = true;
869                                 else
870                                 {
871                                         if (lighthalf)
872                                         {
873                                                 r = 64.0f * currententity->colormod[0];
874                                                 g = 64.0f * currententity->colormod[1];
875                                                 b = 64.0f * currententity->colormod[2];
876                                         }
877                                         else
878                                         {
879                                                 r = 128.0f * currententity->colormod[0];
880                                                 g = 128.0f * currententity->colormod[1];
881                                                 b = 128.0f * currententity->colormod[2];
882                                         }
883                                 }
884                                 for (p=s->polys ; p ; p=p->next)
885                                 {
886                                         // FIXME: could be a transparent water texture
887                                         transpolybegin(s->texinfo->texture->gl_texturenum, s->texinfo->texture->gl_glowtexturenum, 0, currententity->effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
888                                         for (i = 0,v = p->verts[0];i < p->numverts;i++, v += VERTEXSIZE)
889                                         {
890                                                 softwaretransform(v, nv);
891                                                 if (r_waterripple.value)
892                                                         nv[2] += r_waterripple.value * turbsin[(int)((v[3]*0.125f+realtime) * TURBSCALE) & 255] * turbsin[(int)((v[4]*0.125f+realtime) * TURBSCALE) & 255] * (1.0f / 64.0f);
893                                                 if (light)
894                                                 {
895                                                         shadecolor[0] = shadecolor[1] = shadecolor[2] = 128;
896                                                         R_DynamicLightPoint(shadecolor, nv, s->dlightbits);
897                                                         if (lighthalf)
898                                                         {
899                                                                 r = (int) ((float) (shadecolor[0] * currententity->colormod[0])) >> 1;
900                                                                 g = (int) ((float) (shadecolor[1] * currententity->colormod[1])) >> 1;
901                                                                 b = (int) ((float) (shadecolor[2] * currententity->colormod[2])) >> 1;
902                                                         }
903                                                         else
904                                                         {
905                                                                 r = (int) ((float) (shadecolor[0] * currententity->colormod[0]));
906                                                                 g = (int) ((float) (shadecolor[1] * currententity->colormod[1]));
907                                                                 b = (int) ((float) (shadecolor[2] * currententity->colormod[2]));
908                                                         }
909                                                 }
910                                                 transpolyvert(nv[0], nv[1], nv[2], (v[3] + os) * (1.0f/64.0f), (v[4] + ot) * (1.0f/64.0f), r,g,b,alpha);
911                                         }
912                                         transpolyend();
913                                 }
914                                 continue;
915                         }
916                         t = R_TextureAnimation (s->texinfo->texture);
917                         v = s->polys->verts[0];
918                         if (vertexlit || s->texinfo->texture->transparent)
919                         {
920                                 // FIXME: could be a transparent water texture
921                                 transpolybegin(t->gl_texturenum, t->gl_glowtexturenum, 0, currententity->effects & EF_ADDITIVE ? TPOLYTYPE_ADD : TPOLYTYPE_ALPHA);
922                                 if ((currententity->effects & EF_FULLBRIGHT) || !s->samples)
923                                 {
924                                         for (i = 0;i < s->polys->numverts;i++, v += VERTEXSIZE)
925                                         {
926                                                 softwaretransform(v, nv);
927                                                 transpolyvert(nv[0], nv[1], nv[2], v[3], v[4], 255,255,255,modelalpha*255.0f);
928                                         }
929                                 }
930                                 else
931                                 {
932                                         smax = (s->extents[0]>>4)+1;
933                                         tmax = (s->extents[1]>>4)+1;
934                                         size3 = smax*tmax*3; // *3 for colored lighting
935                                         for (i = 0;i < s->polys->numverts;i++, v += VERTEXSIZE)
936                                         {
937                                                 shadecolor[0] = shadecolor[1] = shadecolor[2] = 0;
938                                                 lm = (byte *)((long) s->samples + ((int) v[8] * smax + (int) v[7]) * 3); // LordHavoc: *3 for colored lighting
939                                                 for (maps = 0;maps < MAXLIGHTMAPS && s->styles[maps] != 255;maps++)
940                                                 {
941                                                         scale = d_lightstylevalue[s->styles[maps]] * (1.0 / 128.0);
942                                                         shadecolor[0] += lm[0] * scale;
943                                                         shadecolor[1] += lm[1] * scale;
944                                                         shadecolor[2] += lm[2] * scale;
945                                                         lm += size3; // LordHavoc: *3 for colored lighting
946                                                 }
947                                                 softwaretransform(v, nv);
948                                                 R_DynamicLightPointNoMask(shadecolor, nv); // LordHavoc: dynamic lighting
949                                                 if (lighthalf)
950                                                 {
951                                                         transpolyvert(nv[0], nv[1], nv[2], v[3], v[4], (int) shadecolor[0] >> 1, (int) shadecolor[1] >> 1, (int) shadecolor[2] >> 1, modelalpha*255.0f);
952                                                 }
953                                                 else
954                                                 {
955                                                         transpolyvert(nv[0], nv[1], nv[2], v[3], v[4], shadecolor[0], shadecolor[1], shadecolor[2], modelalpha*255.0f);
956                                                 }
957                                         }
958                                 }
959                                 transpolyend();
960                         }
961                         else
962                         {
963                                 // check for lightmap modification
964                                 if (r_dynamic.value)
965                                 {
966                                         if (s->dlightframe == r_framecount || s->cached_dlight || lighthalf != s->cached_lighthalf) // dynamic this frame or previously, or lighthalf changed
967                                                 R_UpdateLightmap(s, s->lightmaptexturenum);
968                                         else
969                                                 for (maps = 0 ; maps < MAXLIGHTMAPS && s->styles[maps] != 255 ; maps++)
970                                                         if (d_lightstylevalue[s->styles[maps]] != s->cached_light[maps])
971                                                         {
972                                                                 R_UpdateLightmap(s, s->lightmaptexturenum);
973                                                                 break;
974                                                         }
975                                 }
976                                 if (currentwallpoly < MAX_WALLPOLYS && (currentwallvert + s->polys->numverts) <= MAX_WALLVERTS)
977                                 {
978                                         wallpoly[currentwallpoly].texnum = (unsigned short) t->gl_texturenum;
979                                         wallpoly[currentwallpoly].lighttexnum = (unsigned short) lightmap_textures + s->lightmaptexturenum;
980                                         wallpoly[currentwallpoly].glowtexnum = (unsigned short) t->gl_glowtexturenum;
981                                         wallpoly[currentwallpoly].firstvert = currentwallvert;
982                                         wallpoly[currentwallpoly++].verts = s->polys->numverts;
983                                         for (i = 0;i<s->polys->numverts;i++, v += VERTEXSIZE)
984                                         {
985                                                 softwaretransform(v, wallvert[currentwallvert].vert);
986                                                 wallvert[currentwallvert].s = v[3];
987                                                 wallvert[currentwallvert].t = v[4];
988                                                 wallvert[currentwallvert].u = v[5];
989                                                 wallvert[currentwallvert++].v = v[6];
990                                         }
991                                 }
992                         }
993                 }
994         }
995         UploadLightmaps();
996 }
997
998 /*
999 =============================================================
1000
1001         WORLD MODEL
1002
1003 =============================================================
1004 */
1005
1006 void R_StoreEfrags (efrag_t **ppefrag);
1007
1008 /*
1009 ================
1010 R_RecursiveWorldNode
1011 ================
1012 */
1013 //extern qboolean R_CullBox (vec3_t mins, vec3_t maxs);
1014 /*
1015 void R_RecursiveWorldNode (mnode_t *node)
1016 {
1017         int                     c, side;
1018         double          dot;
1019
1020 loc0:
1021 // if a leaf node, draw stuff
1022         if (node->contents < 0)
1023         {
1024                 mleaf_t         *pleaf;
1025                 pleaf = (mleaf_t *)node;
1026
1027                 if (c = pleaf->nummarksurfaces)
1028                 {
1029                         msurface_t      **mark;
1030                         mark = pleaf->firstmarksurface;
1031                         do
1032                         {
1033                                 (*mark)->visframe = r_framecount;
1034                                 mark++;
1035                         } while (--c);
1036                 }
1037
1038         // deal with model fragments in this leaf
1039                 if (pleaf->efrags)
1040                         R_StoreEfrags (&pleaf->efrags);
1041
1042                 return;
1043         }
1044
1045 // node is just a decision point, so go down the apropriate sides
1046
1047 // find which side of the node we are on
1048         dot = (node->plane->type < 3 ? modelorg[node->plane->type] : DotProduct (modelorg, node->plane->normal)) - node->plane->dist;
1049
1050 // recurse down the children, front side first
1051         side = dot < 0;
1052         // LordHavoc: save a stack frame by avoiding a call
1053 //      if (node->children[side]->contents != CONTENTS_SOLID && node->children[side]->visframe == r_visframecount && !R_CullBox (node->children[side]->minmaxs, node->children[side]->minmaxs+3))
1054         // LordHavoc: inlined further to reduce conditions
1055         if (node->children[side]->contents != CONTENTS_SOLID
1056          && node->children[side]->visframe == r_visframecount
1057          && frustum[0].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[0]) != 2
1058          && frustum[1].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[1]) != 2
1059          && frustum[2].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[2]) != 2
1060          && frustum[3].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[3]) != 2)
1061                 R_RecursiveWorldNode (node->children[side]);
1062
1063         // backside
1064         side = dot >= 0;
1065 // draw stuff
1066         if (c = node->numsurfaces)
1067         {
1068                 msurface_t      *surf;
1069                 surf = cl.worldmodel->surfaces + node->firstsurface;
1070
1071                 // LordHavoc: caused a crash due to texsort (it could render twice...)
1072                 // back side
1073                 //side = dot >= -BACKFACE_EPSILON;
1074                 if (dot < 0)
1075                 {
1076                         for (;c;c--, surf++)
1077                         {
1078                                 if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
1079                                 {
1080                                         surf->texturechain = surf->texinfo->texture->texturechain;
1081                                         surf->texinfo->texture->texturechain = surf;
1082                                 }
1083                         }
1084                 }
1085                 else
1086                 {
1087                         for (;c;c--, surf++)
1088                         {
1089                                 if (surf->visframe == r_framecount && (!(surf->flags & SURF_PLANEBACK)))
1090                                 {
1091                                         surf->texturechain = surf->texinfo->texture->texturechain;
1092                                         surf->texinfo->texture->texturechain = surf;
1093                                 }
1094                         }
1095                 }
1096         }
1097
1098 // recurse down the back side
1099         // LordHavoc: save a stack frame by avoiding a call
1100 //      if (node->children[side]->contents != CONTENTS_SOLID && node->children[side]->visframe == r_visframecount && !R_CullBox (node->children[side]->minmaxs, node->children[side]->minmaxs+3))
1101         // LordHavoc: inlined further to reduce conditions
1102         if (node->children[side]->contents != CONTENTS_SOLID
1103          && node->children[side]->visframe == r_visframecount
1104          && frustum[0].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[0]) != 2
1105          && frustum[1].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[1]) != 2
1106          && frustum[2].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[2]) != 2
1107          && frustum[3].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[3]) != 2)
1108         {
1109                 node = node->children[side];
1110                 goto loc0;
1111         }
1112 //              R_RecursiveWorldNode (node->children[side]);
1113 }
1114 */
1115
1116 extern int c_nodes;
1117 void R_WorldNode ()
1118 {
1119         int             c, side;
1120         double  dot;
1121         struct
1122         {
1123                 double dot;
1124                 mnode_t *node;
1125         } nodestack[1024];
1126         int             s = 0;
1127         mnode_t *node;
1128
1129         if (!(node = cl.worldmodel->nodes))
1130                 return;
1131
1132         while(1)
1133         {
1134         // if a leaf node, draw stuff
1135                 c_nodes++;
1136                 if (node->contents < 0)
1137                 {
1138                         if (node->contents != CONTENTS_SOLID)
1139                         {
1140                                 mleaf_t         *pleaf;
1141                                 pleaf = (mleaf_t *)node;
1142
1143                                 if ((c = pleaf->nummarksurfaces))
1144                                 {
1145                                         msurface_t      **mark;
1146                                         mark = pleaf->firstmarksurface;
1147                                         do
1148                                         {
1149                                                 (*mark)->visframe = r_framecount;
1150                                                 mark++;
1151                                         } while (--c);
1152                                 }
1153
1154                                 // deal with model fragments in this leaf
1155                                 if (pleaf->efrags)
1156                                         R_StoreEfrags (&pleaf->efrags);
1157                         }
1158
1159                         if (!s)
1160                                 break;
1161                         node = nodestack[--s].node;
1162                         dot = nodestack[s].dot;
1163                         goto loc0;
1164                 }
1165
1166         // node is just a decision point, so go down the apropriate sides
1167
1168         // find which side of the node we are on
1169                 dot = (node->plane->type < 3 ? modelorg[node->plane->type] : DotProduct (modelorg, node->plane->normal)) - node->plane->dist;
1170
1171         // recurse down the children, front side first
1172                 side = dot < 0;
1173                 if (node->children[side]->visframe == r_visframecount
1174                  && frustum[0].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[0]) != 2
1175                  && frustum[1].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[1]) != 2
1176                  && frustum[2].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[2]) != 2
1177                  && frustum[3].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[3]) != 2)
1178                 {
1179                         nodestack[s].node = node;
1180                         nodestack[s++].dot = dot;
1181                         node = node->children[side];
1182                         continue;
1183                 }
1184 loc0:
1185
1186                 // backside
1187                 side = dot >= 0;
1188         // draw stuff
1189                 if ((c = node->numsurfaces))
1190                 {
1191                         msurface_t      *surf;
1192                         surf = cl.worldmodel->surfaces + node->firstsurface;
1193
1194                         if (side)
1195                         {
1196                                 for (;c;c--, surf++)
1197                                 {
1198                                         if (surf->visframe == r_framecount && !(surf->flags & SURF_PLANEBACK))
1199                                         {
1200                                                 surf->texturechain = surf->texinfo->texture->texturechain;
1201                                                 surf->texinfo->texture->texturechain = surf;
1202                                         }
1203                                 }
1204                         }
1205                         else
1206                         {
1207                                 for (;c;c--, surf++)
1208                                 {
1209                                         if (surf->visframe == r_framecount && (surf->flags & SURF_PLANEBACK))
1210                                         {
1211                                                 surf->texturechain = surf->texinfo->texture->texturechain;
1212                                                 surf->texinfo->texture->texturechain = surf;
1213                                         }
1214                                 }
1215                         }
1216                 }
1217
1218         // recurse down the back side
1219                 if (node->children[side]->visframe == r_visframecount
1220                  && frustum[0].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[0]) != 2
1221                  && frustum[1].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[1]) != 2
1222                  && frustum[2].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[2]) != 2
1223                  && frustum[3].BoxOnPlaneSideFunc(node->children[side]->minmaxs, node->children[side]->minmaxs+3, &frustum[3]) != 2)
1224                 {
1225                         node = node->children[side];
1226                         continue;
1227                 }
1228
1229                 if (!s)
1230                         break;
1231                 node = nodestack[--s].node;
1232                 dot = nodestack[s].dot;
1233                 goto loc0;
1234         }
1235 }
1236
1237
1238 /*
1239 =============
1240 R_DrawWorld
1241 =============
1242 */
1243 void R_DrawWorld (void)
1244 {
1245         entity_t        ent;
1246
1247         memset (&ent, 0, sizeof(ent));
1248         ent.model = cl.worldmodel;
1249         ent.colormod[0] = ent.colormod[1] = ent.colormod[2] = 1;
1250         modelalpha = ent.alpha = 1;
1251         ent.scale = 1;
1252
1253         VectorCopy (r_refdef.vieworg, modelorg);
1254
1255         currententity = &ent;
1256
1257         softwaretransformidentity(); // LordHavoc: clear transform
1258         skyisvisible = false;
1259
1260         if (cl.worldmodel)
1261                 R_WorldNode ();
1262
1263         glClear (GL_DEPTH_BUFFER_BIT);
1264
1265         DrawTextureChains ();
1266
1267         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
1268         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1269 }
1270
1271
1272 /*
1273 ===============
1274 R_MarkLeaves
1275 ===============
1276 */
1277 void R_MarkLeaves (void)
1278 {
1279         byte    *vis;
1280         mnode_t *node;
1281         int             i;
1282
1283         if (r_oldviewleaf == r_viewleaf && !r_novis.value)
1284                 return;
1285         
1286         r_visframecount++;
1287         r_oldviewleaf = r_viewleaf;
1288
1289         if (r_novis.value)
1290         {
1291                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1292                 {
1293                         node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1294                         do
1295                         {
1296                                 if (node->visframe == r_visframecount)
1297                                         break;
1298                                 node->visframe = r_visframecount;
1299                                 node = node->parent;
1300                         } while (node);
1301                 }
1302         }
1303         else
1304         {
1305                 vis = Mod_LeafPVS (r_viewleaf, cl.worldmodel);
1306                 
1307                 for (i=0 ; i<cl.worldmodel->numleafs ; i++)
1308                 {
1309                         if (vis[i>>3] & (1<<(i&7)))
1310                         {
1311                                 node = (mnode_t *)&cl.worldmodel->leafs[i+1];
1312                                 do
1313                                 {
1314                                         if (node->visframe == r_visframecount)
1315                                                 break;
1316                                         node->visframe = r_visframecount;
1317                                         node = node->parent;
1318                                 } while (node);
1319                         }
1320                 }
1321         }
1322 }
1323
1324
1325
1326 /*
1327 =============================================================================
1328
1329   LIGHTMAP ALLOCATION
1330
1331 =============================================================================
1332 */
1333
1334 // returns a texture number and the position inside it
1335 int AllocBlock (int w, int h, int *x, int *y)
1336 {
1337         int             i, j;
1338         int             best, best2;
1339         int             texnum;
1340
1341         for (texnum=0 ; texnum<MAX_LIGHTMAPS ; texnum++)
1342         {
1343                 best = BLOCK_HEIGHT;
1344
1345                 for (i=0 ; i<BLOCK_WIDTH-w ; i+=lightmapalign) // LordHavoc: NVIDIA has broken subimage, so align the lightmaps
1346                 {
1347                         best2 = 0;
1348
1349                         for (j=0 ; j<w ; j++)
1350                         {
1351                                 if (allocated[texnum][i+j] >= best)
1352                                         break;
1353                                 if (allocated[texnum][i+j] > best2)
1354                                         best2 = allocated[texnum][i+j];
1355                         }
1356                         if (j == w)
1357                         {       // this is a valid spot
1358                                 *x = i;
1359                                 *y = best = best2;
1360                         }
1361                 }
1362
1363                 if (best + h > BLOCK_HEIGHT)
1364                         continue;
1365
1366                 if (nosubimagefragments || nosubimage)
1367                 {
1368                         if (!lightmaps[texnum])
1369                                 lightmaps[texnum] = calloc(BLOCK_WIDTH*BLOCK_HEIGHT*4, 1);
1370                 }
1371                 // LordHavoc: clear texture to blank image, fragments are uploaded using subimage
1372                 else if (!allocated[texnum][0])
1373                 {
1374                         byte blank[BLOCK_WIDTH*BLOCK_HEIGHT*3];
1375                         memset(blank, 0, sizeof(blank));
1376                         glBindTexture(GL_TEXTURE_2D, lightmap_textures + texnum);
1377                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1378                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1379                         if (lightmaprgba)
1380                                 glTexImage2D (GL_TEXTURE_2D, 0, 4, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, blank);
1381                         else
1382                                 glTexImage2D (GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, blank);
1383                 }
1384
1385                 for (i=0 ; i<w ; i++)
1386                         allocated[texnum][*x + i] = best + h;
1387
1388                 return texnum;
1389         }
1390
1391         Sys_Error ("AllocBlock: full");
1392         return 0;
1393 }
1394
1395
1396 mvertex_t       *r_pcurrentvertbase;
1397 model_t         *currentmodel;
1398
1399 int     nColinElim;
1400
1401 /*
1402 ================
1403 BuildSurfaceDisplayList
1404 ================
1405 */
1406 void BuildSurfaceDisplayList (msurface_t *fa)
1407 {
1408         int                     i, lindex, lnumverts;
1409         medge_t         *pedges, *r_pedge;
1410         int                     vertpage;
1411         float           *vec;
1412         float           s, t;
1413         glpoly_t        *poly;
1414
1415 // reconstruct the polygon
1416         pedges = currentmodel->edges;
1417         lnumverts = fa->numedges;
1418         vertpage = 0;
1419
1420         //
1421         // draw texture
1422         //
1423         poly = Hunk_Alloc (sizeof(glpoly_t) + (lnumverts-4) * VERTEXSIZE*sizeof(float));
1424         poly->next = fa->polys;
1425         poly->flags = fa->flags;
1426         fa->polys = poly;
1427         poly->numverts = lnumverts;
1428
1429         for (i=0 ; i<lnumverts ; i++)
1430         {
1431                 lindex = currentmodel->surfedges[fa->firstedge + i];
1432
1433                 if (lindex > 0)
1434                 {
1435                         r_pedge = &pedges[lindex];
1436                         vec = r_pcurrentvertbase[r_pedge->v[0]].position;
1437                 }
1438                 else
1439                 {
1440                         r_pedge = &pedges[-lindex];
1441                         vec = r_pcurrentvertbase[r_pedge->v[1]].position;
1442                 }
1443                 s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
1444                 s /= fa->texinfo->texture->width;
1445
1446                 t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
1447                 t /= fa->texinfo->texture->height;
1448
1449                 VectorCopy (vec, poly->verts[i]);
1450                 poly->verts[i][3] = s;
1451                 poly->verts[i][4] = t;
1452
1453                 //
1454                 // lightmap texture coordinates
1455                 //
1456                 s = DotProduct (vec, fa->texinfo->vecs[0]) + fa->texinfo->vecs[0][3];
1457                 s -= fa->texturemins[0];
1458                 poly->verts[i][7] = bound(0l, ((int)s>>4), (fa->extents[0]>>4)); // LordHavoc: raw lightmap coordinates
1459                 s += fa->light_s*16;
1460                 s += 8;
1461                 s /= BLOCK_WIDTH*16; //fa->texinfo->texture->width;
1462
1463                 t = DotProduct (vec, fa->texinfo->vecs[1]) + fa->texinfo->vecs[1][3];
1464                 t -= fa->texturemins[1];
1465                 poly->verts[i][8] = bound(0l, ((int)t>>4), (fa->extents[1]>>4)); // LordHavoc: raw lightmap coordinates
1466                 t += fa->light_t*16;
1467                 t += 8;
1468                 t /= BLOCK_HEIGHT*16; //fa->texinfo->texture->height;
1469
1470                 poly->verts[i][5] = s;
1471                 poly->verts[i][6] = t;
1472         }
1473
1474         //
1475         // remove co-linear points - Ed
1476         //
1477         /*
1478         if (!gl_keeptjunctions.value)
1479         {
1480                 for (i = 0 ; i < lnumverts ; ++i)
1481                 {
1482                         vec3_t v1, v2;
1483                         float *prev, *this, *next;
1484
1485                         prev = poly->verts[(i + lnumverts - 1) % lnumverts];
1486                         this = poly->verts[i];
1487                         next = poly->verts[(i + 1) % lnumverts];
1488
1489                         VectorSubtract( this, prev, v1 );
1490                         VectorNormalize( v1 );
1491                         VectorSubtract( next, prev, v2 );
1492                         VectorNormalize( v2 );
1493
1494                         // skip co-linear points
1495                         #define COLINEAR_EPSILON 0.001
1496                         if ((fabs( v1[0] - v2[0] ) <= COLINEAR_EPSILON) &&
1497                                 (fabs( v1[1] - v2[1] ) <= COLINEAR_EPSILON) && 
1498                                 (fabs( v1[2] - v2[2] ) <= COLINEAR_EPSILON))
1499                         {
1500                                 int j;
1501                                 for (j = i + 1; j < lnumverts; ++j)
1502                                 {
1503                                         int k;
1504                                         for (k = 0; k < VERTEXSIZE; ++k)
1505                                                 poly->verts[j - 1][k] = poly->verts[j][k];
1506                                 }
1507                                 --lnumverts;
1508                                 ++nColinElim;
1509                                 // retry next vertex next time, which is now current vertex
1510                                 --i;
1511                         }
1512                 }
1513         }
1514         */
1515         poly->numverts = lnumverts;
1516
1517 }
1518
1519 /*
1520 ========================
1521 GL_CreateSurfaceLightmap
1522 ========================
1523 */
1524 void GL_CreateSurfaceLightmap (msurface_t *surf)
1525 {
1526         int             smax, tmax;
1527
1528         if (surf->flags & (SURF_DRAWSKY|SURF_DRAWTURB))
1529                 return;
1530
1531         smax = (surf->extents[0]>>4)+1;
1532         tmax = (surf->extents[1]>>4)+1;
1533
1534         surf->lightmaptexturenum = AllocBlock (smax, tmax, &surf->light_s, &surf->light_t);
1535         if (nosubimage || nosubimagefragments)
1536                 return;
1537         glBindTexture(GL_TEXTURE_2D, lightmap_textures + surf->lightmaptexturenum);
1538         smax = ((surf->extents[0]>>4)+lightmapalign) & lightmapalignmask;
1539         if (lightmaprgba)
1540         {
1541                 R_BuildLightMap (surf, templight, smax * 4);
1542                 glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGBA, GL_UNSIGNED_BYTE, templight);
1543         }
1544         else
1545         {
1546                 R_BuildLightMap (surf, templight, smax * 3);
1547                 glTexSubImage2D(GL_TEXTURE_2D, 0, surf->light_s, surf->light_t, smax, tmax, GL_RGB , GL_UNSIGNED_BYTE, templight);
1548         }
1549 }
1550
1551
1552 /*
1553 ==================
1554 GL_BuildLightmaps
1555
1556 Builds the lightmap texture
1557 with all the surfaces from all brush models
1558 ==================
1559 */
1560 void GL_BuildLightmaps (void)
1561 {
1562         int             i, j;
1563         model_t *m;
1564
1565         memset (allocated, 0, sizeof(allocated));
1566
1567         r_framecount = 1;               // no dlightcache
1568
1569         if (gl_nosubimagefragments.value)
1570                 nosubimagefragments = 1;
1571         else
1572                 nosubimagefragments = 0;
1573
1574         if (gl_nosubimage.value)
1575                 nosubimage = 1;
1576         else
1577                 nosubimage = 0;
1578
1579         if (gl_lightmaprgba.value)
1580         {
1581                 lightmaprgba = true;
1582                 lightmapbytes = 4;
1583         }
1584         else
1585         {
1586                 lightmaprgba = false;
1587                 lightmapbytes = 3;
1588         }
1589
1590         // LordHavoc: NVIDIA seems to have a broken glTexSubImage2D,
1591         //            it needs to be aligned on 4 pixel boundaries...
1592         //            so I implemented an adjustable lightmap alignment
1593         if (gl_lightmapalign.value < 1)
1594                 gl_lightmapalign.value = 1;
1595         if (gl_lightmapalign.value > 16)
1596                 gl_lightmapalign.value = 16;
1597         lightmapalign = 1;
1598         while (lightmapalign < gl_lightmapalign.value)
1599                 lightmapalign <<= 1;
1600         gl_lightmapalign.value = lightmapalign;
1601         lightmapalignmask = ~(lightmapalign - 1);
1602         if (nosubimagefragments || nosubimage)
1603         {
1604                 lightmapalign = 1;
1605                 lightmapalignmask = ~0;
1606         }
1607
1608         if (!lightmap_textures)
1609         {
1610                 lightmap_textures = texture_extension_number;
1611                 texture_extension_number += MAX_LIGHTMAPS;
1612         }
1613
1614         for (j=1 ; j<MAX_MODELS ; j++)
1615         {
1616                 m = cl.model_precache[j];
1617                 if (!m)
1618                         break;
1619                 if (m->name[0] == '*')
1620                         continue;
1621                 r_pcurrentvertbase = m->vertexes;
1622                 currentmodel = m;
1623                 for (i=0 ; i<m->numsurfaces ; i++)
1624                 {
1625                         if ( m->surfaces[i].flags & SURF_DRAWTURB )
1626                                 continue;
1627                         if ( m->surfaces[i].flags & SURF_DRAWSKY )
1628                                 continue;
1629                         GL_CreateSurfaceLightmap (m->surfaces + i);
1630                         BuildSurfaceDisplayList (m->surfaces + i);
1631                 }
1632         }
1633
1634         if (nosubimage || nosubimagefragments)
1635         {
1636                 if (gl_mtexable)
1637                         qglSelectTexture(gl_mtex_enum+1);
1638                 for (i = 0;i < MAX_LIGHTMAPS;i++)
1639                 {
1640                         if (!allocated[i][0])
1641                                 break;
1642                         lightmapupdate[i][0] = BLOCK_HEIGHT;
1643                         lightmapupdate[i][1] = 0;
1644                         glBindTexture(GL_TEXTURE_2D, lightmap_textures + i);
1645                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1646                         glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1647                         if (lightmaprgba)
1648                                 glTexImage2D(GL_TEXTURE_2D, 0, 4, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGBA, GL_UNSIGNED_BYTE, lightmaps[i]);
1649                         else
1650                                 glTexImage2D(GL_TEXTURE_2D, 0, 3, BLOCK_WIDTH, BLOCK_HEIGHT, 0, GL_RGB, GL_UNSIGNED_BYTE, lightmaps[i]);
1651                 }
1652                 if (gl_mtexable)
1653                         qglSelectTexture(gl_mtex_enum+0);
1654         }
1655 }
1656