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