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