added TEXF_CLAMP flag for textures
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23 #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_DRAWNOALPHA ? 1 : r_wateralpha.value);
811         float modelorg[3];
812         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
813
814         R_Mesh_Matrix(&ent->matrix);
815
816         memset(&m, 0, sizeof(m));
817         if (ent->effects & EF_ADDITIVE)
818         {
819                 m.blendfunc1 = GL_SRC_ALPHA;
820                 m.blendfunc2 = GL_ONE;
821         }
822         else if (surf->currenttexture->fogtexture != NULL || alpha < 1)
823         {
824                 m.blendfunc1 = GL_SRC_ALPHA;
825                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
826         }
827         else
828         {
829                 m.blendfunc1 = GL_ONE;
830                 m.blendfunc2 = GL_ZERO;
831         }
832         m.tex[0] = R_GetTexture(surf->currenttexture->texture);
833         colorscale = r_colorscale;
834         if (gl_combine.integer)
835         {
836                 m.texrgbscale[0] = 4;
837                 colorscale *= 0.25f;
838         }
839         R_Mesh_State(&m);
840         GL_UseColorArray();
841         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
842         {
843                 R_Mesh_ResizeCheck(mesh->numverts);
844                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
845                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
846                 f = surf->flags & SURF_DRAWFULLBRIGHT ? 1.0f : ((surf->flags & SURF_LIGHTMAP) ? 0 : 0.5f);
847                 R_FillColors(varray_color, mesh->numverts, f, f, f, alpha);
848                 if (!(surf->flags & SURF_DRAWFULLBRIGHT || ent->effects & EF_FULLBRIGHT))
849                 {
850                         if (surf->dlightframe == r_framecount)
851                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
852                         if (surf->flags & SURF_LIGHTMAP)
853                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
854                 }
855                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
856                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
857         }
858
859         if (fogenabled)
860         {
861                 memset(&m, 0, sizeof(m));
862                 m.blendfunc1 = GL_SRC_ALPHA;
863                 m.blendfunc2 = GL_ONE;
864                 m.tex[0] = R_GetTexture(surf->currenttexture->fogtexture);
865                 R_Mesh_State(&m);
866                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
867                 {
868                         R_Mesh_ResizeCheck(mesh->numverts);
869                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
870                         if (m.tex[0])
871                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
872                         RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], alpha, r_colorscale, mesh->numverts, modelorg);
873                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
874                 }
875         }
876 }
877
878 static void RSurfShader_Water(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
879 {
880         const msurface_t *surf;
881         vec3_t center;
882         if ((r_wateralpha.value < 1 && !(texture->flags & SURF_DRAWNOALPHA)) || ent->effects & EF_ADDITIVE || texture->fogtexture)
883         {
884                 for (surf = firstsurf;surf;surf = surf->texturechain)
885                 {
886                         if (surf->visframe == r_framecount)
887                         {
888                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
889                                 R_MeshQueue_AddTransparent(center, RSurfShader_Water_Callback, ent, surf - ent->model->surfaces);
890                         }
891                 }
892         }
893         else
894                 for (surf = firstsurf;surf;surf = surf->texturechain)
895                         if (surf->visframe == r_framecount)
896                                 RSurfShader_Water_Callback(ent, surf - ent->model->surfaces);
897 }
898
899 static void RSurfShader_Wall_Pass_BaseVertex(const entity_render_t *ent, const msurface_t *surf)
900 {
901         float base, colorscale;
902         const surfmesh_t *mesh;
903         rmeshstate_t m;
904         float modelorg[3];
905         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
906         memset(&m, 0, sizeof(m));
907         if (ent->effects & EF_ADDITIVE)
908         {
909                 m.blendfunc1 = GL_SRC_ALPHA;
910                 m.blendfunc2 = GL_ONE;
911         }
912         else if (surf->currenttexture->fogtexture != NULL || ent->alpha < 1)
913         {
914                 m.blendfunc1 = GL_SRC_ALPHA;
915                 m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
916         }
917         else
918         {
919                 m.blendfunc1 = GL_ONE;
920                 m.blendfunc2 = GL_ZERO;
921         }
922         m.tex[0] = R_GetTexture(surf->currenttexture->texture);
923         colorscale = r_colorscale;
924         if (gl_combine.integer)
925         {
926                 m.texrgbscale[0] = 4;
927                 colorscale *= 0.25f;
928         }
929         base = ent->effects & EF_FULLBRIGHT ? 2.0f : r_ambient.value * (1.0f / 64.0f);
930         R_Mesh_State(&m);
931         GL_UseColorArray();
932         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
933         {
934                 R_Mesh_ResizeCheck(mesh->numverts);
935                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
936                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
937                 R_FillColors(varray_color, mesh->numverts, base, base, base, ent->alpha);
938                 if (!(ent->effects & EF_FULLBRIGHT))
939                 {
940                         if (surf->dlightframe == r_framecount)
941                                 RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
942                         if (surf->flags & SURF_LIGHTMAP)
943                                 RSurf_AddLightmapToVertexColors(mesh->lightmapoffsets, varray_color, mesh->numverts, surf->samples, ((surf->extents[0]>>4)+1)*((surf->extents[1]>>4)+1)*3, surf->styles);
944                 }
945                 RSurf_FogColors(varray_vertex, varray_color, colorscale, mesh->numverts, modelorg);
946                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
947         }
948 }
949
950 static void RSurfShader_Wall_Pass_Glow(const entity_render_t *ent, const msurface_t *surf)
951 {
952         const surfmesh_t *mesh;
953         rmeshstate_t m;
954         float modelorg[3];
955         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
956         memset(&m, 0, sizeof(m));
957         m.blendfunc1 = GL_SRC_ALPHA;
958         m.blendfunc2 = GL_ONE;
959         m.tex[0] = R_GetTexture(surf->currenttexture->glowtexture);
960         R_Mesh_State(&m);
961         GL_UseColorArray();
962         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
963         {
964                 R_Mesh_ResizeCheck(mesh->numverts);
965                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
966                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
967                 RSurf_FoggedColors(varray_vertex, varray_color, 1, 1, 1, ent->alpha, r_colorscale, mesh->numverts, modelorg);
968                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
969         }
970 }
971
972 static void RSurfShader_Wall_Pass_Fog(const entity_render_t *ent, const msurface_t *surf)
973 {
974         const surfmesh_t *mesh;
975         rmeshstate_t m;
976         float modelorg[3];
977         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
978         memset(&m, 0, sizeof(m));
979         m.blendfunc1 = GL_SRC_ALPHA;
980         m.blendfunc2 = GL_ONE;
981         m.tex[0] = R_GetTexture(surf->currenttexture->fogtexture);
982         R_Mesh_State(&m);
983         GL_UseColorArray();
984         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
985         {
986                 R_Mesh_ResizeCheck(mesh->numverts);
987                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
988                 if (m.tex[0])
989                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
990                 RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], ent->alpha, r_colorscale, mesh->numverts, modelorg);
991                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
992         }
993 }
994
995 static void RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
996 {
997         const msurface_t *surf;
998         const surfmesh_t *mesh;
999         rmeshstate_t m;
1000         int lightmaptexturenum;
1001         float cl;
1002         memset(&m, 0, sizeof(m));
1003         m.blendfunc1 = GL_ONE;
1004         m.blendfunc2 = GL_ZERO;
1005         m.tex[0] = R_GetTexture(texture->texture);
1006         m.tex[1] = R_GetTexture(firstsurf->lightmaptexture);
1007         m.tex[2] = R_GetTexture(texture->detailtexture);
1008         m.texrgbscale[0] = 1;
1009         m.texrgbscale[1] = 4;
1010         m.texrgbscale[2] = 2;
1011         R_Mesh_State(&m);
1012         cl = (float) (1 << r_lightmapscalebit) * r_colorscale;
1013         GL_Color(cl, cl, cl, 1);
1014         for (surf = firstsurf;surf;surf = surf->texturechain)
1015         {
1016                 if (surf->visframe == r_framecount)
1017                 {
1018                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1019                         if (m.tex[1] != lightmaptexturenum)
1020                         {
1021                                 m.tex[1] = lightmaptexturenum;
1022                                 R_Mesh_State(&m);
1023                         }
1024                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1025                         {
1026                                 R_Mesh_ResizeCheck(mesh->numverts);
1027                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1028                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1029                                 memcpy(varray_texcoord[1], mesh->uvw, mesh->numverts * sizeof(float[4]));
1030                                 memcpy(varray_texcoord[2], mesh->abc, mesh->numverts * sizeof(float[4]));
1031                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1032                         }
1033                 }
1034         }
1035 }
1036
1037 static void RSurfShader_OpaqueWall_Pass_BaseDoubleTex(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1038 {
1039         const msurface_t *surf;
1040         const surfmesh_t *mesh;
1041         rmeshstate_t m;
1042         int lightmaptexturenum;
1043         memset(&m, 0, sizeof(m));
1044         m.blendfunc1 = GL_ONE;
1045         m.blendfunc2 = GL_ZERO;
1046         m.tex[0] = R_GetTexture(texture->texture);
1047         m.tex[1] = R_GetTexture(firstsurf->lightmaptexture);
1048         if (gl_combine.integer)
1049                 m.texrgbscale[1] = 4;
1050         R_Mesh_State(&m);
1051         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1052         for (surf = firstsurf;surf;surf = surf->texturechain)
1053         {
1054                 if (surf->visframe == r_framecount)
1055                 {
1056                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1057                         if (m.tex[1] != lightmaptexturenum)
1058                         {
1059                                 m.tex[1] = lightmaptexturenum;
1060                                 R_Mesh_State(&m);
1061                         }
1062                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1063                         {
1064                                 R_Mesh_ResizeCheck(mesh->numverts);
1065                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1066                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1067                                 memcpy(varray_texcoord[1], mesh->uvw, mesh->numverts * sizeof(float[4]));
1068                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1069                         }
1070                 }
1071         }
1072 }
1073
1074 static void RSurfShader_OpaqueWall_Pass_BaseTexture(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1075 {
1076         const msurface_t *surf;
1077         const surfmesh_t *mesh;
1078         rmeshstate_t m;
1079         memset(&m, 0, sizeof(m));
1080         m.blendfunc1 = GL_ONE;
1081         m.blendfunc2 = GL_ZERO;
1082         m.tex[0] = R_GetTexture(texture->texture);
1083         R_Mesh_State(&m);
1084         GL_Color(1, 1, 1, 1);
1085         for (surf = firstsurf;surf;surf = surf->texturechain)
1086         {
1087                 if (surf->visframe == r_framecount)
1088                 {
1089                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1090                         {
1091                                 R_Mesh_ResizeCheck(mesh->numverts);
1092                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1093                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1094                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1095                         }
1096                 }
1097         }
1098 }
1099
1100 static void RSurfShader_OpaqueWall_Pass_BaseLightmap(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1101 {
1102         const msurface_t *surf;
1103         const surfmesh_t *mesh;
1104         rmeshstate_t m;
1105         int lightmaptexturenum;
1106         memset(&m, 0, sizeof(m));
1107         m.blendfunc1 = GL_ZERO;
1108         m.blendfunc2 = GL_SRC_COLOR;
1109         m.tex[0] = R_GetTexture(firstsurf->lightmaptexture);
1110         if (gl_combine.integer)
1111                 m.texrgbscale[0] = 4;
1112         R_Mesh_State(&m);
1113         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1114         for (surf = firstsurf;surf;surf = surf->texturechain)
1115         {
1116                 if (surf->visframe == r_framecount)
1117                 {
1118                         lightmaptexturenum = R_GetTexture(surf->lightmaptexture);
1119                         if (m.tex[0] != lightmaptexturenum)
1120                         {
1121                                 m.tex[0] = lightmaptexturenum;
1122                                 R_Mesh_State(&m);
1123                         }
1124                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1125                         {
1126                                 R_Mesh_ResizeCheck(mesh->numverts);
1127                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1128                                 memcpy(varray_texcoord[0], mesh->uvw, mesh->numverts * sizeof(float[4]));
1129                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1130                         }
1131                 }
1132         }
1133 }
1134
1135 static void RSurfShader_OpaqueWall_Pass_Light(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1136 {
1137         const msurface_t *surf;
1138         const surfmesh_t *mesh;
1139         float colorscale;
1140         rmeshstate_t m;
1141
1142         memset(&m, 0, sizeof(m));
1143         m.blendfunc1 = GL_SRC_ALPHA;
1144         m.blendfunc2 = GL_ONE;
1145         m.tex[0] = R_GetTexture(texture->texture);
1146         colorscale = r_colorscale;
1147         if (gl_combine.integer)
1148         {
1149                 m.texrgbscale[0] = 4;
1150                 colorscale *= 0.25f;
1151         }
1152         R_Mesh_State(&m);
1153         GL_UseColorArray();
1154         for (surf = firstsurf;surf;surf = surf->texturechain)
1155         {
1156                 if (surf->visframe == r_framecount && surf->dlightframe == r_framecount)
1157                 {
1158                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1159                         {
1160                                 if (RSurf_LightCheck(&ent->inversematrix, surf->dlightbits, mesh))
1161                                 {
1162                                         R_Mesh_ResizeCheck(mesh->numverts);
1163                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1164                                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1165                                         R_FillColors(varray_color, mesh->numverts, 0, 0, 0, 1);
1166                                         RSurf_LightSeparate(&ent->inversematrix, surf->dlightbits, mesh->numverts, varray_vertex, varray_color);
1167                                         RSurf_ScaleColors(varray_color, colorscale, mesh->numverts);
1168                                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1169                                 }
1170                         }
1171                 }
1172         }
1173 }
1174
1175 static void RSurfShader_OpaqueWall_Pass_Fog(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1176 {
1177         const msurface_t *surf;
1178         const surfmesh_t *mesh;
1179         rmeshstate_t m;
1180         float modelorg[3];
1181         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1182         memset(&m, 0, sizeof(m));
1183         m.blendfunc1 = GL_SRC_ALPHA;
1184         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1185         R_Mesh_State(&m);
1186         GL_UseColorArray();
1187         for (surf = firstsurf;surf;surf = surf->texturechain)
1188         {
1189                 if (surf->visframe == r_framecount)
1190                 {
1191                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1192                         {
1193                                 R_Mesh_ResizeCheck(mesh->numverts);
1194                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1195                                 if (m.tex[0])
1196                                         memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1197                                 RSurf_FogPassColors(varray_vertex, varray_color, fogcolor[0], fogcolor[1], fogcolor[2], 1, r_colorscale, mesh->numverts, modelorg);
1198                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1199                         }
1200                 }
1201         }
1202 }
1203
1204 static void RSurfShader_OpaqueWall_Pass_BaseDetail(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1205 {
1206         const msurface_t *surf;
1207         const surfmesh_t *mesh;
1208         rmeshstate_t m;
1209         memset(&m, 0, sizeof(m));
1210         m.blendfunc1 = GL_DST_COLOR;
1211         m.blendfunc2 = GL_SRC_COLOR;
1212         m.tex[0] = R_GetTexture(texture->detailtexture);
1213         R_Mesh_State(&m);
1214         GL_Color(1, 1, 1, 1);
1215         for (surf = firstsurf;surf;surf = surf->texturechain)
1216         {
1217                 if (surf->visframe == r_framecount)
1218                 {
1219                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1220                         {
1221                                 R_Mesh_ResizeCheck(mesh->numverts);
1222                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1223                                 memcpy(varray_texcoord[0], mesh->abc, mesh->numverts * sizeof(float[4]));
1224                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1225                         }
1226                 }
1227         }
1228 }
1229
1230 static void RSurfShader_OpaqueWall_Pass_Glow(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1231 {
1232         const msurface_t *surf;
1233         const surfmesh_t *mesh;
1234         rmeshstate_t m;
1235         memset(&m, 0, sizeof(m));
1236         m.blendfunc1 = GL_SRC_ALPHA;
1237         m.blendfunc2 = GL_ONE;
1238         m.tex[0] = R_GetTexture(texture->glowtexture);
1239         R_Mesh_State(&m);
1240         GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1241         for (surf = firstsurf;surf;surf = surf->texturechain)
1242         {
1243                 if (surf->visframe == r_framecount)
1244                 {
1245                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1246                         {
1247                                 R_Mesh_ResizeCheck(mesh->numverts);
1248                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1249                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1250                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1251                         }
1252                 }
1253         }
1254 }
1255
1256 static void RSurfShader_OpaqueWall_Pass_OpaqueGlow(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1257 {
1258         const msurface_t *surf;
1259         const surfmesh_t *mesh;
1260         rmeshstate_t m;
1261         memset(&m, 0, sizeof(m));
1262         m.blendfunc1 = GL_SRC_ALPHA;
1263         m.blendfunc2 = GL_ZERO;
1264         m.tex[0] = R_GetTexture(texture->glowtexture);
1265         R_Mesh_State(&m);
1266         if (m.tex[0])
1267                 GL_Color(r_colorscale, r_colorscale, r_colorscale, 1);
1268         else
1269                 GL_Color(0, 0, 0, 1);
1270         for (surf = firstsurf;surf;surf = surf->texturechain)
1271         {
1272                 if (surf->visframe == r_framecount)
1273                 {
1274                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1275                         {
1276                                 R_Mesh_ResizeCheck(mesh->numverts);
1277                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1278                                 memcpy(varray_texcoord[0], mesh->str, mesh->numverts * sizeof(float[4]));
1279                                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->index);
1280                         }
1281                 }
1282         }
1283 }
1284
1285 static void RSurfShader_Wall_Vertex_Callback(const void *calldata1, int calldata2)
1286 {
1287         const entity_render_t *ent = calldata1;
1288         const msurface_t *surf = ent->model->surfaces + calldata2;
1289         R_Mesh_Matrix(&ent->matrix);
1290         RSurfShader_Wall_Pass_BaseVertex(ent, surf);
1291         if (surf->currenttexture->glowtexture)
1292                 RSurfShader_Wall_Pass_Glow(ent, surf);
1293         if (fogenabled)
1294                 RSurfShader_Wall_Pass_Fog(ent, surf);
1295 }
1296
1297 static void RSurfShader_Wall_Lightmap(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1298 {
1299         const msurface_t *surf;
1300         vec3_t center;
1301         if (texture->rendertype != SURFRENDER_OPAQUE)
1302         {
1303                 // transparent vertex shaded from lightmap
1304                 for (surf = firstsurf;surf;surf = surf->texturechain)
1305                 {
1306                         if (surf->visframe == r_framecount)
1307                         {
1308                                 Matrix4x4_Transform(&ent->matrix, surf->poly_center, center);
1309                                 R_MeshQueue_AddTransparent(center, RSurfShader_Wall_Vertex_Callback, ent, surf - ent->model->surfaces);
1310                         }
1311                 }
1312         }
1313         else if (r_vertexsurfaces.integer)
1314         {
1315                 // opaque vertex shaded from lightmap
1316                 for (surf = firstsurf;surf;surf = surf->texturechain)
1317                         if (surf->visframe == r_framecount)
1318                                 RSurfShader_Wall_Pass_BaseVertex(ent, surf);
1319                 if (texture->glowtexture)
1320                         for (surf = firstsurf;surf;surf = surf->texturechain)
1321                                 if (surf->visframe == r_framecount)
1322                                         RSurfShader_Wall_Pass_Glow(ent, surf);
1323                 if (fogenabled)
1324                         for (surf = firstsurf;surf;surf = surf->texturechain)
1325                                 if (surf->visframe == r_framecount)
1326                                         RSurfShader_Wall_Pass_Fog(ent, surf);
1327         }
1328         else
1329         {
1330                 // opaque lightmapped
1331                 if (r_textureunits.integer >= 2)
1332                 {
1333                         if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1334                                 RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture, firstsurf);
1335                         else
1336                         {
1337                                 RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture, firstsurf);
1338                                 if (r_detailtextures.integer)
1339                                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, firstsurf);
1340                         }
1341                 }
1342                 else
1343                 {
1344                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, firstsurf);
1345                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, firstsurf);
1346                         if (r_detailtextures.integer)
1347                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, firstsurf);
1348                 }
1349                 if (!r_dlightmap.integer && !(ent->effects & EF_FULLBRIGHT))
1350                         RSurfShader_OpaqueWall_Pass_Light(ent, texture, firstsurf);
1351                 if (texture->glowtexture)
1352                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, firstsurf);
1353                 if (fogenabled)
1354                         RSurfShader_OpaqueWall_Pass_Fog(ent, texture, firstsurf);
1355         }
1356 }
1357
1358 static void RSurfShader_Wall_Lightmap_BaseLighting(const entity_render_t *ent, const texture_t *texture, const msurface_t *firstsurf)
1359 {
1360         const msurface_t *surf;
1361         if (cl.worldmodel->numlights)
1362                 RSurfShader_OpaqueWall_Pass_OpaqueGlow(ent, texture, firstsurf);
1363         else if (r_vertexsurfaces.integer)
1364         {
1365                 // opaque vertex shaded from lightmap
1366                 for (surf = firstsurf;surf;surf = surf->texturechain)
1367                         if (surf->visframe == r_framecount)
1368                                 RSurfShader_Wall_Pass_BaseVertex(ent, surf);
1369                 if (texture->glowtexture)
1370                         for (surf = firstsurf;surf;surf = surf->texturechain)
1371                                 if (surf->visframe == r_framecount)
1372                                         RSurfShader_Wall_Pass_Glow(ent, surf);
1373         }
1374         else
1375         {
1376                 // opaque lightmapped
1377                 if (r_textureunits.integer >= 2)
1378                 {
1379                         if (r_textureunits.integer >= 3 && gl_combine.integer && r_detailtextures.integer)
1380                                 RSurfShader_OpaqueWall_Pass_BaseTripleTexCombine(ent, texture, firstsurf);
1381                         else
1382                         {
1383                                 RSurfShader_OpaqueWall_Pass_BaseDoubleTex(ent, texture, firstsurf);
1384                                 if (r_detailtextures.integer)
1385                                         RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, firstsurf);
1386                         }
1387                 }
1388                 else
1389                 {
1390                         RSurfShader_OpaqueWall_Pass_BaseTexture(ent, texture, firstsurf);
1391                         RSurfShader_OpaqueWall_Pass_BaseLightmap(ent, texture, firstsurf);
1392                         if (r_detailtextures.integer)
1393                                 RSurfShader_OpaqueWall_Pass_BaseDetail(ent, texture, firstsurf);
1394                 }
1395                 if (!r_dlightmap.integer && !(ent->effects & EF_FULLBRIGHT))
1396                         RSurfShader_OpaqueWall_Pass_Light(ent, texture, firstsurf);
1397                 if (texture->glowtexture)
1398                         RSurfShader_OpaqueWall_Pass_Glow(ent, texture, firstsurf);
1399         }
1400 }
1401
1402 Cshader_t Cshader_wall_lightmap = {{NULL, RSurfShader_Wall_Lightmap, RSurfShader_Wall_Lightmap_BaseLighting}, SHADERFLAGS_NEEDLIGHTMAP};
1403 Cshader_t Cshader_water = {{NULL, RSurfShader_Water, NULL}, 0};
1404 Cshader_t Cshader_sky = {{RSurfShader_Sky, NULL, NULL}, 0};
1405
1406 int Cshader_count = 3;
1407 Cshader_t *Cshaders[3] =
1408 {
1409         &Cshader_wall_lightmap,
1410         &Cshader_water,
1411         &Cshader_sky
1412 };
1413
1414 void R_PrepareSurfaces(entity_render_t *ent)
1415 {
1416         int i, texframe, numsurfaces, *surfacevisframes;
1417         model_t *model;
1418         msurface_t *surf, *surfaces;
1419         texture_t *t;
1420         vec3_t modelorg;
1421
1422         if (!ent->model)
1423                 return;
1424
1425         model = ent->model;
1426         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1427         numsurfaces = model->nummodelsurfaces;
1428         surfaces = model->surfaces + model->firstmodelsurface;
1429         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1430
1431         texframe = (int)(cl.time * 5.0f);
1432         for (i = 0;i < model->numtextures;i++)
1433         {
1434                 t = model->textures + i;
1435                 if (ent->effects & EF_ADDITIVE)
1436                         t->rendertype = SURFRENDER_ADD;
1437                 else if (ent->alpha < 1 || t->flags & SURF_WATERALPHA || t->fogtexture != NULL)
1438                         t->rendertype = SURFRENDER_ALPHA;
1439                 else
1440                         t->rendertype = SURFRENDER_OPAQUE;
1441                 if (t->animated)
1442                 {
1443                         t->currentframe[0] = t->anim_frames[0][(t->anim_total[0] >= 2) ? (texframe % t->anim_total[0]) : 0];
1444                         t->currentframe[1] = t->anim_frames[1][(t->anim_total[1] >= 2) ? (texframe % t->anim_total[1]) : 0];
1445                 }
1446         }
1447
1448         if (r_dynamic.integer)
1449                 R_MarkLights(ent);
1450
1451         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1452         {
1453                 if (surfacevisframes[i] == r_framecount)
1454                 {
1455 #if !WORLDNODECULLBACKFACES
1456                         // mark any backface surfaces as not visible
1457                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1458                         {
1459                                 if (!(surf->flags & SURF_PLANEBACK))
1460                                         surfacevisframes[i] = -1;
1461                         }
1462                         else
1463                         {
1464                                 if ((surf->flags & SURF_PLANEBACK))
1465                                         surfacevisframes[i] = -1;
1466                         }
1467                         if (surfacevisframes[i] == r_framecount)
1468 #endif
1469                         {
1470                                 c_faces++;
1471                                 surf->visframe = r_framecount;
1472                                 if (!r_vertexsurfaces.integer && surf->lightmaptexture != NULL)
1473                                 {
1474                                         if (surf->cached_dlight
1475                                          || surf->cached_ambient != r_ambient.value
1476                                          || surf->cached_lightmapscalebit != r_lightmapscalebit)
1477                                                 R_BuildLightMap(ent, surf, false); // base lighting changed
1478                                         else if (r_dynamic.integer)
1479                                         {
1480                                                 if  (surf->styles[0] != 255 && (d_lightstylevalue[surf->styles[0]] != surf->cached_light[0]
1481                                                  || (surf->styles[1] != 255 && (d_lightstylevalue[surf->styles[1]] != surf->cached_light[1]
1482                                                  || (surf->styles[2] != 255 && (d_lightstylevalue[surf->styles[2]] != surf->cached_light[2]
1483                                                  || (surf->styles[3] != 255 && (d_lightstylevalue[surf->styles[3]] != surf->cached_light[3]))))))))
1484                                                         R_BuildLightMap(ent, surf, false); // base lighting changed
1485                                                 else if (surf->dlightframe == r_framecount && r_dlightmap.integer)
1486                                                         R_BuildLightMap(ent, surf, true); // only dlights
1487                                         }
1488                                 }
1489                         }
1490                 }
1491         }
1492 }
1493
1494 void R_DrawSurfaces(entity_render_t *ent, int type)
1495 {
1496         int i;
1497         texture_t *t;
1498         R_Mesh_Matrix(&ent->matrix);
1499         for (i = 0, t = ent->model->textures;i < ent->model->numtextures;i++, t++)
1500                 if (t->shader->shaderfunc[type] && ent->model->texturesurfacechains[i])
1501                         t->shader->shaderfunc[type](ent, t, ent->model->texturesurfacechains[i]);
1502 }
1503
1504 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
1505 {
1506         int i;
1507         float *v;
1508         rmeshstate_t m;
1509         const entity_render_t *ent = calldata1;
1510         const mportal_t *portal = ent->model->portals + calldata2;
1511         memset(&m, 0, sizeof(m));
1512         m.blendfunc1 = GL_SRC_ALPHA;
1513         m.blendfunc2 = GL_ONE_MINUS_SRC_ALPHA;
1514         R_Mesh_Matrix(&ent->matrix);
1515         R_Mesh_State(&m);
1516         R_Mesh_ResizeCheck(portal->numpoints);
1517         i = portal - ent->model->portals;
1518         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_colorscale,
1519                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_colorscale,
1520                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_colorscale,
1521                          0.125f);
1522         if (PlaneDiff(r_origin, (&portal->plane)) > 0)
1523         {
1524                 for (i = portal->numpoints - 1, v = varray_vertex;i >= 0;i--, v += 4)
1525                         VectorCopy(portal->points[i].position, v);
1526         }
1527         else
1528                 for (i = 0, v = varray_vertex;i < portal->numpoints;i++, v += 4)
1529                         VectorCopy(portal->points[i].position, v);
1530         R_Mesh_Draw(portal->numpoints, portal->numpoints - 2, polygonelements);
1531 }
1532
1533 static void R_DrawPortals(entity_render_t *ent)
1534 {
1535         int i;
1536         mportal_t *portal, *endportal;
1537         float temp[3], center[3], f;
1538
1539         if (r_drawportals.integer < 1)
1540                 return;
1541
1542         for (portal = ent->model->portals, endportal = portal + ent->model->numportals;portal < endportal;portal++)
1543         {
1544                 if (portal->here->pvsframe == ent->model->pvsframecount || portal->past->pvsframe == ent->model->pvsframecount)
1545                 {
1546                         if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
1547                         {
1548                                 VectorClear(temp);
1549                                 for (i = 0;i < portal->numpoints;i++)
1550                                         VectorAdd(temp, portal->points[i].position, temp);
1551                                 f = ixtable[portal->numpoints];
1552                                 VectorScale(temp, f, temp);
1553                                 Matrix4x4_Transform(&ent->matrix, temp, center);
1554                                 R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, ent, portal - ent->model->portals);
1555                         }
1556                 }
1557         }
1558 }
1559
1560 void R_PrepareBrushModel(entity_render_t *ent)
1561 {
1562         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1563         msurface_t *surf;
1564         model_t *model;
1565 #if WORLDNODECULLBACKFACES
1566         vec3_t modelorg;
1567 #endif
1568
1569         // because bmodels can be reused, we have to decide which things to render
1570         // from scratch every time
1571         model = ent->model;
1572 #if WORLDNODECULLBACKFACES
1573         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1574 #endif
1575         numsurfaces = model->nummodelsurfaces;
1576         surf = model->surfaces + model->firstmodelsurface;
1577         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1578         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1579         for (i = 0;i < numsurfaces;i++, surf++)
1580         {
1581 #if WORLDNODECULLBACKFACES
1582                 // mark any backface surfaces as not visible
1583                 if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1584                 {
1585                         if ((surf->flags & SURF_PLANEBACK))
1586                         {
1587                                 surfacevisframes[i] = r_framecount;
1588                                 surfacepvsframes[i] = model->pvsframecount;
1589                         }
1590                 }
1591                 else
1592                 {
1593                         if (!(surf->flags & SURF_PLANEBACK))
1594                         {
1595                                 surfacevisframes[i] = r_framecount;
1596                                 surfacepvsframes[i] = model->pvsframecount;
1597                         }
1598                 }
1599 #else
1600                 surfacevisframes[i] = r_framecount;
1601                 surfacepvsframes[i] = model->pvsframecount;
1602 #endif
1603                 surf->dlightframe = -1;
1604         }
1605         R_PrepareSurfaces(ent);
1606 }
1607
1608 void R_SurfaceWorldNode (entity_render_t *ent)
1609 {
1610         int i, numsurfaces, *surfacevisframes, *surfacepvsframes;
1611         msurface_t *surfaces, *surf;
1612         model_t *model;
1613         vec3_t modelorg;
1614
1615         model = ent->model;
1616         numsurfaces = model->nummodelsurfaces;
1617         surfaces = model->surfaces + model->firstmodelsurface;
1618         surfacevisframes = model->surfacevisframes + model->firstmodelsurface;
1619         surfacepvsframes = model->surfacepvsframes + model->firstmodelsurface;
1620         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1621
1622         for (i = 0, surf = surfaces;i < numsurfaces;i++, surf++)
1623         {
1624                 if (surfacepvsframes[i] == model->pvsframecount)
1625                 {
1626 #if WORLDNODECULLBACKFACES
1627                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1628                         {
1629                                 if ((surf->flags & SURF_PLANEBACK) && R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1630                                         surfacevisframes[i] = r_framecount;
1631                         }
1632                         else
1633                         {
1634                                 if (!(surf->flags & SURF_PLANEBACK) && R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1635                                         surfacevisframes[i] = r_framecount;
1636                         }
1637 #else
1638                         if (R_NotCulledBox (surf->poly_mins, surf->poly_maxs))
1639                                 surfacevisframes[i] = r_framecount;
1640 #endif
1641                 }
1642         }
1643 }
1644
1645 /*
1646 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1647 {
1648         int portalstack, i;
1649         mportal_t *p, *pstack[8192];
1650         msurface_t *surf, **mark, **endmark;
1651         mleaf_t *leaf;
1652         // LordHavoc: portal-passage worldnode with PVS;
1653         // follows portals leading outward from viewleaf, does not venture
1654         // offscreen or into leafs that are not visible, faster than Quake's
1655         // RecursiveWorldNode
1656         leaf = viewleaf;
1657         leaf->worldnodeframe = r_framecount;
1658         portalstack = 0;
1659 loc0:
1660         c_leafs++;
1661         if (leaf->nummarksurfaces)
1662         {
1663                 for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1664                 {
1665                         surf = *mark++;
1666                         // make sure surfaces are only processed once
1667                         if (surf->worldnodeframe != r_framecount)
1668                         {
1669                                 surf->worldnodeframe = r_framecount;
1670                                 if (PlaneDist(r_origin, surf->plane) < surf->plane->dist)
1671                                 {
1672                                         if (surf->flags & SURF_PLANEBACK)
1673                                                 surf->visframe = r_framecount;
1674                                 }
1675                                 else
1676                                 {
1677                                         if (!(surf->flags & SURF_PLANEBACK))
1678                                                 surf->visframe = r_framecount;
1679                                 }
1680                         }
1681                 }
1682         }
1683         // follow portals into other leafs
1684         for (p = leaf->portals;p;p = p->next)
1685         {
1686                 leaf = p->past;
1687                 if (leaf->worldnodeframe != r_framecount)
1688                 {
1689                         leaf->worldnodeframe = r_framecount;
1690                         // FIXME: R_NotCulledBox is absolute, should be done relative
1691                         if (leaf->pvsframe == ent->model->pvsframecount && R_NotCulledBox(leaf->mins, leaf->maxs))
1692                         {
1693                                 p->visframe = r_framecount;
1694                                 pstack[portalstack++] = p;
1695                                 goto loc0;
1696 loc1:
1697                                 p = pstack[--portalstack];
1698                         }
1699                 }
1700         }
1701         if (portalstack)
1702                 goto loc1;
1703 }
1704 */
1705
1706 static void R_PortalWorldNode(entity_render_t *ent, mleaf_t *viewleaf)
1707 {
1708         int c, leafstackpos, *mark, *surfacevisframes;
1709 #if WORLDNODECULLBACKFACES
1710         int n;
1711         msurface_t *surf;
1712 #endif
1713         mleaf_t *leaf, *leafstack[8192];
1714         mportal_t *p;
1715         vec3_t modelorg;
1716         msurface_t *surfaces;
1717         // LordHavoc: portal-passage worldnode with PVS;
1718         // follows portals leading outward from viewleaf, does not venture
1719         // offscreen or into leafs that are not visible, faster than Quake's
1720         // RecursiveWorldNode
1721         surfaces = ent->model->surfaces;
1722         surfacevisframes = ent->model->surfacevisframes;
1723         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1724         viewleaf->worldnodeframe = r_framecount;
1725         leafstack[0] = viewleaf;
1726         leafstackpos = 1;
1727         while (leafstackpos)
1728         {
1729                 c_leafs++;
1730                 leaf = leafstack[--leafstackpos];
1731                 // draw any surfaces bounding this leaf
1732                 if (leaf->nummarksurfaces)
1733                 {
1734                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1735                         {
1736 #if WORLDNODECULLBACKFACES
1737                                 n = *mark++;
1738                                 if (surfacevisframes[n] != r_framecount)
1739                                 {
1740                                         surf = surfaces + n;
1741                                         if (PlaneDist(modelorg, surf->plane) < surf->plane->dist)
1742                                         {
1743                                                 if ((surf->flags & SURF_PLANEBACK))
1744                                                         surfacevisframes[n] = r_framecount;
1745                                         }
1746                                         else
1747                                         {
1748                                                 if (!(surf->flags & SURF_PLANEBACK))
1749                                                         surfacevisframes[n] = r_framecount;
1750                                         }
1751                                 }
1752 #else
1753                                 surfacevisframes[*mark++] = r_framecount;
1754 #endif
1755                         }
1756                 }
1757                 // follow portals into other leafs
1758                 for (p = leaf->portals;p;p = p->next)
1759                 {
1760                         // LordHavoc: this DotProduct hurts less than a cache miss
1761                         // (which is more likely to happen if backflowing through leafs)
1762                         if (DotProduct(modelorg, p->plane.normal) < (p->plane.dist + 1))
1763                         {
1764                                 leaf = p->past;
1765                                 if (leaf->worldnodeframe != r_framecount)
1766                                 {
1767                                         leaf->worldnodeframe = r_framecount;
1768                                         // FIXME: R_NotCulledBox is absolute, should be done relative
1769                                         if (leaf->pvsframe == ent->model->pvsframecount && R_NotCulledBox(leaf->mins, leaf->maxs))
1770                                                 leafstack[leafstackpos++] = leaf;
1771                                 }
1772                         }
1773                 }
1774         }
1775         if (r_drawportals.integer)
1776                 R_DrawPortals(ent);
1777 }
1778
1779 void R_PVSUpdate (entity_render_t *ent, mleaf_t *viewleaf)
1780 {
1781         int i, j, l, c, bits, *surfacepvsframes, *mark;
1782         mleaf_t *leaf;
1783         qbyte *vis;
1784         model_t *model;
1785
1786         model = ent->model;
1787         if (model && (model->pvsviewleaf != viewleaf || model->pvsviewleafnovis != r_novis.integer))
1788         {
1789                 model->pvsframecount++;
1790                 model->pvsviewleaf = viewleaf;
1791                 model->pvsviewleafnovis = r_novis.integer;
1792                 if (viewleaf)
1793                 {
1794                         surfacepvsframes = model->surfacepvsframes;
1795                         vis = Mod_LeafPVS (viewleaf, model);
1796                         for (j = 0;j < model->numleafs;j += 8)
1797                         {
1798                                 bits = *vis++;
1799                                 if (bits)
1800                                 {
1801                                         l = model->numleafs - j;
1802                                         if (l > 8)
1803                                                 l = 8;
1804                                         for (i = 0;i < l;i++)
1805                                         {
1806                                                 if (bits & (1 << i))
1807                                                 {
1808                                                         leaf = &model->leafs[j + i + 1];
1809                                                         leaf->pvsframe = model->pvsframecount;
1810                                                         // mark surfaces bounding this leaf as visible
1811                                                         for (c = leaf->nummarksurfaces, mark = leaf->firstmarksurface;c;c--)
1812                                                                 surfacepvsframes[*mark++] = model->pvsframecount;
1813                                                 }
1814                                         }
1815                                 }
1816                         }
1817                 }
1818         }
1819 }
1820
1821 /*
1822 =============
1823 R_DrawWorld
1824 =============
1825 */
1826 void R_DrawWorld (entity_render_t *ent, int baselighting)
1827 {
1828         vec3_t modelorg;
1829         mleaf_t *viewleaf;
1830
1831         Matrix4x4_Transform(&ent->inversematrix, r_origin, modelorg);
1832         viewleaf = Mod_PointInLeaf (modelorg, ent->model);
1833         R_PVSUpdate(ent, viewleaf);
1834
1835         if (!viewleaf)
1836                 return;
1837
1838         if (r_surfaceworldnode.integer || viewleaf->contents == CONTENTS_SOLID)
1839                 R_SurfaceWorldNode (ent);
1840         else
1841                 R_PortalWorldNode (ent, viewleaf);
1842         R_PrepareSurfaces(ent);
1843         R_DrawSurfaces(ent, SHADERSTAGE_SKY);
1844         if (baselighting)
1845                 R_DrawSurfaces(ent, SHADERSTAGE_BASELIGHTING);
1846         else
1847                 R_DrawSurfaces(ent, SHADERSTAGE_NORMAL);
1848 }
1849
1850 void R_Model_Brush_DrawSky (entity_render_t *ent)
1851 {
1852         if (ent != &cl_entities[0].render)
1853                 R_PrepareBrushModel(ent);
1854         R_DrawSurfaces(ent, SHADERSTAGE_SKY);
1855 }
1856
1857 void R_Model_Brush_Draw (entity_render_t *ent)
1858 {
1859         c_bmodels++;
1860         if (ent != &cl_entities[0].render)
1861                 R_PrepareBrushModel(ent);
1862         R_DrawSurfaces(ent, SHADERSTAGE_NORMAL);
1863 }
1864
1865 void R_Model_Brush_DrawBaseLighting (entity_render_t *ent)
1866 {
1867         c_bmodels++;
1868         if (ent != &cl_entities[0].render)
1869                 R_PrepareBrushModel(ent);
1870         R_DrawSurfaces(ent, SHADERSTAGE_BASELIGHTING);
1871         /*
1872         shadowmesh_t *mesh;
1873         if (!cl.worldmodel->numlights)
1874                 GL_Color(0.3, 0.3, 0.3, 1);
1875         for (mesh = ent->model->shadowmesh;mesh;mesh = mesh->next)
1876         {
1877                 R_Mesh_ResizeCheck(mesh->numverts);
1878                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1879                 R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
1880         }
1881         if (!cl.worldmodel->numlights)
1882                 GL_Color(0, 0, 0, 1);
1883         */
1884 }
1885
1886 void R_Model_Brush_DrawShadowVolume (entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int visiblevolume)
1887 {
1888 #if 1
1889         float projectdistance, temp[3];
1890         shadowmesh_t *mesh;
1891         VectorSubtract(relativelightorigin, ent->model->shadowmesh_center, temp);
1892         projectdistance = lightradius + ent->model->shadowmesh_radius - sqrt(DotProduct(temp, temp));
1893         if (projectdistance >= 0.1)
1894         {
1895                 R_Mesh_Matrix(&ent->matrix);
1896                 for (mesh = ent->model->shadowmesh;mesh;mesh = mesh->next)
1897                 {
1898                         R_Mesh_ResizeCheck(mesh->numverts * 2);
1899                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1900                         R_Shadow_Volume(mesh->numverts, mesh->numtriangles, varray_vertex, mesh->elements, mesh->neighbors, relativelightorigin, lightradius, projectdistance, visiblevolume);
1901                 }
1902         }
1903 #else
1904         int i;
1905         msurface_t *surf;
1906         float projectdistance, f, temp[3], lightradius2;
1907         surfmesh_t *mesh;
1908         R_Mesh_Matrix(&ent->matrix);
1909         lightradius2 = lightradius * lightradius;
1910         for (i = 0, surf = ent->model->surfaces + ent->model->firstmodelsurface;i < ent->model->nummodelsurfaces;i++, surf++)
1911         {
1912                 if (surf->rendertype == SURFRENDER_OPAQUE && surf->flags & SURF_SHADOWCAST)
1913                 {
1914                         f = PlaneDiff(relativelightorigin, surf->plane);
1915                         if (surf->flags & SURF_PLANEBACK)
1916                                 f = -f;
1917                         // draw shadows only for backfaces
1918                         projectdistance = lightradius + f;
1919                         if (projectdistance >= 0.1 && projectdistance < lightradius)
1920                         {
1921                                 VectorSubtract(relativelightorigin, surf->poly_center, temp);
1922                                 if (DotProduct(temp, temp) < (surf->poly_radius2 + lightradius2))
1923                                 {
1924                                         for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1925                                         {
1926                                                 R_Mesh_ResizeCheck(mesh->numverts * 2);
1927                                                 memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1928                                                 R_Shadow_Volume(mesh->numverts, mesh->numtriangles, varray_vertex, mesh->index, mesh->triangleneighbors, relativelightorigin, lightradius, projectdistance, visiblevolume);
1929                                         }
1930                                 }
1931                         }
1932                 }
1933         }
1934 #endif
1935 }
1936
1937 void R_Model_Brush_DrawLight(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativeeyeorigin, float lightradius, float lightdistbias, float lightsubtract, float *lightcolor)
1938 {
1939         int tnum;
1940         msurface_t *surf;
1941         texture_t *t;
1942         float f, lightradius2;
1943         surfmesh_t *mesh;
1944         R_Mesh_Matrix(&ent->matrix);
1945         if (ent != &cl_entities[0].render)
1946                 R_PrepareBrushModel(ent);
1947         lightradius2 = lightradius * lightradius;
1948         for (tnum = 0;tnum < ent->model->numtextures;tnum++)
1949         {
1950                 t = ent->model->textures + tnum;
1951                 if (ent->model->texturesurfacechains[tnum] && t->rendertype == SURFRENDER_OPAQUE && t->flags & SURF_SHADOWLIGHT)
1952                 {
1953                         t = t->currentframe[ent->frame != 0];
1954                         for (surf = ent->model->texturesurfacechains[tnum];surf;surf = surf->texturechain)
1955                         {
1956                                 if (surf->visframe == r_framecount)
1957                                 {
1958                                         f = PlaneDiff(relativelightorigin, surf->plane);
1959                                         if (surf->flags & SURF_PLANEBACK)
1960                                                 f = -f;
1961                                         if (f >= -0.1 && f < lightradius)
1962                                         {
1963                                                 for (mesh = surf->mesh;mesh;mesh = mesh->chain)
1964                                                 {
1965                                                         R_Mesh_ResizeCheck(mesh->numverts);
1966                                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
1967                                                         R_Shadow_RenderLighting(mesh->numverts, mesh->numtriangles, mesh->index, mesh->svectors, mesh->tvectors, mesh->normals, mesh->str, relativelightorigin, relativeeyeorigin, lightradius, lightcolor, t->texture, r_notexture, NULL, NULL);
1968                                                 }
1969                                         }
1970                                 }
1971                         }
1972                 }
1973         }
1974 }
1975
1976 /*
1977 extern cvar_t r_shadows;
1978 void R_DrawBrushModelFakeShadow (entity_render_t *ent)
1979 {
1980         int i;
1981         vec3_t relativelightorigin;
1982         rmeshstate_t m;
1983         mlight_t *sl;
1984         rdlight_t *rd;
1985         svbspmesh_t *mesh;
1986
1987         if (r_shadows.integer < 2)
1988                 return;
1989
1990         memset(&m, 0, sizeof(m));
1991         m.blendfunc1 = GL_ONE;
1992         m.blendfunc2 = GL_ONE;
1993         R_Mesh_State(&m);
1994         R_Mesh_Matrix(&ent->matrix);
1995         GL_Color(0.0125 * r_colorscale, 0.025 * r_colorscale, 0.1 * r_colorscale, 1);
1996         if (0)//ent->model == cl.worldmodel)
1997         {
1998                 for (i = 0, sl = cl.worldmodel->lights;i < cl.worldmodel->numlights;i++, sl++)
1999                 {
2000                         if (d_lightstylevalue[sl->style] > 0 && R_NotCulledBox(sl->shadowvolumemins, sl->shadowvolumemaxs))
2001                         {
2002                                 for (mesh = sl->shadowvolume;mesh;mesh = mesh->next)
2003                                 {
2004                                         memcpy(varray_vertex, mesh->verts, mesh->numverts * sizeof(float[4]));
2005                                         R_Mesh_Draw(mesh->numverts, mesh->numtriangles, mesh->elements);
2006                                 }
2007                         }
2008                 }
2009         }
2010         else
2011         {
2012                 for (i = 0, sl = cl.worldmodel->lights;i < cl.worldmodel->numlights;i++, sl++)
2013                 {
2014                         if (d_lightstylevalue[sl->style] > 0
2015                          && ent->maxs[0] >= sl->origin[0] - sl->cullradius
2016                          && ent->mins[0] <= sl->origin[0] + sl->cullradius
2017                          && ent->maxs[1] >= sl->origin[1] - sl->cullradius
2018                          && ent->mins[1] <= sl->origin[1] + sl->cullradius
2019                          && ent->maxs[2] >= sl->origin[2] - sl->cullradius
2020                          && ent->mins[2] <= sl->origin[2] + sl->cullradius)
2021                         {
2022                                 Matrix4x4_Transform(&ent->inversematrix, sl->origin, relativelightorigin);
2023                                 R_DrawBrushModelShadowVolume (ent, relativelightorigin, sl->cullradius, true);
2024                         }
2025                 }
2026         }
2027         for (i = 0, rd = r_dlight;i < r_numdlights;i++, rd++)
2028         {
2029                 if (ent->maxs[0] >= rd->origin[0] - rd->cullradius
2030                  && ent->mins[0] <= rd->origin[0] + rd->cullradius
2031                  && ent->maxs[1] >= rd->origin[1] - rd->cullradius
2032                  && ent->mins[1] <= rd->origin[1] + rd->cullradius
2033                  && ent->maxs[2] >= rd->origin[2] - rd->cullradius
2034                  && ent->mins[2] <= rd->origin[2] + rd->cullradius)
2035                 {
2036                         Matrix4x4_Transform(&ent->inversematrix, rd->origin, relativelightorigin);
2037                         R_DrawBrushModelShadowVolume (ent, relativelightorigin, rd->cullradius, true);
2038                 }
2039         }
2040 }
2041 */
2042
2043 static void gl_surf_start(void)
2044 {
2045 }
2046
2047 static void gl_surf_shutdown(void)
2048 {
2049 }
2050
2051 static void gl_surf_newmap(void)
2052 {
2053 }
2054
2055 void GL_Surf_Init(void)
2056 {
2057         int i;
2058         dlightdivtable[0] = 4194304;
2059         for (i = 1;i < 32768;i++)
2060                 dlightdivtable[i] = 4194304 / (i << 7);
2061
2062         Cvar_RegisterVariable(&r_ambient);
2063         Cvar_RegisterVariable(&r_vertexsurfaces);
2064         Cvar_RegisterVariable(&r_dlightmap);
2065         Cvar_RegisterVariable(&r_drawportals);
2066         Cvar_RegisterVariable(&r_testvis);
2067         Cvar_RegisterVariable(&r_floatbuildlightmap);
2068         Cvar_RegisterVariable(&r_detailtextures);
2069         Cvar_RegisterVariable(&r_surfaceworldnode);
2070
2071         R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
2072 }
2073