Merge PR 'sv_gameplayfix_stepmultipletimes 1: Prevent players moving too far/fast...
[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_CullFrustum(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         unsigned char *surfacevisible;
415         msurface_t *surfaces;
416         model_t *model = r_refdef.scene.worldmodel;
417         if (!model)
418                 return;
419         if (r_trippy.integer)
420                 return;
421         if (r_usesurfaceculling.integer < 1)
422                 return;
423         surfaces = model->data_surfaces;
424         surfacevisible = r_refdef.viewcache.world_surfacevisible;
425         for (surfaceindex = model->submodelsurfaces_start; surfaceindex < model->submodelsurfaces_end; surfaceindex++)
426         {
427                 if (surfacevisible[surfaceindex])
428                 {
429                         if (R_CullFrustum(surfaces[surfaceindex].mins, surfaces[surfaceindex].maxs)
430                          || (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)))
431                                 surfacevisible[surfaceindex] = 0;
432                 }
433         }
434 }
435
436 void R_View_WorldVisibility(qbool forcenovis)
437 {
438         int i, j, *mark;
439         mleaf_t *leaf;
440         mleaf_t *viewleaf;
441         model_t *model = r_refdef.scene.worldmodel;
442
443         if (!model)
444                 return;
445
446         if (r_lockvisibility.integer)
447                 return;
448
449         // clear the visible surface and leaf flags arrays
450         memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
451         if(!r_lockpvs.integer)
452                 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
453
454         r_refdef.viewcache.world_novis = false;
455
456         if (r_refdef.view.usecustompvs)
457         {
458                 // simply cull each marked leaf to the frustum (view pyramid)
459                 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
460                 {
461                         // if leaf is in current pvs and on the screen, mark its surfaces
462                         if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullFrustum(leaf->mins, leaf->maxs))
463                         {
464                                 r_refdef.stats[r_stat_world_leafs]++;
465                                 r_refdef.viewcache.world_leafvisible[j] = true;
466                                 if (leaf->numleafsurfaces)
467                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
468                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
469                         }
470                 }
471         }
472         else
473         {
474                 // if possible find the leaf the view origin is in
475                 viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_refdef.view.origin) : NULL;
476                 // if possible fetch the visible cluster bits
477                 if (!r_lockpvs.integer && model->brush.FatPVS)
478                         model->brush.FatPVS(model, r_refdef.view.origin, 2, r_refdef.viewcache.world_pvsbits, (r_refdef.viewcache.world_numclusters+7)>>3, false);
479
480                 // if floating around in the void (no pvs data available, and no
481                 // portals available), simply use all on-screen leafs.
482                 if (!viewleaf || viewleaf->clusterindex < 0 || forcenovis || !r_refdef.view.usevieworiginculling)
483                 {
484                         // no visibility method: (used when floating around in the void)
485                         // simply cull each leaf to the frustum (view pyramid)
486                         // similar to quake's RecursiveWorldNode but without cache misses
487                         r_refdef.viewcache.world_novis = true;
488                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
489                         {
490                                 if (leaf->clusterindex < 0)
491                                         continue;
492                                 // if leaf is in current pvs and on the screen, mark its surfaces
493                                 if (!R_CullFrustum(leaf->mins, leaf->maxs))
494                                 {
495                                         r_refdef.stats[r_stat_world_leafs]++;
496                                         r_refdef.viewcache.world_leafvisible[j] = true;
497                                         if (leaf->numleafsurfaces)
498                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
499                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
500                                 }
501                         }
502                 }
503                 // just check if each leaf in the PVS is on screen
504                 // (unless portal culling is enabled)
505                 else if (!model->brush.data_portals || r_useportalculling.integer < 1 || (r_useportalculling.integer < 2 && !r_novis.integer))
506                 {
507                         // pvs method:
508                         // simply check if each leaf is in the Potentially Visible Set,
509                         // and cull to frustum (view pyramid)
510                         // similar to quake's RecursiveWorldNode but without cache misses
511                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
512                         {
513                                 if (leaf->clusterindex < 0)
514                                         continue;
515                                 // if leaf is in current pvs and on the screen, mark its surfaces
516                                 if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullFrustum(leaf->mins, leaf->maxs))
517                                 {
518                                         r_refdef.stats[r_stat_world_leafs]++;
519                                         r_refdef.viewcache.world_leafvisible[j] = true;
520                                         if (leaf->numleafsurfaces)
521                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
522                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
523                                 }
524                         }
525                 }
526                 // if desired use a recursive portal flow, culling each portal to
527                 // frustum and checking if the leaf the portal leads to is in the pvs
528                 else
529                 {
530                         int leafstackpos;
531                         mportal_t *p;
532                         mleaf_t *leafstack[8192];
533                         vec3_t cullmins, cullmaxs;
534                         float cullbias = r_nearclip.value * 2.0f; // the nearclip plane can easily end up culling portals in certain perfectly-aligned views, causing view blackouts
535                         // simple-frustum portal method:
536                         // follows portals leading outward from viewleaf, does not venture
537                         // offscreen or into leafs that are not visible, faster than
538                         // Quake's RecursiveWorldNode and vastly better in unvised maps,
539                         // often culls some surfaces that pvs alone would miss
540                         // (such as a room in pvs that is hidden behind a wall, but the
541                         //  passage leading to the room is off-screen)
542                         leafstack[0] = viewleaf;
543                         leafstackpos = 1;
544                         while (leafstackpos)
545                         {
546                                 leaf = leafstack[--leafstackpos];
547                                 if (r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs])
548                                         continue;
549                                 if (leaf->clusterindex < 0)
550                                         continue;
551                                 r_refdef.stats[r_stat_world_leafs]++;
552                                 r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs] = true;
553                                 // mark any surfaces bounding this leaf
554                                 if (leaf->numleafsurfaces)
555                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
556                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
557                                 // follow portals into other leafs
558                                 // the checks are:
559                                 // the leaf has not been visited yet
560                                 // and the leaf is visible in the pvs
561                                 // the portal polygon's bounding box is on the screen
562                                 for (p = leaf->portals;p;p = p->next)
563                                 {
564                                         r_refdef.stats[r_stat_world_portals]++;
565                                         if (r_refdef.viewcache.world_leafvisible[p->past - model->brush.data_leafs])
566                                                 continue;
567                                         if (!CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, p->past->clusterindex))
568                                                 continue;
569                                         cullmins[0] = p->mins[0] - cullbias;
570                                         cullmins[1] = p->mins[1] - cullbias;
571                                         cullmins[2] = p->mins[2] - cullbias;
572                                         cullmaxs[0] = p->maxs[0] + cullbias;
573                                         cullmaxs[1] = p->maxs[1] + cullbias;
574                                         cullmaxs[2] = p->maxs[2] + cullbias;
575                                         if (R_CullFrustum(cullmins, cullmaxs))
576                                                 continue;
577                                         if (r_vis_trace.integer)
578                                         {
579                                                 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))
580                                                         p->tracetime = host.realtime;
581                                                 if (host.realtime - p->tracetime > r_vis_trace_delay.value)
582                                                         continue;
583                                         }
584                                         if (leafstackpos >= (int)(sizeof(leafstack) / sizeof(leafstack[0])))
585                                                 break;
586                                         leafstack[leafstackpos++] = p->past;
587                                 }
588                         }
589                 }
590         }
591
592         // Cull the rest
593         R_View_WorldVisibility_CullSurfaces();
594 }
595
596 void R_Mod_DrawSky(entity_render_t *ent)
597 {
598         if (ent->model == NULL)
599                 return;
600         R_DrawModelSurfaces(ent, true, true, false, false, false, false);
601 }
602
603 void R_Mod_DrawAddWaterPlanes(entity_render_t *ent)
604 {
605         int i, n, flagsmask;
606         model_t *model = ent->model;
607         msurface_t *surfaces;
608         if (model == NULL)
609                 return;
610
611         RSurf_ActiveModelEntity(ent, true, false, false);
612
613         surfaces = model->data_surfaces;
614         flagsmask = MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA;
615
616         // add visible surfaces to draw list
617         if (ent == r_refdef.scene.worldentity)
618         {
619                 for (i = model->submodelsurfaces_start;i < model->submodelsurfaces_end;i++)
620                         if (r_refdef.viewcache.world_surfacevisible[i])
621                                 if (surfaces[i].texture->basematerialflags & flagsmask)
622                                         R_Water_AddWaterPlane(surfaces + i, 0);
623         }
624         else
625         {
626                 if(ent->entitynumber >= MAX_EDICTS) // && CL_VM_TransformView(ent->entitynumber - MAX_EDICTS, NULL, NULL, NULL))
627                         n = ent->entitynumber;
628                 else
629                         n = 0;
630                 for (i = model->submodelsurfaces_start;i < model->submodelsurfaces_end;i++)
631                         if (surfaces[i].texture->basematerialflags & flagsmask)
632                                 R_Water_AddWaterPlane(surfaces + i, n);
633         }
634         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
635 }
636
637 void R_Mod_Draw(entity_render_t *ent)
638 {
639         model_t *model = ent->model;
640         if (model == NULL)
641                 return;
642         R_DrawModelSurfaces(ent, false, true, false, false, false, false);
643 }
644
645 void R_Mod_DrawDepth(entity_render_t *ent)
646 {
647         model_t *model = ent->model;
648         if (model == NULL || model->surfmesh.isanimated)
649                 return;
650         GL_ColorMask(0,0,0,0);
651         GL_Color(1,1,1,1);
652         GL_DepthTest(true);
653         GL_BlendFunc(GL_ONE, GL_ZERO);
654         GL_DepthMask(true);
655 //      R_Mesh_ResetTextureState();
656         R_DrawModelSurfaces(ent, false, false, true, false, false, false);
657         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
658 }
659
660 void R_Mod_DrawDebug(entity_render_t *ent)
661 {
662         if (ent->model == NULL)
663                 return;
664         R_DrawModelSurfaces(ent, false, false, false, true, false, false);
665 }
666
667 void R_Mod_DrawPrepass(entity_render_t *ent)
668 {
669         model_t *model = ent->model;
670         if (model == NULL)
671                 return;
672         R_DrawModelSurfaces(ent, false, true, false, false, true, false);
673 }
674
675 typedef struct r_q1bsp_getlightinfo_s
676 {
677         model_t *model;
678         vec3_t relativelightorigin;
679         float lightradius;
680         int *outleaflist;
681         unsigned char *outleafpvs;
682         int outnumleafs;
683         unsigned char *visitingleafpvs;
684         int *outsurfacelist;
685         unsigned char *outsurfacepvs;
686         unsigned char *tempsurfacepvs;
687         unsigned char *outshadowtrispvs;
688         unsigned char *outlighttrispvs;
689         int outnumsurfaces;
690         vec3_t outmins;
691         vec3_t outmaxs;
692         vec3_t lightmins;
693         vec3_t lightmaxs;
694         const unsigned char *pvs;
695         qbool svbsp_active;
696         qbool svbsp_insertoccluder;
697         qbool noocclusion; // avoids PVS culling
698         qbool frontsidecasting; // casts shadows from surfaces facing the light (otherwise ones facing away)
699         int numfrustumplanes;
700         const mplane_t *frustumplanes;
701 }
702 r_q1bsp_getlightinfo_t;
703
704 #define GETLIGHTINFO_MAXNODESTACK 4096
705
706 static void R_Q1BSP_RecursiveGetLightInfo_BSP(r_q1bsp_getlightinfo_t *info, qbool skipsurfaces)
707 {
708         // nodestack
709         mnode_t *nodestack[GETLIGHTINFO_MAXNODESTACK];
710         int nodestackpos = 0;
711         // node processing
712         mplane_t *plane;
713         mnode_t *node;
714         int sides;
715         // leaf processing
716         mleaf_t *leaf;
717         const msurface_t *surface;
718         const msurface_t *surfaces = info->model->data_surfaces;
719         int numleafsurfaces;
720         int leafsurfaceindex;
721         int surfaceindex;
722         int triangleindex, t;
723         int currentmaterialflags;
724         qbool castshadow;
725         const int *e;
726         const vec_t *v[3];
727         float v2[3][3];
728         qbool insidebox;
729         qbool noocclusion = info->noocclusion;
730         qbool frontsidecasting = info->frontsidecasting;
731         qbool svbspactive = info->svbsp_active;
732         qbool svbspinsertoccluder = info->svbsp_insertoccluder;
733         const int *leafsurfaceindices;
734         qbool addedtris;
735         int i;
736         mportal_t *portal;
737         static float points[128][3];
738         // push the root node onto our nodestack
739         nodestack[nodestackpos++] = info->model->brush.data_nodes;
740         // we'll be done when the nodestack is empty
741         while (nodestackpos)
742         {
743                 // get a node from the stack to process
744                 node = nodestack[--nodestackpos];
745                 // is it a node or a leaf?
746                 plane = node->plane;
747                 if (plane)
748                 {
749                         // node
750 #if 0
751                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
752                                 continue;
753 #endif
754 #if 0
755                         if (!r_shadow_compilingrtlight && R_CullBox(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
756                                 continue;
757 #endif
758                         // axial planes can be processed much more quickly
759                         if (plane->type < 3)
760                         {
761                                 // axial plane
762                                 if (info->lightmins[plane->type] > plane->dist)
763                                         nodestack[nodestackpos++] = node->children[0];
764                                 else if (info->lightmaxs[plane->type] < plane->dist)
765                                         nodestack[nodestackpos++] = node->children[1];
766                                 else
767                                 {
768                                         // recurse front side first because the svbsp building prefers it
769                                         if (info->relativelightorigin[plane->type] >= plane->dist)
770                                         {
771                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
772                                                         nodestack[nodestackpos++] = node->children[0];
773                                                 nodestack[nodestackpos++] = node->children[1];
774                                         }
775                                         else
776                                         {
777                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
778                                                         nodestack[nodestackpos++] = node->children[1];
779                                                 nodestack[nodestackpos++] = node->children[0];
780                                         }
781                                 }
782                         }
783                         else
784                         {
785                                 // sloped plane
786                                 sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
787                                 switch (sides)
788                                 {
789                                 default:
790                                         continue; // ERROR: NAN bounding box!
791                                 case 1:
792                                         nodestack[nodestackpos++] = node->children[0];
793                                         break;
794                                 case 2:
795                                         nodestack[nodestackpos++] = node->children[1];
796                                         break;
797                                 case 3:
798                                         // recurse front side first because the svbsp building prefers it
799                                         if (PlaneDist(info->relativelightorigin, plane) >= 0)
800                                         {
801                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
802                                                         nodestack[nodestackpos++] = node->children[0];
803                                                 nodestack[nodestackpos++] = node->children[1];
804                                         }
805                                         else
806                                         {
807                                                 if (nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
808                                                         nodestack[nodestackpos++] = node->children[1];
809                                                 nodestack[nodestackpos++] = node->children[0];
810                                         }
811                                         break;
812                                 }
813                         }
814                 }
815                 else
816                 {
817                         // leaf
818                         leaf = (mleaf_t *)node;
819 #if 1
820                         if (!info->noocclusion && info->pvs != NULL && !CHECKPVSBIT(info->pvs, leaf->clusterindex))
821                                 continue;
822 #endif
823 #if 1
824                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
825                                 continue;
826 #endif
827 #if 1
828                         if (!r_shadow_compilingrtlight && R_CullBox(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
829                                 continue;
830 #endif
831
832                         if (svbspactive)
833                         {
834                                 // we can occlusion test the leaf by checking if all of its portals
835                                 // are occluded (unless the light is in this leaf - but that was
836                                 // already handled by the caller)
837                                 for (portal = leaf->portals;portal;portal = portal->next)
838                                 {
839                                         for (i = 0;i < portal->numpoints;i++)
840                                                 VectorCopy(portal->points[i].position, points[i]);
841                                         if (SVBSP_AddPolygon(&r_svbsp, portal->numpoints, points[0], false, NULL, NULL, 0) & 2)
842                                                 break;
843                                 }
844                                 if (leaf->portals && portal == NULL)
845                                         continue; // no portals of this leaf visible
846                         }
847
848                         // add this leaf to the reduced light bounds
849                         info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
850                         info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
851                         info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
852                         info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
853                         info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
854                         info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
855
856                         // mark this leaf as being visible to the light
857                         if (info->outleafpvs)
858                         {
859                                 int leafindex = leaf - info->model->brush.data_leafs;
860                                 if (!CHECKPVSBIT(info->outleafpvs, leafindex))
861                                 {
862                                         SETPVSBIT(info->outleafpvs, leafindex);
863                                         info->outleaflist[info->outnumleafs++] = leafindex;
864                                 }
865                         }
866
867                         // when using BIH, we skip the surfaces here
868                         if (skipsurfaces)
869                                 continue;
870
871                         // iterate the surfaces linked by this leaf and check their triangles
872                         leafsurfaceindices = leaf->firstleafsurface;
873                         numleafsurfaces = leaf->numleafsurfaces;
874                         if (svbspinsertoccluder)
875                         {
876                                 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
877                                 {
878                                         surfaceindex = leafsurfaceindices[leafsurfaceindex];
879                                         if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
880                                                 continue;
881                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
882                                         surface = surfaces + surfaceindex;
883                                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
884                                                 continue;
885                                         currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
886                                         castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
887                                         if (!castshadow)
888                                                 continue;
889                                         insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
890                                         for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
891                                         {
892                                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
893                                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
894                                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
895                                                 VectorCopy(v[0], v2[0]);
896                                                 VectorCopy(v[1], v2[1]);
897                                                 VectorCopy(v[2], v2[2]);
898                                                 if (insidebox || TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
899                                                         SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
900                                         }
901                                 }
902                         }
903                         else
904                         {
905                                 for (leafsurfaceindex = 0;leafsurfaceindex < numleafsurfaces;leafsurfaceindex++)
906                                 {
907                                         surfaceindex = leafsurfaceindices[leafsurfaceindex];
908                                         surface = surfaces + surfaceindex;
909                                         if(!surface->texture)
910                                                 continue;       
911                                         if (CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
912                                                 continue;
913                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
914                                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
915                                                 continue;
916                                         addedtris = false;
917                                         currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
918                                         castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
919                                         insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
920                                         for (triangleindex = 0, t = surface->num_firsttriangle, e = info->model->surfmesh.data_element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
921                                         {
922                                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
923                                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
924                                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
925                                                 VectorCopy(v[0], v2[0]);
926                                                 VectorCopy(v[1], v2[1]);
927                                                 VectorCopy(v[2], v2[2]);
928                                                 if (!insidebox && !TriangleBBoxOverlapsBox(v2[0], v2[1], v2[2], info->lightmins, info->lightmaxs))
929                                                         continue;
930                                                 if (svbspactive && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
931                                                         continue;
932                                                 // we don't omit triangles from lighting even if they are
933                                                 // backfacing, because when using shadowmapping they are often
934                                                 // not fully occluded on the horizon of an edge
935                                                 SETPVSBIT(info->outlighttrispvs, t);
936                                                 addedtris = true;
937                                                 if (castshadow)
938                                                 {
939                                                         if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
940                                                         {
941                                                                 // if the material is double sided we
942                                                                 // can't cull by direction
943                                                                 SETPVSBIT(info->outshadowtrispvs, t);
944                                                         }
945                                                         else if (frontsidecasting)
946                                                         {
947                                                                 // front side casting occludes backfaces,
948                                                                 // so they are completely useless as both
949                                                                 // casters and lit polygons
950                                                                 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
951                                                                         SETPVSBIT(info->outshadowtrispvs, t);
952                                                         }
953                                                         else
954                                                         {
955                                                                 // back side casting does not occlude
956                                                                 // anything so we can't cull lit polygons
957                                                                 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
958                                                                         SETPVSBIT(info->outshadowtrispvs, t);
959                                                         }
960                                                 }
961                                         }
962                                         if (addedtris)
963                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
964                                 }
965                         }
966                 }
967         }
968 }
969
970 static void R_Q1BSP_RecursiveGetLightInfo_BIH(r_q1bsp_getlightinfo_t *info, const bih_t *bih)
971 {
972         bih_leaf_t *leaf;
973         bih_node_t *node;
974         int nodenum;
975         int axis;
976         int surfaceindex;
977         int t;
978         int nodeleafindex;
979         int currentmaterialflags;
980         qbool castshadow;
981         qbool noocclusion = info->noocclusion;
982         qbool frontsidecasting = info->frontsidecasting;
983         msurface_t *surface;
984         const int *e;
985         const vec_t *v[3];
986         float v2[3][3];
987         int nodestack[GETLIGHTINFO_MAXNODESTACK];
988         int nodestackpos = 0;
989         // note: because the BSP leafs are not in the BIH tree, the _BSP function
990         // must be called to mark leafs visible for entity culling...
991         // we start at the root node
992         nodestack[nodestackpos++] = bih->rootnode;
993         // we'll be done when the stack is empty
994         while (nodestackpos)
995         {
996                 // pop one off the stack to process
997                 nodenum = nodestack[--nodestackpos];
998                 // node
999                 node = bih->nodes + nodenum;
1000                 if (node->type == BIH_UNORDERED)
1001                 {
1002                         for (nodeleafindex = 0;nodeleafindex < BIH_MAXUNORDEREDCHILDREN && node->children[nodeleafindex] >= 0;nodeleafindex++)
1003                         {
1004                                 leaf = bih->leafs + node->children[nodeleafindex];
1005                                 if (leaf->type != BIH_RENDERTRIANGLE)
1006                                         continue;
1007 #if 1
1008                                 if (!BoxesOverlap(info->lightmins, info->lightmaxs, leaf->mins, leaf->maxs))
1009                                         continue;
1010 #endif
1011 #if 1
1012                                 if (!r_shadow_compilingrtlight && R_CullBox(leaf->mins, leaf->maxs, info->numfrustumplanes, info->frustumplanes))
1013                                         continue;
1014 #endif
1015                                 surfaceindex = leaf->surfaceindex;
1016                                 surface = info->model->data_surfaces + surfaceindex;
1017                                 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
1018                                 castshadow = !(currentmaterialflags & MATERIALFLAG_NOSHADOW);
1019                                 t = leaf->itemindex;
1020                                 e = info->model->surfmesh.data_element3i + t * 3;
1021                                 v[0] = info->model->surfmesh.data_vertex3f + e[0] * 3;
1022                                 v[1] = info->model->surfmesh.data_vertex3f + e[1] * 3;
1023                                 v[2] = info->model->surfmesh.data_vertex3f + e[2] * 3;
1024                                 VectorCopy(v[0], v2[0]);
1025                                 VectorCopy(v[1], v2[1]);
1026                                 VectorCopy(v[2], v2[2]);
1027                                 if (info->svbsp_insertoccluder)
1028                                 {
1029                                         if (castshadow)
1030                                                 SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0);
1031                                         continue;
1032                                 }
1033                                 if (info->svbsp_active && !(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
1034                                         continue;
1035                                 // we don't occlude triangles from lighting even
1036                                 // if they are backfacing, because when using
1037                                 // shadowmapping they are often not fully occluded
1038                                 // on the horizon of an edge
1039                                 SETPVSBIT(info->outlighttrispvs, t);
1040                                 if (castshadow)
1041                                 {
1042                                         if (noocclusion || (currentmaterialflags & MATERIALFLAG_NOCULLFACE))
1043                                         {
1044                                                 // if the material is double sided we
1045                                                 // can't cull by direction
1046                                                 SETPVSBIT(info->outshadowtrispvs, t);
1047                                         }
1048                                         else if (frontsidecasting)
1049                                         {
1050                                                 // front side casting occludes backfaces,
1051                                                 // so they are completely useless as both
1052                                                 // casters and lit polygons
1053                                                 if (PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1054                                                         SETPVSBIT(info->outshadowtrispvs, t);
1055                                         }
1056                                         else
1057                                         {
1058                                                 // back side casting does not occlude
1059                                                 // anything so we can't cull lit polygons
1060                                                 if (!PointInfrontOfTriangle(info->relativelightorigin, v2[0], v2[1], v2[2]))
1061                                                         SETPVSBIT(info->outshadowtrispvs, t);
1062                                         }
1063                                 }
1064                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
1065                                 {
1066                                         SETPVSBIT(info->outsurfacepvs, surfaceindex);
1067                                         info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
1068                                 }
1069                         }
1070                 }
1071                 else
1072                 {
1073                         axis = node->type - BIH_SPLITX;
1074 #if 0
1075                         if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
1076                                 continue;
1077 #endif
1078 #if 0
1079                         if (!r_shadow_compilingrtlight && R_CullBox(node->mins, node->maxs, rtlight->cached_numfrustumplanes, rtlight->cached_frustumplanes))
1080                                 continue;
1081 #endif
1082                         if (info->lightmins[axis] <= node->backmax)
1083                         {
1084                                 if (info->lightmaxs[axis] >= node->frontmin && nodestackpos < GETLIGHTINFO_MAXNODESTACK-1)
1085                                         nodestack[nodestackpos++] = node->front;
1086                                 nodestack[nodestackpos++] = node->back;
1087                                 continue;
1088                         }
1089                         else if (info->lightmaxs[axis] >= node->frontmin)
1090                         {
1091                                 nodestack[nodestackpos++] = node->front;
1092                                 continue;
1093                         }
1094                         else
1095                                 continue; // light falls between children, nothing here
1096                 }
1097         }
1098 }
1099
1100 static void R_Q1BSP_CallRecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, qbool use_svbsp)
1101 {
1102         extern cvar_t r_shadow_usebihculling;
1103         if (use_svbsp)
1104         {
1105                 float origin[3];
1106                 VectorCopy(info->relativelightorigin, origin);
1107                 r_svbsp.maxnodes = max(r_svbsp.maxnodes, 1<<12);
1108                 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1109                 info->svbsp_active = true;
1110                 info->svbsp_insertoccluder = true;
1111                 for (;;)
1112                 {
1113                         SVBSP_Init(&r_svbsp, origin, r_svbsp.maxnodes, r_svbsp.nodes);
1114                         R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1115                         // if that failed, retry with more nodes
1116                         if (r_svbsp.ranoutofnodes)
1117                         {
1118                                 // an upper limit is imposed
1119                                 if (r_svbsp.maxnodes >= 2<<22)
1120                                         break;
1121                                 r_svbsp.maxnodes *= 2;
1122                                 r_svbsp.nodes = (svbsp_node_t*) R_FrameData_Alloc(r_svbsp.maxnodes * sizeof(svbsp_node_t));
1123                                 //Mem_Free(r_svbsp.nodes);
1124                                 //r_svbsp.nodes = (svbsp_node_t*) Mem_Alloc(tempmempool, r_svbsp.maxnodes * sizeof(svbsp_node_t));
1125                         }
1126                         else
1127                                 break;
1128                 }
1129                 // now clear the visibility arrays because we need to redo it
1130                 info->outnumleafs = 0;
1131                 info->outnumsurfaces = 0;
1132                 memset(info->outleafpvs, 0, (info->model->brush.num_leafs + 7) >> 3);
1133                 memset(info->outsurfacepvs, 0, (info->model->num_surfaces + 7) >> 3);
1134                 memset(info->outshadowtrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1135                 memset(info->outlighttrispvs, 0, (info->model->surfmesh.num_triangles + 7) >> 3);
1136         }
1137         else
1138                 info->svbsp_active = false;
1139
1140         // we HAVE to mark the leaf the light is in as lit, because portals are
1141         // irrelevant to a leaf that the light source is inside of
1142         // (and they are all facing away, too)
1143         {
1144                 mnode_t *node = info->model->brush.data_nodes;
1145                 mleaf_t *leaf;
1146                 while (node->plane)
1147                         node = node->children[(node->plane->type < 3 ? info->relativelightorigin[node->plane->type] : DotProduct(info->relativelightorigin,node->plane->normal)) < node->plane->dist];
1148                 leaf = (mleaf_t *)node;
1149                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
1150                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
1151                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
1152                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
1153                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
1154                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
1155                 if (info->outleafpvs)
1156                 {
1157                         int leafindex = leaf - info->model->brush.data_leafs;
1158                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
1159                         {
1160                                 SETPVSBIT(info->outleafpvs, leafindex);
1161                                 info->outleaflist[info->outnumleafs++] = leafindex;
1162                         }
1163                 }
1164         }
1165
1166         info->svbsp_insertoccluder = false;
1167         // 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
1168         if (r_shadow_usebihculling.integer > 0 && (r_shadow_usebihculling.integer == 2 || info->model->brush.num_leafs == 1) && info->model->render_bih.leafs != NULL)
1169         {
1170                 R_Q1BSP_RecursiveGetLightInfo_BSP(info, true);
1171                 R_Q1BSP_RecursiveGetLightInfo_BIH(info, &info->model->render_bih);
1172         }
1173         else
1174                 R_Q1BSP_RecursiveGetLightInfo_BSP(info, false);
1175         // we're using temporary framedata memory, so this pointer will be invalid soon, clear it
1176         r_svbsp.nodes = NULL;
1177         if (developer_extra.integer && use_svbsp)
1178         {
1179                 Con_DPrintf("GetLightInfo: svbsp built with %i nodes, polygon stats:\n", r_svbsp.numnodes);
1180                 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);
1181                 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);
1182         }
1183 }
1184
1185 static msurface_t *r_q1bsp_getlightinfo_surfaces;
1186
1187 static int R_Q1BSP_GetLightInfo_comparefunc(const void *ap, const void *bp)
1188 {
1189         int a = *(int*)ap;
1190         int b = *(int*)bp;
1191         const msurface_t *as = r_q1bsp_getlightinfo_surfaces + a;
1192         const msurface_t *bs = r_q1bsp_getlightinfo_surfaces + b;
1193         if (as->texture < bs->texture)
1194                 return -1;
1195         if (as->texture > bs->texture)
1196                 return 1;
1197         return a - b;
1198 }
1199
1200 extern cvar_t r_shadow_sortsurfaces;
1201
1202 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)
1203 {
1204         r_q1bsp_getlightinfo_t info;
1205         info.frontsidecasting = r_shadow_frontsidecasting.integer != 0;
1206         info.noocclusion = noocclusion || !info.frontsidecasting;
1207         VectorCopy(relativelightorigin, info.relativelightorigin);
1208         info.lightradius = lightradius;
1209         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
1210         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
1211         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
1212         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
1213         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
1214         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
1215         if (ent->model == NULL)
1216         {
1217                 VectorCopy(info.lightmins, outmins);
1218                 VectorCopy(info.lightmaxs, outmaxs);
1219                 *outnumleafspointer = 0;
1220                 *outnumsurfacespointer = 0;
1221                 return;
1222         }
1223         info.model = ent->model;
1224         info.outleaflist = outleaflist;
1225         info.outleafpvs = outleafpvs;
1226         info.outnumleafs = 0;
1227         info.visitingleafpvs = visitingleafpvs;
1228         info.outsurfacelist = outsurfacelist;
1229         info.outsurfacepvs = outsurfacepvs;
1230         info.outshadowtrispvs = outshadowtrispvs;
1231         info.outlighttrispvs = outlighttrispvs;
1232         info.outnumsurfaces = 0;
1233         info.numfrustumplanes = numfrustumplanes;
1234         info.frustumplanes = frustumplanes;
1235         VectorCopy(info.relativelightorigin, info.outmins);
1236         VectorCopy(info.relativelightorigin, info.outmaxs);
1237         memset(visitingleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1238         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
1239         memset(outsurfacepvs, 0, (info.model->num_surfaces + 7) >> 3);
1240         memset(outshadowtrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1241         memset(outlighttrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
1242         if (info.model->brush.GetPVS && !info.noocclusion)
1243                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
1244         else
1245                 info.pvs = NULL;
1246         RSurf_ActiveModelEntity(r_refdef.scene.worldentity, false, false, false);
1247
1248         if (!info.noocclusion && r_shadow_compilingrtlight && r_shadow_realtime_world_compileportalculling.integer && info.model->brush.data_portals)
1249         {
1250                 // use portal recursion for exact light volume culling, and exact surface checking
1251                 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);
1252         }
1253         else if (!info.noocclusion && r_shadow_realtime_dlight_portalculling.integer && info.model->brush.data_portals)
1254         {
1255                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
1256                 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);
1257         }
1258         else
1259         {
1260                 // recurse the bsp tree, checking leafs and surfaces for visibility
1261                 // optionally using svbsp for exact culling of compiled lights
1262                 // (or if the user enables dlight svbsp culling, which is mostly for
1263                 //  debugging not actual use)
1264                 R_Q1BSP_CallRecursiveGetLightInfo(&info, !info.noocclusion && (r_shadow_compilingrtlight ? r_shadow_realtime_world_compilesvbsp.integer : r_shadow_realtime_dlight_svbspculling.integer) != 0);
1265         }
1266
1267         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveModelEntity
1268
1269         // limit combined leaf box to light boundaries
1270         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
1271         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
1272         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
1273         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
1274         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
1275         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
1276
1277         *outnumleafspointer = info.outnumleafs;
1278         *outnumsurfacespointer = info.outnumsurfaces;
1279
1280         // now sort surfaces by texture for faster rendering
1281         r_q1bsp_getlightinfo_surfaces = info.model->data_surfaces;
1282         if (r_shadow_sortsurfaces.integer)
1283                 qsort(info.outsurfacelist, info.outnumsurfaces, sizeof(*info.outsurfacelist), R_Q1BSP_GetLightInfo_comparefunc);
1284 }
1285
1286 void R_Mod_CompileShadowMap(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
1287 {
1288         model_t *model = ent->model;
1289         msurface_t *surface;
1290         int surfacelistindex;
1291         int sidetotals[6] = { 0, 0, 0, 0, 0, 0 }, sidemasks = 0;
1292         int i;
1293         // FIXME: the sidetotals code incorrectly assumes that static_meshchain is
1294         // a single mesh - to prevent that from crashing (sideoffsets, sidetotals
1295         // exceeding the number of triangles in a single mesh) we have to make sure
1296         // that we make only a single mesh - so over-estimate the size of the mesh
1297         // to match the model.
1298         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Begin(r_main_mempool, model->surfmesh.num_vertices, model->surfmesh.num_triangles);
1299         R_Shadow_PrepareShadowSides(model->surfmesh.num_triangles);
1300         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1301         {
1302                 surface = model->data_surfaces + surfacelist[surfacelistindex];
1303                 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);
1304         }
1305         R_Shadow_ShadowMapFromList(model->surfmesh.num_vertices, model->surfmesh.num_triangles, model->surfmesh.data_vertex3f, model->surfmesh.data_element3i, numshadowsides, sidetotals, shadowsides, shadowsideslist);
1306         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Finish(r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, true);
1307         r_shadow_compilingrtlight->static_shadowmap_receivers &= sidemasks;
1308         for(i = 0;i<6;i++)
1309                 if(!sidetotals[i])
1310                         r_shadow_compilingrtlight->static_shadowmap_casters &= ~(1 << i);
1311 }
1312
1313 #define RSURF_MAX_BATCHSURFACES 8192
1314
1315 static const msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
1316
1317 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)
1318 {
1319         model_t *model = ent->model;
1320         const msurface_t *surface;
1321         int modelsurfacelistindex, batchnumsurfaces;
1322         // check the box in modelspace, it was already checked in worldspace
1323         if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
1324                 return;
1325         R_FrameData_SetMark();
1326         // identify lit faces within the bounding box
1327         for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1328         {
1329                 surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1330                 if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1331                         continue;
1332                 rsurface.texture = R_GetCurrentTexture(surface->texture);
1333                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1334                         continue;
1335                 if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1336                         continue;
1337                 r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1338                 r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1339                 batchsurfacelist[0] = surface;
1340                 batchnumsurfaces = 1;
1341                 while(++modelsurfacelistindex < modelnumsurfaces && batchnumsurfaces < RSURF_MAX_BATCHSURFACES)
1342                 {
1343                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1344                         if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1345                                 continue;
1346                         if (surface->texture != batchsurfacelist[0]->texture)
1347                                 break;
1348                         if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1349                                 continue;
1350                         r_refdef.stats[r_stat_lights_dynamicshadowtriangles] += surface->num_triangles;
1351                         r_refdef.stats[r_stat_lights_shadowtriangles] += surface->num_triangles;
1352                         batchsurfacelist[batchnumsurfaces++] = surface;
1353                 }
1354                 --modelsurfacelistindex;
1355                 GL_CullFace(rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE ? GL_NONE : r_refdef.view.cullface_back);
1356                 RSurf_PrepareVerticesForBatch(BATCHNEED_ARRAY_VERTEX | BATCHNEED_ALLOWMULTIDRAW, batchnumsurfaces, batchsurfacelist);
1357                 R_Mesh_PrepareVertices_Vertex3f(rsurface.batchnumvertices, rsurface.batchvertex3f, rsurface.batchvertex3f_vertexbuffer, rsurface.batchvertex3f_bufferoffset);
1358                 RSurf_DrawBatch();
1359         }
1360         R_FrameData_ReturnToMark();
1361 }
1362
1363 #define BATCHSIZE 1024
1364
1365 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
1366 {
1367         int i, j, endsurface;
1368         texture_t *t;
1369         const msurface_t *surface;
1370         R_FrameData_SetMark();
1371         // note: in practice this never actually receives batches
1372         R_Shadow_RenderMode_Begin();
1373         R_Shadow_RenderMode_ActiveLight(rtlight);
1374         R_Shadow_RenderMode_Lighting(true, rtlight->shadowmapatlassidesize != 0, (ent->flags & RENDER_NOSELFSHADOW) != 0);
1375         R_Shadow_SetupEntityLight(ent);
1376         for (i = 0;i < numsurfaces;i = j)
1377         {
1378                 j = i + 1;
1379                 surface = rsurface.modelsurfaces + surfacelist[i];
1380                 t = surface->texture;
1381                 rsurface.texture = R_GetCurrentTexture(t);
1382                 endsurface = min(j + BATCHSIZE, numsurfaces);
1383                 for (j = i;j < endsurface;j++)
1384                 {
1385                         surface = rsurface.modelsurfaces + surfacelist[j];
1386                         if (t != surface->texture)
1387                                 break;
1388                         R_Shadow_RenderLighting(1, &surface);
1389                 }
1390         }
1391         R_Shadow_RenderMode_End();
1392         R_FrameData_ReturnToMark();
1393 }
1394
1395 extern qbool r_shadow_usingdeferredprepass;
1396 void R_Mod_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist, const unsigned char *lighttrispvs)
1397 {
1398         model_t *model = ent->model;
1399         const msurface_t *surface;
1400         int i, k, kend, l, endsurface, batchnumsurfaces, texturenumsurfaces;
1401         const msurface_t **texturesurfacelist;
1402         texture_t *tex;
1403         CHECKGLERROR
1404         R_FrameData_SetMark();
1405         // this is a double loop because non-visible surface skipping has to be
1406         // fast, and even if this is not the world model (and hence no visibility
1407         // checking) the input surface list and batch buffer are different formats
1408         // so some processing is necessary.  (luckily models have few surfaces)
1409         for (i = 0;i < numsurfaces;)
1410         {
1411                 batchnumsurfaces = 0;
1412                 endsurface = min(i + RSURF_MAX_BATCHSURFACES, numsurfaces);
1413                 if (ent == r_refdef.scene.worldentity)
1414                 {
1415                         for (;i < endsurface;i++)
1416                                 if (r_refdef.viewcache.world_surfacevisible[surfacelist[i]])
1417                                         batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1418                 }
1419                 else
1420                 {
1421                         for (;i < endsurface;i++)
1422                                 batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1423                 }
1424                 if (!batchnumsurfaces)
1425                         continue;
1426                 for (k = 0;k < batchnumsurfaces;k = kend)
1427                 {
1428                         surface = batchsurfacelist[k];
1429                         tex = surface->texture;
1430                         rsurface.texture = R_GetCurrentTexture(tex);
1431                         // gather surfaces into a batch range
1432                         for (kend = k;kend < batchnumsurfaces && tex == batchsurfacelist[kend]->texture;kend++)
1433                                 ;
1434                         // now figure out what to do with this particular range of surfaces
1435                         // VorteX: added MATERIALFLAG_NORTLIGHT
1436                         if ((rsurface.texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_NORTLIGHT)) != MATERIALFLAG_WALL)
1437                                 continue;
1438                         if (r_fb.water.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION | MATERIALFLAG_CAMERA)))
1439                                 continue;
1440                         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
1441                         {
1442                                 vec3_t tempcenter, center;
1443                                 for (l = k;l < kend;l++)
1444                                 {
1445                                         surface = batchsurfacelist[l];
1446                                         if (r_transparent_sortsurfacesbynearest.integer)
1447                                         {
1448                                                 tempcenter[0] = bound(surface->mins[0], rsurface.localvieworigin[0], surface->maxs[0]);
1449                                                 tempcenter[1] = bound(surface->mins[1], rsurface.localvieworigin[1], surface->maxs[1]);
1450                                                 tempcenter[2] = bound(surface->mins[2], rsurface.localvieworigin[2], surface->maxs[2]);
1451                                         }
1452                                         else
1453                                         {
1454                                                 tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
1455                                                 tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
1456                                                 tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
1457                                         }
1458                                         Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
1459                                         if (ent->transparent_offset) // transparent offset
1460                                         {
1461                                                 center[0] += r_refdef.view.forward[0]*ent->transparent_offset;
1462                                                 center[1] += r_refdef.view.forward[1]*ent->transparent_offset;
1463                                                 center[2] += r_refdef.view.forward[2]*ent->transparent_offset;
1464                                         }
1465                                         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);
1466                                 }
1467                                 continue;
1468                         }
1469                         if (r_shadow_usingdeferredprepass)
1470                                 continue;
1471                         texturenumsurfaces = kend - k;
1472                         texturesurfacelist = batchsurfacelist + k;
1473                         R_Shadow_RenderLighting(texturenumsurfaces, texturesurfacelist);
1474                 }
1475         }
1476         R_FrameData_ReturnToMark();
1477 }
1478
1479 //Made by [515]
1480 static void R_ReplaceWorldTexture_f(cmd_state_t *cmd)
1481 {
1482         model_t         *m;
1483         texture_t       *t;
1484         int                     i;
1485         const char      *r, *newt;
1486         skinframe_t *skinframe;
1487         if (!r_refdef.scene.worldmodel)
1488         {
1489                 Con_Printf("There is no worldmodel\n");
1490                 return;
1491         }
1492         m = r_refdef.scene.worldmodel;
1493
1494         if(Cmd_Argc(cmd) < 2)
1495         {
1496                 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
1497                 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
1498                 return;
1499         }
1500         if(!cl.islocalgame || !cl.worldmodel)
1501         {
1502                 Con_Print("This command works only in singleplayer\n");
1503                 return;
1504         }
1505         r = Cmd_Argv(cmd, 1);
1506         newt = Cmd_Argv(cmd, 2);
1507         if(!newt[0])
1508                 newt = r;
1509         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1510         {
1511                 if(/*t->width && !strcasecmp(t->name, r)*/ matchpattern( t->name, r, true ) )
1512                 {
1513                         if ((skinframe = R_SkinFrame_LoadExternal(newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PICMIP, true, false)))
1514                         {
1515 //                              t->skinframes[0] = skinframe;
1516                                 t->currentskinframe = skinframe;
1517                                 Con_Printf("%s replaced with %s\n", r, newt);
1518                         }
1519                         else
1520                         {
1521                                 Con_Printf("%s was not found\n", newt);
1522                                 return;
1523                         }
1524                 }
1525         }
1526 }
1527
1528 //Made by [515]
1529 static void R_ListWorldTextures_f(cmd_state_t *cmd)
1530 {
1531         model_t         *m;
1532         texture_t       *t;
1533         int                     i;
1534         if (!r_refdef.scene.worldmodel)
1535         {
1536                 Con_Printf("There is no worldmodel\n");
1537                 return;
1538         }
1539         m = r_refdef.scene.worldmodel;
1540
1541         Con_Print("Worldmodel textures :\n");
1542         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1543                 if (t->name[0] && strcasecmp(t->name, "NO TEXTURE FOUND"))
1544                         Con_Printf("%s\n", t->name);
1545 }
1546
1547 #if 0
1548 static void gl_surf_start(void)
1549 {
1550 }
1551
1552 static void gl_surf_shutdown(void)
1553 {
1554 }
1555
1556 static void gl_surf_newmap(void)
1557 {
1558 }
1559 #endif
1560
1561 void GL_Surf_Init(void)
1562 {
1563
1564         Cvar_RegisterVariable(&r_ambient);
1565         Cvar_RegisterVariable(&r_lockpvs);
1566         Cvar_RegisterVariable(&r_lockvisibility);
1567         Cvar_RegisterVariable(&r_useportalculling);
1568         Cvar_RegisterVariable(&r_usesurfaceculling);
1569         Cvar_RegisterVariable(&r_vis_trace);
1570         Cvar_RegisterVariable(&r_vis_trace_samples);
1571         Cvar_RegisterVariable(&r_vis_trace_delay);
1572         Cvar_RegisterVariable(&r_vis_trace_eyejitter);
1573         Cvar_RegisterVariable(&r_vis_trace_enlarge);
1574         Cvar_RegisterVariable(&r_vis_trace_expand);
1575         Cvar_RegisterVariable(&r_vis_trace_pad);
1576         Cvar_RegisterVariable(&r_vis_trace_surfaces);
1577         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
1578
1579         Cmd_AddCommand(CF_CLIENT, "r_replacemaptexture", R_ReplaceWorldTexture_f, "override a map texture for testing purposes");
1580         Cmd_AddCommand(CF_CLIENT, "r_listmaptextures", R_ListWorldTextures_f, "list all textures used by the current map");
1581
1582         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
1583 }
1584