gl backend now has functions for color array and flat color states (GL_UseColorArray...
[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 #define MAX_LIGHTMAP_SIZE 256
25
26 static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
27 static float floatblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
28
29 static qbyte templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
30
31 cvar_t r_ambient = {0, "r_ambient", "0"};
32 cvar_t r_vertexsurfaces = {0, "r_vertexsurfaces", "0"};
33 cvar_t r_dlightmap = {CVAR_SAVE, "r_dlightmap", "1"};
34 cvar_t r_drawportals = {0, "r_drawportals", "0"};
35 cvar_t r_testvis = {0, "r_testvis", "0"};
36 cvar_t r_floatbuildlightmap = {0, "r_floatbuildlightmap", "0"};
37 cvar_t r_detailtextures = {CVAR_SAVE, "r_detailtextures", "1"};
38 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "0"};
39
40 static int dlightdivtable[32768];
41
42 // variables used by R_PVSUpdate
43 int r_pvsframecount = 0;
44 mleaf_t *r_pvsviewleaf = NULL;
45 int r_pvsviewleafnovis = 0;
46
47 static int R_IntAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
48 {
49         int sdtable[256], lnum, td, maxdist, maxdist2, maxdist3, i, s, t, smax, tmax, smax3, red, green, blue, lit, dist2, impacts, impactt, subtract, k;
50         unsigned int *bl;
51         float dist, impact[3], local[3];
52
53         lit = false;
54
55         smax = (surf->extents[0] >> 4) + 1;
56         tmax = (surf->extents[1] >> 4) + 1;
57         smax3 = smax * 3;
58
59         for (lnum = 0; lnum < r_numdlights; lnum++)
60         {
61                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
62                         continue;                                       // not lit by this light
63
64                 Matrix4x4_Transform(matrix, r_dlight[lnum].origin, local);
65                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
66
67                 // for comparisons to minimum acceptable light
68                 // compensate for LIGHTOFFSET
69                 maxdist = (int) r_dlight[lnum].cullradius2 + LIGHTOFFSET;
70
71                 dist2 = dist * dist;
72                 dist2 += LIGHTOFFSET;
73                 if (dist2 >= maxdist)
74                         continue;
75
76                 if (surf->plane->type < 3)
77                 {
78                         VectorCopy(local, impact);
79                         impact[surf->plane->type] -= dist;
80                 }
81                 else
82                 {
83                         impact[0] = local[0] - surf->plane->normal[0] * dist;
84                         impact[1] = local[1] - surf->plane->normal[1] * dist;
85                         impact[2] = local[2] - surf->plane->normal[2] * dist;
86                 }
87
88                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
89                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
90
91                 s = bound(0, impacts, smax * 16) - impacts;
92                 t = bound(0, impactt, tmax * 16) - impactt;
93                 i = s * s + t * t + dist2;
94                 if (i > maxdist)
95                         continue;
96
97                 // reduce calculations
98                 for (s = 0, i = impacts; s < smax; s++, i -= 16)
99                         sdtable[s] = i * i + dist2;
100
101                 maxdist3 = maxdist - dist2;
102
103                 // convert to 8.8 blocklights format
104                 red = r_dlight[lnum].light[0] * (1.0f / 128.0f);
105                 green = r_dlight[lnum].light[1] * (1.0f / 128.0f);
106                 blue = r_dlight[lnum].light[2] * (1.0f / 128.0f);
107                 subtract = (int) (r_dlight[lnum].subtract * 4194304.0f);
108                 bl = intblocklights;
109
110                 i = impactt;
111                 for (t = 0;t < tmax;t++, i -= 16)
112                 {
113                         td = i * i;
114                         // make sure some part of it is visible on this line
115                         if (td < maxdist3)
116                         {
117                                 maxdist2 = maxdist - td;
118                                 for (s = 0;s < smax;s++)
119                                 {
120                                         if (sdtable[s] < maxdist2)
121                                         {
122                                                 k = dlightdivtable[(sdtable[s] + td) >> 7] - subtract;
123                                                 if (k > 0)
124                                                 {
125                                                         bl[0] += (red   * k);
126                                                         bl[1] += (green * k);
127                                                         bl[2] += (blue  * k);
128                                                         lit = true;
129                                                 }
130                                         }
131                                         bl += 3;
132                                 }
133                         }
134                         else // skip line
135                                 bl += smax3;
136                 }
137         }
138         return lit;
139 }
140
141 static int R_FloatAddDynamicLights (const matrix4x4_t *matrix, msurface_t *surf)
142 {
143         int lnum, s, t, smax, tmax, smax3, lit, impacts, impactt;
144         float sdtable[256], *bl, k, dist, dist2, maxdist, maxdist2, maxdist3, td1, td, red, green, blue, impact[3], local[3], subtract;
145
146         lit = false;
147
148         smax = (surf->extents[0] >> 4) + 1;
149         tmax = (surf->extents[1] >> 4) + 1;
150         smax3 = smax * 3;
151
152         for (lnum = 0; lnum < r_numdlights; lnum++)
153         {
154                 if (!(surf->dlightbits[lnum >> 5] & (1 << (lnum & 31))))
155                         continue;                                       // not lit by this light
156
157                 Matrix4x4_Transform(matrix, r_dlight[lnum].origin, local);
158                 dist = DotProduct (local, surf->plane->normal) - surf->plane->dist;
159
160                 // for comparisons to minimum acceptable light
161                 // compensate for LIGHTOFFSET
162                 maxdist = (int) r_dlight[lnum].cullradius2 + LIGHTOFFSET;
163
164                 dist2 = dist * dist;
165                 dist2 += LIGHTOFFSET;
166                 if (dist2 >= maxdist)
167                         continue;
168
169                 if (surf->plane->type < 3)
170                 {
171                         VectorCopy(local, impact);
172                         impact[surf->plane->type] -= dist;
173                 }
174                 else
175                 {
176                         impact[0] = local[0] - surf->plane->normal[0] * dist;
177                         impact[1] = local[1] - surf->plane->normal[1] * dist;
178                         impact[2] = local[2] - surf->plane->normal[2] * dist;
179                 }
180
181                 impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
182                 impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
183
184                 td = bound(0, impacts, smax * 16) - impacts;
185                 td1 = bound(0, impactt, tmax * 16) - impactt;
186                 td = td * td + td1 * td1 + dist2;
187                 if (td > maxdist)
188                         continue;
189
190                 // reduce calculations
191                 for (s = 0, td1 = impacts; s < smax; s++, td1 -= 16.0f)
192                         sdtable[s] = td1 * td1 + dist2;
193
194                 maxdist3 = maxdist - dist2;
195
196                 // convert to 8.8 blocklights format
197                 red = r_dlight[lnum].light[0];
198                 green = r_dlight[lnum].light[1];
199                 blue = r_dlight[lnum].light[2];
200                 subtract = r_dlight[lnum].subtract * 32768.0f;
201                 bl = floatblocklights;
202
203                 td1 = impactt;
204                 for (t = 0;t < tmax;t++, td1 -= 16.0f)
205                 {
206                         td = td1 * td1;
207                         // make sure some part of it is visible on this line
208                         if (td < maxdist3)
209                         {
210                                 maxdist2 = maxdist - td;
211                                 for (s = 0;s < smax;s++)
212                                 {
213                                         if (sdtable[s] < maxdist2)
214                                         {
215                                                 k = (32768.0f / (sdtable[s] + td)) - subtract;
216                                                 bl[0] += red   * k;
217                                                 bl[1] += green * k;
218                                                 bl[2] += blue  * k;
219                                                 lit = true;
220                                         }
221                                         bl += 3;
222                                 }
223                         }
224                         else // skip line
225                                 bl += smax3;
226                 }
227         }
228         return lit;
229 }
230
231 /*
232 ===============
233 R_BuildLightMap
234
235 Combine and scale multiple lightmaps into the 8.8 format in blocklights
236 ===============
237 */
238 static void R_BuildLightMap (const entity_render_t *ent, msurface_t *surf, int dlightchanged)
239 {
240         if (!r_floatbuildlightmap.integer)
241         {
242                 int smax, tmax, i, j, size, size3, shift, maps, stride, l;
243                 unsigned int *bl, scale;
244                 qbyte *lightmap, *out, *stain;
245
246                 // update cached lighting info
247                 surf->cached_dlight = 0;
248                 surf->cached_lightmapscalebit = r_lightmapscalebit;
249                 surf->cached_ambient = r_ambient.value;
250                 surf->cached_light[0] = d_lightstylevalue[surf->styles[0]];
251                 surf->cached_light[1] = d_lightstylevalue[surf->styles[1]];
252                 surf->cached_light[2] = d_lightstylevalue[surf->styles[2]];
253                 surf->cached_light[3] = d_lightstylevalue[surf->styles[3]];
254
255                 smax = (surf->extents[0]>>4)+1;
256                 tmax = (surf->extents[1]>>4)+1;
257                 size = smax*tmax;
258                 size3 = size*3;
259                 lightmap = surf->samples;
260
261         // set to full bright if no light data
262                 bl = intblocklights;
263                 if ((ent->effects & EF_FULLBRIGHT) || !ent->model->lightdata)
264                 {
265                         for (i = 0;i < size3;i++)
266                                 bl[i] = 255*256;
267                 }
268                 else
269                 {
270         // clear to no light
271                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
272                         if (j)
273                         {
274                                 for (i = 0;i < size3;i++)
275                                         *bl++ = j;
276                         }
277                         else
278                                 memset(bl, 0, size*3*sizeof(unsigned int));
279
280                         if (surf->dlightframe == r_framecount && r_dlightmap.integer)
281                         {
282                                 surf->cached_dlight = R_IntAddDynamicLights(&ent->inversematrix, surf);
283                                 if (surf->cached_dlight)
284                                         c_light_polys++;
285                                 else if (dlightchanged)
286                                         return; // don't upload if only updating dlights and none mattered
287                         }
288
289         // add all the lightmaps
290                         if (lightmap)
291                         {
292                                 bl = intblocklights;
293                                 for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
294                                         for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
295                                                 bl[i] += lightmap[i] * scale;
296                         }
297                 }
298
299                 stain = surf->stainsamples;
300                 bl = intblocklights;
301                 out = templight;
302                 // deal with lightmap brightness scale
303                 shift = 7 + r_lightmapscalebit + 8;
304                 if (ent->model->lightmaprgba)
305                 {
306                         stride = (surf->lightmaptexturestride - smax) * 4;
307                         for (i = 0;i < tmax;i++, out += stride)
308                         {
309                                 for (j = 0;j < smax;j++)
310                                 {
311                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
312                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
313                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
314                                         *out++ = 255;
315                                 }
316                         }
317                 }
318                 else
319                 {
320                         stride = (surf->lightmaptexturestride - smax) * 3;
321                         for (i = 0;i < tmax;i++, out += stride)
322                         {
323                                 for (j = 0;j < smax;j++)
324                                 {
325                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
326                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
327                                         l = (*bl++ * *stain++) >> shift;*out++ = min(l, 255);
328                                 }
329                         }
330                 }
331
332                 R_UpdateTexture(surf->lightmaptexture, templight);
333         }
334         else
335         {
336                 int smax, tmax, i, j, size, size3, maps, stride, l;
337                 float *bl, scale;
338                 qbyte *lightmap, *out, *stain;
339
340                 // update cached lighting info
341                 surf->cached_dlight = 0;
342                 surf->cached_lightmapscalebit = r_lightmapscalebit;
343                 surf->cached_ambient = r_ambient.value;
344                 surf->cached_light[0] = d_lightstylevalue[surf->styles[0]];
345                 surf->cached_light[1] = d_lightstylevalue[surf->styles[1]];
346                 surf->cached_light[2] = d_lightstylevalue[surf->styles[2]];
347                 surf->cached_light[3] = d_lightstylevalue[surf->styles[3]];
348
349                 smax = (surf->extents[0]>>4)+1;
350                 tmax = (surf->extents[1]>>4)+1;
351                 size = smax*tmax;
352                 size3 = size*3;
353                 lightmap = surf->samples;
354
355         // set to full bright if no light data
356                 bl = floatblocklights;
357                 if ((ent->effects & EF_FULLBRIGHT) || !ent->model->lightdata)
358                         j = 255*256;
359                 else
360                         j = r_ambient.value * 512.0f; // would be 128.0f logically, but using 512.0f to match winquake style
361
362                 // clear to no light
363                 if (j)
364                 {
365                         for (i = 0;i < size3;i++)
366                                 *bl++ = j;
367                 }
368                 else
369                         memset(bl, 0, size*3*sizeof(float));
370
371                 if (surf->dlightframe == r_framecount && r_dlightmap.integer)
372                 {
373                         surf->cached_dlight = R_FloatAddDynamicLights(&ent->inversematrix, surf);
374                         if (surf->cached_dlight)
375                                 c_light_polys++;
376                         else if (dlightchanged)
377                                 return; // don't upload if only updating dlights and none mattered
378                 }
379
380                 // add all the lightmaps
381                 if (lightmap)
382                 {
383                         bl = floatblocklights;
384                         for (maps = 0;maps < MAXLIGHTMAPS && surf->styles[maps] != 255;maps++, lightmap += size3)
385                                 for (scale = d_lightstylevalue[surf->styles[maps]], i = 0;i < size3;i++)
386                                         bl[i] += lightmap[i] * scale;
387                 }
388
389                 stain = surf->stainsamples;
390                 bl = floatblocklights;
391                 out = templight;
392                 // deal with lightmap brightness scale
393                 scale = 1.0f / (1 << (7 + r_lightmapscalebit + 8));
394                 if (ent->model->lightmaprgba)
395                 {
396                         stride = (surf->lightmaptexturestride - smax) * 4;
397                         for (i = 0;i < tmax;i++, out += stride)
398                         {
399                                 for (j = 0;j < smax;j++)
400                                 {
401                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
402                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
403                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
404                                         *out++ = 255;
405                                 }
406                         }
407                 }
408                 else
409                 {
410                         stride = (surf->lightmaptexturestride - smax) * 3;
411                         for (i = 0;i < tmax;i++, out += stride)
412                         {
413                                 for (j = 0;j < smax;j++)
414                                 {
415                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
416                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
417                                         l = *bl++ * *stain++ * scale;*out++ = min(l, 255);
418                                 }
419                         }
420                 }
421
422                 R_UpdateTexture(surf->lightmaptexture, templight);
423         }
424 }
425
426 void R_StainNode (mnode_t *node, model_t *model, vec3_t origin, float radius, float fcolor[8])
427 {
428         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
429         msurface_t *surf, *endsurf;
430         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
431         qbyte *bl;
432         vec3_t impact;
433
434         maxdist = radius * radius;
435         invradius = 1.0f / radius;
436
437 loc0:
438         if (node->contents < 0)
439                 return;
440         ndist = PlaneDiff(origin, node->plane);
441         if (ndist > radius)
442         {
443                 node = node->children[0];
444                 goto loc0;
445         }
446         if (ndist < -radius)
447         {
448                 node = node->children[1];
449                 goto loc0;
450         }
451
452         dist2 = ndist * ndist;
453         maxdist3 = maxdist - dist2;
454
455         if (node->plane->type < 3)
456         {
457                 VectorCopy(origin, impact);
458                 impact[node->plane->type] -= ndist;
459         }
460         else
461         {
462                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
463                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
464                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
465         }
466
467         for (surf = model->surfaces + node->firstsurface, endsurf = surf + node->numsurfaces;surf < endsurf;surf++)
468         {
469                 if (surf->stainsamples)
470                 {
471                         smax = (surf->extents[0] >> 4) + 1;
472                         tmax = (surf->extents[1] >> 4) + 1;
473
474                         impacts = DotProduct (impact, surf->texinfo->vecs[0]) + surf->texinfo->vecs[0][3] - surf->texturemins[0];
475                         impactt = DotProduct (impact, surf->texinfo->vecs[1]) + surf->texinfo->vecs[1][3] - surf->texturemins[1];
476
477                         s = bound(0, impacts, smax * 16) - impacts;
478                         t = bound(0, impactt, tmax * 16) - impactt;
479                         i = s * s + t * t + dist2;
480                         if (i > maxdist)
481                                 continue;
482
483                         // reduce calculations
484                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
485                                 sdtable[s] = i * i + dist2;
486
487                         bl = surf->stainsamples;
488                         smax3 = smax * 3;
489                         stained = false;
490
491                         i = impactt;
492                         for (t = 0;t < tmax;t++, i -= 16)
493                         {
494                                 td = i * i;
495                                 // make sure some part of it is visible on this line
496                                 if (td < maxdist3)
497                                 {
498                                         maxdist2 = maxdist - td;
499                                         for (s = 0;s < smax;s++)
500                                         {
501                                                 if (sdtable[s] < maxdist2)
502                                                 {
503                                                         ratio = lhrandom(0.0f, 1.0f);
504                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
505                                                         if (a >= (1.0f / 64.0f))
506                                                         {
507                                                                 if (a > 1)
508                                                                         a = 1;
509                                                                 bl[0] = (qbyte) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
510                                                                 bl[1] = (qbyte) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
511                                                                 bl[2] = (qbyte) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
512                                                                 stained = true;
513                                                         }
514                                                 }
515                                                 bl += 3;
516                                         }
517                                 }
518                                 else // skip line
519                                         bl += smax3;
520                         }
521                         // force lightmap upload
522                         if (stained)
523                                 surf->cached_dlight = true;
524                 }
525         }
526
527         if (node->children[0]->contents >= 0)
528         {
529                 if (node->children[1]->contents >= 0)
530                 {
531                         R_StainNode(node->children[0], model, origin, radius, fcolor);
532                         node = node->children[1];
533                         goto loc0;
534                 }
535                 else
536                 {
537                         node = node->children[0];
538                         goto loc0;
539                 }
540         }
541         else if (node->children[1]->contents >= 0)
542         {
543                 node = node->children[1];
544                 goto loc0;
545         }
546 }
547
548 void R_Stain (vec3_t origin, float radius, int cr1, int cg1, int cb1, int ca1, int cr2, int cg2, int cb2, int ca2)
549 {
550         int n;
551         float fcolor[8];
552         entity_render_t *ent;
553         model_t *model;
554         vec3_t org;
555         fcolor[0] = cr1;
556         fcolor[1] = cg1;
557         fcolor[2] = cb1;
558         fcolor[3] = ca1 * (1.0f / 64.0f);
559         fcolor[4] = cr2 - cr1;
560         fcolor[5] = cg2 - cg1;
561         fcolor[6] = cb2 - cb1;
562         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
563
564         model = cl.worldmodel;
565         if (model)
566                 R_StainNode(model->nodes + model->hulls[0].firstclipnode, model, origin, radius, fcolor);
567
568         // look for embedded bmodels
569         for (n = 0;n < cl_num_brushmodel_entities;n++)
570         {
571                 ent = cl_brushmodel_entities[n];
572                 model = ent->model;
573                 if (model && model->name[0] == '*')
574                 {
575                         Mod_CheckLoaded(model);
576                         if (model->type == mod_brush)
577                         {
578                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
579                                 R_StainNode(model->nodes + model->hulls[0].firstclipnode, model, org, radius, fcolor);
580                         }
581                 }
582         }
583 }
584
585
586 /*
587 =============================================================
588
589         BRUSH MODELS
590
591 =============================================================
592 */
593
594 static void RSurf_AddLightmapToVertexColors(const int *lightmapoffsets, float *c, int numverts, const qbyte *samples, int size3, const qbyte *styles)
595 {
596         int i;
597         float scale;
598         const qbyte *lm;
599         if (styles[0] != 255)
600         {
601                 for (i = 0;i < numverts;i++, c += 4)
602                 {
603                         lm = samples + lightmapoffsets[i];
604                         scale = d_lightstylevalue[styles[0]] * (1.0f / 32768.0f);
605                         VectorMA(c, scale, lm, c);
606                         if (styles[1] != 255)
607                         {
608                                 lm += size3;
609                                 scale = d_lightstylevalue[styles[1]] * (1.0f / 32768.0f);
610                                 VectorMA(c, scale, lm, c);
611                                 if (styles[2] != 255)
612                                 {
613                                         lm += size3;
614                                         scale = d_lightstylevalue[styles[2]] * (1.0f / 32768.0f);
615                                         VectorMA(c, scale, lm, c);
616                                         if (styles[3] != 255)
617                                         {
618                                                 lm += size3;
619                                                 scale = d_lightstylevalue[styles[3]] * (1.0f / 32768.0f);
620                                                 VectorMA(c, scale, lm, c);
621                                         }
622                                 }
623                         }
624                 }
625         }
626 }
627
628 static void RSurf_FogColors(const float *v, float *c, float colorscale, int numverts, const float *modelorg)
629 {
630         int i;
631         float diff[3], f;
632         if (fogenabled)
633         {
634                 for (i = 0;i < numverts;i++, v += 4, c += 4)
635                 {
636                         VectorSubtract(v, modelorg, diff);
637                         f = colorscale * (1 - exp(fogdensity/DotProduct(diff, diff)));
638                         VectorScale(c, f, c);
639                 }
640         }
641         else if (colorscale != 1)
642                 for (i = 0;i < numverts;i++, c += 4)
643                         VectorScale(c, colorscale, c);
644 }
645
646 static void RSurf_FoggedColors(const float *v, float *c, float r, float g, float b, float a, float colorscale, int numverts, const float *modelorg)
647 {
648         int i;
649         float diff[3], f;
650         r *= colorscale;
651         g *= colorscale;
652         b *= colorscale;
653         if (fogenabled)
654         {
655                 for (i = 0;i < numverts;i++, v += 4, c += 4)
656                 {
657                         VectorSubtract(v, modelorg, diff);
658                         f = 1 - exp(fogdensity/DotProduct(diff, diff));
659                         c[0] = r * f;
660                         c[1] = g * f;
661                         c[2] = b * f;
662                         c[3] = a;
663                 }
664         }
665         else
666         {
667                 for (i = 0;i < numverts;i++, c += 4)
668                 {
669                         c[0] = r;
670                         c[1] = g;
671                         c[2] = b;
672                         c[3] = a;
673                 }
674         }
675 }
676
677 static void RSurf_FogPassColors(const float *v, float *c, float r, float g, float b, float a, float colorscale, int numverts, const float *modelorg)
678 {
679         int i;
680         float diff[3], f;
681         r *= colorscale;
682         g *= colorscale;
683         b *= colorscale;
684         for (i = 0;i < numverts;i++, v += 4, c += 4)
685         {
686                 VectorSubtract(v, modelorg, diff);
687                 f = exp(fogdensity/DotProduct(diff, diff));
688                 c[0] = r;
689                 c[1] = g;
690                 c[2] = b;
691                 c[3] = a * f;
692         }
693 }
694
695 static void RSurf_ScaleColors(float *c, float scale, int numverts)
696 {
697         int i;
698         if (scale != 1)
699                 for (i = 0;i < numverts;i++, c += 4)
700                         VectorScale(c, scale, c);
701 }
702
703 static int RSurf_LightSeparate(const matrix4x4_t *matrix, const int *dlightbits, int numverts, const float *vert, float *color)
704 {
705         float f;
706         const float *v;
707         float *c;
708         int i, l, lit = false;
709         const rdlight_t *rd;
710         vec3_t lightorigin;
711         for (l = 0;l < r_numdlights;l++)
712         {
713                 if (dlightbits[l >> 5] & (1 << (l & 31)))
714                 {
715                         rd = &r_dlight[l];
716                         Matrix4x4_Transform(matrix, rd->origin, lightorigin);
717                         for (i = 0, v = vert, c = color;i < numverts;i++, v += 4, c += 4)
718                         {
719                                 f = VectorDistance2(v, lightorigin) + LIGHTOFFSET;
720                                 if (f < rd->cullradius2)
721                                 {
722                                         f = (1.0f / f) - rd->subtract;
723                                         VectorMA(c, f, rd->light, c);
724                                         lit = true;
725                                 }
726                         }
727                 }
728         }
729         return lit;
730 }
731
732 // note: this untransforms lights to do the checking,
733 // and takes surf->mesh->verts data
734 static int RSurf_LightCheck(const matrix4x4_t *matrix, const int *dlightbits, const surfmesh_t *mesh)
735 {
736         int i, l;
737         const rdlight_t *rd;
738         vec3_t lightorigin;
739         const float *v;
740         for (l = 0;l < r_numdlights;l++)
741         {
742                 if (dlightbits[l >> 5] & (1 << (l & 31)))
743                 {
744                         rd = &r_dlight[l];
745                         Matrix4x4_Transform(matrix, rd->origin, lightorigin);
746                         for (i = 0, v = mesh->verts;i < mesh->numverts;i++, v += 4)
747                                 if (VectorDistance2(v, lightorigin) < rd->cullradius2)
748                                         return true;
749                 }
750         }
751         return false;
752 }
753
754 static void RSurfShader_Sky(const entity_render_t *ent, const texture_t *texture)
755 {
756         const msurface_t *surf;
757         const surfmesh_t *mesh;
758         rmeshstate_t m;
759
760         // LordHavoc: HalfLife maps have freaky skypolys...
761         if (ent->model->ishlbsp)
762                 return;
763
764         if (skyrendernow)
765         {
766                 skyrendernow = false;
767                 if (skyrendermasked)
768                         R_Sky();
769         }
770
771         R_Mesh_Matrix(&ent->matrix);
772
773         // draw depth-only polys
774         memset(&m, 0, sizeof(m));
775         if (skyrendermasked)
776         {
777                 m.blendfunc1 = GL_ZERO;
778                 m.blendfunc2 = GL_ONE;
779         }
780         else
781         {
782                 // fog sky
783                 m.blendfunc1 = GL_ONE;
784                 m.blendfunc2 = GL_ZERO;
785         }
786         m.depthwrite = true;
787         R_Mesh_State(&m);
788         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
789         {
790                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
791                 {
792                         R_Mesh_ResizeCheck(mesh->numverts);
793                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
794                         GL_Color(fogcolor[0] * r_colorscale, fogcolor[1] * r_colorscale, fogcolor[2] * r_colorscale, 1);
795                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
796                 }
797         }
798 }
799
800 static void RSurfShader_Water_Callback(const void *calldata1, int calldata2)
801 {
802         const entity_render_t *ent = calldata1;
803         const msurface_t *surf = ent->model->surfaces + calldata2;
804         float f, colorscale;
805         const surfmesh_t *mesh;
806         rmeshstate_t m;
807         float alpha = ent->alpha * (surf->flags & SURF_DRAWNOALPHA ? 1 : r_wateralpha.value);
808         float modelorg[3];
809         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
810
811         R_Mesh_Matrix(&ent->matrix);
812
813         memset(&m, 0, sizeof(m));
814         if (ent->effects & EF_ADDITIVE)
815         {
816                 m.blendfunc1 = GL_SRC_ALPHA;
817                 m.blendfunc2 = GL_ONE;
818         }
819         else if (surf->currenttexture->fogtexture != NULL || alpha < 1)
820         {
821                 m.blendfunc1 = GL_SRC_ALPHA;
822                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
823         }
824         else
825         {
826                 m.blendfunc1 = GL_ONE;
827                 m.blendfunc2 = GL_ZERO;
828         }
829         m.tex[0] = R_GetTexture(surf->currenttexture->texture);
830         colorscale = r_colorscale;
831         if (gl_combine.integer)
832         {
833                 m.texrgbscale[0] = 4;
834                 colorscale *= 0.25f;
835         }
836         R_Mesh_State(&m);
837         GL_UseColorArray();
838         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
839         {
840                 R_Mesh_ResizeCheck(mesh->numverts);
841                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
842                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
843                 f = surf->flags & SURF_DRAWFULLBRIGHT ? 1.0f : ((surf->flags & SURF_LIGHTMAP) ? 0 : 0.5f);
844                 R_FillColors(varray_color, mesh->numverts, f, f, f, alpha);
845                 if (!(surf->flags & SURF_DRAWFULLBRIGHT || ent->effects & EF_FULLBRIGHT))
846                 {
847                         if (surf->dlightframe == r_framecount)
848                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
849                         if (surf->flags & SURF_LIGHTMAP)
850                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
851                 }
852                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
853                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
854         }
855
856         if (fogenabled)
857         {
858                 memset(&m, 0, sizeof(m));
859                 m.blendfunc1 = GL_SRC_ALPHA;
860                 m.blendfunc2 = GL_ONE;
861                 m.tex[0] = R_GetTexture(surf->currenttexture->fogtexture);
862                 R_Mesh_State(&m);
863                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
864                 {
865                         R_Mesh_ResizeCheck(mesh->numverts);
866                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
867                         if (m.tex[0])
868                                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
869                         RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], alpha, r_colorscale, mesh->numverts, modelorg);
870                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
871                 }
872         }
873 }
874
875 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture)
876 {
877         const msurface_t *surf;
878         vec3_t center;
879         if ((r_wateralpha.value < 1 && !(texture->flags & SURF_DRAWNOALPHA)) || ent->effects & EF_ADDITIVE || texture->fogtexture)
880         {
881                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
882                 {
883                         Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
884                         R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->surfaces);
885                 }
886         }
887         else
888                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
889                         RSurfShader_Water_Callback(ent, surf - ent->model->surfaces);
890 }
891
892 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf)
893 {
894         float base, colorscale;
895         const surfmesh_t *mesh;
896         rmeshstate_t m;
897         float modelorg[3];
898         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
899         memset(&m, 0, sizeof(m));
900         if (ent->effects & EF_ADDITIVE)
901         {
902                 m.blendfunc1 = GL_SRC_ALPHA;
903                 m.blendfunc2 = GL_ONE;
904         }
905         else if (surf->currenttexture->fogtexture != NULL || ent->alpha < 1)
906         {
907                 m.blendfunc1 = GL_SRC_ALPHA;
908                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
909         }
910         else
911         {
912                 m.blendfunc1 = GL_ONE;
913                 m.blendfunc2 = GL_ZERO;
914         }
915         m.tex[0] = R_GetTexture(surf->currenttexture->texture);
916         colorscale = r_colorscale;
917         if (gl_combine.integer)
918         {
919                 m.texrgbscale[0] = 4;
920                 colorscale *= 0.25f;
921         }
922         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
923         R_Mesh_State(&m);
924         GL_UseColorArray();
925         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
926         {
927                 R_Mesh_ResizeCheck(mesh->numverts);
928                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
929                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
930                 R_FillColors(varray_color, mesh->numverts, base, base, base, ent->alpha);
931                 if (!(ent->effects & EF_FULLBRIGHT))
932                 {
933                         if (surf->dlightframe == r_framecount)
934                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
935                         if (surf->flags & SURF_LIGHTMAP)
936                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
937                 }
938                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
939                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
940         }
941 }
942
943 static void RSurfShader_Wall_Pass_BaseFullbright(const entity_render_t *ent, const msurface_t *surf)
944 {
945         const surfmesh_t *mesh;
946         rmeshstate_t m;
947         float modelorg[3];
948         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
949         memset(&m, 0, sizeof(m));
950         if (ent->effects & EF_ADDITIVE)
951         {
952                 m.blendfunc1 = GL_SRC_ALPHA;
953                 m.blendfunc2 = GL_ONE;
954         }
955         else if (surf->currenttexture->fogtexture != NULL || ent->alpha < 1)
956         {
957                 m.blendfunc1 = GL_SRC_ALPHA;
958                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
959         }
960         else
961         {
962                 m.blendfunc1 = GL_ONE;
963                 m.blendfunc2 = GL_ZERO;
964         }
965         m.tex[0] = R_GetTexture(surf->currenttexture->texture);
966         R_Mesh_State(&m);
967         GL_UseColorArray();
968         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
969         {
970                 R_Mesh_ResizeCheck(mesh->numverts);
971                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
972                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
973                 RSurf_FoggedColors(varray_vertex, varray_color, 1, 1, 1, ent->alpha, r_colorscale, mesh->numverts, modelorg);
974                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
975         }
976 }
977
978 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf)
979 {
980         const surfmesh_t *mesh;
981         rmeshstate_t m;
982         float modelorg[3];
983         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
984         memset(&m, 0, sizeof(m));
985         m.blendfunc1 = GL_SRC_ALPHA;
986         m.blendfunc2 = GL_ONE;
987         m.tex[0] = R_GetTexture(surf->currenttexture->glowtexture);
988         R_Mesh_State(&m);
989         GL_UseColorArray();
990         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
991         {
992                 R_Mesh_ResizeCheck(mesh->numverts);
993                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
994                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
995                 RSurf_FoggedColors(varray_vertex, varray_color, 1, 1, 1, ent->alpha, r_colorscale, mesh->numverts, modelorg);
996                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
997         }
998 }
999
1000 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf)
1001 {
1002         const surfmesh_t *mesh;
1003         rmeshstate_t m;
1004         float modelorg[3];
1005         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1006         memset(&m, 0, sizeof(m));
1007         m.blendfunc1 = GL_SRC_ALPHA;
1008         m.blendfunc2 = GL_ONE;
1009         m.tex[0] = R_GetTexture(surf->currenttexture->fogtexture);
1010         R_Mesh_State(&m);
1011         GL_UseColorArray();
1012         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1013         {
1014                 R_Mesh_ResizeCheck(mesh->numverts);
1015                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1016                 if (m.tex[0])
1017                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1018                 RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], ent->alpha, r_colorscale, mesh->numverts, modelorg);
1019                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1020         }
1021 }
1022
1023 static void RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(const entity_render_t *ent, const texture_t *texture)
1024 {
1025         const msurface_t *surf;
1026         const surfmesh_t *mesh;
1027         rmeshstate_t m;
1028         int lightmaptexturenum;
1029         float cl;
1030         memset(&m, 0, sizeof(m));
1031         m.blendfunc1 = GL_ONE;
1032         m.blendfunc2 = GL_ZERO;
1033         m.tex[0] = R_GetTexture(texture->texture);
1034         m.tex[1] = R_GetTexture(texture->surfacechain->lightmaptexture);
1035         m.tex[2] = R_GetTexture(texture->detailtexture);
1036         m.texrgbscale[0] = 1;
1037         m.texrgbscale[1] = 4;
1038         m.texrgbscale[2] = 2;
1039         R_Mesh_State(&m);
1040         cl = (float) (1 << r_lightmapscalebit) * r_colorscale;
1041         GL_Color(cl, cl, cl, 1);
1042         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1043         {
1044                 lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1045                 if (m.tex[1] != lightmaptexturenum)
1046                 {
1047                         m.tex[1] = lightmaptexturenum;
1048                         R_Mesh_State(&m);
1049                 }
1050                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1051                 {
1052                         R_Mesh_ResizeCheck(mesh->numverts);
1053                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1054                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1055                         memcpy(varray_texcoord[1], mesh->uv, mesh->numverts * sizeof(float[2]));
1056                         memcpy(varray_texcoord[2], mesh->ab, mesh->numverts * sizeof(float[2]));
1057                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1058                 }
1059         }
1060 }
1061
1062 static void RSurfShader_OpaqueWall_Pass_BaseDoubleTex(const entity_render_t *ent, const texture_t *texture)
1063 {
1064         const msurface_t *surf;
1065         const surfmesh_t *mesh;
1066         rmeshstate_t m;
1067         int lightmaptexturenum;
1068         memset(&m, 0, sizeof(m));
1069         m.blendfunc1 = GL_ONE;
1070         m.blendfunc2 = GL_ZERO;
1071         m.tex[0] = R_GetTexture(texture->texture);
1072         m.tex[1] = R_GetTexture(texture->surfacechain->lightmaptexture);
1073         if (gl_combine.integer)
1074                 m.texrgbscale[1] = 4;
1075         R_Mesh_State(&m);
1076         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1077         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1078         {
1079                 lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1080                 if (m.tex[1] != lightmaptexturenum)
1081                 {
1082                         m.tex[1] = lightmaptexturenum;
1083                         R_Mesh_State(&m);
1084                 }
1085                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1086                 {
1087                         R_Mesh_ResizeCheck(mesh->numverts);
1088                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1089                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1090                         memcpy(varray_texcoord[1], mesh->uv, mesh->numverts * sizeof(float[2]));
1091                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1092                 }
1093         }
1094 }
1095
1096 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture)
1097 {
1098         const msurface_t *surf;
1099         const surfmesh_t *mesh;
1100         rmeshstate_t m;
1101         memset(&m, 0, sizeof(m));
1102         m.blendfunc1 = GL_ONE;
1103         m.blendfunc2 = GL_ZERO;
1104         m.tex[0] = R_GetTexture(texture->texture);
1105         R_Mesh_State(&m);
1106         GL_Color(1, 1, 1, 1);
1107         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1108         {
1109                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1110                 {
1111                         R_Mesh_ResizeCheck(mesh->numverts);
1112                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1113                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1114                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1115                 }
1116         }
1117 }
1118
1119 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture)
1120 {
1121         const msurface_t *surf;
1122         const surfmesh_t *mesh;
1123         rmeshstate_t m;
1124         int lightmaptexturenum;
1125         memset(&m, 0, sizeof(m));
1126         m.blendfunc1 = GL_ZERO;
1127         m.blendfunc2 = GL_SRC_COLOR;
1128         m.tex[0] = R_GetTexture(texture->surfacechain->lightmaptexture);
1129         if (gl_combine.integer)
1130                 m.texrgbscale[0] = 4;
1131         R_Mesh_State(&m);
1132         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1133         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1134         {
1135                 lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1136                 if (m.tex[0] != lightmaptexturenum)
1137                 {
1138                         m.tex[0] = lightmaptexturenum;
1139                         R_Mesh_State(&m);
1140                 }
1141                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1142                 {
1143                         R_Mesh_ResizeCheck(mesh->numverts);
1144                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1145                         memcpy(varray_texcoord[0], mesh->uv, mesh->numverts * sizeof(float[2]));
1146                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1147                 }
1148         }
1149 }
1150
1151 static void RSurfShader_OpaqueWall_Pass_Light(const entity_render_t *ent, const texture_t *texture)
1152 {
1153         const msurface_t *surf;
1154         const surfmesh_t *mesh;
1155         float colorscale;
1156         rmeshstate_t m;
1157
1158         memset(&m, 0, sizeof(m));
1159         m.blendfunc1 = GL_SRC_ALPHA;
1160         m.blendfunc2 = GL_ONE;
1161         m.tex[0] = R_GetTexture(texture->texture);
1162         colorscale = r_colorscale;
1163         if (gl_combine.integer)
1164         {
1165                 m.texrgbscale[0] = 4;
1166                 colorscale *= 0.25f;
1167         }
1168         R_Mesh_State(&m);
1169         GL_UseColorArray();
1170         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1171         {
1172                 if (surf->dlightframe == r_framecount)
1173                 {
1174                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1175                         {
1176                                 if (RSurf_LightCheck(&ent->inversematrix, surf->dlightbits, mesh))
1177                                 {
1178                                         R_Mesh_ResizeCheck(mesh->numverts);
1179                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1180                                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1181                                         R_FillColors(varray_color, mesh->numverts, 0, 0, 0, 1);
1182                                         RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
1183                                         RSurf_ScaleColors(varray_color, colorscale, mesh->numverts);
1184                                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1185                                 }
1186                         }
1187                 }
1188         }
1189 }
1190
1191 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture)
1192 {
1193         const msurface_t *surf;
1194         const surfmesh_t *mesh;
1195         rmeshstate_t m;
1196         float modelorg[3];
1197         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1198         memset(&m, 0, sizeof(m));
1199         m.blendfunc1 = GL_SRC_ALPHA;
1200         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1201         R_Mesh_State(&m);
1202         GL_UseColorArray();
1203         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1204         {
1205                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1206                 {
1207                         R_Mesh_ResizeCheck(mesh->numverts);
1208                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1209                         if (m.tex[0])
1210                                 memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1211                         RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], 1, r_colorscale, mesh->numverts, modelorg);
1212                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1213                 }
1214         }
1215 }
1216
1217 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture)
1218 {
1219         const msurface_t *surf;
1220         const surfmesh_t *mesh;
1221         rmeshstate_t m;
1222         memset(&m, 0, sizeof(m));
1223         m.blendfunc1 = GL_DST_COLOR;
1224         m.blendfunc2 = GL_SRC_COLOR;
1225         m.tex[0] = R_GetTexture(texture->detailtexture);
1226         R_Mesh_State(&m);
1227         GL_Color(1, 1, 1, 1);
1228         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1229         {
1230                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1231                 {
1232                         R_Mesh_ResizeCheck(mesh->numverts);
1233                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1234                         memcpy(varray_texcoord[0], mesh->ab, mesh->numverts * sizeof(float[2]));
1235                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1236                 }
1237         }
1238 }
1239
1240 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture)
1241 {
1242         const msurface_t *surf;
1243         const surfmesh_t *mesh;
1244         rmeshstate_t m;
1245         memset(&m, 0, sizeof(m));
1246         m.blendfunc1 = GL_SRC_ALPHA;
1247         m.blendfunc2 = GL_ONE;
1248         m.tex[0] = R_GetTexture(texture->glowtexture);
1249         R_Mesh_State(&m);
1250         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1251         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1252         {
1253                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1254                 {
1255                         R_Mesh_ResizeCheck(mesh->numverts);
1256                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1257                         memcpy(varray_texcoord[0], mesh->st, mesh->numverts * sizeof(float[2]));
1258                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1259                 }
1260         }
1261 }
1262
1263 static void RSurfShader_Wall_Fullbright_Callback(const void *calldata1, int calldata2)
1264 {
1265         const entity_render_t *ent = calldata1;
1266         const msurface_t *surf = ent->model->surfaces + calldata2;
1267         R_Mesh_Matrix(&ent->matrix);
1268         RSurfShader_Wall_Pass_BaseFullbright(ent, surf);
1269         if (surf->currenttexture->glowtexture)
1270                 RSurfShader_Wall_Pass_Glow(ent, surf);
1271         if (fogenabled)
1272                 RSurfShader_Wall_Pass_Fog(ent, surf);
1273 }
1274
1275 static void RSurfShader_Wall_Fullbright(const entity_render_t *ent, const texture_t *texture)
1276 {
1277         const msurface_t *surf;
1278         vec3_t center;
1279         if (ent->effects & EF_ADDITIVE || ent->alpha < 1 || texture->fogtexture != NULL)
1280         {
1281                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1282                 {
1283                         Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1284                         R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Fullbright_Callback, ent, surf - ent->model->surfaces);
1285                 }
1286         }
1287         else
1288         {
1289                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1290                         RSurfShader_Wall_Pass_BaseFullbright(ent, surf);
1291                 if (texture->glowtexture)
1292                         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1293                                 RSurfShader_Wall_Pass_Glow(ent, surf);
1294                 if (fogenabled)
1295                         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1296                                 RSurfShader_Wall_Pass_Fog(ent, surf);
1297         }
1298 }
1299
1300 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1301 {
1302         const entity_render_t *ent = calldata1;
1303         const msurface_t *surf = ent->model->surfaces + calldata2;
1304         R_Mesh_Matrix(&ent->matrix);
1305         RSurfShader_Wall_Pass_BaseVertex(ent, surf);
1306         if (surf->currenttexture->glowtexture)
1307                 RSurfShader_Wall_Pass_Glow(ent, surf);
1308         if (fogenabled)
1309                 RSurfShader_Wall_Pass_Fog(ent, surf);
1310 }
1311
1312 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture)
1313 {
1314         const msurface_t *surf;
1315         vec3_t center;
1316         if (ent->effects & EF_ADDITIVE || ent->alpha < 1 || texture->fogtexture != NULL)
1317         {
1318                 // transparent vertex shaded from lightmap
1319                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1320                 {
1321                         Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1322                         R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->surfaces);
1323                 }
1324         }
1325         else if (r_vertexsurfaces.integer)
1326         {
1327                 // opaque vertex shaded from lightmap
1328                 for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1329                         RSurfShader_Wall_Pass_BaseVertex(ent, surf);
1330                 if (texture->glowtexture)
1331                         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1332                                 RSurfShader_Wall_Pass_Glow(ent, surf);
1333                 if (fogenabled)
1334                         for (surf = texture->surfacechain;surf;surf = surf->texturechain)
1335                                 RSurfShader_Wall_Pass_Fog(ent, surf);
1336         }
1337         else
1338         {
1339                 // opaque lightmapped
1340                 if (r_textureunits.integer >= 2)
1341                 {
1342                         if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1343                                 RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture);
1344                         else
1345                         {
1346                                 RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture);
1347                                 if (r_detailtextures.integer)
1348                                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture);
1349                         }
1350                 }
1351                 else
1352                 {
1353                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture);
1354                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture);
1355                         if (r_detailtextures.integer)
1356                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture);
1357                 }
1358                 if (!r_dlightmap.integer && !(ent->effects & EF_FULLBRIGHT))
1359                         RSurfShader_OpaqueWall_Pass_Light(ent, texture);
1360                 if (texture->glowtexture)
1361                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture);
1362                 if (fogenabled)
1363                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture);
1364         }
1365 }
1366
1367 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap}, SHADERFLAGS_NEEDLIGHTMAP};
1368 Cshader_t Cshader_wall_fullbright = {{NULL, RSurfShader_Wall_Fullbright}, 0};
1369 Cshader_t Cshader_water = {{NULL, RSurfShader_Water}, 0};
1370 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL}, 0};
1371
1372 int Cshader_count = 4;
1373 Cshader_t *Cshaders[4] =
1374 {
1375         &Cshader_wall_lightmap,
1376         &Cshader_wall_fullbright,
1377         &Cshader_water,
1378         &Cshader_sky
1379 };
1380
1381 void R_DrawSurfaces(entity_render_t *ent, int sky, int normal)
1382 {
1383         int i, alttextures, texframe, framecount, numtextures, numsurfaces, *surfacevisframes;
1384         texture_t *t, *textures;
1385         model_t *model;
1386         msurface_t *surf, *surfaces;
1387         vec3_t modelorg;
1388
1389         if (!ent->model)
1390                 return;
1391
1392         // mark the surfaces touched by dynamic lights
1393         if (normal && r_dynamic.integer)
1394                 R_MarkLights(ent);
1395
1396         R_Mesh_Matrix(&ent->matrix);
1397
1398         model = ent->model;
1399         alttextures = ent->frame != 0;
1400         texframe = (int)(cl.time * 5.0f);
1401
1402         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1403
1404         numtextures = model->numtextures;
1405         textures = model->textures;
1406         numsurfaces = model->nummodelsurfaces;
1407         surfaces = model->surfaces + model->firstmodelsurface;
1408         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1409
1410         for (i = 0;i < numtextures;i++)
1411                 textures[i].surfacechain = NULL;
1412
1413         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1414         {
1415                 if (surfacevisframes[i] == r_framecount)
1416                 {
1417 #if !WORLDNODECULLBACKFACES
1418                         // mark any backface surfaces as not visible
1419                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1420                         {
1421                                 if (!(surf->flags & SURF_PLANEBACK))
1422                                         surfacevisframes[i] = -1;
1423                         }
1424                         else
1425                         {
1426                                 if ((surf->flags & SURF_PLANEBACK))
1427                                         surfacevisframes[i] = -1;
1428                         }
1429                         if (surfacevisframes[i] == r_framecount)
1430 #endif
1431                         {
1432                                 c_faces++;
1433                                 t = surf->texinfo->texture;
1434                                 if (t->animated)
1435                                 {
1436                                         framecount = t->anim_total[alttextures];
1437                                         if (framecount >= 2)
1438                                                 t = t->anim_frames[alttextures][texframe % framecount];
1439                                         else
1440                                                 t = t->anim_frames[alttextures][0];
1441                                 }
1442                                 surf->currenttexture = t;
1443                                 surf->texturechain = t->surfacechain;
1444                                 t->surfacechain = surf;
1445                                 if (!r_vertexsurfaces.integer && surf->lightmaptexture != NULL)
1446                                 {
1447                                         if (surf->cached_dlight
1448                                         || surf->cached_ambient != r_ambient.value
1449                                         || surf->cached_lightmapscalebit != r_lightmapscalebit)
1450                                                 R_BuildLightMap(ent, surf, false); // base lighting changed
1451                                         else if (r_dynamic.integer)
1452                                         {
1453                                                 if  (surf->styles[0] != 255 && (d_lightstylevalue[surf->styles[0]] != surf->cached_light[0]
1454                                                 || (surf->styles[1] != 255 && (d_lightstylevalue[surf->styles[1]] != surf->cached_light[1]
1455                                                 || (surf->styles[2] != 255 && (d_lightstylevalue[surf->styles[2]] != surf->cached_light[2]
1456                                                 || (surf->styles[3] != 255 && (d_lightstylevalue[surf->styles[3]] != surf->cached_light[3]))))))))
1457                                                         R_BuildLightMap(ent, surf, false); // base lighting changed
1458                                                 else if (surf->dlightframe == r_framecount && r_dlightmap.integer)
1459                                                         R_BuildLightMap(ent, surf, true); // only dlights
1460                                         }
1461                                 }
1462                         }
1463                 }
1464         }
1465
1466         if (sky)
1467                 for (i = 0, t = textures;i < numtextures;i++, t++)
1468                         if (t->surfacechain && t->shader->shaderfunc[SHADERSTAGE_SKY])
1469                                 t->shader->shaderfunc[SHADERSTAGE_SKY](ent, t);
1470
1471         if (normal)
1472                 for (i = 0, t = textures;i < numtextures;i++, t++)
1473                         if (t->surfacechain && t->shader->shaderfunc[SHADERSTAGE_NORMAL])
1474                                 t->shader->shaderfunc[SHADERSTAGE_NORMAL](ent, t);
1475 }
1476
1477 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1478 {
1479         int i;
1480         float *v;
1481         rmeshstate_t m;
1482         const entity_render_t *ent = calldata1;
1483         const mportal_t *portal = ent->model->portals + calldata2;
1484         memset(&m, 0, sizeof(m));
1485         m.blendfunc1 = GL_SRC_ALPHA;
1486         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1487         R_Mesh_Matrix(&ent->matrix);
1488         R_Mesh_State(&m);
1489         R_Mesh_ResizeCheck(portal->numpoints);
1490         i = portal - ent->model->portals;
1491         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_colorscale,
1492                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_colorscale,
1493                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_colorscale,
1494                          0.125f);
1495         if (PlaneDiff(r_origin, (&portal->plane)) > 0)
1496         {
1497                 for (i = portal->numpoints - 1, v = varray_vertex;i >= 0;i--, v += 4)
1498                         VectorCopy(portal->points[i].position, v);
1499         }
1500         else
1501                 for (i = 0, v = varray_vertex;i < portal->numpoints;i++, v += 4)
1502                         VectorCopy(portal->points[i].position, v);
1503         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1504 }
1505
1506 static void R_DrawPortals(entity_render_t *ent)
1507 {
1508         int i;
1509         mportal_t *portal, *endportal;
1510         float temp[3], center[3], f;
1511
1512         if (r_drawportals.integer < 1)
1513                 return;
1514
1515         for (portal = ent->model->portals, endportal = portal + ent->model->numportals;portal < endportal;portal++)
1516         {
1517                 if (portal->here->pvsframe == r_pvsframecount || portal->past->pvsframe == r_pvsframecount)
1518                 {
1519                         if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1520                         {
1521                                 VectorClear(temp);
1522                                 for (i = 0;i < portal->numpoints;i++)
1523                                         VectorAdd(temp, portal->points[i].position, temp);
1524                                 f = ixtable[portal->numpoints];
1525                                 VectorScale(temp, f, temp);
1526                                 Matrix4x4_Transform(&ent->matrix, temp, center);
1527                                 R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->portals);
1528                         }
1529                 }
1530         }
1531 }
1532
1533 void R_DrawBrushModel(entity_render_t *ent, int sky, int normal)
1534 {
1535         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1536         msurface_t *surf;
1537         model_t *model;
1538 #if WORLDNODECULLBACKFACES
1539         vec3_t modelorg;
1540 #endif
1541
1542         // because bmodels can be reused, we have to decide which things to render
1543         // from scratch every time
1544         model = ent->model;
1545 #if WORLDNODECULLBACKFACES
1546         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1547 #endif
1548         numsurfaces = model->nummodelsurfaces;
1549         surf = model->surfaces + model->firstmodelsurface;
1550         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1551         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1552         for (i = 0;i < numsurfaces;i++, surf++)
1553         {
1554 #if WORLDNODECULLBACKFACES
1555                 // mark any backface surfaces as not visible
1556                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1557                 {
1558                         if ((surf->flags & SURF_PLANEBACK))
1559                         {
1560                                 surfacevisframes[i] = r_framecount;
1561                                 surfacepvsframes[i] = r_pvsframecount;
1562                         }
1563                 }
1564                 else
1565                 {
1566                         if (!(surf->flags & SURF_PLANEBACK))
1567                         {
1568                                 surfacevisframes[i] = r_framecount;
1569                                 surfacepvsframes[i] = r_pvsframecount;
1570                         }
1571                 }
1572 #else
1573                 surfacevisframes[i] = r_framecount;
1574                 surfacepvsframes[i] = r_pvsframecount;
1575 #endif
1576                 surf->dlightframe = -1;
1577         }
1578         R_DrawSurfaces(ent, sky, normal);
1579 }
1580
1581 void R_SurfaceWorldNode (entity_render_t *ent)
1582 {
1583         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1584         msurface_t *surfaces, *surf;
1585         model_t *model;
1586         vec3_t modelorg;
1587
1588         model = ent->model;
1589         numsurfaces = model->nummodelsurfaces;
1590         surfaces = model->surfaces + model->firstmodelsurface;
1591         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1592         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1593         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1594
1595         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1596         {
1597                 if (surfacepvsframes[i] == r_pvsframecount)
1598                 {
1599 #if WORLDNODECULLBACKFACES
1600                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1601                         {
1602                                 if ((surf->flags & SURF_PLANEBACK) && R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1603                                         surfacevisframes[i] = r_framecount;
1604                         }
1605                         else
1606                         {
1607                                 if (!(surf->flags & SURF_PLANEBACK) && R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1608                                         surfacevisframes[i] = r_framecount;
1609                         }
1610 #else
1611                         if (R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1612                                 surfacevisframes[i] = r_framecount;
1613 #endif
1614                 }
1615         }
1616 }
1617
1618 /*
1619 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1620 {
1621         int portalstack, i;
1622         mportal_t *p, *pstack[8192];
1623         msurface_t *surf, **mark, **endmark;
1624         mleaf_t *leaf;
1625         // LordHavoc: portal-passage worldnode with PVS;
1626         // follows portals leading outward from viewleaf, does not venture
1627         // offscreen or into leafs that are not visible, faster than Quake's
1628         // RecursiveWorldNode
1629         leaf = viewleaf;
1630         leaf->worldnodeframe = r_framecount;
1631         portalstack = 0;
1632 loc0:
1633         c_leafs++;
1634         if (leaf->nummarksurfaces)
1635         {
1636                 for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1637                 {
1638                         surf = *mark++;
1639                         // make sure surfaces are only processed once
1640                         if (surf->worldnodeframe != r_framecount)
1641                         {
1642                                 surf->worldnodeframe = r_framecount;
1643                                 if (PlaneDist(r_origin, surf->plane) < surf->plane->dist)
1644                                 {
1645                                         if (surf->flags & SURF_PLANEBACK)
1646                                                 surf->visframe = r_framecount;
1647                                 }
1648                                 else
1649                                 {
1650                                         if (!(surf->flags & SURF_PLANEBACK))
1651                                                 surf->visframe = r_framecount;
1652                                 }
1653                         }
1654                 }
1655         }
1656         // follow portals into other leafs
1657         for (p = leaf->portals;p;p = p->next)
1658         {
1659                 leaf = p->past;
1660                 if (leaf->worldnodeframe != r_framecount)
1661                 {
1662                         leaf->worldnodeframe = r_framecount;
1663                         // FIXME: R_NotCulledBox is absolute, should be done relative
1664                         if (leaf->pvsframe == r_pvsframecount && R_NotCulledBox(leaf->mins, leaf->maxs))
1665                         {
1666                                 p->visframe = r_framecount;
1667                                 pstack[portalstack++] = p;
1668                                 goto loc0;
1669 loc1:
1670                                 p = pstack[--portalstack];
1671                         }
1672                 }
1673         }
1674         if (portalstack)
1675                 goto loc1;
1676 }
1677 */
1678
1679 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1680 {
1681         int c, leafstackpos, *mark, *surfacevisframes;
1682 #if WORLDNODECULLBACKFACES
1683         int n;
1684         msurface_t *surf;
1685 #endif
1686         mleaf_t *leaf, *leafstack[8192];
1687         mportal_t *p;
1688         vec3_t modelorg;
1689         msurface_t *surfaces;
1690         // LordHavoc: portal-passage worldnode with PVS;
1691         // follows portals leading outward from viewleaf, does not venture
1692         // offscreen or into leafs that are not visible, faster than Quake's
1693         // RecursiveWorldNode
1694         surfaces = ent->model->surfaces;
1695         surfacevisframes = ent->model->surfacevisframes;
1696         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1697         viewleaf->worldnodeframe = r_framecount;
1698         leafstack[0] = viewleaf;
1699         leafstackpos = 1;
1700         while (leafstackpos)
1701         {
1702                 c_leafs++;
1703                 leaf = leafstack[--leafstackpos];
1704                 // draw any surfaces bounding this leaf
1705                 if (leaf->nummarksurfaces)
1706                 {
1707                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1708                         {
1709 #if WORLDNODECULLBACKFACES
1710                                 n = *mark++;
1711                                 if (surfacevisframes[n] != r_framecount)
1712                                 {
1713                                         surf = surfaces + n;
1714                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1715                                         {
1716                                                 if ((surf->flags & SURF_PLANEBACK))
1717                                                         surfacevisframes[n] = r_framecount;
1718                                         }
1719                                         else
1720                                         {
1721                                                 if (!(surf->flags & SURF_PLANEBACK))
1722                                                         surfacevisframes[n] = r_framecount;
1723                                         }
1724                                 }
1725 #else
1726                                 surfacevisframes[*mark++] = r_framecount;
1727 #endif
1728                         }
1729                 }
1730                 // follow portals into other leafs
1731                 for (p = leaf->portals;p;p = p->next)
1732                 {
1733                         // LordHavoc: this DotProduct hurts less than a cache miss
1734                         // (which is more likely to happen if backflowing through leafs)
1735                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1736                         {
1737                                 leaf = p->past;
1738                                 if (leaf->worldnodeframe != r_framecount)
1739                                 {
1740                                         leaf->worldnodeframe = r_framecount;
1741                                         // FIXME: R_NotCulledBox is absolute, should be done relative
1742                                         if (leaf->pvsframe == r_pvsframecount && R_NotCulledBox(leaf->mins, leaf->maxs))
1743                                                 leafstack[leafstackpos++] = leaf;
1744                                 }
1745                         }
1746                 }
1747         }
1748         if (r_drawportals.integer)
1749                 R_DrawPortals(ent);
1750 }
1751
1752 void R_PVSUpdate (mleaf_t *viewleaf)
1753 {
1754         int i, j, l, c, bits, *surfacepvsframes, *mark;
1755         mleaf_t *leaf;
1756         qbyte *vis;
1757
1758         if (r_pvsviewleaf == viewleaf && r_pvsviewleafnovis == r_novis.integer)
1759                 return;
1760
1761         r_pvsframecount++;
1762         r_pvsviewleaf = viewleaf;
1763         r_pvsviewleafnovis = r_novis.integer;
1764
1765         if (viewleaf)
1766         {
1767                 surfacepvsframes = cl.worldmodel->surfacepvsframes;
1768                 vis = Mod_LeafPVS (viewleaf, cl.worldmodel);
1769                 for (j = 0;j < cl.worldmodel->numleafs;j += 8)
1770                 {
1771                         bits = *vis++;
1772                         if (bits)
1773                         {
1774                                 l = cl.worldmodel->numleafs - j;
1775                                 if (l > 8)
1776                                         l = 8;
1777                                 for (i = 0;i < l;i++)
1778                                 {
1779                                         if (bits & (1 << i))
1780                                         {
1781                                                 leaf = &cl.worldmodel->leafs[j + i + 1];
1782                                                 leaf->pvsframe = r_pvsframecount;
1783                                                 // mark surfaces bounding this leaf as visible
1784                                                 for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1785                                                         surfacepvsframes[*mark++] = r_pvsframecount;
1786                                         }
1787                                 }
1788                         }
1789                 }
1790         }
1791 }
1792
1793 /*
1794 =============
1795 R_DrawWorld
1796 =============
1797 */
1798 void R_DrawWorld (entity_render_t *ent)
1799 {
1800         mleaf_t *viewleaf;
1801         viewleaf = Mod_PointInLeaf (r_origin, cl.worldmodel);
1802         R_PVSUpdate(viewleaf);
1803         if (!viewleaf)
1804                 return;
1805         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1806                 R_SurfaceWorldNode (ent);
1807         else
1808                 R_PortalWorldNode (ent, viewleaf);
1809         R_DrawSurfaces(ent, true, true);
1810 }
1811
1812 /*
1813 =================
1814 R_DrawBrushModel
1815 =================
1816 */
1817 void R_DrawBrushModelSky (entity_render_t *ent)
1818 {
1819         R_DrawBrushModel(ent, true, false);
1820 }
1821
1822 void R_DrawBrushModelNormal (entity_render_t *ent)
1823 {
1824         c_bmodels++;
1825         R_DrawBrushModel(ent, false, true);
1826 }
1827
1828 static void gl_surf_start(void)
1829 {
1830 }
1831
1832 static void gl_surf_shutdown(void)
1833 {
1834 }
1835
1836 static void gl_surf_newmap(void)
1837 {
1838         // reset pvs visibility variables so it will update on first frame
1839         r_pvsframecount = 1;
1840         r_pvsviewleaf = NULL;
1841         r_pvsviewleafnovis = false;
1842 }
1843
1844 void GL_Surf_Init(void)
1845 {
1846         int i;
1847         dlightdivtable[0] = 4194304;
1848         for (i = 1;i < 32768;i++)
1849                 dlightdivtable[i] = 4194304 / (i << 7);
1850
1851         Cvar_RegisterVariable(&r_ambient);
1852         Cvar_RegisterVariable(&r_vertexsurfaces);
1853         Cvar_RegisterVariable(&r_dlightmap);
1854         Cvar_RegisterVariable(&r_drawportals);
1855         Cvar_RegisterVariable(&r_testvis);
1856         Cvar_RegisterVariable(&r_floatbuildlightmap);
1857         Cvar_RegisterVariable(&r_detailtextures);
1858         Cvar_RegisterVariable(&r_surfaceworldnode);
1859
1860         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
1861 }
1862