]> git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rsurf.c
gl: Fix r_lockpvs behaving like r_lockvisibility. Minor refactoring
[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 #include "portals.h"
25 #include "csprogs.h"
26 #include "image.h"
27
28 cvar_t r_ambient = {CF_CLIENT, "r_ambient", "0", "brightens map, value is 0-128"};
29 cvar_t r_lockpvs = {CF_CLIENT, "r_lockpvs", "0", "disables pvs switching, allows you to walk around and inspect what is visible from a given location in the map (anything not visible from your current location will not be drawn)"};
30 cvar_t r_lockvisibility = {CF_CLIENT, "r_lockvisibility", "0", "disables visibility updates, allows you to walk around and inspect what is visible from a given viewpoint in the map (anything offscreen at the moment this is enabled will not be drawn)"};
31 cvar_t r_useportalculling = {CF_CLIENT, "r_useportalculling", "1", "improve framerate with r_novis 1 by using portal culling - still not as good as compiled visibility data in the map, but it helps (a value of 2 forces use of this even with vis data, which improves framerates in maps without too much complexity, but hurts in extremely complex maps, which is why 2 is not the default mode)"};
32 cvar_t r_usesurfaceculling = {CF_CLIENT, "r_usesurfaceculling", "1", "skip off-screen surfaces (1 = cull surfaces if the map is likely to benefit, 2 = always cull surfaces)"};
33 cvar_t r_vis_trace = {CF_CLIENT, "r_vis_trace", "0", "test if each portal or leaf is visible using tracelines"};
34 cvar_t r_vis_trace_samples = {CF_CLIENT, "r_vis_trace_samples", "1", "use this many randomly positioned tracelines each frame to refresh the visible timer"};
35 cvar_t r_vis_trace_delay = {CF_CLIENT, "r_vis_trace_delay", "1", "keep a portal visible for this many seconds"};
36 cvar_t r_vis_trace_eyejitter = {CF_CLIENT, "r_vis_trace_eyejitter", "8", "use a random offset of this much on the start of each traceline"};
37 cvar_t r_vis_trace_enlarge = {CF_CLIENT, "r_vis_trace_enlarge", "0", "make portal bounds bigger for tests by (1+this)*size"};
38 cvar_t r_vis_trace_expand = {CF_CLIENT, "r_vis_trace_expand", "0", "make portal bounds bigger for tests by this many units"};
39 cvar_t r_vis_trace_pad = {CF_CLIENT, "r_vis_trace_pad", "8", "accept traces that hit within this many units of the portal"};
40 cvar_t r_vis_trace_surfaces = {CF_CLIENT, "r_vis_trace_surfaces", "0", "also use tracelines to cull surfaces"};
41 cvar_t r_q3bsp_renderskydepth = {CF_CLIENT, "r_q3bsp_renderskydepth", "0", "draws sky depth masking in q3 maps (as in q1 maps), this means for example that sky polygons can hide other things"};
42
43 /*
44 ===============
45 R_BuildLightMap
46
47 Combine and scale multiple lightmaps into the 8.8 format in blocklights
48 ===============
49 */
50 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface, int combine)
51 {
52         int smax, tmax, i, size, size3, maps, l;
53         int *bl, scale;
54         unsigned char *lightmap, *out, *stain;
55         model_t *model = ent->model;
56         int *intblocklights;
57         unsigned char *templight;
58
59         smax = (surface->lightmapinfo->extents[0]>>4)+1;
60         tmax = (surface->lightmapinfo->extents[1]>>4)+1;
61         size = smax*tmax;
62         size3 = size*3;
63
64         r_refdef.stats[r_stat_lightmapupdatepixels] += size;
65         r_refdef.stats[r_stat_lightmapupdates]++;
66
67         if (cl.buildlightmapmemorysize < size*sizeof(int[3]))
68         {
69                 cl.buildlightmapmemorysize = size*sizeof(int[3]);
70                 if (cl.buildlightmapmemory)
71                         Mem_Free(cl.buildlightmapmemory);
72                 cl.buildlightmapmemory = (unsigned char *) Mem_Alloc(cls.levelmempool, cl.buildlightmapmemorysize);
73         }
74
75         // these both point at the same buffer, templight is only used for final
76         // processing and can replace the intblocklights data as it goes
77         intblocklights = (int *)cl.buildlightmapmemory;
78         templight = (unsigned char *)cl.buildlightmapmemory;
79
80         // update cached lighting info
81         model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = false;
82
83         lightmap = surface->lightmapinfo->samples;
84
85 // set to full bright if no light data
86         bl = intblocklights;
87         if (!model->brushq1.lightdata)
88         {
89                 for (i = 0;i < size3;i++)
90                         bl[i] = 128*256;
91         }
92         else
93         {
94 // clear to no light
95                 memset(bl, 0, size3*sizeof(*bl));
96
97 // add all the lightmaps
98                 if (lightmap)
99                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
100                                 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
101                                         bl[i] += lightmap[i] * scale;
102         }
103
104         stain = surface->lightmapinfo->stainsamples;
105         bl = intblocklights;
106         out = templight;
107         // the >> 16 shift adjusts down 8 bits to account for the stainmap
108         // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
109         // be doubled during rendering to achieve 2x overbright
110         // (0 = 0.0, 128 = 1.0, 256 = 2.0)
111         if (stain)
112         {
113                 for (i = 0;i < size;i++, bl += 3, stain += 3, out += 4)
114                 {
115                         l = (bl[0] * stain[0]) >> 16;out[2] = min(l, 255);
116                         l = (bl[1] * stain[1]) >> 16;out[1] = min(l, 255);
117                         l = (bl[2] * stain[2]) >> 16;out[0] = min(l, 255);
118                         out[3] = 255;
119                 }
120         }
121         else
122         {
123                 for (i = 0;i < size;i++, bl += 3, out += 4)
124                 {
125                         l = bl[0] >> 8;out[2] = min(l, 255);
126                         l = bl[1] >> 8;out[1] = min(l, 255);
127                         l = bl[2] >> 8;out[0] = min(l, 255);
128                         out[3] = 255;
129                 }
130         }
131
132         if(vid_sRGB.integer && vid_sRGB_fallback.integer && !vid.sRGB3D)
133                 Image_MakesRGBColorsFromLinear_Lightmap(templight, templight, size);
134         R_UpdateTexture(surface->lightmaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], 0, smax, tmax, 1, combine);
135
136         // update the surface's deluxemap if it has one
137         if (surface->deluxemaptexture != r_texture_blanknormalmap)
138         {
139                 vec3_t n;
140                 unsigned char *normalmap = surface->lightmapinfo->nmapsamples;
141                 lightmap = surface->lightmapinfo->samples;
142                 // clear to no normalmap
143                 bl = intblocklights;
144                 memset(bl, 0, size3*sizeof(*bl));
145                 // add all the normalmaps
146                 if (lightmap && normalmap)
147                 {
148                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3, normalmap += size3)
149                         {
150                                 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size;i++)
151                                 {
152                                         // add the normalmap with weighting proportional to the style's lightmap intensity
153                                         l = (int)(VectorLength(lightmap + i*3) * scale);
154                                         bl[i*3+0] += ((int)normalmap[i*3+0] - 128) * l;
155                                         bl[i*3+1] += ((int)normalmap[i*3+1] - 128) * l;
156                                         bl[i*3+2] += ((int)normalmap[i*3+2] - 128) * l;
157                                 }
158                         }
159                 }
160                 bl = intblocklights;
161                 out = templight;
162                 // we simply renormalize the weighted normals to get a valid deluxemap
163                 for (i = 0;i < size;i++, bl += 3, out += 4)
164                 {
165                         VectorCopy(bl, n);
166                         VectorNormalize(n);
167                         l = (int)(n[0] * 128 + 128);out[2] = bound(0, l, 255);
168                         l = (int)(n[1] * 128 + 128);out[1] = bound(0, l, 255);
169                         l = (int)(n[2] * 128 + 128);out[0] = bound(0, l, 255);
170                         out[3] = 255;
171                 }
172                 R_UpdateTexture(surface->deluxemaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], 0, smax, tmax, 1, r_q1bsp_lightmap_updates_combine.integer);
173         }
174 }
175
176 static void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
177 {
178         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
179         msurface_t *surface, *endsurface;
180         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
181         unsigned char *bl;
182         vec3_t impact;
183
184         maxdist = radius * radius;
185         invradius = 1.0f / radius;
186
187 loc0:
188         if (!node->plane)
189                 return;
190         ndist = PlaneDiff(origin, node->plane);
191         if (ndist > radius)
192         {
193                 node = node->children[0];
194                 goto loc0;
195         }
196         if (ndist < -radius)
197         {
198                 node = node->children[1];
199                 goto loc0;
200         }
201
202         dist2 = ndist * ndist;
203         maxdist3 = maxdist - dist2;
204
205         if (node->plane->type < 3)
206         {
207                 VectorCopy(origin, impact);
208                 impact[node->plane->type] -= ndist;
209         }
210         else
211         {
212                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
213                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
214                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
215         }
216
217         for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
218         {
219                 if (surface->lightmapinfo->stainsamples)
220                 {
221                         smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
222                         tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
223
224                         impacts = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0]);
225                         impactt = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1]);
226
227                         s = bound(0, impacts, smax * 16) - impacts;
228                         t = bound(0, impactt, tmax * 16) - impactt;
229                         i = (int)(s * s + t * t + dist2);
230                         if ((i > maxdist) || (smax > (int)(sizeof(sdtable)/sizeof(sdtable[0])))) // smax overflow fix from Andreas Dehmel
231                                 continue;
232
233                         // reduce calculations
234                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
235                                 sdtable[s] = i * i + dist2;
236
237                         bl = surface->lightmapinfo->stainsamples;
238                         smax3 = smax * 3;
239                         stained = false;
240
241                         i = impactt;
242                         for (t = 0;t < tmax;t++, i -= 16)
243                         {
244                                 td = i * i;
245                                 // make sure some part of it is visible on this line
246                                 if (td < maxdist3)
247                                 {
248                                         maxdist2 = maxdist - td;
249                                         for (s = 0;s < smax;s++)
250                                         {
251                                                 if (sdtable[s] < maxdist2)
252                                                 {
253                                                         ratio = lhrandom(0.0f, 1.0f);
254                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
255                                                         if (a >= (1.0f / 64.0f))
256                                                         {
257                                                                 if (a > 1)
258                                                                         a = 1;
259                                                                 bl[0] = (unsigned char) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
260                                                                 bl[1] = (unsigned char) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
261                                                                 bl[2] = (unsigned char) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
262                                                                 stained = true;
263                                                         }
264                                                 }
265                                                 bl += 3;
266                                         }
267                                 }
268                                 else // skip line
269                                         bl += smax3;
270                         }
271                         // force lightmap upload
272                         if (stained)
273                                 model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = true;
274                 }
275         }
276
277         if (node->children[0]->plane)
278         {
279                 if (node->children[1]->plane)
280                 {
281                         R_StainNode(node->children[0], model, origin, radius, fcolor);
282                         node = node->children[1];
283                         goto loc0;
284                 }
285                 else
286                 {
287                         node = node->children[0];
288                         goto loc0;
289                 }
290         }
291         else if (node->children[1]->plane)
292         {
293                 node = node->children[1];
294                 goto loc0;
295         }
296 }
297
298 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)
299 {
300         int n;
301         float fcolor[8];
302         entity_render_t *ent;
303         model_t *model;
304         vec3_t org;
305         if (r_refdef.scene.worldmodel == NULL || !r_refdef.scene.worldmodel->brush.data_nodes || !r_refdef.scene.worldmodel->brushq1.lightdata)
306                 return;
307         fcolor[0] = cr1;
308         fcolor[1] = cg1;
309         fcolor[2] = cb1;
310         fcolor[3] = ca1 * (1.0f / 64.0f);
311         fcolor[4] = cr2 - cr1;
312         fcolor[5] = cg2 - cg1;
313         fcolor[6] = cb2 - cb1;
314         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
315
316         R_StainNode(r_refdef.scene.worldmodel->brush.data_nodes + r_refdef.scene.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.scene.worldmodel, origin, radius, fcolor);
317
318         // look for embedded bmodels
319         for (n = 0;n < cl.num_brushmodel_entities;n++)
320         {
321                 ent = &cl.entities[cl.brushmodel_entities[n]].render;
322                 model = ent->model;
323                 if (model && model->name[0] == '*')
324                 {
325                         if (model->brush.data_nodes)
326                         {
327                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
328                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
329                         }
330                 }
331         }
332 }
333
334
335 /*
336 =============================================================
337
338         BRUSH MODELS
339
340 =============================================================
341 */
342
343 static void R_DrawPortal_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
344 {
345         // due to the hacky nature of this function's parameters, this is never
346         // called with a batch, so numsurfaces is always 1, and the surfacelist
347         // contains only a leaf number for coloring purposes
348         const mportal_t *portal = (mportal_t *)ent;
349         qbool isvis;
350         int i, numpoints;
351         float *v;
352         float vertex3f[POLYGONELEMENTS_MAXPOINTS*3];
353         CHECKGLERROR
354         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
355         GL_DepthMask(false);
356         GL_DepthRange(0, 1);
357         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
358         GL_DepthTest(true);
359         GL_CullFace(GL_NONE);
360         R_EntityMatrix(&identitymatrix);
361
362         numpoints = min(portal->numpoints, POLYGONELEMENTS_MAXPOINTS);
363
364 //      R_Mesh_ResetTextureState();
365
366         isvis = (portal->here->clusterindex >= 0 && portal->past->clusterindex >= 0 && portal->here->clusterindex != portal->past->clusterindex);
367
368         i = surfacelist[0] >> 1;
369         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
370                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
371                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
372                          isvis ? 0.125f : 0.03125f);
373         for (i = 0, v = vertex3f;i < numpoints;i++, v += 3)
374                 VectorCopy(portal->points[i].position, v);
375         R_Mesh_PrepareVertices_Generic_Arrays(numpoints, vertex3f, NULL, NULL);
376         R_SetupShader_Generic_NoTexture(false, false);
377         R_Mesh_Draw(0, numpoints, 0, numpoints - 2, polygonelement3i, NULL, 0, polygonelement3s, NULL, 0);
378 }
379
380 // LadyHavoc: this is just a nice debugging tool, very slow
381 void R_DrawPortals(void)
382 {
383         int i, leafnum;
384         mportal_t *portal;
385         float center[3], f;
386         model_t *model = r_refdef.scene.worldmodel;
387         if (model == NULL)
388                 return;
389         for (leafnum = 0;leafnum < model->brush.num_leafs;leafnum++)
390         {
391                 if (r_refdef.viewcache.world_leafvisible[leafnum])
392                 {
393                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
394                         for (portal = model->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
395                         {
396                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
397                                 if (!R_CullBox(portal->mins, portal->maxs))
398                                 {
399                                         VectorClear(center);
400                                         for (i = 0;i < portal->numpoints;i++)
401                                                 VectorAdd(center, portal->points[i].position, center);
402                                         f = ixtable[portal->numpoints];
403                                         VectorScale(center, f, center);
404                                         R_MeshQueue_AddTransparent(TRANSPARENTSORT_DISTANCE, center, R_DrawPortal_Callback, (entity_render_t *)portal, leafnum, rsurface.rtlight);
405                                 }
406                         }
407                 }
408         }
409 }
410
411 static void R_View_WorldVisibility_CullSurfaces(void)
412 {
413         int surfaceindex;
414         int surfaceindexstart;
415         int surfaceindexend;
416         unsigned char *surfacevisible;
417         msurface_t *surfaces;
418         model_t *model = r_refdef.scene.worldmodel;
419         if (!model)
420                 return;
421         if (r_trippy.integer)
422                 return;
423         if (r_usesurfaceculling.integer < 1)
424                 return;
425         surfaceindexstart = model->firstmodelsurface;
426         surfaceindexend = surfaceindexstart + model->nummodelsurfaces;
427         surfaces = model->data_surfaces;
428         surfacevisible = r_refdef.viewcache.world_surfacevisible;
429         for (surfaceindex = surfaceindexstart; surfaceindex < surfaceindexend; surfaceindex++)
430         {
431                 if (surfacevisible[surfaceindex])
432                 {
433                         if (R_CullBox(surfaces[surfaceindex].mins, surfaces[surfaceindex].maxs)
434                          || (r_vis_trace_surfaces.integer && !R_CanSeeBox(r_vis_trace_samples.integer, r_vis_trace_eyejitter.value, r_vis_trace_enlarge.value, r_vis_trace_expand.value, r_vis_trace_pad.value, r_refdef.view.origin, surfaces[surfaceindex].mins, surfaces[surfaceindex].maxs)))
435                                 surfacevisible[surfaceindex] = 0;
436                 }
437         }
438 }
439
440 void R_View_WorldVisibility(qbool forcenovis)
441 {
442         int i, j, *mark;
443         mleaf_t *leaf;
444         mleaf_t *viewleaf;
445         model_t *model = r_refdef.scene.worldmodel;
446
447         if (!model)
448                 return;
449
450         if (r_lockvisibility.integer)
451                 return;
452
453         // clear the visible surface and leaf flags arrays
454         memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
455         if(!r_lockpvs.integer)
456                 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
457
458         r_refdef.viewcache.world_novis = false;
459
460         if (r_refdef.view.usecustompvs)
461         {
462                 // simply cull each marked leaf to the frustum (view pyramid)
463                 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
464                 {
465                         // if leaf is in current pvs and on the screen, mark its surfaces
466                         if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
467                         {
468                                 r_refdef.stats[r_stat_world_leafs]++;
469                                 r_refdef.viewcache.world_leafvisible[j] = true;
470                                 if (leaf->numleafsurfaces)
471                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
472                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
473                         }
474                 }
475         }
476         else
477         {
478                 // if possible find the leaf the view origin is in
479                 viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_refdef.view.origin) : NULL;
480                 // if possible fetch the visible cluster bits
481                 if (!r_lockpvs.integer && model->brush.FatPVS)
482                         model->brush.FatPVS(model, r_refdef.view.origin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
483
484                 // if floating around in the void (no pvs data available, and no
485                 // portals available), simply use all on-screen leafs.
486                 if (!viewleaf || viewleaf->clusterindex < 0 || forcenovis || !r_refdef.view.usevieworiginculling)
487                 {
488                         // no visibility method: (used when floating around in the void)
489                         // simply cull each leaf to the frustum (view pyramid)
490                         // similar to quake's RecursiveWorldNode but without cache misses
491                         r_refdef.viewcache.world_novis = true;
492                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
493                         {
494                                 if (leaf->clusterindex < 0)
495                                         continue;
496                                 // if leaf is in current pvs and on the screen, mark its surfaces
497                                 if (!R_CullBox(leaf->mins, leaf->maxs))
498                                 {
499                                         r_refdef.stats[r_stat_world_leafs]++;
500                                         r_refdef.viewcache.world_leafvisible[j] = true;
501                                         if (leaf->numleafsurfaces)
502                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
503                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
504                                 }
505                         }
506                 }
507                 // just check if each leaf in the PVS is on screen
508                 // (unless portal culling is enabled)
509                 else if (!model->brush.data_portals || r_useportalculling.integer < 1 || (r_useportalculling.integer < 2 && !r_novis.integer))
510                 {
511                         // pvs method:
512                         // simply check if each leaf is in the Potentially Visible Set,
513                         // and cull to frustum (view pyramid)
514                         // similar to quake's RecursiveWorldNode but without cache misses
515                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
516                         {
517                                 if (leaf->clusterindex < 0)
518                                         continue;
519                                 // if leaf is in current pvs and on the screen, mark its surfaces
520                                 if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
521                                 {
522                                         r_refdef.stats[r_stat_world_leafs]++;
523                                         r_refdef.viewcache.world_leafvisible[j] = true;
524                                         if (leaf->numleafsurfaces)
525                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
526                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
527                                 }
528                         }
529                 }
530                 // if desired use a recursive portal flow, culling each portal to
531                 // frustum and checking if the leaf the portal leads to is in the pvs
532                 else
533                 {
534                         int leafstackpos;
535                         mportal_t *p;
536                         mleaf_t *leafstack[8192];
537                         vec3_t cullmins, cullmaxs;
538                         float cullbias = r_nearclip.value * 2.0f; // the nearclip plane can easily end up culling portals in certain perfectly-aligned views, causing view blackouts
539                         // simple-frustum portal method:
540                         // follows portals leading outward from viewleaf, does not venture
541                         // offscreen or into leafs that are not visible, faster than
542                         // Quake's RecursiveWorldNode and vastly better in unvised maps,
543                         // often culls some surfaces that pvs alone would miss
544                         // (such as a room in pvs that is hidden behind a wall, but the
545                         //  passage leading to the room is off-screen)
546                         leafstack[0] = viewleaf;
547                         leafstackpos = 1;
548                         while (leafstackpos)
549                         {
550                                 leaf = leafstack[--leafstackpos];
551                                 if (r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs])
552                                         continue;
553                                 if (leaf->clusterindex < 0)
554                                         continue;
555                                 r_refdef.stats[r_stat_world_leafs]++;
556                                 r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs] = true;
557                                 // mark any surfaces bounding this leaf
558                                 if (leaf->numleafsurfaces)
559                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
560                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
561                                 // follow portals into other leafs
562                                 // the checks are:
563                                 // the leaf has not been visited yet
564                                 // and the leaf is visible in the pvs
565                                 // the portal polygon's bounding box is on the screen
566                                 for (p = leaf->portals;p;p = p->next)
567                                 {
568                                         r_refdef.stats[r_stat_world_portals]++;
569                                         if (r_refdef.viewcache.world_leafvisible[p->past - model->brush.data_leafs])
570                                                 continue;
571                                         if (!CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, p->past->clusterindex))
572                                                 continue;
573                                         cullmins[0] = p->mins[0] - cullbias;
574                                         cullmins[1] = p->mins[1] - cullbias;
575                                         cullmins[2] = p->mins[2] - cullbias;
576                                         cullmaxs[0] = p->maxs[0] + cullbias;
577                                         cullmaxs[1] = p->maxs[1] + cullbias;
578                                         cullmaxs[2] = p->maxs[2] + cullbias;
579                                         if (R_CullBox(cullmins, cullmaxs))
580                                                 continue;
581                                         if (r_vis_trace.integer)
582                                         {
583                                                 if (p->tracetime != host.realtime && R_CanSeeBox(r_vis_trace_samples.value, r_vis_trace_eyejitter.value, r_vis_trace_enlarge.value, r_vis_trace_expand.value, r_vis_trace_pad.value, r_refdef.view.origin, cullmins, cullmaxs))
584                                                         p->tracetime = host.realtime;
585                                                 if (host.realtime - p->tracetime > r_vis_trace_delay.value)
586                                                         continue;
587                                         }
588                                         if (leafstackpos >= (int)(sizeof(leafstack) / sizeof(leafstack[0])))
589                                                 break;
590                                         leafstack[leafstackpos++] = p->past;
591                                 }
592                         }
593                 }
594         }
595
596         // Cull the rest
597         R_View_WorldVisibility_CullSurfaces();
598 }
599
600 void R_Mod_DrawSky(entity_render_t *ent)
601 {
602         if (ent->model == NULL)
603                 return;
604         R_DrawModelSurfaces(ent, true, true, false, false, false, false);
605 }
606
607 void R_Mod_DrawAddWaterPlanes(entity_render_t *ent)
608 {
609         int i, j, n, flagsmask;
610         model_t *model = ent->model;
611         msurface_t *surfaces;
612         if (model == NULL)
613                 return;
614
615         RSurf_ActiveModelEntity(ent, true, false, false);
616
617         surfaces = model->data_surfaces;
618         flagsmask = MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA;
619
620         // add visible surfaces to draw list
621         if (ent == r_refdef.scene.worldentity)
622         {
623                 for (i = 0;i < model->nummodelsurfaces;i++)
624                 {
625                         j = model->sortedmodelsurfaces[i];
626                         if (r_refdef.viewcache.world_surfacevisible[j])
627                                 if (surfaces[j].texture->basematerialflags & flagsmask)
628                                         R_Water_AddWaterPlane(surfaces + j, 0);
629                 }
630         }
631         else
632         {
633                 if(ent->entitynumber >= MAX_EDICTS) // && CL_VM_TransformView(ent->entitynumber - MAX_EDICTS, NULL, NULL, NULL))
634                         n = ent->entitynumber;
635                 else
636                         n = 0;
637                 for (i = 0;i < model->nummodelsurfaces;i++)
638                 {
639                         j = model->sortedmodelsurfaces[i];
640                         if (surfaces[j].texture->basematerialflags & flagsmask)
641                                 R_Water_AddWaterPlane(surfaces + j, n);
642                 }
643         }
644         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
645 }
646
647 void R_Mod_Draw(entity_render_t *ent)
648 {
649         model_t *model = ent->model;
650         if (model == NULL)
651                 return;
652         R_DrawModelSurfaces(ent, false, true, false, false, false, false);
653 }
654
655 void R_Mod_DrawDepth(entity_render_t *ent)
656 {
657         model_t *model = ent->model;
658         if (model == NULL || model->surfmesh.isanimated)
659                 return;
660         GL_ColorMask(0,0,0,0);
661         GL_Color(1,1,1,1);
662         GL_DepthTest(true);
663         GL_BlendFunc(GL_ONE, GL_ZERO);
664         GL_DepthMask(true);
665 //      R_Mesh_ResetTextureState();
666         R_DrawModelSurfaces(ent, false, false, true, false, false, false);
667         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
668 }
669
670 void R_Mod_DrawDebug(entity_render_t *ent)
671 {
672         if (ent->model == NULL)
673                 return;
674         R_DrawModelSurfaces(ent, false, false, false, true, false, false);
675 }
676
677 void R_Mod_DrawPrepass(entity_render_t *ent)
678 {
679         model_t *model = ent->model;
680         if (model == NULL)
681                 return;
682         R_DrawModelSurfaces(ent, false, true, false, false, true, false);
683 }
684
685 typedef struct r_q1bsp_getlightinfo_s
686 {
687         model_t *model;
688         vec3_t relativelightorigin;
689         float lightradius;
690         int *outleaflist;
691         unsigned char *outleafpvs;
692         int outnumleafs;
693         unsigned char *visitingleafpvs;
694         int *outsurfacelist;
695         unsigned char *outsurfacepvs;
696         unsigned char *tempsurfacepvs;
697         unsigned char *outshadowtrispvs;
698         unsigned char *outlighttrispvs;
699         int outnumsurfaces;
700         vec3_t outmins;
701         vec3_t outmaxs;
702         vec3_t lightmins;
703         vec3_t lightmaxs;
704         const unsigned char *pvs;
705         qbool svbsp_active;
706         qbool svbsp_insertoccluder;
707         qbool noocclusion; // avoids PVS culling
708         qbool frontsidecasting; // casts shadows from surfaces facing the light (otherwise ones facing away)
709         int numfrustumplanes;
710         const mplane_t *frustumplanes;
711 }
712 r_q1bsp_getlightinfo_t;
713
714 #define GETLIGHTINFO_MAXNODESTACK 4096
715
716 static void R_Q1BSP_RecursiveGetLightInfo_BSP(r_q1bsp_getlightinfo_t *info, qbool skipsurfaces)
717 {
718         // nodestack
719         mnode_t *nodestack[GETLIGHTINFO_MAXNODESTACK];
720         int nodestackpos = 0;
721         // node processing
722         mplane_t *plane;
723         mnode_t *node;
724         int sides;
725         // leaf processing
726         mleaf_t *leaf;
727         const msurface_t *surface;
728         const msurface_t *surfaces = info->model->data_surfaces;
729         int numleafsurfaces;
730         int leafsurfaceindex;
731         int surfaceindex;
732         int triangleindex, t;
733         int currentmaterialflags;
734         qbool castshadow;
735         const int *e;
736         const vec_t *v[3];
737         float v2[3][3];
738         qbool insidebox;
739         qbool noocclusion = info->noocclusion;
740         qbool frontsidecasting = info->frontsidecasting;
741         qbool svbspactive = info->svbsp_active;
742         qbool svbspinsertoccluder = info->svbsp_insertoccluder;
743         const int *leafsurfaceindices;
744         qbool addedtris;
745         int i;
746         mportal_t *portal;
747         static float points[128][3];
748         // push the root node onto our nodestack
749         nodestack[nodestackpos++] = info->model->brush.data_nodes;
750         // we'll be done when the nodestack is empty
751         while (nodestackpos)
752         {
753                 // get a node from the stack to process
754                 node = nodestack[--nodestackpos];
755                 // is it a node or a leaf?
756                 plane = node->plane;
757                 if (plane)
758                 {
759                         // node
760 #if 0
761                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
762                                 continue;
763 #endif
764 #if 0
765                         if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
766                                 continue;
767 #endif
768                         // axial planes can be processed much more quickly
769                         if (plane->type < 3)
770                         {
771                                 // axial plane
772                                 if (info->lightmins[plane->type] > plane->dist)
773                                         nodestack[nodestackpos++] = node->children[0];
774                                 else if (info->lightmaxs[plane->type] < plane->dist)
775                                         nodestack[nodestackpos++] = node->children[1];
776                                 else
777                                 {
778                                         // recurse front side first because the svbsp building prefers it
779                                         if (info->relativelightorigin[plane->type] >= plane->dist)
780                                         {
781                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
782                                                         nodestack[nodestackpos++] = node->children[0];
783                                                 nodestack[nodestackpos++] = node->children[1];
784                                         }
785                                         else
786                                         {
787                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
788                                                         nodestack[nodestackpos++] = node->children[1];
789                                                 nodestack[nodestackpos++] = node->children[0];
790                                         }
791                                 }
792                         }
793                         else
794                         {
795                                 // sloped plane
796                                 sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
797                                 switch (sides)
798                                 {
799                                 default:
800                                         continue; // ERROR: NAN bounding box!
801                                 case 1:
802                                         nodestack[nodestackpos++] = node->children[0];
803                                         break;
804                                 case 2:
805                                         nodestack[nodestackpos++] = node->children[1];
806                                         break;
807                                 case 3:
808                                         // recurse front side first because the svbsp building prefers it
809                                         if (PlaneDist(info->relativelightorigin, plane) >= 0)
810                                         {
811                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
812                                                         nodestack[nodestackpos++] = node->children[0];
813                                                 nodestack[nodestackpos++] = node->children[1];
814                                         }
815                                         else
816                                         {
817                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
818                                                         nodestack[nodestackpos++] = node->children[1];
819                                                 nodestack[nodestackpos++] = node->children[0];
820                                         }
821                                         break;
822                                 }
823                         }
824                 }
825                 else
826                 {
827                         // leaf
828                         leaf = (mleaf_t *)node;
829 #if 1
830                         if (!info->noocclusion && info->pvs != NULL && !CHECKPVSBIT(info->pvs, leaf->clusterindex))
831                                 continue;
832 #endif
833 #if 1
834                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
835                                 continue;
836 #endif
837 #if 1
838                         if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
839                                 continue;
840 #endif
841
842                         if (svbspactive)
843                         {
844                                 // we can occlusion test the leaf by checking if all of its portals
845                                 // are occluded (unless the light is in this leaf - but that was
846                                 // already handled by the caller)
847                                 for (portal = leaf->portals;portal;portal = portal->next)
848                                 {
849                                         for (i = 0;i < portal->numpoints;i++)
850                                                 VectorCopy(portal->points[i].position, points[i]);
851                                         if (SVBSP_AddPolygon(&r_svbsp, portal->numpoints, points[0], false, NULL, NULL, 0) & 2)
852                                                 break;
853                                 }
854                                 if (leaf->portals && portal == NULL)
855                                         continue; // no portals of this leaf visible
856                         }
857
858                         // add this leaf to the reduced light bounds
859                         info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
860                         info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
861                         info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
862                         info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
863                         info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
864                         info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
865
866                         // mark this leaf as being visible to the light
867                         if (info->outleafpvs)
868                         {
869                                 int leafindex = leaf - info->model->brush.data_leafs;
870                                 if (!CHECKPVSBIT(info->outleafpvs, leafindex))
871                                 {
872                                         SETPVSBIT(info->outleafpvs, leafindex);
873                                         info->outleaflist[info->outnumleafs++] = leafindex;
874                                 }
875                         }
876
877                         // when using BIH, we skip the surfaces here
878                         if (skipsurfaces)
879                                 continue;
880
881                         // iterate the surfaces linked by this leaf and check their triangles
882                         leafsurfaceindices = leaf->firstleafsurface;
883                         numleafsurfaces = leaf->numleafsurfaces;
884                         if (svbspinsertoccluder)
885                         {
886                                 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
887                                 {
888                                         surfaceindex = leafsurfaceindices[leafsurfaceindex];
889                                         if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
890                                                 continue;
891                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
892                                         surface = surfaces + surfaceindex;
893                                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
894                                                 continue;
895                                         currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
896                                         castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
897                                         if (!castshadow)
898                                                 continue;
899                                         insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
900                                         for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
901                                         {
902                                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
903                                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
904                                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
905                                                 VectorCopy(v[0], v2[0]);
906                                                 VectorCopy(v[1], v2[1]);
907                                                 VectorCopy(v[2], v2[2]);
908                                                 if (insidebox || TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
909                                                         SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
910                                         }
911                                 }
912                         }
913                         else
914                         {
915                                 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
916                                 {
917                                         surfaceindex = leafsurfaceindices[leafsurfaceindex];
918                                         surface = surfaces + surfaceindex;
919                                         if(!surface->texture)
920                                                 continue;       
921                                         if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
922                                                 continue;
923                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
924                                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
925                                                 continue;
926                                         addedtris = false;
927                                         currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
928                                         castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
929                                         insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
930                                         for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
931                                         {
932                                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
933                                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
934                                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
935                                                 VectorCopy(v[0], v2[0]);
936                                                 VectorCopy(v[1], v2[1]);
937                                                 VectorCopy(v[2], v2[2]);
938                                                 if (!insidebox && !TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
939                                                         continue;
940                                                 if (svbspactive && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
941                                                         continue;
942                                                 // we don't omit triangles from lighting even if they are
943                                                 // backfacing, because when using shadowmapping they are often
944                                                 // not fully occluded on the horizon of an edge
945                                                 SETPVSBIT(info->outlighttrispvs, t);
946                                                 addedtris = true;
947                                                 if (castshadow)
948                                                 {
949                                                         if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
950                                                         {
951                                                                 // if the material is double sided we
952                                                                 // can't cull by direction
953                                                                 SETPVSBIT(info->outshadowtrispvs, t);
954                                                         }
955                                                         else if (frontsidecasting)
956                                                         {
957                                                                 // front side casting occludes backfaces,
958                                                                 // so they are completely useless as both
959                                                                 // casters and lit polygons
960                                                                 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
961                                                                         SETPVSBIT(info->outshadowtrispvs, t);
962                                                         }
963                                                         else
964                                                         {
965                                                                 // back side casting does not occlude
966                                                                 // anything so we can't cull lit polygons
967                                                                 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
968                                                                         SETPVSBIT(info->outshadowtrispvs, t);
969                                                         }
970                                                 }
971                                         }
972                                         if (addedtris)
973                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
974                                 }
975                         }
976                 }
977         }
978 }
979
980 static void R_Q1BSP_RecursiveGetLightInfo_BIH(r_q1bsp_getlightinfo_t *info, const bih_t *bih)
981 {
982         bih_leaf_t *leaf;
983         bih_node_t *node;
984         int nodenum;
985         int axis;
986         int surfaceindex;
987         int t;
988         int nodeleafindex;
989         int currentmaterialflags;
990         qbool castshadow;
991         qbool noocclusion = info->noocclusion;
992         qbool frontsidecasting = info->frontsidecasting;
993         msurface_t *surface;
994         const int *e;
995         const vec_t *v[3];
996         float v2[3][3];
997         int nodestack[GETLIGHTINFO_MAXNODESTACK];
998         int nodestackpos = 0;
999         // note: because the BSP leafs are not in the BIH tree, the _BSP function
1000         // must be called to mark leafs visible for entity culling...
1001         // we start at the root node
1002         nodestack[nodestackpos++] = bih->rootnode;
1003         // we'll be done when the stack is empty
1004         while (nodestackpos)
1005         {
1006                 // pop one off the stack to process
1007                 nodenum = nodestack[--nodestackpos];
1008                 // node
1009                 node = bih->nodes + nodenum;
1010                 if (node->type == BIH_UNORDERED)
1011                 {
1012                         for (nodeleafindex = 0;nodeleafindex < BIH_MAXUNORDEREDCHILDREN && node->children[nodeleafindex] >= 0;nodeleafindex++)
1013                         {
1014                                 leaf = bih->leafs + node->children[nodeleafindex];
1015                                 if (leaf->type != BIH_RENDERTRIANGLE)
1016                                         continue;
1017 #if 1
1018                                 if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
1019                                         continue;
1020 #endif
1021 #if 1
1022                                 if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
1023                                         continue;
1024 #endif
1025                                 surfaceindex = leaf->surfaceindex;
1026                                 surface = info->model->data_surfaces + surfaceindex;
1027                                 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
1028                                 castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
1029                                 t = leaf->itemindex;
1030                                 e = info->model->surfmesh.data_element3i + t * 3;
1031                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
1032                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
1033                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
1034                                 VectorCopy(v[0], v2[0]);
1035                                 VectorCopy(v[1], v2[1]);
1036                                 VectorCopy(v[2], v2[2]);
1037                                 if (info->svbsp_insertoccluder)
1038                                 {
1039                                         if (castshadow)
1040                                                 SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
1041                                         continue;
1042                                 }
1043                                 if (info->svbsp_active && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
1044                                         continue;
1045                                 // we don't occlude triangles from lighting even
1046                                 // if they are backfacing, because when using
1047                                 // shadowmapping they are often not fully occluded
1048                                 // on the horizon of an edge
1049                                 SETPVSBIT(info->outlighttrispvs, t);
1050                                 if (castshadow)
1051                                 {
1052                                         if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
1053                                         {
1054                                                 // if the material is double sided we
1055                                                 // can't cull by direction
1056                                                 SETPVSBIT(info->outshadowtrispvs, t);
1057                                         }
1058                                         else if (frontsidecasting)
1059                                         {
1060                                                 // front side casting occludes backfaces,
1061                                                 // so they are completely useless as both
1062                                                 // casters and lit polygons
1063                                                 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1064                                                         SETPVSBIT(info->outshadowtrispvs, t);
1065                                         }
1066                                         else
1067                                         {
1068                                                 // back side casting does not occlude
1069                                                 // anything so we can't cull lit polygons
1070                                                 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1071                                                         SETPVSBIT(info->outshadowtrispvs, t);
1072                                         }
1073                                 }
1074                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
1075                                 {
1076                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
1077                                         info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
1078                                 }
1079                         }
1080                 }
1081                 else
1082                 {
1083                         axis = node->type - BIH_SPLITX;
1084 #if 0
1085                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
1086                                 continue;
1087 #endif
1088 #if 0
1089                         if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
1090                                 continue;
1091 #endif
1092                         if (info->lightmins[axis] <= node->backmax)
1093                         {
1094                                 if (info->lightmaxs[axis] >= node->frontmin && nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
1095                                         nodestack[nodestackpos++] = node->front;
1096                                 nodestack[nodestackpos++] = node->back;
1097                                 continue;
1098                         }
1099                         else if (info->lightmaxs[axis] >= node->frontmin)
1100                         {
1101                                 nodestack[nodestackpos++] = node->front;
1102                                 continue;
1103                         }
1104                         else
1105                                 continue; // light falls between children, nothing here
1106                 }
1107         }
1108 }
1109
1110 static void R_Q1BSP_CallRecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, qbool use_svbsp)
1111 {
1112         extern cvar_t r_shadow_usebihculling;
1113         if (use_svbsp)
1114         {
1115                 float origin[3];
1116                 VectorCopy(info->relativelightorigin, origin);
1117                 r_svbsp.maxnodes = max(r_svbsp.maxnodes, 1<<12);
1118                 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1119                 info->svbsp_active = true;
1120                 info->svbsp_insertoccluder = true;
1121                 for (;;)
1122                 {
1123                         SVBSP_Init(&r_svbsp, origin, r_svbsp.maxnodes, r_svbsp.nodes);
1124                         R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1125                         // if that failed, retry with more nodes
1126                         if (r_svbsp.ranoutofnodes)
1127                         {
1128                                 // an upper limit is imposed
1129                                 if (r_svbsp.maxnodes >= 2<<22)
1130                                         break;
1131                                 r_svbsp.maxnodes *= 2;
1132                                 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1133                                 //Mem_Free(r_svbsp.nodes);
1134                                 //r_svbsp.nodes = (svbsp_node_t*) Mem_Alloc(tempmempool, r_svbsp.maxnodes * sizeof(svbsp_node_t));
1135                         }
1136                         else
1137                                 break;
1138                 }
1139                 // now clear the visibility arrays because we need to redo it
1140                 info->outnumleafs = 0;
1141                 info->outnumsurfaces = 0;
1142                 memset(info->outleafpvs, 0, (info->model->brush.num_leafs + 7) >> 3);
1143                 memset(info->outsurfacepvs, 0, (info->model->nummodelsurfaces + 7) >> 3);
1144                 memset(info->outshadowtrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1145                 memset(info->outlighttrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1146         }
1147         else
1148                 info->svbsp_active = false;
1149
1150         // we HAVE to mark the leaf the light is in as lit, because portals are
1151         // irrelevant to a leaf that the light source is inside of
1152         // (and they are all facing away, too)
1153         {
1154                 mnode_t *node = info->model->brush.data_nodes;
1155                 mleaf_t *leaf;
1156                 while (node->plane)
1157                         node = node->children[(node->plane->type < 3 ? info->relativelightorigin[node->plane->type] : DotProduct(info->relativelightorigin,node->plane->normal)) < node->plane->dist];
1158                 leaf = (mleaf_t *)node;
1159                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
1160                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
1161                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
1162                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
1163                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
1164                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
1165                 if (info->outleafpvs)
1166                 {
1167                         int leafindex = leaf - info->model->brush.data_leafs;
1168                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
1169                         {
1170                                 SETPVSBIT(info->outleafpvs, leafindex);
1171                                 info->outleaflist[info->outnumleafs++] = leafindex;
1172                         }
1173                 }
1174         }
1175
1176         info->svbsp_insertoccluder = false;
1177         // use BIH culling on single leaf maps (generally this only happens if running a model as a map), otherwise use BSP culling to make use of vis data
1178         if (r_shadow_usebihculling.integer > 0 && (r_shadow_usebihculling.integer == 2 || info->model->brush.num_leafs == 1) && info->model->render_bih.leafs != NULL)
1179         {
1180                 R_Q1BSP_RecursiveGetLightInfo_BSP(info, true);
1181                 R_Q1BSP_RecursiveGetLightInfo_BIH(info, &info->model->render_bih);
1182         }
1183         else
1184                 R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1185         // we're using temporary framedata memory, so this pointer will be invalid soon, clear it
1186         r_svbsp.nodes = NULL;
1187         if (developer_extra.integer && use_svbsp)
1188         {
1189                 Con_DPrintf("GetLightInfo: svbsp built with %i nodes, polygon stats:\n", r_svbsp.numnodes);
1190                 Con_DPrintf("occluders: %i accepted, %i rejected, %i fragments accepted, %i fragments rejected.\n", r_svbsp.stat_occluders_accepted, r_svbsp.stat_occluders_rejected, r_svbsp.stat_occluders_fragments_accepted, r_svbsp.stat_occluders_fragments_rejected);
1191                 Con_DPrintf("queries  : %i accepted, %i rejected, %i fragments accepted, %i fragments rejected.\n", r_svbsp.stat_queries_accepted, r_svbsp.stat_queries_rejected, r_svbsp.stat_queries_fragments_accepted, r_svbsp.stat_queries_fragments_rejected);
1192         }
1193 }
1194
1195 static msurface_t *r_q1bsp_getlightinfo_surfaces;
1196
1197 static int R_Q1BSP_GetLightInfo_comparefunc(const void *ap, const void *bp)
1198 {
1199         int a = *(int*)ap;
1200         int b = *(int*)bp;
1201         const msurface_t *as = r_q1bsp_getlightinfo_surfaces + a;
1202         const msurface_t *bs = r_q1bsp_getlightinfo_surfaces + b;
1203         if (as->texture < bs->texture)
1204                 return -1;
1205         if (as->texture > bs->texture)
1206                 return 1;
1207         return a - b;
1208 }
1209
1210 extern cvar_t r_shadow_sortsurfaces;
1211
1212 void R_Mod_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outleaflist, unsigned char *outleafpvs, int *outnumleafspointer, int *outsurfacelist, unsigned char *outsurfacepvs, int *outnumsurfacespointer, unsigned char *outshadowtrispvs, unsigned char *outlighttrispvs, unsigned char *visitingleafpvs, int numfrustumplanes, const mplane_t *frustumplanes, qbool noocclusion)
1213 {
1214         r_q1bsp_getlightinfo_t info;
1215         info.frontsidecasting = r_shadow_frontsidecasting.integer != 0;
1216         info.noocclusion = noocclusion || !info.frontsidecasting;
1217         VectorCopy(relativelightorigin, info.relativelightorigin);
1218         info.lightradius = lightradius;
1219         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
1220         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
1221         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
1222         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
1223         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
1224         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
1225         if (ent->model == NULL)
1226         {
1227                 VectorCopy(info.lightmins, outmins);
1228                 VectorCopy(info.lightmaxs, outmaxs);
1229                 *outnumleafspointer = 0;
1230                 *outnumsurfacespointer = 0;
1231                 return;
1232         }
1233         info.model = ent->model;
1234         info.outleaflist = outleaflist;
1235         info.outleafpvs = outleafpvs;
1236         info.outnumleafs = 0;
1237         info.visitingleafpvs = visitingleafpvs;
1238         info.outsurfacelist = outsurfacelist;
1239         info.outsurfacepvs = outsurfacepvs;
1240         info.outshadowtrispvs = outshadowtrispvs;
1241         info.outlighttrispvs = outlighttrispvs;
1242         info.outnumsurfaces = 0;
1243         info.numfrustumplanes = numfrustumplanes;
1244         info.frustumplanes = frustumplanes;
1245         VectorCopy(info.relativelightorigin, info.outmins);
1246         VectorCopy(info.relativelightorigin, info.outmaxs);
1247         memset(visitingleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1248         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1249         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
1250         memset(outshadowtrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1251         memset(outlighttrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1252         if (info.model->brush.GetPVS && !info.noocclusion)
1253                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
1254         else
1255                 info.pvs = NULL;
1256         RSurf_ActiveModelEntity(r_refdef.scene.worldentity, false, false, false);
1257
1258         if (!info.noocclusion && r_shadow_compilingrtlight && r_shadow_realtime_world_compileportalculling.integer && info.model->brush.data_portals)
1259         {
1260                 // use portal recursion for exact light volume culling, and exact surface checking
1261                 Portal_Visibility(info.model, info.relativelightorigin, info.outleaflist, info.outleafpvs, &info.outnumleafs, info.outsurfacelist, info.outsurfacepvs, &info.outnumsurfaces, NULL, 0, true, info.lightmins, info.lightmaxs, info.outmins, info.outmaxs, info.outshadowtrispvs, info.outlighttrispvs, info.visitingleafpvs);
1262         }
1263         else if (!info.noocclusion && r_shadow_realtime_dlight_portalculling.integer && info.model->brush.data_portals)
1264         {
1265                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
1266                 Portal_Visibility(info.model, info.relativelightorigin, info.outleaflist, info.outleafpvs, &info.outnumleafs, info.outsurfacelist, info.outsurfacepvs, &info.outnumsurfaces, NULL, 0, r_shadow_realtime_dlight_portalculling.integer >= 2, info.lightmins, info.lightmaxs, info.outmins, info.outmaxs, info.outshadowtrispvs, info.outlighttrispvs, info.visitingleafpvs);
1267         }
1268         else
1269         {
1270                 // recurse the bsp tree, checking leafs and surfaces for visibility
1271                 // optionally using svbsp for exact culling of compiled lights
1272                 // (or if the user enables dlight svbsp culling, which is mostly for
1273                 //  debugging not actual use)
1274                 R_Q1BSP_CallRecursiveGetLightInfo(&info, !info.noocclusion && (r_shadow_compilingrtlight ? r_shadow_realtime_world_compilesvbsp.integer : r_shadow_realtime_dlight_svbspculling.integer) != 0);
1275         }
1276
1277         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
1278
1279         // limit combined leaf box to light boundaries
1280         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
1281         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
1282         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
1283         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
1284         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
1285         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
1286
1287         *outnumleafspointer = info.outnumleafs;
1288         *outnumsurfacespointer = info.outnumsurfaces;
1289
1290         // now sort surfaces by texture for faster rendering
1291         r_q1bsp_getlightinfo_surfaces = info.model->data_surfaces;
1292         if (r_shadow_sortsurfaces.integer)
1293                 qsort(info.outsurfacelist, info.outnumsurfaces, sizeof(*info.outsurfacelist), R_Q1BSP_GetLightInfo_comparefunc);
1294 }
1295
1296 void R_Mod_CompileShadowMap(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
1297 {
1298         model_t *model = ent->model;
1299         msurface_t *surface;
1300         int surfacelistindex;
1301         int sidetotals[6] = { 0, 0, 0, 0, 0, 0 }, sidemasks = 0;
1302         int i;
1303         // FIXME: the sidetotals code incorrectly assumes that static_meshchain is
1304         // a single mesh - to prevent that from crashing (sideoffsets, sidetotals
1305         // exceeding the number of triangles in a single mesh) we have to make sure
1306         // that we make only a single mesh - so over-estimate the size of the mesh
1307         // to match the model.
1308         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Begin(r_main_mempool, model->surfmesh.num_vertices, model->surfmesh.num_triangles);
1309         R_Shadow_PrepareShadowSides(model->surfmesh.num_triangles);
1310         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1311         {
1312                 surface = model->data_surfaces + surfacelist[surfacelistindex];
1313                 sidemasks |= R_Shadow_ChooseSidesFromBox(surface->num_firsttriangle, surface->num_triangles, model->surfmesh.data_vertex3f, model->surfmesh.data_element3i, &r_shadow_compilingrtlight->matrix_worldtolight, relativelightorigin, relativelightdirection, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs, surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW ? NULL : sidetotals);
1314         }
1315         R_Shadow_ShadowMapFromList(model->surfmesh.num_vertices, model->surfmesh.num_triangles, model->surfmesh.data_vertex3f, model->surfmesh.data_element3i, numshadowsides, sidetotals, shadowsides, shadowsideslist);
1316         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Finish(r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, true);
1317         r_shadow_compilingrtlight->static_shadowmap_receivers &= sidemasks;
1318         for(i = 0;i<6;i++)
1319                 if(!sidetotals[i])
1320                         r_shadow_compilingrtlight->static_shadowmap_casters &= ~(1 << i);
1321 }
1322
1323 #define RSURF_MAX_BATCHSURFACES 8192
1324
1325 static const msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
1326
1327 void R_Mod_DrawShadowMap(int side, entity_render_t *ent, const vec3_t relativelightorigin, const vec3_t relativelightdirection, float lightradius, int modelnumsurfaces, const int *modelsurfacelist, const unsigned char *surfacesides, const vec3_t lightmins, const vec3_t lightmaxs)
1328 {
1329         model_t *model = ent->model;
1330         const msurface_t *surface;
1331         int modelsurfacelistindex, batchnumsurfaces;
1332         // check the box in modelspace, it was already checked in worldspace
1333         if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
1334                 return;
1335         R_FrameData_SetMark();
1336         // identify lit faces within the bounding box
1337         for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1338         {
1339                 surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1340                 if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1341                         continue;
1342                 rsurface.texture = R_GetCurrentTexture(surface->texture);
1343                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1344                         continue;
1345                 if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1346                         continue;
1347                 r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1348                 r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1349                 batchsurfacelist[0] = surface;
1350                 batchnumsurfaces = 1;
1351                 while(++modelsurfacelistindex < modelnumsurfaces && batchnumsurfaces < RSURF_MAX_BATCHSURFACES)
1352                 {
1353                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1354                         if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1355                                 continue;
1356                         if (surface->texture != batchsurfacelist[0]->texture)
1357                                 break;
1358                         if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1359                                 continue;
1360                         r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1361                         r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1362                         batchsurfacelist[batchnumsurfaces++] = surface;
1363                 }
1364                 --modelsurfacelistindex;
1365                 GL_CullFace(rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE ? GL_NONE : r_refdef.view.cullface_back);
1366                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ALLOWMULTIDRAW, batchnumsurfaces, batchsurfacelist);
1367                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
1368                 RSurf_DrawBatch();
1369         }
1370         R_FrameData_ReturnToMark();
1371 }
1372
1373 #define BATCHSIZE 1024
1374
1375 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
1376 {
1377         int i, j, endsurface;
1378         texture_t *t;
1379         const msurface_t *surface;
1380         R_FrameData_SetMark();
1381         // note: in practice this never actually receives batches
1382         R_Shadow_RenderMode_Begin();
1383         R_Shadow_RenderMode_ActiveLight(rtlight);
1384         R_Shadow_RenderMode_Lighting(true, rtlight->shadowmapatlassidesize != 0, (ent->flags & RENDER_NOSELFSHADOW) != 0);
1385         R_Shadow_SetupEntityLight(ent);
1386         for (i = 0;i < numsurfaces;i = j)
1387         {
1388                 j = i + 1;
1389                 surface = rsurface.modelsurfaces + surfacelist[i];
1390                 t = surface->texture;
1391                 rsurface.texture = R_GetCurrentTexture(t);
1392                 endsurface = min(j + BATCHSIZE, numsurfaces);
1393                 for (j = i;j < endsurface;j++)
1394                 {
1395                         surface = rsurface.modelsurfaces + surfacelist[j];
1396                         if (t != surface->texture)
1397                                 break;
1398                         R_Shadow_RenderLighting(1, &surface);
1399                 }
1400         }
1401         R_Shadow_RenderMode_End();
1402         R_FrameData_ReturnToMark();
1403 }
1404
1405 extern qbool r_shadow_usingdeferredprepass;
1406 void R_Mod_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist, const unsigned char *lighttrispvs)
1407 {
1408         model_t *model = ent->model;
1409         const msurface_t *surface;
1410         int i, k, kend, l, endsurface, batchnumsurfaces, texturenumsurfaces;
1411         const msurface_t **texturesurfacelist;
1412         texture_t *tex;
1413         CHECKGLERROR
1414         R_FrameData_SetMark();
1415         // this is a double loop because non-visible surface skipping has to be
1416         // fast, and even if this is not the world model (and hence no visibility
1417         // checking) the input surface list and batch buffer are different formats
1418         // so some processing is necessary.  (luckily models have few surfaces)
1419         for (i = 0;i < numsurfaces;)
1420         {
1421                 batchnumsurfaces = 0;
1422                 endsurface = min(i + RSURF_MAX_BATCHSURFACES, numsurfaces);
1423                 if (ent == r_refdef.scene.worldentity)
1424                 {
1425                         for (;i < endsurface;i++)
1426                                 if (r_refdef.viewcache.world_surfacevisible[surfacelist[i]])
1427                                         batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1428                 }
1429                 else
1430                 {
1431                         for (;i < endsurface;i++)
1432                                 batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1433                 }
1434                 if (!batchnumsurfaces)
1435                         continue;
1436                 for (k = 0;k < batchnumsurfaces;k = kend)
1437                 {
1438                         surface = batchsurfacelist[k];
1439                         tex = surface->texture;
1440                         rsurface.texture = R_GetCurrentTexture(tex);
1441                         // gather surfaces into a batch range
1442                         for (kend = k;kend < batchnumsurfaces && tex == batchsurfacelist[kend]->texture;kend++)
1443                                 ;
1444                         // now figure out what to do with this particular range of surfaces
1445                         // VorteX: added MATERIALFLAG_NORTLIGHT
1446                         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_NORTLIGHT)) != MATERIALFLAG_WALL)
1447                                 continue;
1448                         if (r_fb.water.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
1449                                 continue;
1450                         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
1451                         {
1452                                 vec3_t tempcenter, center;
1453                                 for (l = k;l < kend;l++)
1454                                 {
1455                                         surface = batchsurfacelist[l];
1456                                         if (r_transparent_sortsurfacesbynearest.integer)
1457                                         {
1458                                                 tempcenter[0] = bound(surface->mins[0], rsurface.localvieworigin[0], surface->maxs[0]);
1459                                                 tempcenter[1] = bound(surface->mins[1], rsurface.localvieworigin[1], surface->maxs[1]);
1460                                                 tempcenter[2] = bound(surface->mins[2], rsurface.localvieworigin[2], surface->maxs[2]);
1461                                         }
1462                                         else
1463                                         {
1464                                                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
1465                                                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
1466                                                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
1467                                         }
1468                                         Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
1469                                         if (ent->transparent_offset) // transparent offset
1470                                         {
1471                                                 center[0] += r_refdef.view.forward[0]*ent->transparent_offset;
1472                                                 center[1] += r_refdef.view.forward[1]*ent->transparent_offset;
1473                                                 center[2] += r_refdef.view.forward[2]*ent->transparent_offset;
1474                                         }
1475                                         R_MeshQueue_AddTransparent((rsurface.entity->flags & RENDER_WORLDOBJECT) ? TRANSPARENTSORT_SKY : ((rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST) ? TRANSPARENTSORT_HUD : rsurface.texture->transparentsort), center, R_Q1BSP_DrawLight_TransparentCallback, ent, surface - rsurface.modelsurfaces, rsurface.rtlight);
1476                                 }
1477                                 continue;
1478                         }
1479                         if (r_shadow_usingdeferredprepass)
1480                                 continue;
1481                         texturenumsurfaces = kend - k;
1482                         texturesurfacelist = batchsurfacelist + k;
1483                         R_Shadow_RenderLighting(texturenumsurfaces, texturesurfacelist);
1484                 }
1485         }
1486         R_FrameData_ReturnToMark();
1487 }
1488
1489 //Made by [515]
1490 static void R_ReplaceWorldTexture_f(cmd_state_t *cmd)
1491 {
1492         model_t         *m;
1493         texture_t       *t;
1494         int                     i;
1495         const char      *r, *newt;
1496         skinframe_t *skinframe;
1497         if (!r_refdef.scene.worldmodel)
1498         {
1499                 Con_Printf("There is no worldmodel\n");
1500                 return;
1501         }
1502         m = r_refdef.scene.worldmodel;
1503
1504         if(Cmd_Argc(cmd) < 2)
1505         {
1506                 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
1507                 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
1508                 return;
1509         }
1510         if(!cl.islocalgame || !cl.worldmodel)
1511         {
1512                 Con_Print("This command works only in singleplayer\n");
1513                 return;
1514         }
1515         r = Cmd_Argv(cmd, 1);
1516         newt = Cmd_Argv(cmd, 2);
1517         if(!newt[0])
1518                 newt = r;
1519         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1520         {
1521                 if(/*t->width && !strcasecmp(t->name, r)*/ matchpattern( t->name, r, true ) )
1522                 {
1523                         if ((skinframe = R_SkinFrame_LoadExternal(newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PICMIP, true, false)))
1524                         {
1525 //                              t->skinframes[0] = skinframe;
1526                                 t->currentskinframe = skinframe;
1527                                 Con_Printf("%s replaced with %s\n", r, newt);
1528                         }
1529                         else
1530                         {
1531                                 Con_Printf("%s was not found\n", newt);
1532                                 return;
1533                         }
1534                 }
1535         }
1536 }
1537
1538 //Made by [515]
1539 static void R_ListWorldTextures_f(cmd_state_t *cmd)
1540 {
1541         model_t         *m;
1542         texture_t       *t;
1543         int                     i;
1544         if (!r_refdef.scene.worldmodel)
1545         {
1546                 Con_Printf("There is no worldmodel\n");
1547                 return;
1548         }
1549         m = r_refdef.scene.worldmodel;
1550
1551         Con_Print("Worldmodel textures :\n");
1552         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1553                 if (t->name[0] && strcasecmp(t->name, "NO TEXTURE FOUND"))
1554                         Con_Printf("%s\n", t->name);
1555 }
1556
1557 #if 0
1558 static void gl_surf_start(void)
1559 {
1560 }
1561
1562 static void gl_surf_shutdown(void)
1563 {
1564 }
1565
1566 static void gl_surf_newmap(void)
1567 {
1568 }
1569 #endif
1570
1571 void GL_Surf_Init(void)
1572 {
1573
1574         Cvar_RegisterVariable(&r_ambient);
1575         Cvar_RegisterVariable(&r_lockpvs);
1576         Cvar_RegisterVariable(&r_lockvisibility);
1577         Cvar_RegisterVariable(&r_useportalculling);
1578         Cvar_RegisterVariable(&r_usesurfaceculling);
1579         Cvar_RegisterVariable(&r_vis_trace);
1580         Cvar_RegisterVariable(&r_vis_trace_samples);
1581         Cvar_RegisterVariable(&r_vis_trace_delay);
1582         Cvar_RegisterVariable(&r_vis_trace_eyejitter);
1583         Cvar_RegisterVariable(&r_vis_trace_enlarge);
1584         Cvar_RegisterVariable(&r_vis_trace_expand);
1585         Cvar_RegisterVariable(&r_vis_trace_pad);
1586         Cvar_RegisterVariable(&r_vis_trace_surfaces);
1587         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
1588
1589         Cmd_AddCommand(CF_CLIENT, "r_replacemaptexture", R_ReplaceWorldTexture_f, "override a map texture for testing purposes");
1590         Cmd_AddCommand(CF_CLIENT, "r_listmaptextures", R_ListWorldTextures_f, "list all textures used by the current map");
1591
1592         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
1593 }
1594