]> icculus.org git repositories - divverent/darkplaces.git/blob - gl_rsurf.c
csqc patch from [515], seems to work with [515]'s dpcsqc test mod, needs a lot of...
[divverent/darkplaces.git] / gl_rsurf.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 See the GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 */
20 // r_surf.c: surface-related refresh code
21
22 #include "quakedef.h"
23 #include "r_shadow.h"
24 #include "portals.h"
25
26 #define MAX_LIGHTMAP_SIZE 256
27
28 cvar_t r_ambient = {0, "r_ambient", "0"};
29 cvar_t r_drawportals = {0, "r_drawportals", "0"};
30 cvar_t r_lockpvs = {0, "r_lockpvs", "0"};
31 cvar_t r_lockvisibility = {0, "r_lockvisibility", "0"};
32 cvar_t r_useportalculling = {0, "r_useportalculling", "1"};
33 cvar_t r_drawcollisionbrushes_polygonfactor = {0, "r_drawcollisionbrushes_polygonfactor", "-1"};
34 cvar_t r_drawcollisionbrushes_polygonoffset = {0, "r_drawcollisionbrushes_polygonoffset", "0"};
35 cvar_t r_q3bsp_renderskydepth = {0, "r_q3bsp_renderskydepth", "0"};
36
37 // flag arrays used for visibility checking on world model
38 // (all other entities have no per-surface/per-leaf visibility checks)
39 // TODO: dynamic resize according to r_refdef.worldmodel->brush.num_clusters
40 unsigned char r_pvsbits[(32768+7)>>3];
41 // TODO: dynamic resize according to r_refdef.worldmodel->brush.num_leafs
42 unsigned char r_worldleafvisible[32768];
43 // TODO: dynamic resize according to r_refdef.worldmodel->num_surfaces
44 unsigned char r_worldsurfacevisible[262144];
45
46 /*
47 ===============
48 R_BuildLightMap
49
50 Combine and scale multiple lightmaps into the 8.8 format in blocklights
51 ===============
52 */
53 void R_BuildLightMap (const entity_render_t *ent, msurface_t *surface)
54 {
55         int smax, tmax, i, j, size, size3, maps, stride, l;
56         unsigned int *bl, scale;
57         unsigned char *lightmap, *out, *stain;
58         static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
59         static unsigned char templight[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*4];
60
61         // update cached lighting info
62         surface->cached_dlight = 0;
63
64         smax = (surface->lightmapinfo->extents[0]>>4)+1;
65         tmax = (surface->lightmapinfo->extents[1]>>4)+1;
66         size = smax*tmax;
67         size3 = size*3;
68         lightmap = surface->lightmapinfo->samples;
69
70 // set to full bright if no light data
71         bl = intblocklights;
72         if (!ent->model->brushq1.lightdata)
73         {
74                 for (i = 0;i < size3;i++)
75                         bl[i] = 255*256;
76         }
77         else
78         {
79 // clear to no light
80                 memset(bl, 0, size*3*sizeof(unsigned int));
81
82 // add all the lightmaps
83                 if (lightmap)
84                 {
85                         bl = intblocklights;
86                         for (maps = 0;maps < MAXLIGHTMAPS && surface->lightmapinfo->styles[maps] != 255;maps++, lightmap += size3)
87                                 for (scale = r_refdef.lightstylevalue[surface->lightmapinfo->styles[maps]], i = 0;i < size3;i++)
88                                         bl[i] += lightmap[i] * scale;
89                 }
90         }
91
92         stain = surface->lightmapinfo->stainsamples;
93         bl = intblocklights;
94         out = templight;
95         // the >> 16 shift adjusts down 8 bits to account for the stainmap
96         // scaling, and remaps the 0-65536 (2x overbright) to 0-256, it will
97         // be doubled during rendering to achieve 2x overbright
98         // (0 = 0.0, 128 = 1.0, 256 = 2.0)
99         if (ent->model->brushq1.lightmaprgba)
100         {
101                 stride = (surface->lightmapinfo->lightmaptexturestride - smax) * 4;
102                 for (i = 0;i < tmax;i++, out += stride)
103                 {
104                         for (j = 0;j < smax;j++)
105                         {
106                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
107                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
108                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
109                                 *out++ = 255;
110                         }
111                 }
112         }
113         else
114         {
115                 stride = (surface->lightmapinfo->lightmaptexturestride - smax) * 3;
116                 for (i = 0;i < tmax;i++, out += stride)
117                 {
118                         for (j = 0;j < smax;j++)
119                         {
120                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
121                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
122                                 l = (*bl++ * *stain++) >> 16;*out++ = min(l, 255);
123                         }
124                 }
125         }
126
127         R_UpdateTexture(surface->lightmaptexture, templight);
128 }
129
130 void R_StainNode (mnode_t *node, model_t *model, const vec3_t origin, float radius, const float fcolor[8])
131 {
132         float ndist, a, ratio, maxdist, maxdist2, maxdist3, invradius, sdtable[256], td, dist2;
133         msurface_t *surface, *endsurface;
134         int i, s, t, smax, tmax, smax3, impacts, impactt, stained;
135         unsigned char *bl;
136         vec3_t impact;
137
138         maxdist = radius * radius;
139         invradius = 1.0f / radius;
140
141 loc0:
142         if (!node->plane)
143                 return;
144         ndist = PlaneDiff(origin, node->plane);
145         if (ndist > radius)
146         {
147                 node = node->children[0];
148                 goto loc0;
149         }
150         if (ndist < -radius)
151         {
152                 node = node->children[1];
153                 goto loc0;
154         }
155
156         dist2 = ndist * ndist;
157         maxdist3 = maxdist - dist2;
158
159         if (node->plane->type < 3)
160         {
161                 VectorCopy(origin, impact);
162                 impact[node->plane->type] -= ndist;
163         }
164         else
165         {
166                 impact[0] = origin[0] - node->plane->normal[0] * ndist;
167                 impact[1] = origin[1] - node->plane->normal[1] * ndist;
168                 impact[2] = origin[2] - node->plane->normal[2] * ndist;
169         }
170
171         for (surface = model->data_surfaces + node->firstsurface, endsurface = surface + node->numsurfaces;surface < endsurface;surface++)
172         {
173                 if (surface->lightmapinfo->stainsamples)
174                 {
175                         smax = (surface->lightmapinfo->extents[0] >> 4) + 1;
176                         tmax = (surface->lightmapinfo->extents[1] >> 4) + 1;
177
178                         impacts = DotProduct (impact, surface->lightmapinfo->texinfo->vecs[0]) + surface->lightmapinfo->texinfo->vecs[0][3] - surface->lightmapinfo->texturemins[0];
179                         impactt = DotProduct (impact, surface->lightmapinfo->texinfo->vecs[1]) + surface->lightmapinfo->texinfo->vecs[1][3] - surface->lightmapinfo->texturemins[1];
180
181                         s = bound(0, impacts, smax * 16) - impacts;
182                         t = bound(0, impactt, tmax * 16) - impactt;
183                         i = s * s + t * t + dist2;
184                         if (i > maxdist)
185                                 continue;
186
187                         // reduce calculations
188                         for (s = 0, i = impacts; s < smax; s++, i -= 16)
189                                 sdtable[s] = i * i + dist2;
190
191                         bl = surface->lightmapinfo->stainsamples;
192                         smax3 = smax * 3;
193                         stained = false;
194
195                         i = impactt;
196                         for (t = 0;t < tmax;t++, i -= 16)
197                         {
198                                 td = i * i;
199                                 // make sure some part of it is visible on this line
200                                 if (td < maxdist3)
201                                 {
202                                         maxdist2 = maxdist - td;
203                                         for (s = 0;s < smax;s++)
204                                         {
205                                                 if (sdtable[s] < maxdist2)
206                                                 {
207                                                         ratio = lhrandom(0.0f, 1.0f);
208                                                         a = (fcolor[3] + ratio * fcolor[7]) * (1.0f - sqrt(sdtable[s] + td) * invradius);
209                                                         if (a >= (1.0f / 64.0f))
210                                                         {
211                                                                 if (a > 1)
212                                                                         a = 1;
213                                                                 bl[0] = (unsigned char) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
214                                                                 bl[1] = (unsigned char) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
215                                                                 bl[2] = (unsigned char) ((float) bl[2] + a * ((fcolor[2] + ratio * fcolor[6]) - (float) bl[2]));
216                                                                 stained = true;
217                                                         }
218                                                 }
219                                                 bl += 3;
220                                         }
221                                 }
222                                 else // skip line
223                                         bl += smax3;
224                         }
225                         // force lightmap upload
226                         if (stained)
227                                 surface->cached_dlight = true;
228                 }
229         }
230
231         if (node->children[0]->plane)
232         {
233                 if (node->children[1]->plane)
234                 {
235                         R_StainNode(node->children[0], model, origin, radius, fcolor);
236                         node = node->children[1];
237                         goto loc0;
238                 }
239                 else
240                 {
241                         node = node->children[0];
242                         goto loc0;
243                 }
244         }
245         else if (node->children[1]->plane)
246         {
247                 node = node->children[1];
248                 goto loc0;
249         }
250 }
251
252 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)
253 {
254         int n;
255         float fcolor[8];
256         entity_render_t *ent;
257         model_t *model;
258         vec3_t org;
259         if (r_refdef.worldmodel == NULL || !r_refdef.worldmodel->brush.data_nodes || !r_refdef.worldmodel->brushq1.lightdata)
260                 return;
261         fcolor[0] = cr1;
262         fcolor[1] = cg1;
263         fcolor[2] = cb1;
264         fcolor[3] = ca1 * (1.0f / 64.0f);
265         fcolor[4] = cr2 - cr1;
266         fcolor[5] = cg2 - cg1;
267         fcolor[6] = cb2 - cb1;
268         fcolor[7] = (ca2 - ca1) * (1.0f / 64.0f);
269
270         R_StainNode(r_refdef.worldmodel->brush.data_nodes + r_refdef.worldmodel->brushq1.hulls[0].firstclipnode, r_refdef.worldmodel, origin, radius, fcolor);
271
272         // look for embedded bmodels
273         for (n = 0;n < cl_num_brushmodel_entities;n++)
274         {
275                 ent = &cl_entities[cl_brushmodel_entities[n]].render;
276                 model = ent->model;
277                 if (model && model->name[0] == '*')
278                 {
279                         if (model->brush.data_nodes)
280                         {
281                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
282                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
283                         }
284                 }
285         }
286 }
287
288
289 /*
290 =============================================================
291
292         BRUSH MODELS
293
294 =============================================================
295 */
296
297 static void R_DrawPortal_Callback(const entity_render_t *ent, int surfacenumber, const rtlight_t *rtlight)
298 {
299         const mportal_t *portal = (mportal_t *)ent;
300         int i;
301         float *v;
302         rmeshstate_t m;
303         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
304         GL_DepthMask(false);
305         GL_DepthTest(true);
306         R_Mesh_Matrix(&r_identitymatrix);
307
308         memset(&m, 0, sizeof(m));
309         m.pointer_vertex = varray_vertex3f;
310         R_Mesh_State(&m);
311
312         i = surfacenumber;
313         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f),
314                          ((i & 0x0038) >> 3) * (1.0f / 7.0f),
315                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f),
316                          0.125f);
317         if (PlaneDiff(r_vieworigin, (&portal->plane)) < 0)
318         {
319                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
320                         VectorCopy(portal->points[i].position, v);
321         }
322         else
323                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
324                         VectorCopy(portal->points[i].position, v);
325         GL_LockArrays(0, portal->numpoints);
326         R_Mesh_Draw(0, portal->numpoints, portal->numpoints - 2, polygonelements);
327         GL_LockArrays(0, 0);
328 }
329
330 // LordHavoc: this is just a nice debugging tool, very slow
331 static void R_DrawPortals(void)
332 {
333         int i, leafnum;
334         mportal_t *portal;
335         float center[3], f;
336         model_t *model = r_refdef.worldmodel;
337         if (model == NULL)
338                 return;
339         for (leafnum = 0;leafnum < r_refdef.worldmodel->brush.num_leafs;leafnum++)
340         {
341                 if (r_worldleafvisible[leafnum])
342                 {
343                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
344                         for (portal = r_refdef.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
345                         {
346                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
347                                 if (!R_CullBox(portal->mins, portal->maxs))
348                                 {
349                                         VectorClear(center);
350                                         for (i = 0;i < portal->numpoints;i++)
351                                                 VectorAdd(center, portal->points[i].position, center);
352                                         f = ixtable[portal->numpoints];
353                                         VectorScale(center, f, center);
354                                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, (entity_render_t *)portal, leafnum, r_shadow_rtlight);
355                                 }
356                         }
357                 }
358         }
359 }
360
361 static void R_DrawCollisionBrush(colbrushf_t *brush)
362 {
363         int i;
364         rmeshstate_t m;
365         memset(&m, 0, sizeof(m));
366         m.pointer_vertex = brush->points->v;
367         R_Mesh_State(&m);
368         i = (int)(((size_t)brush) / sizeof(colbrushf_t));
369         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
370         GL_LockArrays(0, brush->numpoints);
371         R_Mesh_Draw(0, brush->numpoints, brush->numtriangles, brush->elements);
372         GL_LockArrays(0, 0);
373 }
374
375 static void R_DrawCollisionSurface(entity_render_t *ent, msurface_t *surface)
376 {
377         int i;
378         rmeshstate_t m;
379         if (!surface->num_collisiontriangles)
380                 return;
381         memset(&m, 0, sizeof(m));
382         m.pointer_vertex = surface->data_collisionvertex3f;
383         R_Mesh_State(&m);
384         i = (int)(((size_t)surface) / sizeof(msurface_t));
385         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
386         GL_LockArrays(0, surface->num_collisionvertices);
387         R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i);
388         GL_LockArrays(0, 0);
389 }
390
391 void R_WorldVisibility(void)
392 {
393         int i, j, *mark;
394         mleaf_t *leaf;
395         mleaf_t *viewleaf;
396         model_t *model = r_refdef.worldmodel;
397
398         if (!model)
399                 return;
400
401         // if possible find the leaf the view origin is in
402         viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_vieworigin) : NULL;
403         // if possible fetch the visible cluster bits
404         if (!r_lockpvs.integer && model->brush.FatPVS)
405                 model->brush.FatPVS(model, r_vieworigin, 2, r_pvsbits, sizeof(r_pvsbits));
406
407         if (!r_lockvisibility.integer)
408         {
409                 // clear the visible surface and leaf flags arrays
410                 memset(r_worldsurfacevisible, 0, model->num_surfaces);
411                 memset(r_worldleafvisible, 0, model->brush.num_leafs);
412
413                 // if floating around in the void (no pvs data available, and no
414                 // portals available), simply use all on-screen leafs.
415                 if (!viewleaf || viewleaf->clusterindex < 0)
416                 {
417                         // no visibility method: (used when floating around in the void)
418                         // simply cull each leaf to the frustum (view pyramid)
419                         // similar to quake's RecursiveWorldNode but without cache misses
420                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
421                         {
422                                 // if leaf is in current pvs and on the screen, mark its surfaces
423                                 if (!R_CullBox(leaf->mins, leaf->maxs))
424                                 {
425                                         renderstats.world_leafs++;
426                                         r_worldleafvisible[j] = true;
427                                         if (leaf->numleafsurfaces)
428                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
429                                                         r_worldsurfacevisible[*mark] = true;
430                                 }
431                         }
432                 }
433                 // if the user prefers to disable portal culling (testing?), simply
434                 // use all on-screen leafs that are in the pvs.
435                 else if (!r_useportalculling.integer)
436                 {
437                         // pvs method:
438                         // simply check if each leaf is in the Potentially Visible Set,
439                         // and cull to frustum (view pyramid)
440                         // similar to quake's RecursiveWorldNode but without cache misses
441                         for (j = 0, leaf = model->brush.data_leafs;j < model->brush.num_leafs;j++, leaf++)
442                         {
443                                 // if leaf is in current pvs and on the screen, mark its surfaces
444                                 if (CHECKPVSBIT(r_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
445                                 {
446                                         renderstats.world_leafs++;
447                                         r_worldleafvisible[j] = true;
448                                         if (leaf->numleafsurfaces)
449                                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
450                                                         r_worldsurfacevisible[*mark] = true;
451                                 }
452                         }
453                 }
454                 // otherwise use a recursive portal flow, culling each portal to
455                 // frustum and checking if the leaf the portal leads to is in the pvs
456                 else
457                 {
458                         int leafstackpos;
459                         mportal_t *p;
460                         mleaf_t *leafstack[8192];
461                         // simple-frustum portal method:
462                         // follows portals leading outward from viewleaf, does not venture
463                         // offscreen or into leafs that are not visible, faster than
464                         // Quake's RecursiveWorldNode and vastly better in unvised maps,
465                         // often culls some surfaces that pvs alone would miss
466                         // (such as a room in pvs that is hidden behind a wall, but the
467                         //  passage leading to the room is off-screen)
468                         leafstack[0] = viewleaf;
469                         leafstackpos = 1;
470                         while (leafstackpos)
471                         {
472                                 renderstats.world_leafs++;
473                                 leaf = leafstack[--leafstackpos];
474                                 r_worldleafvisible[leaf - model->brush.data_leafs] = true;
475                                 // mark any surfaces bounding this leaf
476                                 if (leaf->numleafsurfaces)
477                                         for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
478                                                 r_worldsurfacevisible[*mark] = true;
479                                 // follow portals into other leafs
480                                 // the checks are:
481                                 // if viewer is behind portal (portal faces outward into the scene)
482                                 // and the portal polygon's bounding box is on the screen
483                                 // and the leaf has not been visited yet
484                                 // and the leaf is visible in the pvs
485                                 // (the first two checks won't cause as many cache misses as the leaf checks)
486                                 for (p = leaf->portals;p;p = p->next)
487                                 {
488                                         renderstats.world_portals++;
489                                         if (DotProduct(r_vieworigin, p->plane.normal) < (p->plane.dist + 1) && !R_CullBox(p->mins, p->maxs) && !r_worldleafvisible[p->past - model->brush.data_leafs] && CHECKPVSBIT(r_pvsbits, p->past->clusterindex))
490                                                 leafstack[leafstackpos++] = p->past;
491                                 }
492                         }
493                 }
494         }
495
496         if (r_drawportals.integer)
497                 R_DrawPortals();
498 }
499
500 void R_Q1BSP_DrawSky(entity_render_t *ent)
501 {
502         if (ent->model == NULL)
503                 return;
504         if (r_drawcollisionbrushes.integer < 2)
505                 R_DrawSurfaces(ent, true);
506 }
507
508 void R_Q1BSP_Draw(entity_render_t *ent)
509 {
510         model_t *model = ent->model;
511         if (model == NULL)
512                 return;
513         if (r_drawcollisionbrushes.integer < 2)
514                 R_DrawSurfaces(ent, false);
515         if (r_drawcollisionbrushes.integer >= 1 && model->brush.num_brushes)
516         {
517                 int i;
518                 msurface_t *surface;
519                 q3mbrush_t *brush;
520                 R_Mesh_Matrix(&ent->matrix);
521                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
522                 GL_DepthMask(false);
523                 GL_DepthTest(true);
524                 qglPolygonOffset(r_drawcollisionbrushes_polygonfactor.value, r_drawcollisionbrushes_polygonoffset.value);
525                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
526                         if (brush->colbrushf && brush->colbrushf->numtriangles)
527                                 R_DrawCollisionBrush(brush->colbrushf);
528                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
529                         if (surface->num_collisiontriangles)
530                                 R_DrawCollisionSurface(ent, surface);
531                 qglPolygonOffset(0, 0);
532         }
533 }
534
535 typedef struct r_q1bsp_getlightinfo_s
536 {
537         model_t *model;
538         vec3_t relativelightorigin;
539         float lightradius;
540         int *outleaflist;
541         unsigned char *outleafpvs;
542         int outnumleafs;
543         int *outsurfacelist;
544         unsigned char *outsurfacepvs;
545         int outnumsurfaces;
546         vec3_t outmins;
547         vec3_t outmaxs;
548         vec3_t lightmins;
549         vec3_t lightmaxs;
550         const unsigned char *pvs;
551 }
552 r_q1bsp_getlightinfo_t;
553
554 void R_Q1BSP_RecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, mnode_t *node)
555 {
556         int sides;
557         mleaf_t *leaf;
558         for (;;)
559         {
560                 mplane_t *plane = node->plane;
561                 //if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
562                 //      return;
563                 if (!plane)
564                         break;
565                 if (plane->type < 3)
566                         sides = ((info->lightmaxs[plane->type] >= plane->dist) | ((info->lightmins[plane->type] < plane->dist) << 1));
567                 else
568                         sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, plane);
569                 if (sides == 3)
570                 {
571                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
572                         node = node->children[1];
573                 }
574                 else
575                         node = node->children[sides - 1];
576         }
577         leaf = (mleaf_t *)node;
578         if (info->pvs == NULL || CHECKPVSBIT(info->pvs, leaf->clusterindex))
579         {
580                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
581                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
582                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
583                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
584                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
585                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
586                 if (info->outleafpvs)
587                 {
588                         int leafindex = leaf - info->model->brush.data_leafs;
589                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
590                         {
591                                 SETPVSBIT(info->outleafpvs, leafindex);
592                                 info->outleaflist[info->outnumleafs++] = leafindex;
593                         }
594                 }
595                 if (info->outsurfacepvs)
596                 {
597                         int leafsurfaceindex;
598                         for (leafsurfaceindex = 0;leafsurfaceindex < leaf->numleafsurfaces;leafsurfaceindex++)
599                         {
600                                 int surfaceindex = leaf->firstleafsurface[leafsurfaceindex];
601                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
602                                 {
603                                         msurface_t *surface = info->model->data_surfaces + surfaceindex;
604                                         if (BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
605                                         {
606                                                 int triangleindex, t;
607                                                 const int *e;
608                                                 const vec_t *v[3];
609                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = info->model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
610                                                 {
611                                                         v[0] = info->model->brush.shadowmesh->vertex3f + e[0] * 3;
612                                                         v[1] = info->model->brush.shadowmesh->vertex3f + e[1] * 3;
613                                                         v[2] = info->model->brush.shadowmesh->vertex3f + e[2] * 3;
614                                                         if (PointInfrontOfTriangle(info->relativelightorigin, v[0], v[1], v[2]) && info->lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && info->lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && info->lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && info->lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && info->lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && info->lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
615                                                         {
616                                                                 SETPVSBIT(info->outsurfacepvs, surfaceindex);
617                                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
618                                                                 break;
619                                                         }
620                                                 }
621                                         }
622                                 }
623                         }
624                 }
625         }
626 }
627
628 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)
629 {
630         r_q1bsp_getlightinfo_t info;
631         VectorCopy(relativelightorigin, info.relativelightorigin);
632         info.lightradius = lightradius;
633         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
634         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
635         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
636         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
637         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
638         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
639         if (ent->model == NULL)
640         {
641                 VectorCopy(info.lightmins, outmins);
642                 VectorCopy(info.lightmaxs, outmaxs);
643                 *outnumleafspointer = 0;
644                 *outnumsurfacespointer = 0;
645                 return;
646         }
647         info.model = ent->model;
648         info.outleaflist = outleaflist;
649         info.outleafpvs = outleafpvs;
650         info.outnumleafs = 0;
651         info.outsurfacelist = outsurfacelist;
652         info.outsurfacepvs = outsurfacepvs;
653         info.outnumsurfaces = 0;
654         VectorCopy(info.relativelightorigin, info.outmins);
655         VectorCopy(info.relativelightorigin, info.outmaxs);
656         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
657         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
658         if (info.model->brush.GetPVS)
659                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
660         else
661                 info.pvs = NULL;
662         R_UpdateAllTextureInfo(ent);
663         if (r_shadow_compilingrtlight)
664         {
665                 // use portal recursion for exact light volume culling, and exact surface checking
666                 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);
667         }
668         else if (r_shadow_realtime_dlight_portalculling.integer)
669         {
670                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
671                 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);
672         }
673         else
674         {
675                 // use BSP recursion as lights are often small
676                 R_Q1BSP_RecursiveGetLightInfo(&info, info.model->brush.data_nodes);
677         }
678
679         // limit combined leaf box to light boundaries
680         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
681         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
682         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
683         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
684         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
685         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
686
687         *outnumleafspointer = info.outnumleafs;
688         *outnumsurfacespointer = info.outnumsurfaces;
689 }
690
691 void R_Q1BSP_CompileShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist)
692 {
693         model_t *model = ent->model;
694         msurface_t *surface;
695         int surfacelistindex;
696         float projectdistance = lightradius + model->radius*2 + r_shadow_projectdistance.value;
697         texture_t *texture;
698         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Begin(r_shadow_mempool, 32768, 32768, NULL, NULL, NULL, false, false, true);
699         R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
700         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
701         {
702                 surface = model->data_surfaces + surfacelist[surfacelistindex];
703                 texture = surface->texture;
704                 if ((texture->basematerialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
705                         continue;
706                 if ((texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2)) || (ent->flags & RENDER_NOCULLFACE))
707                         continue;
708                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, r_shadow_compilingrtlight->cullmins, r_shadow_compilingrtlight->cullmaxs, surface->mins, surface->maxs);
709         }
710         R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, lightradius + model->radius + projectdistance, numshadowmark, shadowmarklist);
711         r_shadow_compilingrtlight->static_meshchain_shadow = Mod_ShadowMesh_Finish(r_shadow_mempool, r_shadow_compilingrtlight->static_meshchain_shadow, false, false);
712 }
713
714 extern float *rsurface_vertex3f;
715 extern float *rsurface_svector3f;
716 extern float *rsurface_tvector3f;
717 extern float *rsurface_normal3f;
718 extern void RSurf_SetVertexPointer(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t modelorg);
719
720 void R_Q1BSP_DrawShadowVolume(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, int numsurfaces, const int *surfacelist, const vec3_t lightmins, const vec3_t lightmaxs)
721 {
722         model_t *model = ent->model;
723         msurface_t *surface;
724         int surfacelistindex;
725         float projectdistance = lightradius + model->radius*2 + r_shadow_projectdistance.value;
726         vec3_t modelorg;
727         texture_t *texture;
728         // check the box in modelspace, it was already checked in worldspace
729         if (!BoxesOverlap(ent->model->normalmins, ent->model->normalmaxs, lightmins, lightmaxs))
730                 return;
731         if (r_drawcollisionbrushes.integer >= 2)
732                 return;
733         R_UpdateAllTextureInfo(ent);
734         if (model->brush.shadowmesh)
735         {
736                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
737                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
738                 {
739                         surface = model->data_surfaces + surfacelist[surfacelistindex];
740                         texture = surface->texture->currentframe;
741                         if ((texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
742                                 continue;
743                         if ((texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2)) || (ent->flags & RENDER_NOCULLFACE))
744                                 continue;
745                         R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
746                 }
747                 R_Shadow_VolumeFromList(model->brush.shadowmesh->numverts, model->brush.shadowmesh->numtriangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, model->brush.shadowmesh->neighbor3i, relativelightorigin, lightradius + model->radius + projectdistance, numshadowmark, shadowmarklist);
748         }
749         else
750         {
751                 projectdistance = lightradius + ent->model->radius*2;
752                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
753                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
754                 {
755                         surface = model->data_surfaces + surfacelist[surfacelistindex];
756                         // FIXME: get current skin
757                         texture = surface->texture;//R_FetchAliasSkin(ent, surface->groupmesh);
758                         if (texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT) || !surface->num_triangles)
759                                 continue;
760                         RSurf_SetVertexPointer(ent, texture, surface, modelorg);
761                         // identify lit faces within the bounding box
762                         R_Shadow_PrepareShadowMark(surface->groupmesh->num_triangles);
763                         R_Shadow_MarkVolumeFromBox(surface->num_firsttriangle, surface->num_triangles, rsurface_vertex3f, surface->groupmesh->data_element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
764                         R_Shadow_VolumeFromList(surface->groupmesh->num_vertices, surface->groupmesh->num_triangles, rsurface_vertex3f, surface->groupmesh->data_element3i, surface->groupmesh->data_neighbor3i, relativelightorigin, projectdistance, numshadowmark, shadowmarklist);
765                 }
766         }
767 }
768
769 static void R_Q1BSP_DrawLight_TransparentCallback(const entity_render_t *ent, int surfacenumber, const rtlight_t *rtlight)
770 {
771         msurface_t *surface = ent->model->data_surfaces + surfacenumber;
772         texture_t *texture = surface->texture;
773         R_UpdateTextureInfo(ent, texture);
774         texture = texture->currentframe;
775         R_Shadow_RenderMode_Begin();
776         R_Shadow_RenderMode_ActiveLight((rtlight_t *)rtlight);
777         R_Shadow_RenderMode_Lighting(false, true);
778         R_Shadow_SetupEntityLight(ent);
779         R_Shadow_RenderSurfacesLighting(ent, texture, 1, &surface);
780         R_Shadow_RenderMode_End();
781 }
782
783 #define RSURF_MAX_BATCHSURFACES 1024
784
785 void R_Q1BSP_DrawLight(entity_render_t *ent, int numsurfaces, const int *surfacelist)
786 {
787         model_t *model = ent->model;
788         msurface_t *surface;
789         texture_t *texture;
790         int surfacelistindex, batchnumsurfaces;
791         msurface_t *batchsurfacelist[RSURF_MAX_BATCHSURFACES];
792         vec3_t modelorg;
793         texture_t *tex;
794         qboolean skip;
795         if (r_drawcollisionbrushes.integer >= 2)
796                 return;
797         R_UpdateAllTextureInfo(ent);
798         Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
799         tex = NULL;
800         texture = NULL;
801         skip = false;
802         batchnumsurfaces = 0;
803         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
804         {
805                 if ((ent == r_refdef.worldentity && !r_worldsurfacevisible[surfacelist[surfacelistindex]]))
806                         continue;
807                 surface = model->data_surfaces + surfacelist[surfacelistindex];
808                 renderstats.lights_lighttriangles += surface->num_triangles;
809                 if (tex != surface->texture)
810                 {
811                         if (batchnumsurfaces > 0)
812                         {
813                                 if (texture->currentmaterialflags & MATERIALFLAG_TRANSPARENT)
814                                 {
815                                         int batchsurfaceindex;
816                                         for (batchsurfaceindex = 0;batchsurfaceindex < batchnumsurfaces;batchsurfaceindex++)
817                                         {
818                                                 msurface_t *batchsurface = batchsurfacelist[batchsurfaceindex];
819                                                 vec3_t tempcenter, center;
820                                                 tempcenter[0] = (batchsurface->mins[0] + batchsurface->maxs[0]) * 0.5f;
821                                                 tempcenter[1] = (batchsurface->mins[1] + batchsurface->maxs[1]) * 0.5f;
822                                                 tempcenter[2] = (batchsurface->mins[2] + batchsurface->maxs[2]) * 0.5f;
823                                                 Matrix4x4_Transform(&ent->matrix, tempcenter, center);
824                                                 R_MeshQueue_AddTransparent(texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_vieworigin : center, R_Q1BSP_DrawLight_TransparentCallback, ent, batchsurface - ent->model->data_surfaces, r_shadow_rtlight);
825                                         }
826                                 }
827                                 else
828                                         R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist);
829                                 batchnumsurfaces = 0;
830                         }
831                         tex = surface->texture;
832                         texture = surface->texture->currentframe;
833                         skip = (texture->currentmaterialflags & MATERIALFLAG_SKY) != 0;
834                         if (skip)
835                                 continue;
836                 }
837                 if (!skip && surface->num_triangles)
838                 {
839                         if (batchnumsurfaces == RSURF_MAX_BATCHSURFACES)
840                         {
841                                 if (texture->currentmaterialflags & MATERIALFLAG_TRANSPARENT)
842                                 {
843                                         int batchsurfaceindex;
844                                         for (batchsurfaceindex = 0;batchsurfaceindex < batchnumsurfaces;batchsurfaceindex++)
845                                         {
846                                                 msurface_t *batchsurface = batchsurfacelist[batchsurfaceindex];
847                                                 vec3_t tempcenter, center;
848                                                 tempcenter[0] = (batchsurface->mins[0] + batchsurface->maxs[0]) * 0.5f;
849                                                 tempcenter[1] = (batchsurface->mins[1] + batchsurface->maxs[1]) * 0.5f;
850                                                 tempcenter[2] = (batchsurface->mins[2] + batchsurface->maxs[2]) * 0.5f;
851                                                 Matrix4x4_Transform(&ent->matrix, tempcenter, center);
852                                                 R_MeshQueue_AddTransparent(texture->currentmaterialflags & MATERIALFLAG_NODEPTHTEST ? r_vieworigin : center, R_Q1BSP_DrawLight_TransparentCallback, ent, batchsurface - ent->model->data_surfaces, r_shadow_rtlight);
853                                         }
854                                 }
855                                 else
856                                         R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist);
857                                 batchnumsurfaces = 0;
858                         }
859                         batchsurfacelist[batchnumsurfaces++] = surface;
860                 }
861         }
862         if (batchnumsurfaces > 0)
863         {
864                 R_Shadow_RenderSurfacesLighting(ent, texture, batchnumsurfaces, batchsurfacelist);
865                 batchnumsurfaces = 0;
866         }
867         qglEnable(GL_CULL_FACE);
868 }
869
870 //Made by [515]
871 void R_ReplaceWorldTexture (void)
872 {
873         model_t         *m;
874         texture_t       *t;
875         int                     i;
876         const char      *r, *newt;
877         m = r_refdef.worldmodel;
878
879         if(Cmd_Argc() < 2)
880         {
881                 Con_Print("r_replacemaptexture <texname> <newtexname> - replaces texture\n");
882                 Con_Print("r_replacemaptexture <texname> - switch back to default texture\n");
883                 return;
884         }
885         if(!cl.islocalgame || !cl.worldmodel)
886         {
887                 Con_Print("This command works only in singleplayer\n");
888                 return;
889         }
890         r = Cmd_Argv(1);
891         newt = Cmd_Argv(2);
892         if(!newt[0])
893                 newt = r;
894         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
895         {
896                 if(t->width && !strcasecmp(t->name, r))
897                 {
898                         if(Mod_LoadSkinFrame(&t->skin, (char*)newt, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, r_fullbrights.integer))
899                         {
900                                 Con_Printf("%s replaced with %s\n", r, newt);
901                                 return;
902                         }
903                         else
904                         {
905                                 Con_Printf("%s was not found\n", newt);
906                                 Mod_LoadSkinFrame(&t->skin, (char*)r, TEXF_MIPMAP | TEXF_ALPHA | TEXF_PRECACHE | TEXF_PICMIP, false, r_fullbrights.integer);//back to default
907                                 return;
908                         }
909                 }
910         }
911 }
912
913 //Made by [515]
914 void R_ListWorldTextures (void)
915 {
916         model_t         *m;
917         texture_t       *t;
918         int                     i;
919         m = r_refdef.worldmodel;
920
921         Con_Print("Worldmodel textures :\n");
922         for(i=0,t=m->data_textures;i<m->num_textures;i++,t++)
923                 if(t->skin.base != r_texture_notexture)
924                         Con_Printf("%s\n", t->name);
925 }
926
927 #if 0
928 static void gl_surf_start(void)
929 {
930 }
931
932 static void gl_surf_shutdown(void)
933 {
934 }
935
936 static void gl_surf_newmap(void)
937 {
938 }
939 #endif
940
941 void GL_Surf_Init(void)
942 {
943
944         Cvar_RegisterVariable(&r_ambient);
945         Cvar_RegisterVariable(&r_drawportals);
946         Cvar_RegisterVariable(&r_lockpvs);
947         Cvar_RegisterVariable(&r_lockvisibility);
948         Cvar_RegisterVariable(&r_useportalculling);
949         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonfactor);
950         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
951         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
952
953         Cmd_AddCommand ("r_replacemaptexture", R_ReplaceWorldTexture);          // By [515]
954         Cmd_AddCommand ("r_listmaptextures", R_ListWorldTextures);                      // By [515]
955
956         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
957 }
958