finished model/map rendering merge, model renderer has been completely removed
[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_testvis = {0, "r_testvis", "0"};
31 cvar_t r_detailtextures = {CVAR_SAVE, "r_detailtextures", "1"};
32 cvar_t r_surfaceworldnode = {0, "r_surfaceworldnode", "0"};
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 qbyte r_pvsbits[(32768+7)>>3];
41 // TODO: dynamic resize according to r_refdef.worldmodel->brush.num_leafs
42 qbyte r_worldleafvisible[32768];
43 // TODO: dynamic resize according to r_refdef.worldmodel->num_surfaces
44 qbyte 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         qbyte *lightmap, *out, *stain;
58         static unsigned int intblocklights[MAX_LIGHTMAP_SIZE*MAX_LIGHTMAP_SIZE*3]; // LordHavoc: *3 for colored lighting
59         static qbyte 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 = d_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         qbyte *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] = (qbyte) ((float) bl[0] + a * ((fcolor[0] + ratio * fcolor[4]) - (float) bl[0]));
214                                                                 bl[1] = (qbyte) ((float) bl[1] + a * ((fcolor[1] + ratio * fcolor[5]) - (float) bl[1]));
215                                                                 bl[2] = (qbyte) ((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                         Mod_CheckLoaded(model);
280                         if (model->brush.data_nodes)
281                         {
282                                 Matrix4x4_Transform(&ent->inversematrix, origin, org);
283                                 R_StainNode(model->brush.data_nodes + model->brushq1.hulls[0].firstclipnode, model, org, radius, fcolor);
284                         }
285                 }
286         }
287 }
288
289
290 /*
291 =============================================================
292
293         BRUSH MODELS
294
295 =============================================================
296 */
297
298 static void R_DrawPortal_Callback(const void *calldata1, int calldata2)
299 {
300         int i;
301         float *v;
302         rmeshstate_t m;
303         const mportal_t *portal = calldata1;
304         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
305         GL_DepthMask(false);
306         GL_DepthTest(true);
307         R_Mesh_Matrix(&r_identitymatrix);
308
309         memset(&m, 0, sizeof(m));
310         m.pointer_vertex = varray_vertex3f;
311         R_Mesh_State(&m);
312
313         i = calldata2;
314         GL_Color(((i & 0x0007) >> 0) * (1.0f / 7.0f),
315                          ((i & 0x0038) >> 3) * (1.0f / 7.0f),
316                          ((i & 0x01C0) >> 6) * (1.0f / 7.0f),
317                          0.125f);
318         if (PlaneDiff(r_vieworigin, (&portal->plane)) < 0)
319         {
320                 for (i = portal->numpoints - 1, v = varray_vertex3f;i >= 0;i--, v += 3)
321                         VectorCopy(portal->points[i].position, v);
322         }
323         else
324                 for (i = 0, v = varray_vertex3f;i < portal->numpoints;i++, v += 3)
325                         VectorCopy(portal->points[i].position, v);
326         GL_LockArrays(0, portal->numpoints);
327         R_Mesh_Draw(0, portal->numpoints, portal->numpoints - 2, polygonelements);
328         GL_LockArrays(0, 0);
329 }
330
331 // LordHavoc: this is just a nice debugging tool, very slow
332 static void R_DrawPortals(void)
333 {
334         int i, leafnum;//, portalnum;
335         mportal_t *portal;
336         float center[3], f;
337         model_t *model = r_refdef.worldmodel;
338         if (model == NULL)
339                 return;
340         for (leafnum = 0;leafnum < r_refdef.worldmodel->brush.num_leafs;leafnum++)
341         {
342                 if (r_worldleafvisible[leafnum])
343                 {
344                         //for (portalnum = 0, portal = model->brush.data_portals;portalnum < model->brush.num_portals;portalnum++, portal++)
345                         for (portal = r_refdef.worldmodel->brush.data_leafs[leafnum].portals;portal;portal = portal->next)
346                         {
347                                 if (portal->numpoints <= POLYGONELEMENTS_MAXPOINTS)
348                                 if (!R_CullBox(portal->mins, portal->maxs))
349                                 {
350                                         VectorClear(center);
351                                         for (i = 0;i < portal->numpoints;i++)
352                                                 VectorAdd(center, portal->points[i].position, center);
353                                         f = ixtable[portal->numpoints];
354                                         VectorScale(center, f, center);
355                                         //R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, portal, portalnum);
356                                         R_MeshQueue_AddTransparent(center, R_DrawPortal_Callback, portal, leafnum);
357                                 }
358                         }
359                 }
360         }
361 }
362
363 static void R_DrawCollisionBrush(colbrushf_t *brush)
364 {
365         int i;
366         rmeshstate_t m;
367         memset(&m, 0, sizeof(m));
368         m.pointer_vertex = brush->points->v;
369         R_Mesh_State(&m);
370         i = (int)(((size_t)brush) / sizeof(colbrushf_t));
371         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
372         GL_LockArrays(0, brush->numpoints);
373         R_Mesh_Draw(0, brush->numpoints, brush->numtriangles, brush->elements);
374         GL_LockArrays(0, 0);
375 }
376
377 static void R_DrawCollisionSurface(entity_render_t *ent, msurface_t *surface)
378 {
379         int i;
380         rmeshstate_t m;
381         if (!surface->num_collisiontriangles)
382                 return;
383         memset(&m, 0, sizeof(m));
384         m.pointer_vertex = surface->data_collisionvertex3f;
385         R_Mesh_State(&m);
386         i = (int)(((size_t)surface) / sizeof(msurface_t));
387         GL_Color((i & 31) * (1.0f / 32.0f), ((i >> 5) & 31) * (1.0f / 32.0f), ((i >> 10) & 31) * (1.0f / 32.0f), 0.2f);
388         GL_LockArrays(0, surface->num_collisionvertices);
389         R_Mesh_Draw(0, surface->num_collisionvertices, surface->num_collisiontriangles, surface->data_collisionelement3i);
390         GL_LockArrays(0, 0);
391 }
392
393 void R_WorldVisibility(void)
394 {
395         int i, j, *mark;
396         mleaf_t *leaf;
397         mleaf_t *viewleaf;
398         model_t *model = r_refdef.worldmodel;
399
400         if (!model)
401                 return;
402
403         // if possible find the leaf the view origin is in
404         viewleaf = model->brush.PointInLeaf ? model->brush.PointInLeaf(model, r_vieworigin) : NULL;
405         // if possible fetch the visible cluster bits
406         if (model->brush.FatPVS)
407                 model->brush.FatPVS(model, r_vieworigin, 2, r_pvsbits, sizeof(r_pvsbits));
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 the user prefers surfaceworldnode (testing?) or the viewleaf could
414         // not be found, or the viewleaf is not part of the visible world
415         // (floating around in the void), use the pvs method
416         if (r_surfaceworldnode.integer || !viewleaf || viewleaf->clusterindex < 0)
417         {
418                 // pvs method:
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 (CHECKPVSBIT(r_pvsbits, leaf->clusterindex) && !R_CullBox(leaf->mins, leaf->maxs))
424                         {
425                                 c_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         else
434         {
435                 int leafstackpos;
436                 mportal_t *p;
437                 mleaf_t *leafstack[8192];
438                 // portal method:
439                 // follows portals leading outward from viewleaf, does not venture
440                 // offscreen or into leafs that are not visible, faster than Quake's
441                 // RecursiveWorldNode and vastly better in unvised maps, often culls a
442                 // lot of surface that pvs alone would miss
443                 leafstack[0] = viewleaf;
444                 leafstackpos = 1;
445                 while (leafstackpos)
446                 {
447                         c_leafs++;
448                         leaf = leafstack[--leafstackpos];
449                         r_worldleafvisible[leaf - model->brush.data_leafs] = true;
450                         // mark any surfaces bounding this leaf
451                         if (leaf->numleafsurfaces)
452                                 for (i = 0, mark = leaf->firstleafsurface;i < leaf->numleafsurfaces;i++, mark++)
453                                         r_worldsurfacevisible[*mark] = true;
454                         // follow portals into other leafs
455                         // the checks are:
456                         // if viewer is behind portal (portal faces outward into the scene)
457                         // and the portal polygon's bounding box is on the screen
458                         // and the leaf has not been visited yet
459                         // and the leaf is visible in the pvs
460                         // (the first two checks won't cause as many cache misses as the leaf checks)
461                         for (p = leaf->portals;p;p = p->next)
462                                 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))
463                                         leafstack[leafstackpos++] = p->past;
464                 }
465         }
466
467         if (r_drawportals.integer)
468                 R_DrawPortals();
469 }
470
471 void R_Q1BSP_DrawSky(entity_render_t *ent)
472 {
473         if (ent->model == NULL)
474                 return;
475         if (r_drawcollisionbrushes.integer < 2)
476                 R_DrawSurfaces(ent, true);
477 }
478
479 void R_Q1BSP_Draw(entity_render_t *ent)
480 {
481         if (ent->model == NULL)
482                 return;
483         c_bmodels++;
484         if (r_drawcollisionbrushes.integer < 2)
485                 R_DrawSurfaces(ent, false);
486         if (r_drawcollisionbrushes.integer >= 1 && ent->model->brush.num_brushes)
487         {
488                 int i;
489                 model_t *model = ent->model;
490                 msurface_t *surface;
491                 q3mbrush_t *brush;
492                 GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
493                 GL_DepthMask(false);
494                 GL_DepthTest(true);
495                 qglPolygonOffset(r_drawcollisionbrushes_polygonfactor.value, r_drawcollisionbrushes_polygonoffset.value);
496                 for (i = 0, brush = model->brush.data_brushes + model->firstmodelbrush;i < model->nummodelbrushes;i++, brush++)
497                         if (brush->colbrushf && brush->colbrushf->numtriangles)
498                                 R_DrawCollisionBrush(brush->colbrushf);
499                 for (i = 0, surface = model->data_surfaces + model->firstmodelsurface;i < model->nummodelsurfaces;i++, surface++)
500                         if (surface->num_collisiontriangles)
501                                 R_DrawCollisionSurface(ent, surface);
502                 qglPolygonOffset(0, 0);
503         }
504 }
505
506 typedef struct r_q1bsp_getlightinfo_s
507 {
508         model_t *model;
509         vec3_t relativelightorigin;
510         float lightradius;
511         int *outleaflist;
512         qbyte *outleafpvs;
513         int outnumleafs;
514         int *outsurfacelist;
515         qbyte *outsurfacepvs;
516         int outnumsurfaces;
517         vec3_t outmins;
518         vec3_t outmaxs;
519         vec3_t lightmins;
520         vec3_t lightmaxs;
521         const qbyte *pvs;
522 }
523 r_q1bsp_getlightinfo_t;
524
525 void R_Q1BSP_RecursiveGetLightInfo(r_q1bsp_getlightinfo_t *info, mnode_t *node)
526 {
527         int sides;
528         mleaf_t *leaf;
529         for (;;)
530         {
531                 if (!BoxesOverlap(info->lightmins, info->lightmaxs, node->mins, node->maxs))
532                         return;
533                 if (!node->plane)
534                         break;
535                 sides = BoxOnPlaneSide(info->lightmins, info->lightmaxs, node->plane) - 1;
536                 if (sides == 2)
537                 {
538                         R_Q1BSP_RecursiveGetLightInfo(info, node->children[0]);
539                         node = node->children[1];
540                 }
541                 else
542                         node = node->children[sides];
543         }
544         leaf = (mleaf_t *)node;
545         if (info->pvs == NULL || CHECKPVSBIT(info->pvs, leaf->clusterindex))
546         {
547                 info->outmins[0] = min(info->outmins[0], leaf->mins[0]);
548                 info->outmins[1] = min(info->outmins[1], leaf->mins[1]);
549                 info->outmins[2] = min(info->outmins[2], leaf->mins[2]);
550                 info->outmaxs[0] = max(info->outmaxs[0], leaf->maxs[0]);
551                 info->outmaxs[1] = max(info->outmaxs[1], leaf->maxs[1]);
552                 info->outmaxs[2] = max(info->outmaxs[2], leaf->maxs[2]);
553                 if (info->outleafpvs)
554                 {
555                         int leafindex = leaf - info->model->brush.data_leafs;
556                         if (!CHECKPVSBIT(info->outleafpvs, leafindex))
557                         {
558                                 SETPVSBIT(info->outleafpvs, leafindex);
559                                 info->outleaflist[info->outnumleafs++] = leafindex;
560                         }
561                 }
562                 if (info->outsurfacepvs)
563                 {
564                         int leafsurfaceindex;
565                         for (leafsurfaceindex = 0;leafsurfaceindex < leaf->numleafsurfaces;leafsurfaceindex++)
566                         {
567                                 int surfaceindex = leaf->firstleafsurface[leafsurfaceindex];
568                                 if (!CHECKPVSBIT(info->outsurfacepvs, surfaceindex))
569                                 {
570                                         msurface_t *surface = info->model->data_surfaces + surfaceindex;
571                                         if (BoxesOverlap(info->lightmins, info->lightmaxs, surface->mins, surface->maxs))
572                                         if ((surface->texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT)) == MATERIALFLAG_WALL)
573                                         {
574                                                 int triangleindex, t;
575                                                 const int *e;
576                                                 const vec_t *v[3];
577                                                 for (triangleindex = 0, t = surface->num_firstshadowmeshtriangle, e = info->model->brush.shadowmesh->element3i + t * 3;triangleindex < surface->num_triangles;triangleindex++, t++, e += 3)
578                                                 {
579                                                         v[0] = info->model->brush.shadowmesh->vertex3f + e[0] * 3;
580                                                         v[1] = info->model->brush.shadowmesh->vertex3f + e[1] * 3;
581                                                         v[2] = info->model->brush.shadowmesh->vertex3f + e[2] * 3;
582                                                         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])))
583                                                         {
584                                                                 SETPVSBIT(info->outsurfacepvs, surfaceindex);
585                                                                 info->outsurfacelist[info->outnumsurfaces++] = surfaceindex;
586                                                                 break;
587                                                         }
588                                                 }
589                                         }
590                                 }
591                         }
592                 }
593         }
594 }
595
596 void R_Q1BSP_GetLightInfo(entity_render_t *ent, vec3_t relativelightorigin, float lightradius, vec3_t outmins, vec3_t outmaxs, int *outleaflist, qbyte *outleafpvs, int *outnumleafspointer, int *outsurfacelist, qbyte *outsurfacepvs, int *outnumsurfacespointer)
597 {
598         r_q1bsp_getlightinfo_t info;
599         VectorCopy(relativelightorigin, info.relativelightorigin);
600         info.lightradius = lightradius;
601         info.lightmins[0] = info.relativelightorigin[0] - info.lightradius;
602         info.lightmins[1] = info.relativelightorigin[1] - info.lightradius;
603         info.lightmins[2] = info.relativelightorigin[2] - info.lightradius;
604         info.lightmaxs[0] = info.relativelightorigin[0] + info.lightradius;
605         info.lightmaxs[1] = info.relativelightorigin[1] + info.lightradius;
606         info.lightmaxs[2] = info.relativelightorigin[2] + info.lightradius;
607         if (ent->model == NULL)
608         {
609                 VectorCopy(info.lightmins, outmins);
610                 VectorCopy(info.lightmaxs, outmaxs);
611                 *outnumleafspointer = 0;
612                 *outnumsurfacespointer = 0;
613                 return;
614         }
615         info.model = ent->model;
616         info.outleaflist = outleaflist;
617         info.outleafpvs = outleafpvs;
618         info.outnumleafs = 0;
619         info.outsurfacelist = outsurfacelist;
620         info.outsurfacepvs = outsurfacepvs;
621         info.outnumsurfaces = 0;
622         VectorCopy(info.relativelightorigin, info.outmins);
623         VectorCopy(info.relativelightorigin, info.outmaxs);
624         memset(outleafpvs, 0, (info.model->brush.num_leafs + 7) >> 3);
625         memset(outsurfacepvs, 0, (info.model->nummodelsurfaces + 7) >> 3);
626         if (info.model->brush.GetPVS)
627                 info.pvs = info.model->brush.GetPVS(info.model, info.relativelightorigin);
628         else
629                 info.pvs = NULL;
630         R_UpdateAllTextureInfo(ent);
631         if (r_shadow_compilingrtlight)
632         {
633                 // use portal recursion for exact light volume culling, and exact surface checking
634                 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);
635         }
636         else if (r_shadow_realtime_dlight_portalculling.integer)
637         {
638                 // use portal recursion for exact light volume culling, but not the expensive exact surface checking
639                 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);
640         }
641         else
642         {
643                 // use BSP recursion as lights are often small
644                 R_Q1BSP_RecursiveGetLightInfo(&info, info.model->brush.data_nodes);
645         }
646
647         // limit combined leaf box to light boundaries
648         outmins[0] = max(info.outmins[0] - 1, info.lightmins[0]);
649         outmins[1] = max(info.outmins[1] - 1, info.lightmins[1]);
650         outmins[2] = max(info.outmins[2] - 1, info.lightmins[2]);
651         outmaxs[0] = min(info.outmaxs[0] + 1, info.lightmaxs[0]);
652         outmaxs[1] = min(info.outmaxs[1] + 1, info.lightmaxs[1]);
653         outmaxs[2] = min(info.outmaxs[2] + 1, info.lightmaxs[2]);
654
655         *outnumleafspointer = info.outnumleafs;
656         *outnumsurfacespointer = info.outnumsurfaces;
657 }
658
659 extern float *rsurface_vertex3f;
660 extern float *rsurface_svector3f;
661 extern float *rsurface_tvector3f;
662 extern float *rsurface_normal3f;
663 extern void RSurf_SetVertexPointer(const entity_render_t *ent, const texture_t *texture, const msurface_t *surface, const vec3_t modelorg);
664
665 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)
666 {
667         model_t *model = ent->model;
668         msurface_t *surface;
669         int surfacelistindex;
670         float projectdistance = lightradius + model->radius + r_shadow_projectdistance.value;
671         vec3_t modelorg;
672         texture_t *texture;
673         // check the box in modelspace, it was already checked in worldspace
674         if (!BoxesOverlap(ent->model->normalmins, ent->model->normalmaxs, lightmins, lightmaxs))
675                 return;
676         if (r_drawcollisionbrushes.integer >= 2)
677                 return;
678         if (!r_shadow_compilingrtlight)
679                 R_UpdateAllTextureInfo(ent);
680         if (model->brush.shadowmesh)
681         {
682                 R_Shadow_PrepareShadowMark(model->brush.shadowmesh->numtriangles);
683                 if (r_shadow_compilingrtlight)
684                 {
685                         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
686                         {
687                                 surface = model->data_surfaces + surfacelist[surfacelistindex];
688                                 texture = surface->texture;
689                                 if ((texture->basematerialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
690                                         continue;
691                                 if (texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
692                                         continue;
693                                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
694                         }
695                 }
696                 else
697                 {
698                         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
699                         {
700                                 surface = model->data_surfaces + surfacelist[surfacelistindex];
701                                 texture = surface->texture->currentframe;
702                                 if ((texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT | MATERIALFLAG_WALL)) != MATERIALFLAG_WALL)
703                                         continue;
704                                 if (texture->textureflags & (Q3TEXTUREFLAG_TWOSIDED | Q3TEXTUREFLAG_AUTOSPRITE | Q3TEXTUREFLAG_AUTOSPRITE2))
705                                         continue;
706                                 R_Shadow_MarkVolumeFromBox(surface->num_firstshadowmeshtriangle, surface->num_triangles, model->brush.shadowmesh->vertex3f, model->brush.shadowmesh->element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
707                         }
708                 }
709                 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);
710         }
711         else
712         {
713                 projectdistance = lightradius + ent->model->radius;
714                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
715                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
716                 {
717                         surface = model->data_surfaces + surfacelist[surfacelistindex];
718                         // FIXME: get current skin
719                         texture = surface->texture;//R_FetchAliasSkin(ent, surface->groupmesh);
720                         if (texture->currentmaterialflags & (MATERIALFLAG_NODRAW | MATERIALFLAG_TRANSPARENT) || !surface->num_triangles)
721                                 continue;
722                         RSurf_SetVertexPointer(ent, texture, surface, modelorg);
723                         // identify lit faces within the bounding box
724                         R_Shadow_PrepareShadowMark(surface->groupmesh->num_triangles);
725                         R_Shadow_MarkVolumeFromBox(surface->num_firsttriangle, surface->num_triangles, rsurface_vertex3f, surface->groupmesh->data_element3i, relativelightorigin, lightmins, lightmaxs, surface->mins, surface->maxs);
726                         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);
727                 }
728         }
729 }
730
731 void R_Q1BSP_DrawLight(entity_render_t *ent, float *lightcolor, int numsurfaces, const int *surfacelist)
732 {
733         model_t *model = ent->model;
734         msurface_t *surface;
735         texture_t *texture;
736         int surfacelistindex;
737         vec3_t modelorg;
738         if (r_drawcollisionbrushes.integer >= 2)
739                 return;
740         if (r_shadow_compilingrtlight)
741         {
742                 // if compiling an rtlight, capture the meshes
743                 int tri;
744                 int *e;
745                 float *lightmins, *lightmaxs, *v[3], *vertex3f;
746                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
747                 {
748                         surface = model->data_surfaces + surfacelist[surfacelistindex];
749                         texture = surface->texture;
750                         if ((texture->basematerialflags & (MATERIALFLAG_WALL | MATERIALFLAG_TRANSPARENT)) != MATERIALFLAG_WALL || !surface->num_triangles)
751                                 continue;
752                         e = surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle;
753                         vertex3f = surface->groupmesh->data_vertex3f;
754                         lightmins = r_shadow_compilingrtlight->cullmins;
755                         lightmaxs = r_shadow_compilingrtlight->cullmaxs;
756                         for (tri = 0;tri < surface->num_triangles;tri++, e += 3)
757                         {
758                                 v[0] = vertex3f + e[0] * 3;
759                                 v[1] = vertex3f + e[1] * 3;
760                                 v[2] = vertex3f + e[2] * 3;
761                                 if (PointInfrontOfTriangle(r_shadow_compilingrtlight->shadoworigin, v[0], v[1], v[2]) && lightmaxs[0] > min(v[0][0], min(v[1][0], v[2][0])) && lightmins[0] < max(v[0][0], max(v[1][0], v[2][0])) && lightmaxs[1] > min(v[0][1], min(v[1][1], v[2][1])) && lightmins[1] < max(v[0][1], max(v[1][1], v[2][1])) && lightmaxs[2] > min(v[0][2], min(v[1][2], v[2][2])) && lightmins[2] < max(v[0][2], max(v[1][2], v[2][2])))
762                                         Mod_ShadowMesh_AddMesh(r_shadow_mempool, r_shadow_compilingrtlight->static_meshchain_light, surface->texture->skin.base, surface->texture->skin.gloss, surface->texture->skin.nmap, surface->groupmesh->data_vertex3f, surface->groupmesh->data_svector3f, surface->groupmesh->data_tvector3f, surface->groupmesh->data_normal3f, surface->groupmesh->data_texcoordtexture2f, 1, e);
763                         }
764                 }
765         }
766         else
767         {
768                 R_UpdateAllTextureInfo(ent);
769                 Matrix4x4_Transform(&ent->inversematrix, r_vieworigin, modelorg);
770                 for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
771                 {
772                         if (ent == r_refdef.worldentity && !r_worldsurfacevisible[surfacelist[surfacelistindex]])
773                                 continue;
774                         surface = model->data_surfaces + surfacelist[surfacelistindex];
775                         texture = surface->texture->currentframe;
776                         // FIXME: transparent surfaces need to be lit later
777                         if ((texture->currentmaterialflags & (MATERIALFLAG_WALL | MATERIALFLAG_TRANSPARENT)) != MATERIALFLAG_WALL || !surface->num_triangles)
778                                 continue;
779                         if (texture->textureflags & Q3TEXTUREFLAG_TWOSIDED)
780                                 qglDisable(GL_CULL_FACE);
781                         RSurf_SetVertexPointer(ent, texture, surface, modelorg);
782                         if (!rsurface_svector3f)
783                         {
784                                 rsurface_svector3f = varray_svector3f;
785                                 rsurface_tvector3f = varray_tvector3f;
786                                 rsurface_normal3f = varray_normal3f;
787                                 Mod_BuildTextureVectorsAndNormals(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, rsurface_vertex3f, surface->groupmesh->data_texcoordtexture2f, surface->groupmesh->data_element3i + surface->num_firsttriangle * 3, rsurface_svector3f, rsurface_tvector3f, rsurface_normal3f);
788                         }
789                         // FIXME: add colormapping
790                         R_Shadow_RenderLighting(surface->num_firstvertex, surface->num_vertices, surface->num_triangles, (surface->groupmesh->data_element3i + 3 * surface->num_firsttriangle), rsurface_vertex3f, rsurface_svector3f, rsurface_tvector3f, rsurface_normal3f, surface->groupmesh->data_texcoordtexture2f, lightcolor, vec3_origin, vec3_origin, texture->skin.base, NULL, NULL, texture->skin.nmap, texture->skin.gloss);
791                         if (texture->textureflags & Q3TEXTUREFLAG_TWOSIDED)
792                                 qglEnable(GL_CULL_FACE);
793                 }
794         }
795 }
796
797 #if 0
798 static void gl_surf_start(void)
799 {
800 }
801
802 static void gl_surf_shutdown(void)
803 {
804 }
805
806 static void gl_surf_newmap(void)
807 {
808 }
809 #endif
810
811 void GL_Surf_Init(void)
812 {
813
814         Cvar_RegisterVariable(&r_ambient);
815         Cvar_RegisterVariable(&r_drawportals);
816         Cvar_RegisterVariable(&r_testvis);
817         Cvar_RegisterVariable(&r_detailtextures);
818         Cvar_RegisterVariable(&r_surfaceworldnode);
819         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonfactor);
820         Cvar_RegisterVariable(&r_drawcollisionbrushes_polygonoffset);
821         Cvar_RegisterVariable(&r_q3bsp_renderskydepth);
822
823         //R_RegisterModule("GL_Surf", gl_surf_start, gl_surf_shutdown, gl_surf_newmap);
824 }
825