]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - gl_rsurf.c
migrated a large number of #define MAX values to quakedef.h and added a
[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
26 cvar_t r_ambient = {0, "r_ambient", "0", "brightens map, value is 0-128"};
27 cvar_t r_lockpvs = {0, "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)"};
28 cvar_t r_lockvisibility = {0, "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)"};
29 cvar_t r_useportalculling = {0, "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)"};
30 cvar_t r_q3bsp_renderskydepth = {0, "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"};
31
32 /*
33 ===============
34 R_BuildLightMap
35
36 Combine and scale multiple lightmaps into the 8.8 format in blocklights
37 ===============
38 */
39 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface)
40 {
41         int smax, tmax, i, size, size3, maps, l;
42         int *bl, scale;
43         unsigned char *lightmap, *out, *stain;
44         dp_model_t *model = ent->model;
45         int *intblocklights;
46         unsigned char *templight;
47
48         smax = (surface->lightmapinfo->extents[0]>>4)+1;
49         tmax = (surface->lightmapinfo->extents[1]>>4)+1;
50         size = smax*tmax;
51         size3 = size*3;
52
53         r_refdef.stats.lightmapupdatepixels += size;
54         r_refdef.stats.lightmapupdates++;
55
56         if (cl.buildlightmapmemorysize < size*sizeof(int[3]))
57         {
58                 cl.buildlightmapmemorysize = size*sizeof(int[3]);
59                 if (cl.buildlightmapmemory)
60                         Mem_Free(cl.buildlightmapmemory);
61                 cl.buildlightmapmemory = (unsigned char *) Mem_Alloc(cls.levelmempool, cl.buildlightmapmemorysize);
62         }
63
64         // these both point at the same buffer, templight is only used for final
65         // processing and can replace the intblocklights data as it goes
66         intblocklights = (int *)cl.buildlightmapmemory;
67         templight = (unsigned char *)cl.buildlightmapmemory;
68
69         // update cached lighting info
70         model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = false;
71
72         lightmap = surface->lightmapinfo->samples;
73
74 // set to full bright if no light data
75         bl = intblocklights;
76         if (!model->brushq1.lightdata)
77         {
78                 for (i = 0;i < size3;i++)
79                         bl[i] = 128*256;
80         }
81         else
82         {
83 // clear to no light
84                 memset(bl, 0, size3*sizeof(*bl));
85
86 // add all the lightmaps
87                 if (lightmap)
88                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
89                                 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
90                                         bl[i] += lightmap[i] * scale;
91         }
92
93         stain = surface->lightmapinfo->stainsamples;
94         bl = intblocklights;
95         out = templight;
96         // the >> 16 shift adjusts down 8 bits to account for the stainmap
97         // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
98         // be doubled during rendering to achieve 2x overbright
99         // (0 = 0.0, 128 = 1.0, 256 = 2.0)
100         if (stain)
101         {
102                 for (i = 0;i < size;i++, bl += 3, stain += 3, out += 4)
103                 {
104                         l = (bl[0] * stain[0]) >> 16;out[2] = min(l, 255);
105                         l = (bl[1] * stain[1]) >> 16;out[1] = min(l, 255);
106                         l = (bl[2] * stain[2]) >> 16;out[0] = min(l, 255);
107                         out[3] = 255;
108                 }
109         }
110         else
111         {
112                 for (i = 0;i < size;i++, bl += 3, out += 4)
113                 {
114                         l = bl[0] >> 8;out[2] = min(l, 255);
115                         l = bl[1] >> 8;out[1] = min(l, 255);
116                         l = bl[2] >> 8;out[0] = min(l, 255);
117                         out[3] = 255;
118                 }
119         }
120
121         R_UpdateTexture(surface->lightmaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], smax, tmax);
122
123         // update the surface's deluxemap if it has one
124         if (surface->deluxemaptexture != r_texture_blanknormalmap)
125         {
126                 vec3_t n;
127                 unsigned char *normalmap = surface->lightmapinfo->nmapsamples;
128                 lightmap = surface->lightmapinfo->samples;
129                 // clear to no normalmap
130                 bl = intblocklights;
131                 memset(bl, 0, size3*sizeof(*bl));
132                 // add all the normalmaps
133                 if (lightmap && normalmap)
134                 {
135                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3, normalmap += size3)
136                         {
137                                 for (scale = r_refdef.scene.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size;i++)
138                                 {
139                                         // add the normalmap with weighting proportional to the style's lightmap intensity
140                                         l = (int)(VectorLength(lightmap + i*3) * scale);
141                                         bl[i*3+0] += ((int)normalmap[i*3+0] - 128) * l;
142                                         bl[i*3+1] += ((int)normalmap[i*3+1] - 128) * l;
143                                         bl[i*3+2] += ((int)normalmap[i*3+2] - 128) * l;
144                                 }
145                         }
146                 }
147                 bl = intblocklights;
148                 out = templight;
149                 // we simply renormalize the weighted normals to get a valid deluxemap
150                 for (i = 0;i < size;i++, bl += 3, out += 4)
151                 {
152                         VectorCopy(bl, n);
153                         VectorNormalize(n);
154                         l = (int)(n[0] * 128 + 128);out[2] = bound(0, l, 255);
155                         l = (int)(n[1] * 128 + 128);out[1] = bound(0, l, 255);
156                         l = (int)(n[2] * 128 + 128);out[0] = bound(0, l, 255);
157                         out[3] = 255;
158                 }
159                 R_UpdateTexture(surface->deluxemaptexture, templight, surface->lightmapinfo->lightmaporigin[0], surface->lightmapinfo->lightmaporigin[1], smax, tmax);
160         }
161 }
162
163 void R_StainNode (mnode_t *node, dp_model_t *model, const vec3_t origin, float radius, const float fcolor[8])
164 {
165         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
166         msurface_t *surface, *endsurface;
167         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
168         unsigned char *bl;
169         vec3_t impact;
170
171         maxdist = radius * radius;
172         invradius = 1.0f / radius;
173
174 loc0:
175         if (!node->plane)
176                 return;
177         ndist = PlaneDiff(origin, node->plane);
178         if (ndist > radius)
179         {
180                 node = node->children[0];
181                 goto loc0;
182         }
183         if (ndist < -radius)
184         {
185                 node = node->children[1];
186                 goto loc0;
187         }
188
189         dist2 = ndist * ndist;
190         maxdist3 = maxdist - dist2;
191
192         if (node->plane->type < 3)
193         {
194                 VectorCopy(origin, impact);
195                 impact[node->plane->type] -= ndist;
196         }
197         else
198         {
199                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
200                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
201                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
202         }
203
204         for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
205         {
206                 if (surface->lightmapinfo->stainsamples)
207                 {
208                         smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
209                         tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
210
211                         impacts = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0]);
212                         impactt = (int)(DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1]);
213
214                         s = bound(0, impacts, smax * 16) - impacts;
215                         t = bound(0, impactt, tmax * 16) - impactt;
216                         i = (int)(s * s + t * t + dist2);
217                         if ((i > maxdist) || (smax > (int)(sizeof(sdtable)/sizeof(sdtable[0])))) // smax overflow fix from Andreas Dehmel
218                                 continue;
219
220                         // reduce calculations
221                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
222                                 sdtable[s] = i * i + dist2;
223
224                         bl = surface->lightmapinfo->stainsamples;
225                         smax3 = smax * 3;
226                         stained = false;
227
228                         i = impactt;
229                         for (t = 0;t < tmax;t++, i -= 16)
230                         {
231                                 td = i * i;
232                                 // make sure some part of it is visible on this line
233                                 if (td < maxdist3)
234                                 {
235                                         maxdist2 = maxdist - td;
236                                         for (s = 0;s < smax;s++)
237                                         {
238                                                 if (sdtable[s] < maxdist2)
239                                                 {
240                                                         ratio = lhrandom(0.0f, 1.0f);
241                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
242                                                         if (a >= (1.0f / 64.0f))
243                                                         {
244                                                                 if (a > 1)
245                                                                         a = 1;
246                                                                 bl[0] = (unsigned char) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
247                                                                 bl[1] = (unsigned char) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
248                                                                 bl[2] = (unsigned char) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
249                                                                 stained = true;
250                                                         }
251                                                 }
252                                                 bl += 3;
253                                         }
254                                 }
255                                 else // skip line
256                                         bl += smax3;
257                         }
258                         // force lightmap upload
259                         if (stained)
260                                 model->brushq1.lightmapupdateflags[surface - model->data_surfaces] = true;
261                 }
262         }
263
264         if (node->children[0]->plane)
265         {
266                 if (node->children[1]->plane)
267                 {
268                         R_StainNode(node->children[0], model, origin, radius, fcolor);
269                         node = node->children[1];
270                         goto loc0;
271                 }
272                 else
273                 {
274                         node = node->children[0];
275                         goto loc0;
276                 }
277         }
278         else if (node->children[1]->plane)
279         {
280                 node = node->children[1];
281                 goto loc0;
282         }
283 }
284
285 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)
286 {
287         int n;
288         float fcolor[8];
289         entity_render_t *ent;
290         dp_model_t *model;
291         vec3_t org;
292         if (r_refdef.scene.worldmodel == NULL || !r_refdef.scene.worldmodel->brush.data_nodes || !r_refdef.scene.worldmodel->brushq1.lightdata)
293                 return;
294         fcolor[0] = cr1;
295         fcolor[1] = cg1;
296         fcolor[2] = cb1;
297         fcolor[3] = ca1 * (1.0f / 64.0f);
298         fcolor[4] = cr2 - cr1;
299         fcolor[5] = cg2 - cg1;
300         fcolor[6] = cb2 - cb1;
301         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
302
303         R_StainNode(r_refdef.scene.worldmodel->brush.data_nodes + r_refdef.scene.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.scene.worldmodel, origin, radius, fcolor);
304
305         // look for embedded bmodels
306         for (n = 0;n < cl.num_brushmodel_entities;n++)
307         {
308                 ent = &cl.entities[cl.brushmodel_entities[n]].render;
309                 model = ent->model;
310                 if (model && model->name[0] == '*')
311                 {
312                         if (model->brush.data_nodes)
313                         {
314                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
315                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
316                         }
317                 }
318         }
319 }
320
321
322 /*
323 =============================================================
324
325         BRUSH MODELS
326
327 =============================================================
328 */
329
330 static void R_DrawPortal_Callback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
331 {
332         // due to the hacky nature of this function's parameters, this is never
333         // called with a batch, so numsurfaces is always 1, and the surfacelist
334         // contains only a leaf number for coloring purposes
335         const mportal_t *portal = (mportal_t *)ent;
336         qboolean isvis;
337         int i, numpoints;
338         float *v;
339         float vertex3f[POLYGONELEMENTS_MAXPOINTS*3];
340         CHECKGLERROR
341         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
342         GL_DepthMask(false);
343         GL_DepthRange(0, 1);
344         GL_PolygonOffset(r_refdef.polygonfactor, r_refdef.polygonoffset);
345         GL_DepthTest(true);
346         GL_CullFace(GL_NONE);
347         R_Mesh_Matrix(&identitymatrix);
348
349         numpoints = min(portal->numpoints, POLYGONELEMENTS_MAXPOINTS);
350
351         R_Mesh_VertexPointer(vertex3f, 0, 0);
352         R_Mesh_ColorPointer(NULL, 0, 0);
353         R_Mesh_ResetTextureState();
354         R_SetupGenericShader(false);
355
356         isvis = (portal->here->clusterindex >= 0 && portal->past->clusterindex >= 0 && portal->here->clusterindex != portal->past->clusterindex);
357
358         i = surfacelist[0] >> 1;
359         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f) * r_refdef.view.colorscale,
360                          ((i & 0x0038) >> 3) * (1.0f / 7.0f) * r_refdef.view.colorscale,
361                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f) * r_refdef.view.colorscale,
362                          isvis ? 0.125f : 0.03125f);
363         for (i = 0, v = vertex3f;i < numpoints;i++, v += 3)
364                 VectorCopy(portal->points[i].position, v);
365         R_Mesh_Draw(0, numpoints, 0, numpoints - 2, polygonelement3i, polygonelement3s, 0, 0);
366 }
367
368 // LordHavoc: this is just a nice debugging tool, very slow
369 void R_DrawPortals(void)
370 {
371         int i, leafnum;
372         mportal_t *portal;
373         float center[3], f;
374         dp_model_t *model = r_refdef.scene.worldmodel;
375         if (model == NULL)
376                 return;
377         for (leafnum = 0;leafnum < r_refdef.scene.worldmodel->brush.num_leafs;leafnum++)
378         {
379                 if (r_refdef.viewcache.world_leafvisible[leafnum])
380                 {
381                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
382                         for (portal = r_refdef.scene.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
383                         {
384                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
385                                 if (!R_CullBox(portal->mins, portal->maxs))
386                                 {
387                                         VectorClear(center);
388                                         for (i = 0;i < portal->numpoints;i++)
389                                                 VectorAdd(center, portal->points[i].position, center);
390                                         f = ixtable[portal->numpoints];
391                                         VectorScale(center, f, center);
392                                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, (entity_render_t *)portal, leafnum, rsurface.rtlight);
393                                 }
394                         }
395                 }
396         }
397 }
398
399 void R_View_WorldVisibility(qboolean forcenovis)
400 {
401         int i, j, *mark;
402         mleaf_t *leaf;
403         mleaf_t *viewleaf;
404         dp_model_t *model = r_refdef.scene.worldmodel;
405
406         if (!model)
407                 return;
408
409         if (r_refdef.view.usecustompvs)
410         {
411                 // clear the visible surface and leaf flags arrays
412                 memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
413                 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
414                 r_refdef.viewcache.world_novis = false;
415
416                 // simply cull each marked leaf to the frustum (view pyramid)
417                 for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
418                 {
419                         // if leaf is in current pvs and on the screen, mark its surfaces
420                         if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
421                         {
422                                 r_refdef.stats.world_leafs++;
423                                 r_refdef.viewcache.world_leafvisible[j] = true;
424                                 if (leaf->numleafsurfaces)
425                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
426                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
427                         }
428                 }
429                 return;
430         }
431
432         // if possible find the leaf the view origin is in
433         viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_refdef.view.origin) : NULL;
434         // if possible fetch the visible cluster bits
435         if (!r_lockpvs.integer && model->brush.FatPVS)
436                 model->brush.FatPVS(model, r_refdef.view.origin, 2, r_refdef.viewcache.world_pvsbits, sizeof(r_refdef.viewcache.world_pvsbits), false);
437
438         if (!r_lockvisibility.integer)
439         {
440                 // clear the visible surface and leaf flags arrays
441                 memset(r_refdef.viewcache.world_surfacevisible, 0, model->num_surfaces);
442                 memset(r_refdef.viewcache.world_leafvisible, 0, model->brush.num_leafs);
443
444                 r_refdef.viewcache.world_novis = false;
445
446                 // if floating around in the void (no pvs data available, and no
447                 // portals available), simply use all on-screen leafs.
448                 if (!viewleaf || viewleaf->clusterindex < 0 || forcenovis)
449                 {
450                         // no visibility method: (used when floating around in the void)
451                         // simply cull each leaf to the frustum (view pyramid)
452                         // similar to quake's RecursiveWorldNode but without cache misses
453                         r_refdef.viewcache.world_novis = true;
454                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
455                         {
456                                 // if leaf is in current pvs and on the screen, mark its surfaces
457                                 if (!R_CullBox(leaf->mins, leaf->maxs))
458                                 {
459                                         r_refdef.stats.world_leafs++;
460                                         r_refdef.viewcache.world_leafvisible[j] = true;
461                                         if (leaf->numleafsurfaces)
462                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
463                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
464                                 }
465                         }
466                 }
467                 // just check if each leaf in the PVS is on screen
468                 // (unless portal culling is enabled)
469                 else if (!model->brush.data_portals || r_useportalculling.integer < 1 || (r_useportalculling.integer < 2 && !r_novis.integer))
470                 {
471                         // pvs method:
472                         // simply check if each leaf is in the Potentially Visible Set,
473                         // and cull to frustum (view pyramid)
474                         // similar to quake's RecursiveWorldNode but without cache misses
475                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
476                         {
477                                 // if leaf is in current pvs and on the screen, mark its surfaces
478                                 if (CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
479                                 {
480                                         r_refdef.stats.world_leafs++;
481                                         r_refdef.viewcache.world_leafvisible[j] = true;
482                                         if (leaf->numleafsurfaces)
483                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
484                                                         r_refdef.viewcache.world_surfacevisible[*mark] = true;
485                                 }
486                         }
487                 }
488                 // if desired use a recursive portal flow, culling each portal to
489                 // frustum and checking if the leaf the portal leads to is in the pvs
490                 else
491                 {
492                         int leafstackpos;
493                         mportal_t *p;
494                         mleaf_t *leafstack[8192];
495                         // simple-frustum portal method:
496                         // follows portals leading outward from viewleaf, does not venture
497                         // offscreen or into leafs that are not visible, faster than
498                         // Quake's RecursiveWorldNode and vastly better in unvised maps,
499                         // often culls some surfaces that pvs alone would miss
500                         // (such as a room in pvs that is hidden behind a wall, but the
501                         //  passage leading to the room is off-screen)
502                         leafstack[0] = viewleaf;
503                         leafstackpos = 1;
504                         while (leafstackpos)
505                         {
506                                 leaf = leafstack[--leafstackpos];
507                                 if (r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs])
508                                         continue;
509                                 r_refdef.stats.world_leafs++;
510                                 r_refdef.viewcache.world_leafvisible[leaf - model->brush.data_leafs] = true;
511                                 // mark any surfaces bounding this leaf
512                                 if (leaf->numleafsurfaces)
513                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
514                                                 r_refdef.viewcache.world_surfacevisible[*mark] = true;
515                                 // follow portals into other leafs
516                                 // the checks are:
517                                 // if viewer is behind portal (portal faces outward into the scene)
518                                 // and the portal polygon's bounding box is on the screen
519                                 // and the leaf has not been visited yet
520                                 // and the leaf is visible in the pvs
521                                 // (the first two checks won't cause as many cache misses as the leaf checks)
522                                 for (p = leaf->portals;p;p = p->next)
523                                 {
524                                         r_refdef.stats.world_portals++;
525                                         if (DotProduct(r_refdef.view.origin, p->plane.normal) < (p->plane.dist + 1)
526                                          && !r_refdef.viewcache.world_leafvisible[p->past - model->brush.data_leafs]
527                                          && CHECKPVSBIT(r_refdef.viewcache.world_pvsbits, p->past->clusterindex)
528                                          && !R_CullBox(p->mins, p->maxs)
529                                          && leafstackpos < (int)(sizeof(leafstack) / sizeof(leafstack[0])))
530                                                 leafstack[leafstackpos++] = p->past;
531                                 }
532                         }
533                 }
534         }
535 }
536
537 void R_Q1BSP_DrawSky(entity_render_t *ent)
538 {
539         if (ent->model == NULL)
540                 return;
541         if (ent == r_refdef.scene.worldentity)
542                 R_DrawWorldSurfaces(true, true, false, false);
543         else
544                 R_DrawModelSurfaces(ent, true, true, false, false);
545 }
546
547 extern void R_Water_AddWaterPlane(msurface_t *surface);
548 void R_Q1BSP_DrawAddWaterPlanes(entity_render_t *ent)
549 {
550         int i, j, flagsmask;
551         dp_model_t *model = ent->model;
552         msurface_t *surfaces;
553         if (model == NULL)
554                 return;
555
556         if (ent == r_refdef.scene.worldentity)
557                 RSurf_ActiveWorldEntity();
558         else
559                 RSurf_ActiveModelEntity(ent, false, false);
560
561         surfaces = model->data_surfaces;
562         flagsmask = MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION;
563
564         // add visible surfaces to draw list
565         if (ent == r_refdef.scene.worldentity)
566         {
567                 for (i = 0;i < model->nummodelsurfaces;i++)
568                 {
569                         j = model->sortedmodelsurfaces[i];
570                         if (r_refdef.viewcache.world_surfacevisible[j])
571                                 if (surfaces[j].texture->basematerialflags & flagsmask)
572                                         R_Water_AddWaterPlane(surfaces + j);
573                 }
574         }
575         else
576         {
577                 for (i = 0;i < model->nummodelsurfaces;i++)
578                 {
579                         j = model->sortedmodelsurfaces[i];
580                         if (surfaces[j].texture->basematerialflags & flagsmask)
581                                 R_Water_AddWaterPlane(surfaces + j);
582                 }
583         }
584         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
585 }
586
587 void R_Q1BSP_Draw(entity_render_t *ent)
588 {
589         dp_model_t *model = ent->model;
590         if (model == NULL)
591                 return;
592         if (ent == r_refdef.scene.worldentity)
593                 R_DrawWorldSurfaces(false, true, false, false);
594         else
595                 R_DrawModelSurfaces(ent, false, true, false, false);
596 }
597
598 void R_Q1BSP_DrawDepth(entity_render_t *ent)
599 {
600         dp_model_t *model = ent->model;
601         if (model == NULL)
602                 return;
603         GL_ColorMask(0,0,0,0);
604         GL_Color(1,1,1,1);
605         GL_DepthTest(true);
606         GL_BlendFunc(GL_ONE, GL_ZERO);
607         GL_DepthMask(true);
608         GL_AlphaTest(false);
609         R_Mesh_ColorPointer(NULL, 0, 0);
610         R_Mesh_ResetTextureState();
611         R_SetupDepthOrShadowShader();
612         if (ent == r_refdef.scene.worldentity)
613                 R_DrawWorldSurfaces(false, false, true, false);
614         else
615                 R_DrawModelSurfaces(ent, false, false, true, false);
616         GL_ColorMask(r_refdef.view.colormask[0], r_refdef.view.colormask[1], r_refdef.view.colormask[2], 1);
617 }
618
619 void R_Q1BSP_DrawDebug(entity_render_t *ent)
620 {
621         if (ent->model == NULL)
622                 return;
623         if (ent == r_refdef.scene.worldentity)
624                 R_DrawWorldSurfaces(false, false, false, true);
625         else
626                 R_DrawModelSurfaces(ent, false, false, false, true);
627 }
628
629 typedef struct r_q1bsp_getlightinfo_s
630 {
631         dp_model_t *model;
632         vec3_t relativelightorigin;
633         float lightradius;
634         int *outleaflist;
635         unsigned char *outleafpvs;
636         int outnumleafs;
637         unsigned char *visitingleafpvs;
638         int *outsurfacelist;
639         unsigned char *outsurfacepvs;
640         unsigned char *tempsurfacepvs;
641         unsigned char *outshadowtrispvs;
642         unsigned char *outlighttrispvs;
643         int outnumsurfaces;
644         vec3_t outmins;
645         vec3_t outmaxs;
646         vec3_t lightmins;
647         vec3_t lightmaxs;
648         const unsigned char *pvs;
649         qboolean svbsp_active;
650         qboolean svbsp_insertoccluder;
651 }
652 r_q1bsp_getlightinfo_t;
653
654 static void R_Q1BSP_RecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, mnode_t *node)
655 {
656         int sides;
657         mleaf_t *leaf;
658         for (;;)
659         {
660                 mplane_t *plane = node->plane;
661                 //if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
662                 //      return;
663                 if (!plane)
664                         break;
665                 //if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rsurface.rtlight_numfrustumplanes, rsurface.rtlight_frustumplanes))
666                 //      return;
667                 if (plane->type < 3)
668                 {
669                         if (info->lightmins[plane->type] > plane->dist)
670                                 node = node->children[0];
671                         else if (info->lightmaxs[plane->type] < plane->dist)
672                                 node = node->children[1];
673                         else if (info->relativelightorigin[plane->type] >= plane->dist)
674                         {
675                                 R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
676                                 node = node->children[1];
677                         }
678                         else
679                         {
680                                 R_Q1BSP_RecursiveGetLightInfo(info, node->children[1]);
681                                 node = node->children[0];
682                         }
683                 }
684                 else
685                 {
686                         sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
687                         if (sides == 3)
688                         {
689                                 // recurse front side first because the svbsp building prefers it
690                                 if (PlaneDist(info->relativelightorigin, plane) >= 0)
691                                 {
692                                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
693                                         node = node->children[1];
694                                 }
695                                 else
696                                 {
697                                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[1]);
698                                         node = node->children[0];
699                                 }
700                         }
701                         else if (sides == 0)
702                                 return; // ERROR: NAN bounding box!
703                         else
704                                 node = node->children[sides - 1];
705                 }
706         }
707         if (!r_shadow_compilingrtlight && R_CullBoxCustomPlanes(node->mins, node->maxs, rsurface.rtlight_numfrustumplanes, rsurface.rtlight_frustumplanes))
708                 return;
709         leaf = (mleaf_t *)node;
710         if (info->svbsp_active)
711         {
712                 int i;
713                 mportal_t *portal;
714                 double points[128][3];
715                 for (portal = leaf->portals;portal;portal = portal->next)
716                 {
717                         for (i = 0;i < portal->numpoints;i++)
718                                 VectorCopy(portal->points[i].position, points[i]);
719                         if (SVBSP_AddPolygon(&r_svbsp, portal->numpoints, points[0], false, NULL, NULL, 0) & 2)
720                                 break;
721                 }
722                 if (portal == NULL)
723                         return; // no portals of this leaf visible
724         }
725         else
726         {
727                 if (r_shadow_frontsidecasting.integer && info->pvs != NULL && !CHECKPVSBIT(info->pvs, leaf->clusterindex))
728                         return;
729         }
730         // inserting occluders does not alter the leaf info
731         if (!info->svbsp_insertoccluder)
732         {
733                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
734                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
735                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
736                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
737                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
738                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
739                 if (info->outleafpvs)
740                 {
741                         int leafindex = leaf - info->model->brush.data_leafs;
742                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
743                         {
744                                 SETPVSBIT(info->outleafpvs, leafindex);
745                                 info->outleaflist[info->outnumleafs++] = leafindex;
746                         }
747                 }
748         }
749         if (info->outsurfacepvs)
750         {
751                 int leafsurfaceindex;
752                 int surfaceindex;
753                 int triangleindex, t;
754                 int currentmaterialflags;
755                 msurface_t *surface;
756                 const int *e;
757                 const vec_t *v[3];
758                 double v2[3][3];
759                 for (leafsurfaceindex = 0;leafsurfaceindex < leaf->numleafsurfaces;leafsurfaceindex++)
760                 {
761                         surfaceindex = leaf->firstleafsurface[leafsurfaceindex];
762                         if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
763                         {
764                                 surface = info->model->data_surfaces + surfaceindex;
765                                 currentmaterialflags = R_GetCurrentTexture(surface->texture)->currentmaterialflags;
766                                 if (BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs)
767                                  && (!info->svbsp_insertoccluder || !(currentmaterialflags & MATERIALFLAG_NOSHADOW)))
768                                 {
769                                         qboolean addedtris = false;
770                                         qboolean insidebox = BoxInsideBox(surface->mins, surface->maxs, info->lightmins, info->lightmaxs);
771                                         for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = info->model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
772                                         {
773                                                 v[0] = info->model->brush.shadowmesh->vertex3f + e[0] * 3;
774                                                 v[1] = info->model->brush.shadowmesh->vertex3f + e[1] * 3;
775                                                 v[2] = info->model->brush.shadowmesh->vertex3f + e[2] * 3;
776                                                 if (insidebox || TriangleOverlapsBox(v[0], v[1], v[2], info->lightmins, info->lightmaxs))
777                                                 {
778                                                         if (info->svbsp_insertoccluder)
779                                                         {
780                                                                 if (!(currentmaterialflags & MATERIALFLAG_NOCULLFACE) && r_shadow_frontsidecasting.integer != PointInfrontOfTriangle(info->relativelightorigin, v[0], v[1], v[2]))
781                                                                         continue;
782                                                                 if (currentmaterialflags & MATERIALFLAG_NOSHADOW)
783                                                                         continue;
784                                                                 VectorCopy(v[0], v2[0]);
785                                                                 VectorCopy(v[1], v2[1]);
786                                                                 VectorCopy(v[2], v2[2]);
787                                                                 if (!(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], true, NULL, NULL, 0) & 2))
788                                                                         continue;
789                                                                 addedtris = true;
790                                                         }
791                                                         else
792                                                         {
793                                                                 if (info->svbsp_active)
794                                                                 {
795                                                                         VectorCopy(v[0], v2[0]);
796                                                                         VectorCopy(v[1], v2[1]);
797                                                                         VectorCopy(v[2], v2[2]);
798                                                                         if (!(SVBSP_AddPolygon(&r_svbsp, 3, v2[0], false, NULL, NULL, 0) & 2))
799                                                                                 continue;
800                                                                 }
801                                                                 if (currentmaterialflags & MATERIALFLAG_NOCULLFACE)
802                                                                 {
803                                                                         // if the material is double sided we
804                                                                         // can't cull by direction
805                                                                         SETPVSBIT(info->outlighttrispvs, t);
806                                                                         addedtris = true;
807                                                                         if (!(currentmaterialflags & MATERIALFLAG_NOSHADOW))
808                                                                                 SETPVSBIT(info->outshadowtrispvs, t);
809                                                                 }
810                                                                 else if (r_shadow_frontsidecasting.integer)
811                                                                 {
812                                                                         // front side casting occludes backfaces,
813                                                                         // so they are completely useless as both
814                                                                         // casters and lit polygons
815                                                                         if (!PointInfrontOfTriangle(info->relativelightorigin, v[0], v[1], v[2]))
816                                                                                 continue;
817                                                                         SETPVSBIT(info->outlighttrispvs, t);
818                                                                         addedtris = true;
819                                                                         if (!(currentmaterialflags & MATERIALFLAG_NOSHADOW))
820                                                                                 SETPVSBIT(info->outshadowtrispvs, t);
821                                                                 }
822                                                                 else
823                                                                 {
824                                                                         // back side casting does not occlude
825                                                                         // anything so we can't cull lit polygons
826                                                                         SETPVSBIT(info->outlighttrispvs, t);
827                                                                         addedtris = true;
828                                                                         if (!PointInfrontOfTriangle(info->relativelightorigin, v[0], v[1], v[2]) && !(currentmaterialflags & MATERIALFLAG_NOSHADOW))
829                                                                                 SETPVSBIT(info->outshadowtrispvs, t);
830                                                                 }
831                                                         }
832                                                 }
833                                         }
834                                         if (addedtris)
835                                         {
836                                                 SETPVSBIT(info->outsurfacepvs, surfaceindex);
837                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
838                                         }
839                                 }
840                         }
841                 }
842         }
843 }
844
845 static void R_Q1BSP_CallRecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, qboolean use_svbsp)
846 {
847         if (use_svbsp)
848         {
849                 double origin[3];
850                 VectorCopy(info->relativelightorigin, origin);
851                 if (!r_svbsp.nodes)
852                 {
853                         r_svbsp.maxnodes = max(r_svbsp.maxnodes, 1<<18);
854                         r_svbsp.nodes = (svbsp_node_t*) Mem_Alloc(r_main_mempool, r_svbsp.maxnodes * sizeof(svbsp_node_t));
855                 }
856                 info->svbsp_active = true;
857                 info->svbsp_insertoccluder = true;
858                 for (;;)
859                 {
860                         SVBSP_Init(&r_svbsp, origin, r_svbsp.maxnodes, r_svbsp.nodes);
861                         R_Q1BSP_RecursiveGetLightInfo(info, info->model->brush.data_nodes);
862                         // if that failed, retry with more nodes
863                         if (r_svbsp.ranoutofnodes)
864                         {
865                                 // an upper limit is imposed
866                                 if (r_svbsp.maxnodes >= 2<<22)
867                                         break;
868                                 Mem_Free(r_svbsp.nodes);
869                                 r_svbsp.maxnodes *= 2;
870                                 r_svbsp.nodes = (svbsp_node_t*) Mem_Alloc(tempmempool, r_svbsp.maxnodes * sizeof(svbsp_node_t));
871                         }
872                         else
873                                 break;
874                 }
875                 // now clear the surfacepvs array because we need to redo it
876                 memset(info->outsurfacepvs, 0, (info->model->nummodelsurfaces + 7) >> 3);
877                 info->outnumsurfaces = 0;
878         }
879         else
880                 info->svbsp_active = false;
881
882         // we HAVE to mark the leaf the light is in as lit, because portals are
883         // irrelevant to a leaf that the light source is inside of
884         // (and they are all facing away, too)
885         {
886                 mnode_t *node = info->model->brush.data_nodes;
887                 mleaf_t *leaf;
888                 while (node->plane)
889                         node = node->children[(node->plane->type < 3 ? info->relativelightorigin[node->plane->type] : DotProduct(info->relativelightorigin,node->plane->normal)) < node->plane->dist];
890                 leaf = (mleaf_t *)node;
891                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
892                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
893                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
894                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
895                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
896                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
897                 if (info->outleafpvs)
898                 {
899                         int leafindex = leaf - info->model->brush.data_leafs;
900                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
901                         {
902                                 SETPVSBIT(info->outleafpvs, leafindex);
903                                 info->outleaflist[info->outnumleafs++] = leafindex;
904                         }
905                 }
906         }
907
908         info->svbsp_insertoccluder = false;
909         R_Q1BSP_RecursiveGetLightInfo(info, info->model->brush.data_nodes);
910         if (developer.integer >= 100 && use_svbsp)
911         {
912                 Con_Printf("GetLightInfo: svbsp built with %i nodes, polygon stats:\n", r_svbsp.numnodes);
913                 Con_Printf("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);
914                 Con_Printf("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);
915         }
916 }
917
918 void R_Q1BSP_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)
919 {
920         r_q1bsp_getlightinfo_t info;
921         VectorCopy(relativelightorigin, info.relativelightorigin);
922         info.lightradius = lightradius;
923         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
924         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
925         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
926         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
927         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
928         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
929         if (ent->model == NULL)
930         {
931                 VectorCopy(info.lightmins, outmins);
932                 VectorCopy(info.lightmaxs, outmaxs);
933                 *outnumleafspointer = 0;
934                 *outnumsurfacespointer = 0;
935                 return;
936         }
937         info.model = ent->model;
938         info.outleaflist = outleaflist;
939         info.outleafpvs = outleafpvs;
940         info.outnumleafs = 0;
941         info.visitingleafpvs = visitingleafpvs;
942         info.outsurfacelist = outsurfacelist;
943         info.outsurfacepvs = outsurfacepvs;
944         info.outshadowtrispvs = outshadowtrispvs;
945         info.outlighttrispvs = outlighttrispvs;
946         info.outnumsurfaces = 0;
947         VectorCopy(info.relativelightorigin, info.outmins);
948         VectorCopy(info.relativelightorigin, info.outmaxs);
949         memset(visitingleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
950         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
951         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
952         if (info.model->brush.shadowmesh)
953                 memset(outshadowtrispvs, 0, (info.model->brush.shadowmesh->numtriangles + 7) >> 3);
954         else
955                 memset(outshadowtrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
956         memset(outlighttrispvs, 0, (info.model->surfmesh.num_triangles + 7) >> 3);
957         if (info.model->brush.GetPVS && r_shadow_frontsidecasting.integer)
958                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
959         else
960                 info.pvs = NULL;
961         RSurf_ActiveWorldEntity();
962
963         if (r_shadow_frontsidecasting.integer && r_shadow_compilingrtlight && r_shadow_realtime_world_compileportalculling.integer && info.model->brush.data_portals)
964         {
965                 // use portal recursion for exact light volume culling, and exact surface checking
966                 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);
967         }
968         else if (r_shadow_frontsidecasting.integer && r_shadow_realtime_dlight_portalculling.integer && info.model->brush.data_portals)
969         {
970                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
971                 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);
972         }
973         else
974         {
975                 // recurse the bsp tree, checking leafs and surfaces for visibility
976                 // optionally using svbsp for exact culling of compiled lights
977                 // (or if the user enables dlight svbsp culling, which is mostly for
978                 //  debugging not actual use)
979                 R_Q1BSP_CallRecursiveGetLightInfo(&info, (r_shadow_compilingrtlight ? r_shadow_realtime_world_compilesvbsp.integer : r_shadow_realtime_dlight_svbspculling.integer) != 0);
980         }
981
982         rsurface.entity = NULL; // used only by R_GetCurrentTexture and RSurf_ActiveWorldEntity/RSurf_ActiveModelEntity
983
984         // limit combined leaf box to light boundaries
985         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
986         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
987         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
988         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
989         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
990         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
991
992         *outnumleafspointer = info.outnumleafs;
993         *outnumsurfacespointer = info.outnumsurfaces;
994 }
995
996 void R_Q1BSP_CompileShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
997 {
998         dp_model_t *model = ent->model;
999         msurface_t *surface;
1000         int surfacelistindex;
1001         float projectdistance = relativelightdirection ? lightradius : lightradius + model->radius*2 + r_shadow_projectdistance.value;
1002         r_shadow_compilingrtlight->static_meshchain_shadow_zfail = Mod_ShadowMesh_Begin(r_main_mempool, 32768, 32768, NULL, NULL, NULL, false, false, true);
1003         R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
1004         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1005         {
1006                 surface = model->data_surfaces + surfacelist[surfacelistindex];
1007                 if (surface->texture->basematerialflags & MATERIALFLAG_NOSHADOW)
1008                         continue;
1009                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, relativelightdirection, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs);
1010         }
1011         R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist, ent->mins, ent->maxs);
1012         r_shadow_compilingrtlight->static_meshchain_shadow_zfail = Mod_ShadowMesh_Finish(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_zfail, false, false, true);
1013 }
1014
1015 extern cvar_t r_polygonoffset_submodel_factor;
1016 extern cvar_t r_polygonoffset_submodel_offset;
1017 void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, const vec3_t relativelightorigin, const vec3_t relativelightdirection, float lightradius, int modelnumsurfaces, const int *modelsurfacelist, const vec3_t lightmins, const vec3_t lightmaxs)
1018 {
1019         dp_model_t *model = ent->model;
1020         const msurface_t *surface;
1021         int modelsurfacelistindex;
1022         float projectdistance = relativelightdirection ? lightradius : lightradius + model->radius*2 + r_shadow_projectdistance.value;
1023         // check the box in modelspace, it was already checked in worldspace
1024         if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
1025                 return;
1026         if (ent->model->brush.submodel)
1027                 GL_PolygonOffset(r_refdef.shadowpolygonfactor + r_polygonoffset_submodel_factor.value, r_refdef.shadowpolygonoffset + r_polygonoffset_submodel_offset.value);
1028         if (model->brush.shadowmesh)
1029         {
1030                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
1031                 for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1032                 {
1033                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1034                         if (R_GetCurrentTexture(surface->texture)->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1035                                 continue;
1036                         R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, relativelightdirection, lightmins, lightmaxs, surface->mins, surface->maxs);
1037                 }
1038                 R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist, ent->mins, ent->maxs);
1039         }
1040         else
1041         {
1042                 projectdistance = lightradius + model->radius*2;
1043                 R_Shadow_PrepareShadowMark(model->surfmesh.num_triangles);
1044                 // identify lit faces within the bounding box
1045                 for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1046                 {
1047                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1048                         rsurface.texture = R_GetCurrentTexture(surface->texture);
1049                         if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1050                                 continue;
1051                         RSurf_PrepareVerticesForBatch(false, false, 1, &surface);
1052                         R_Shadow_MarkVolumeFromBox(surface->num_firsttriangle, surface->num_triangles, rsurface.vertex3f, rsurface.modelelement3i, relativelightorigin, relativelightdirection, lightmins, lightmaxs, surface->mins, surface->maxs);
1053                 }
1054                 R_Shadow_VolumeFromList(model->surfmesh.num_vertices, model->surfmesh.num_triangles, rsurface.vertex3f, model->surfmesh.data_element3i, model->surfmesh.data_neighbor3i, relativelightorigin, relativelightdirection, projectdistance, numshadowmark, shadowmarklist, ent->mins, ent->maxs);
1055         }
1056         if (ent->model->brush.submodel)
1057                 GL_PolygonOffset(r_refdef.shadowpolygonfactor, r_refdef.shadowpolygonoffset);
1058 }
1059
1060 void R_Q1BSP_CompileShadowMap(entity_render_t *ent, vec3_t relativelightorigin, vec3_t relativelightdirection, float lightradius, int numsurfaces, const int *surfacelist)
1061 {
1062         dp_model_t *model = ent->model;
1063         msurface_t *surface;
1064         int surfacelistindex;
1065         int sidetotals[6] = { 0, 0, 0, 0, 0, 0 }, sidemasks = 0;
1066         int i;
1067         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Begin(r_main_mempool, 32768, 32768, NULL, NULL, NULL, false, false, true);
1068         R_Shadow_PrepareShadowSides(model->brush.shadowmesh->numtriangles);
1069         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
1070         {
1071                 surface = model->data_surfaces + surfacelist[surfacelistindex];
1072                 sidemasks |= R_Shadow_ChooseSidesFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->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);
1073         }
1074         R_Shadow_ShadowMapFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, numshadowsides, sidetotals, shadowsides, shadowsideslist);
1075         r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap = Mod_ShadowMesh_Finish(r_main_mempool, r_shadow_compilingrtlight->static_meshchain_shadow_shadowmap, false, false, true);
1076         r_shadow_compilingrtlight->static_shadowmap_receivers &= sidemasks;
1077         for(i = 0;i<6;i++)
1078                 if(!sidetotals[i])
1079                         r_shadow_compilingrtlight->static_shadowmap_casters &= ~(1 << i);
1080 }
1081
1082 void R_Q1BSP_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)
1083 {
1084         dp_model_t *model = ent->model;
1085         const msurface_t *surface, *batch[1024];
1086         int modelsurfacelistindex, batchsize;
1087         // check the box in modelspace, it was already checked in worldspace
1088         if (!BoxesOverlap(model->normalmins, model->normalmaxs, lightmins, lightmaxs))
1089                 return;
1090         // identify lit faces within the bounding box
1091         for (modelsurfacelistindex = 0;modelsurfacelistindex < modelnumsurfaces;modelsurfacelistindex++)
1092         {
1093                 surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1094                 if (surfacesides && !(surfacesides[modelsurfacelistindex] && (1 << side)))
1095                         continue;
1096                 rsurface.texture = R_GetCurrentTexture(surface->texture);
1097                 if (rsurface.texture->currentmaterialflags & MATERIALFLAG_NOSHADOW)
1098                         continue;
1099                 if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1100                         continue;
1101                 r_refdef.stats.lights_dynamicshadowtriangles += surface->num_triangles;
1102                 r_refdef.stats.lights_shadowtriangles += surface->num_triangles;
1103                 batch[0] = surface;
1104                 batchsize = 1;
1105                 while(++modelsurfacelistindex < modelnumsurfaces && batchsize < (int)(sizeof(batch)/sizeof(batch[0])))
1106                 {
1107                         surface = model->data_surfaces + modelsurfacelist[modelsurfacelistindex];
1108                         if (surfacesides && !(surfacesides[modelsurfacelistindex] & (1 << side)))
1109                                 continue;
1110                         if (surface->texture != batch[0]->texture)
1111                                 break;
1112                         if (!BoxesOverlap(lightmins, lightmaxs, surface->mins, surface->maxs))
1113                                 continue;
1114                         r_refdef.stats.lights_dynamicshadowtriangles += surface->num_triangles;
1115                         r_refdef.stats.lights_shadowtriangles += surface->num_triangles;
1116                         batch[batchsize++] = surface;
1117                 }
1118                 --modelsurfacelistindex;
1119                 GL_CullFace(rsurface.texture->currentmaterialflags & MATERIALFLAG_NOCULLFACE ? GL_NONE : r_refdef.view.cullface_back);
1120                 RSurf_PrepareVerticesForBatch(false, false, batchsize, batch);
1121                 RSurf_DrawBatch_Simple(batchsize, batch);
1122                 GL_LockArrays(0, 0);
1123         }
1124 }
1125
1126 #define BATCHSIZE 1024
1127
1128 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
1129 {
1130         int i, j, endsurface;
1131         texture_t *t;
1132         const msurface_t *surface;
1133         // note: in practice this never actually receives batches), oh well
1134         R_Shadow_RenderMode_Begin();
1135         R_Shadow_RenderMode_ActiveLight(rtlight);
1136         R_Shadow_RenderMode_Lighting(false, true, false);
1137         R_Shadow_SetupEntityLight(ent);
1138         for (i = 0;i < numsurfaces;i = j)
1139         {
1140                 j = i + 1;
1141                 surface = rsurface.modelsurfaces + surfacelist[i];
1142                 t = surface->texture;
1143                 rsurface.texture = R_GetCurrentTexture(t);
1144                 endsurface = min(j + BATCHSIZE, numsurfaces);
1145                 for (j = i;j < endsurface;j++)
1146                 {
1147                         surface = rsurface.modelsurfaces + surfacelist[j];
1148                         if (t != surface->texture)
1149                                 break;
1150                         RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
1151                         R_Shadow_RenderLighting(surface->num_firstvertex, surface->num_vertices, surface->num_firsttriangle, surface->num_triangles, ent->model->surfmesh.data_element3i, ent->model->surfmesh.data_element3s, ent->model->surfmesh.ebo3i, ent->model->surfmesh.ebo3s);
1152                 }
1153         }
1154         R_Shadow_RenderMode_End();
1155 }
1156
1157 #define RSURF_MAX_BATCHSURFACES 8192
1158
1159 void R_Q1BSP_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist, const unsigned char *trispvs)
1160 {
1161         dp_model_t *model = ent->model;
1162         const msurface_t *surface;
1163         int i, k, kend, l, m, mend, endsurface, batchnumsurfaces, batchnumtriangles, batchfirstvertex, batchlastvertex, batchfirsttriangle;
1164         qboolean usebufferobject, culltriangles;
1165         const int *element3i;
1166         msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
1167         int batchelements[BATCHSIZE*3];
1168         texture_t *tex;
1169         CHECKGLERROR
1170         culltriangles = r_shadow_culltriangles.integer && !(ent->flags & RENDER_NOSELFSHADOW);
1171         element3i = rsurface.modelelement3i;
1172         // this is a double loop because non-visible surface skipping has to be
1173         // fast, and even if this is not the world model (and hence no visibility
1174         // checking) the input surface list and batch buffer are different formats
1175         // so some processing is necessary.  (luckily models have few surfaces)
1176         for (i = 0;i < numsurfaces;)
1177         {
1178                 batchnumsurfaces = 0;
1179                 endsurface = min(i + RSURF_MAX_BATCHSURFACES, numsurfaces);
1180                 if (ent == r_refdef.scene.worldentity)
1181                 {
1182                         for (;i < endsurface;i++)
1183                                 if (r_refdef.viewcache.world_surfacevisible[surfacelist[i]])
1184                                         batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1185                 }
1186                 else
1187                 {
1188                         for (;i < endsurface;i++)
1189                                 batchsurfacelist[batchnumsurfaces++] = model->data_surfaces + surfacelist[i];
1190                 }
1191                 if (!batchnumsurfaces)
1192                         continue;
1193                 for (k = 0;k < batchnumsurfaces;k = kend)
1194                 {
1195                         surface = batchsurfacelist[k];
1196                         tex = surface->texture;
1197                         rsurface.texture = R_GetCurrentTexture(tex);
1198                         // gather surfaces into a batch range
1199                         for (kend = k;kend < batchnumsurfaces && tex == batchsurfacelist[kend]->texture;kend++)
1200                                 ;
1201                         // now figure out what to do with this particular range of surfaces
1202                         if (!(rsurface.texture->currentmaterialflags & MATERIALFLAG_WALL))
1203                                 continue;
1204                         if (r_waterstate.renderingscene && (rsurface.texture->currentmaterialflags & (MATERIALFLAG_WATERSHADER | MATERIALFLAG_REFRACTION | MATERIALFLAG_REFLECTION)))
1205                                 continue;
1206                         if (rsurface.texture->currentmaterialflags & MATERIALFLAGMASK_DEPTHSORTED)
1207                         {
1208                                 vec3_t tempcenter, center;
1209                                 for (l = k;l < kend;l++)
1210                                 {
1211                                         surface = batchsurfacelist[l];
1212                                         tempcenter[0] = (surface->mins[0] + surface->maxs[0]) * 0.5f;
1213                                         tempcenter[1] = (surface->mins[1] + surface->maxs[1]) * 0.5f;
1214                                         tempcenter[2] = (surface->mins[2] + surface->maxs[2]) * 0.5f;
1215                                         Matrix4x4_Transform(&rsurface.matrix, tempcenter, center);
1216                                         R_MeshQueue_AddTransparent(rsurface.texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_refdef.view.origin : center, R_Q1BSP_DrawLight_TransparentCallback, ent, surface - rsurface.modelsurfaces, rsurface.rtlight);
1217                                 }
1218                                 continue;
1219                         }
1220                         batchnumtriangles = 0;
1221                         batchfirsttriangle = surface->num_firsttriangle;
1222                         m = 0; // hush warning
1223                         for (l = k;l < kend;l++)
1224                         {
1225                                 surface = batchsurfacelist[l];
1226                                 RSurf_PrepareVerticesForBatch(true, true, 1, &surface);
1227                                 for (m = surface->num_firsttriangle, mend = m + surface->num_triangles;m < mend;m++)
1228                                 {
1229                                         if (trispvs)
1230                                         {
1231                                                 if (!CHECKPVSBIT(trispvs, m))
1232                                                 {
1233                                                         usebufferobject = false;
1234                                                         continue;
1235                                                 }
1236                                         }
1237                                         else if (culltriangles)
1238                                         {
1239                                                 if (r_shadow_frontsidecasting.integer && !PointInfrontOfTriangle(rsurface.entitylightorigin, rsurface.vertex3f + element3i[m*3+0]*3, rsurface.vertex3f + element3i[m*3+1]*3, rsurface.vertex3f + element3i[m*3+2]*3))
1240                                                 {
1241                                                         usebufferobject = false;
1242                                                         continue;
1243                                                 }
1244                                         }
1245                                         if (batchnumtriangles >= BATCHSIZE)
1246                                         {
1247                                                 r_refdef.stats.lights_lighttriangles += batchnumtriangles;
1248                                                 Mod_VertexRangeFromElements(batchnumtriangles*3, batchelements, &batchfirstvertex, &batchlastvertex);
1249                                                 // use the element buffer if all triangles are consecutive
1250                                                 if (m == batchfirsttriangle + batchnumtriangles)
1251                                                         R_Shadow_RenderLighting(batchfirstvertex, batchlastvertex + 1 - batchfirstvertex, batchfirsttriangle, batchnumtriangles, ent->model->surfmesh.data_element3i, ent->model->surfmesh.data_element3s, ent->model->surfmesh.ebo3i, ent->model->surfmesh.ebo3s);
1252                                                 else
1253                                                         R_Shadow_RenderLighting(batchfirstvertex, batchlastvertex + 1 - batchfirstvertex, 0, batchnumtriangles, batchelements, NULL, 0, 0);
1254                                                 usebufferobject = true;
1255                                                 batchnumtriangles = 0;
1256                                                 batchfirsttriangle = m;
1257                                         }
1258                                         batchelements[batchnumtriangles*3+0] = element3i[m*3+0];
1259                                         batchelements[batchnumtriangles*3+1] = element3i[m*3+1];
1260                                         batchelements[batchnumtriangles*3+2] = element3i[m*3+2];
1261                                         batchnumtriangles++;
1262                                 }
1263                         }
1264                         if (batchnumtriangles > 0)
1265                         {
1266                                 r_refdef.stats.lights_lighttriangles += batchnumtriangles;
1267                                 Mod_VertexRangeFromElements(batchnumtriangles*3, batchelements, &batchfirstvertex, &batchlastvertex);
1268                                 // use the element buffer if all triangles are consecutive
1269                                 if (m == batchfirsttriangle + batchnumtriangles)
1270                                         R_Shadow_RenderLighting(batchfirstvertex, batchlastvertex + 1 - batchfirstvertex, batchfirsttriangle, batchnumtriangles, ent->model->surfmesh.data_element3i, ent->model->surfmesh.data_element3s, ent->model->surfmesh.ebo3i, ent->model->surfmesh.ebo3s);
1271                                 else
1272                                         R_Shadow_RenderLighting(batchfirstvertex, batchlastvertex + 1 - batchfirstvertex, 0, batchnumtriangles, batchelements, NULL, 0, 0);
1273                         }
1274                 }
1275         }
1276 }
1277
1278 //Made by [515]
1279 void R_ReplaceWorldTexture (void)
1280 {
1281         dp_model_t              *m;
1282         texture_t       *t;
1283         int                     i;
1284         const char      *r, *newt;
1285         skinframe_t *skinframe;
1286         if (!r_refdef.scene.worldmodel)
1287         {
1288                 Con_Printf("There is no worldmodel\n");
1289                 return;
1290         }
1291         m = r_refdef.scene.worldmodel;
1292
1293         if(Cmd_Argc() < 2)
1294         {
1295                 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
1296                 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
1297                 return;
1298         }
1299         if(!cl.islocalgame || !cl.worldmodel)
1300         {
1301                 Con_Print("This command works only in singleplayer\n");
1302                 return;
1303         }
1304         r = Cmd_Argv(1);
1305         newt = Cmd_Argv(2);
1306         if(!newt[0])
1307                 newt = r;
1308         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1309         {
1310                 if(/*t->width && !strcasecmp(t->name, r)*/ matchpattern( t->name, r, true ) )
1311                 {
1312                         if ((skinframe = R_SkinFrame_LoadExternal(newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, true)))
1313                         {
1314 //                              t->skinframes[0] = skinframe;
1315                                 t->currentskinframe = skinframe;
1316                                 t->currentskinframe = skinframe;
1317                                 Con_Printf("%s replaced with %s\n", r, newt);
1318                         }
1319                         else
1320                         {
1321                                 Con_Printf("%s was not found\n", newt);
1322                                 return;
1323                         }
1324                 }
1325         }
1326 }
1327
1328 //Made by [515]
1329 void R_ListWorldTextures (void)
1330 {
1331         dp_model_t              *m;
1332         texture_t       *t;
1333         int                     i;
1334         if (!r_refdef.scene.worldmodel)
1335         {
1336                 Con_Printf("There is no worldmodel\n");
1337                 return;
1338         }
1339         m = r_refdef.scene.worldmodel;
1340
1341         Con_Print("Worldmodel textures :\n");
1342         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
1343                 if (t->numskinframes)
1344                         Con_Printf("%s\n", t->name);
1345 }
1346
1347 #if 0
1348 static void gl_surf_start(void)
1349 {
1350 }
1351
1352 static void gl_surf_shutdown(void)
1353 {
1354 }
1355
1356 static void gl_surf_newmap(void)
1357 {
1358 }
1359 #endif
1360
1361 void GL_Surf_Init(void)
1362 {
1363
1364         Cvar_RegisterVariable(&r_ambient);
1365         Cvar_RegisterVariable(&r_lockpvs);
1366         Cvar_RegisterVariable(&r_lockvisibility);
1367         Cvar_RegisterVariable(&r_useportalculling);
1368         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
1369
1370         Cmd_AddCommand ("r_replacemaptexture", R_ReplaceWorldTexture, "override a map texture for testing purposes");
1371         Cmd_AddCommand ("r_listmaptextures", R_ListWorldTextures, "list all textures used by the current map");
1372
1373         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
1374 }
1375