]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/light_ydnar.c
Merge remote branch 'icculus/master'
[xonotic/netradiant.git] / tools / quake3 / q3map2 / light_ydnar.c
1 /* -------------------------------------------------------------------------------
2
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
5
6 This file is part of GtkRadiant.
7
8 GtkRadiant is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
12
13 GtkRadiant is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GtkRadiant; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
22 ----------------------------------------------------------------------------------
23
24 This code has been altered significantly from its original form, to support
25 several games based on the Quake III Arena engine, in the form of "Q3Map2."
26
27 ------------------------------------------------------------------------------- */
28
29
30
31 /* marker */
32 #define LIGHT_YDNAR_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41
42 /*
43 ColorToBytes()
44 ydnar: moved to here 2001-02-04
45 */
46
47 void ColorToBytes( const float *color, byte *colorBytes, float scale )
48 {
49         int             i;
50         float   max, gamma;
51         vec3_t  sample;
52         float   inv, dif;
53         
54         
55         /* ydnar: scaling necessary for simulating r_overbrightBits on external lightmaps */
56         if( scale <= 0.0f )
57                 scale = 1.0f;
58         
59         /* make a local copy */
60         VectorScale( color, scale, sample );
61         
62         /* muck with it */
63         gamma = 1.0f / lightmapGamma;
64         for( i = 0; i < 3; i++ )
65         {
66                 /* handle negative light */
67                 if( sample[ i ] < 0.0f )
68                 {
69                         sample[ i ] = 0.0f;
70                         continue;
71                 }
72                 
73                 /* gamma */
74                 sample[ i ] = pow( sample[ i ] / 255.0f, gamma ) * 255.0f;
75         }
76
77         if (lightmapExposure == 1)
78         {
79                 /* clamp with color normalization */
80                 max = sample[ 0 ];
81                 if( sample[ 1 ] > max )
82                         max = sample[ 1 ];
83                 if( sample[ 2 ] > max )
84                         max = sample[ 2 ];
85                 if( max > 255.0f )
86                         VectorScale( sample, (255.0f / max), sample );
87         }
88         else
89         {
90                 if (lightmapExposure==0)
91                 {
92                         lightmapExposure=1.0f;
93                 }
94                 inv=1.f/lightmapExposure;
95                 //Exposure
96
97                 max = sample[ 0 ];
98                 if( sample[ 1 ] > max )
99                         max = sample[ 1 ];
100                 if( sample[ 2 ] > max )
101                         max = sample[ 2 ];
102
103                 dif = (1-  exp(-max * inv) )  *  255;
104
105                 if (max >0)
106                 {
107                         dif = dif / max;
108                 }
109                 else
110                 {
111                         dif = 0;
112                 }
113
114                 for (i=0;i<3;i++)
115                 {
116                         sample[i]*=dif;
117                 }
118         }
119
120         
121         /* compensate for ingame overbrighting/bitshifting */
122         VectorScale( sample, (1.0f / lightmapCompensate), sample );
123         
124         /* store it off */
125         colorBytes[ 0 ] = sample[ 0 ];
126         colorBytes[ 1 ] = sample[ 1 ];
127         colorBytes[ 2 ] = sample[ 2 ];
128 }
129
130
131
132 /* -------------------------------------------------------------------------------
133
134 this section deals with phong shading (normal interpolation across brush faces)
135
136 ------------------------------------------------------------------------------- */
137
138 /*
139 SmoothNormals()
140 smooths together coincident vertex normals across the bsp
141 */
142
143 #define MAX_SAMPLES                             256
144 #define THETA_EPSILON                   0.000001
145 #define EQUAL_NORMAL_EPSILON    0.01
146
147 void SmoothNormals( void )
148 {
149         int                                     i, j, k, f, cs, numVerts, numVotes, fOld, start;
150         float                           shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle;
151         bspDrawSurface_t        *ds;
152         shaderInfo_t            *si;
153         float                           *shadeAngles;
154         byte                            *smoothed;
155         vec3_t                          average, diff;
156         int                                     indexes[ MAX_SAMPLES ];
157         vec3_t                          votes[ MAX_SAMPLES ];
158         
159         
160         /* allocate shade angle table */
161         shadeAngles = safe_malloc( numBSPDrawVerts * sizeof( float ) );
162         memset( shadeAngles, 0, numBSPDrawVerts * sizeof( float ) );
163         
164         /* allocate smoothed table */
165         cs = (numBSPDrawVerts / 8) + 1;
166         smoothed = safe_malloc( cs );
167         memset( smoothed, 0, cs );
168         
169         /* set default shade angle */
170         defaultShadeAngle = DEG2RAD( shadeAngleDegrees );
171         maxShadeAngle = 0;
172         
173         /* run through every surface and flag verts belonging to non-lightmapped surfaces
174            and set per-vertex smoothing angle */
175         for( i = 0; i < numBSPDrawSurfaces; i++ )
176         {
177                 /* get drawsurf */
178                 ds = &bspDrawSurfaces[ i ];
179                 
180                 /* get shader for shade angle */
181                 si = surfaceInfos[ i ].si;
182                 if( si->shadeAngleDegrees )
183                         shadeAngle = DEG2RAD( si->shadeAngleDegrees );
184                 else
185                         shadeAngle = defaultShadeAngle;
186                 if( shadeAngle > maxShadeAngle )
187                         maxShadeAngle = shadeAngle;
188                 
189                 /* flag its verts */
190                 for( j = 0; j < ds->numVerts; j++ )
191                 {
192                         f = ds->firstVert + j;
193                         shadeAngles[ f ] = shadeAngle;
194                         if( ds->surfaceType == MST_TRIANGLE_SOUP )
195                                 smoothed[ f >> 3 ] |= (1 << (f & 7));
196                 }
197                 
198                 /* ydnar: optional force-to-trisoup */
199                 if( trisoup && ds->surfaceType == MST_PLANAR )
200                 {
201                         ds->surfaceType = MST_TRIANGLE_SOUP;
202                         ds->lightmapNum[ 0 ] = -3;
203                 }
204         }
205         
206         /* bail if no surfaces have a shade angle */
207         if( maxShadeAngle == 0 )
208         {
209                 free( shadeAngles );
210                 free( smoothed );
211                 return;
212         }
213         
214         /* init pacifier */
215         fOld = -1;
216         start = I_FloatTime();
217         
218         /* go through the list of vertexes */
219         for( i = 0; i < numBSPDrawVerts; i++ )
220         {
221                 /* print pacifier */
222                 f = 10 * i / numBSPDrawVerts;
223                 if( f != fOld )
224                 {
225                         fOld = f;
226                         Sys_Printf( "%i...", f );
227                 }
228                 
229                 /* already smoothed? */
230                 if( smoothed[ i >> 3 ] & (1 << (i & 7)) )
231                         continue;
232                 
233                 /* clear */
234                 VectorClear( average );
235                 numVerts = 0;
236                 numVotes = 0;
237                 
238                 /* build a table of coincident vertexes */
239                 for( j = i; j < numBSPDrawVerts && numVerts < MAX_SAMPLES; j++ )
240                 {
241                         /* already smoothed? */
242                         if( smoothed[ j >> 3 ] & (1 << (j & 7)) )
243                                 continue;
244                         
245                         /* test vertexes */
246                         if( VectorCompare( yDrawVerts[ i ].xyz, yDrawVerts[ j ].xyz ) == qfalse )
247                                 continue;
248                         
249                         /* use smallest shade angle */
250                         shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]);
251                         
252                         /* check shade angle */
253                         dot = DotProduct( bspDrawVerts[ i ].normal, bspDrawVerts[ j ].normal );
254                         if( dot > 1.0 )
255                                 dot = 1.0;
256                         else if( dot < -1.0 )
257                                 dot = -1.0;
258                         testAngle = acos( dot ) + THETA_EPSILON;
259                         if( testAngle >= shadeAngle )
260                         {
261                                 //Sys_Printf( "F(%3.3f >= %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) );
262                                 continue;
263                         }
264                         //Sys_Printf( "P(%3.3f < %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) );
265                         
266                         /* add to the list */
267                         indexes[ numVerts++ ] = j;
268                         
269                         /* flag vertex */
270                         smoothed[ j >> 3 ] |= (1 << (j & 7));
271                         
272                         /* see if this normal has already been voted */
273                         for( k = 0; k < numVotes; k++ )
274                         {
275                                 VectorSubtract( bspDrawVerts[ j ].normal, votes[ k ], diff );
276                                 if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON &&
277                                         fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON &&
278                                         fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON )
279                                         break;
280                         }
281                         
282                         /* add a new vote? */
283                         if( k == numVotes && numVotes < MAX_SAMPLES )
284                         {
285                                 VectorAdd( average, bspDrawVerts[ j ].normal, average );
286                                 VectorCopy( bspDrawVerts[ j ].normal, votes[ numVotes ] );
287                                 numVotes++;
288                         }
289                 }
290                 
291                 /* don't average for less than 2 verts */
292                 if( numVerts < 2 )
293                         continue;
294                 
295                 /* average normal */
296                 if( VectorNormalize( average, average ) > 0 )
297                 {
298                         /* smooth */
299                         for( j = 0; j < numVerts; j++ )
300                                 VectorCopy( average, yDrawVerts[ indexes[ j ] ].normal );
301                 }
302         }
303         
304         /* free the tables */
305         free( shadeAngles );
306         free( smoothed );
307         
308         /* print time */
309         Sys_Printf( " (%i)\n", (int) (I_FloatTime() - start) );
310 }
311
312
313
314 /* -------------------------------------------------------------------------------
315
316 this section deals with phong shaded lightmap tracing
317
318 ------------------------------------------------------------------------------- */
319
320 /* 9th rewrite (recursive subdivision of a lightmap triangle) */
321
322 /*
323 CalcTangentVectors()
324 calculates the st tangent vectors for normalmapping
325 */
326
327 static qboolean CalcTangentVectors( int numVerts, bspDrawVert_t **dv, vec3_t *stv, vec3_t *ttv )
328 {
329         int                     i;
330         float           bb, s, t;
331         vec3_t          bary;
332         
333         
334         /* calculate barycentric basis for the triangle */
335         bb = (dv[ 1 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 2 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]) - (dv[ 2 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 1 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]);
336         if( fabs( bb ) < 0.00000001f )
337                 return qfalse;
338         
339         /* do each vertex */
340         for( i = 0; i < numVerts; i++ )
341         {
342                 /* calculate s tangent vector */
343                 s = dv[ i ]->st[ 0 ] + 10.0f;
344                 t = dv[ i ]->st[ 1 ];
345                 bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb;
346                 bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb;
347                 bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb;
348                 
349                 stv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ];
350                 stv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ];
351                 stv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ];
352                 
353                 VectorSubtract( stv[ i ], dv[ i ]->xyz, stv[ i ] );
354                 VectorNormalize( stv[ i ], stv[ i ] );
355                 
356                 /* calculate t tangent vector */
357                 s = dv[ i ]->st[ 0 ];
358                 t = dv[ i ]->st[ 1 ] + 10.0f;
359                 bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb;
360                 bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb;
361                 bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb;
362                 
363                 ttv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ];
364                 ttv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ];
365                 ttv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ];
366                 
367                 VectorSubtract( ttv[ i ], dv[ i ]->xyz, ttv[ i ] );
368                 VectorNormalize( ttv[ i ], ttv[ i ] );
369                 
370                 /* debug code */
371                 //%     Sys_FPrintf( SYS_VRB, "%d S: (%f %f %f) T: (%f %f %f)\n", i,
372                 //%             stv[ i ][ 0 ], stv[ i ][ 1 ], stv[ i ][ 2 ], ttv[ i ][ 0 ], ttv[ i ][ 1 ], ttv[ i ][ 2 ] );
373         }
374         
375         /* return to caller */
376         return qtrue;
377 }
378
379
380
381
382 /*
383 PerturbNormal()
384 perterbs the normal by the shader's normalmap in tangent space
385 */
386
387 static void PerturbNormal( bspDrawVert_t *dv, shaderInfo_t *si, vec3_t pNormal, vec3_t stv[ 3 ], vec3_t ttv[ 3 ] )
388 {
389         int                     i;
390         vec4_t          bump;
391         
392         
393         /* passthrough */
394         VectorCopy( dv->normal, pNormal );
395         
396         /* sample normalmap */
397         if( RadSampleImage( si->normalImage->pixels, si->normalImage->width, si->normalImage->height, dv->st, bump ) == qfalse )
398                 return;
399         
400         /* remap sampled normal from [0,255] to [-1,-1] */
401         for( i = 0; i < 3; i++ )
402                 bump[ i ] = (bump[ i ] - 127.0f) * (1.0f / 127.5f);
403         
404         /* scale tangent vectors and add to original normal */
405         VectorMA( dv->normal, bump[ 0 ], stv[ 0 ], pNormal );
406         VectorMA( pNormal, bump[ 1 ], ttv[ 0 ], pNormal );
407         VectorMA( pNormal, bump[ 2 ], dv->normal, pNormal );
408         
409         /* renormalize and return */
410         VectorNormalize( pNormal, pNormal );
411 }
412
413
414
415 /*
416 MapSingleLuxel()
417 maps a luxel for triangle bv at
418 */
419
420 #define NUDGE                   0.5f
421 #define BOGUS_NUDGE             -99999.0f
422
423 static int MapSingleLuxel( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv, vec4_t plane, float pass, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] )
424 {
425         int                             i, x, y, numClusters, *clusters, pointCluster, *cluster;
426         float                   *luxel, *origin, *normal, d, lightmapSampleOffset;
427         shaderInfo_t    *si;
428         vec3_t                  pNormal;
429         vec3_t                  vecs[ 3 ];
430         vec3_t                  nudged;
431         vec3_t                  cverts[ 3 ];
432         vec3_t                  temp;
433         vec4_t                  sideplane, hostplane;
434         vec3_t                  origintwo;
435         int                             j, next;
436         float                   e;
437         float                   *nudge;
438         static float    nudges[][ 2 ] =
439                                         {
440                                                 //%{ 0, 0 },            /* try center first */
441                                                 { -NUDGE, 0 },          /* left */
442                                                 { NUDGE, 0 },           /* right */
443                                                 { 0, NUDGE },           /* up */
444                                                 { 0, -NUDGE },          /* down */
445                                                 { -NUDGE, NUDGE },      /* left/up */
446                                                 { NUDGE, -NUDGE },      /* right/down */
447                                                 { NUDGE, NUDGE },       /* right/up */
448                                                 { -NUDGE, -NUDGE },     /* left/down */
449                                                 { BOGUS_NUDGE, BOGUS_NUDGE }
450                                         };
451         
452         
453         /* find luxel xy coords (fixme: subtract 0.5?) */
454         x = dv->lightmap[ 0 ][ 0 ];
455         y = dv->lightmap[ 0 ][ 1 ];
456         if( x < 0 )
457                 x = 0;
458         else if( x >= lm->sw )
459                 x = lm->sw - 1;
460         if( y < 0 )
461                 y = 0;
462         else if( y >= lm->sh )
463                 y = lm->sh - 1;
464         
465         /* set shader and cluster list */
466         if( info != NULL )
467         {
468                 si = info->si;
469                 numClusters = info->numSurfaceClusters;
470                 clusters = &surfaceClusters[ info->firstSurfaceCluster ];
471         }
472         else
473         {
474                 si = NULL;
475                 numClusters = 0;
476                 clusters = NULL;
477         }
478         
479         /* get luxel, origin, cluster, and normal */
480         luxel = SUPER_LUXEL( 0, x, y );
481         origin = SUPER_ORIGIN( x, y );
482         normal = SUPER_NORMAL( x, y );
483         cluster = SUPER_CLUSTER( x, y );
484         
485         /* don't attempt to remap occluded luxels for planar surfaces */
486         if( (*cluster) == CLUSTER_OCCLUDED && lm->plane != NULL )
487                 return (*cluster);
488         
489         /* only average the normal for premapped luxels */
490         else if( (*cluster) >= 0 )
491         {
492                 /* do bumpmap calculations */
493                 if( stv != NULL )
494                         PerturbNormal( dv, si, pNormal, stv, ttv );
495                 else
496                         VectorCopy( dv->normal, pNormal );
497                 
498                 /* add the additional normal data */
499                 VectorAdd( normal, pNormal, normal );
500                 luxel[ 3 ] += 1.0f;
501                 return (*cluster);
502         }
503         
504         /* otherwise, unmapped luxels (*cluster == CLUSTER_UNMAPPED) will have their full attributes calculated */
505         
506         /* get origin */
507         
508         /* axial lightmap projection */
509         if( lm->vecs != NULL )
510         {
511                 /* calculate an origin for the sample from the lightmap vectors */
512                 VectorCopy( lm->origin, origin );
513                 for( i = 0; i < 3; i++ )
514                 {
515                         /* add unless it's the axis, which is taken care of later */
516                         if( i == lm->axisNum )
517                                 continue;
518                         origin[ i ] += (x * lm->vecs[ 0 ][ i ]) + (y * lm->vecs[ 1 ][ i ]);
519                 }
520                 
521                 /* project the origin onto the plane */
522                 d = DotProduct( origin, plane ) - plane[ 3 ];
523                 d /= plane[ lm->axisNum ];
524                 origin[ lm->axisNum ] -= d;
525         }
526         
527         /* non axial lightmap projection (explicit xyz) */
528         else
529                 VectorCopy( dv->xyz, origin );
530
531         //////////////////////
532         //27's test to make sure samples stay within the triangle boundaries
533         //1) Test the sample origin to see if it lays on the wrong side of any edge (x/y)
534         //2) if it does, nudge it onto the correct side.
535
536         if (worldverts!=NULL && lightmapTriangleCheck)
537         {
538                 for (j=0;j<3;j++)
539                 {
540                         VectorCopy(worldverts[j],cverts[j]);
541                 }
542                 PlaneFromPoints(hostplane,cverts[0],cverts[1],cverts[2]);
543
544                 for (j=0;j<3;j++)
545                 {
546                         for (i=0;i<3;i++)
547                         {
548                                 //build plane using 2 edges and a normal
549                                 next=(i+1)%3;
550
551                                 VectorCopy(cverts[next],temp);
552                                 VectorAdd(temp,hostplane,temp);
553                                 PlaneFromPoints(sideplane,cverts[i],cverts[ next ], temp);
554
555                                 //planetest sample point
556                                 e=DotProduct(origin,sideplane);
557                                 e=e-sideplane[3];
558                                 if (e>0)
559                                 {
560                                         //we're bad.
561                                         //VectorClear(origin);
562                                         //Move the sample point back inside triangle bounds
563                                         origin[0]-=sideplane[0]*(e+1);
564                                         origin[1]-=sideplane[1]*(e+1);
565                                         origin[2]-=sideplane[2]*(e+1);
566 #ifdef DEBUG_27_1
567                                         VectorClear(origin);
568 #endif
569                                 }
570                         }
571                 }
572         }
573
574         ////////////////////////
575         
576         /* planar surfaces have precalculated lightmap vectors for nudging */
577         if( lm->plane != NULL )
578         {
579                 VectorCopy( lm->vecs[ 0 ], vecs[ 0 ] );
580                 VectorCopy( lm->vecs[ 1 ], vecs[ 1 ] );
581                 VectorCopy( lm->plane, vecs[ 2 ] );
582         }
583         
584         /* non-planar surfaces must calculate them */
585         else
586         {
587                 if( plane != NULL )
588                         VectorCopy( plane, vecs[ 2 ] );
589                 else
590                         VectorCopy( dv->normal, vecs[ 2 ] );
591                 MakeNormalVectors( vecs[ 2 ], vecs[ 0 ], vecs[ 1 ] );
592         }
593         
594         /* push the origin off the surface a bit */
595         if( si != NULL )
596                 lightmapSampleOffset = si->lightmapSampleOffset;
597         else
598                 lightmapSampleOffset = DEFAULT_LIGHTMAP_SAMPLE_OFFSET;
599         if( lm->axisNum < 0 )
600                 VectorMA( origin, lightmapSampleOffset, vecs[ 2 ], origin );
601         else if( vecs[ 2 ][ lm->axisNum ] < 0.0f )
602                 origin[ lm->axisNum ] -= lightmapSampleOffset;
603         else
604                 origin[ lm->axisNum ] += lightmapSampleOffset;
605         
606         VectorCopy(origin,origintwo);
607         if(lightmapExtraVisClusterNudge)
608         {
609                 origintwo[0]+=vecs[2][0];
610                 origintwo[1]+=vecs[2][1];
611                 origintwo[2]+=vecs[2][2];
612         }
613
614         /* get cluster */
615         pointCluster = ClusterForPointExtFilter( origintwo, LUXEL_EPSILON, numClusters, clusters );
616         
617         /* another retarded hack, storing nudge count in luxel[ 1 ] */
618         luxel[ 1 ] = 0.0f;      
619         
620         /* point in solid? (except in dark mode) */
621         if( pointCluster < 0 && dark == qfalse )
622         {
623                 /* nudge the the location around */
624                 nudge = nudges[ 0 ];
625                 while( nudge[ 0 ] > BOGUS_NUDGE && pointCluster < 0 )
626                 {
627                         /* nudge the vector around a bit */
628                         for( i = 0; i < 3; i++ )
629                         {
630                                 /* set nudged point*/
631                                 nudged[ i ] = origintwo[ i ] + (nudge[ 0 ] * vecs[ 0 ][ i ]) + (nudge[ 1 ] * vecs[ 1 ][ i ]);
632                         }
633                         nudge += 2;
634                         
635                         /* get pvs cluster */
636                         pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters ); //% + 0.625 );
637                         if( pointCluster >= 0 )
638                                 VectorCopy( nudged, origin );
639                         luxel[ 1 ] += 1.0f;
640                 }
641         }
642         
643         /* as a last resort, if still in solid, try drawvert origin offset by normal (except in dark mode) */
644         if( pointCluster < 0 && si != NULL && dark == qfalse )
645         {
646                 VectorMA( dv->xyz, lightmapSampleOffset, dv->normal, nudged );
647                 pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters );
648                 if( pointCluster >= 0 )
649                         VectorCopy( nudged, origin );
650                 luxel[ 1 ] += 1.0f;
651         }
652         
653         /* valid? */
654         if( pointCluster < 0 )
655         {
656                 (*cluster) = CLUSTER_OCCLUDED;
657                 VectorClear( origin );
658                 VectorClear( normal );
659                 numLuxelsOccluded++;
660                 return (*cluster);
661         }
662         
663         /* debug code */
664         //%     Sys_Printf( "%f %f %f\n", origin[ 0 ], origin[ 1 ], origin[ 2 ] );
665         
666         /* do bumpmap calculations */
667         if( stv )
668                 PerturbNormal( dv, si, pNormal, stv, ttv );
669         else
670                 VectorCopy( dv->normal, pNormal );
671         
672         /* store the cluster and normal */
673         (*cluster) = pointCluster;
674         VectorCopy( pNormal, normal );
675         
676         /* store explicit mapping pass and implicit mapping pass */
677         luxel[ 0 ] = pass;
678         luxel[ 3 ] = 1.0f;
679         
680         /* add to count */
681         numLuxelsMapped++;
682         
683         /* return ok */
684         return (*cluster);
685 }
686
687
688
689 /*
690 MapTriangle_r()
691 recursively subdivides a triangle until its edges are shorter
692 than the distance between two luxels (thanks jc :)
693 */
694
695 static void MapTriangle_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], vec4_t plane, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] )
696 {
697         bspDrawVert_t   mid, *dv2[ 3 ];
698         int                             max;
699         
700         
701         /* map the vertexes */
702         #if 0
703         MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv );
704         MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv );
705         MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv );
706         #endif
707         
708         /* subdivide calc */
709         {
710                 int                     i;
711                 float           *a, *b, dx, dy, dist, maxDist;
712                 
713                 
714                 /* find the longest edge and split it */
715                 max = -1;
716                 maxDist = 0;
717                 for( i = 0; i < 3; i++ )
718                 {
719                         /* get verts */
720                         a = dv[ i ]->lightmap[ 0 ];
721                         b = dv[ (i + 1) % 3 ]->lightmap[ 0 ];
722                         
723                         /* get dists */
724                         dx = a[ 0 ] - b[ 0 ];
725                         dy = a[ 1 ] - b[ 1 ];
726                         dist = (dx * dx) + (dy * dy);   //% sqrt( (dx * dx) + (dy * dy) );
727                         
728                         /* longer? */
729                         if( dist > maxDist )
730                         {
731                                 maxDist = dist;
732                                 max = i;
733                         }
734                 }
735                 
736                 /* try to early out */
737                 if( max < 0 || maxDist <= subdivideThreshold )  /* ydnar: was i < 0 instead of max < 0 (?) */
738                         return;
739         }
740         
741         /* split the longest edge and map it */
742         LerpDrawVert( dv[ max ], dv[ (max + 1) % 3 ], &mid );
743         MapSingleLuxel( lm, info, &mid, plane, 1, stv, ttv, worldverts );
744         
745         /* push the point up a little bit to account for fp creep (fixme: revisit this) */
746         //%     VectorMA( mid.xyz, 2.0f, mid.normal, mid.xyz );
747         
748         /* recurse to first triangle */
749         VectorCopy( dv, dv2 );
750         dv2[ max ] = &mid;
751         MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts );
752         
753         /* recurse to second triangle */
754         VectorCopy( dv, dv2 );
755         dv2[ (max + 1) % 3 ] = &mid;
756         MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts );
757 }
758
759
760
761 /*
762 MapTriangle()
763 seed function for MapTriangle_r()
764 requires a cw ordered triangle
765 */
766
767 static qboolean MapTriangle( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], qboolean mapNonAxial )
768 {
769         int                             i;
770         vec4_t                  plane;
771         vec3_t                  *stv, *ttv, stvStatic[ 3 ], ttvStatic[ 3 ];
772         vec3_t                  worldverts[ 3 ];
773         
774         
775         /* get plane if possible */
776         if( lm->plane != NULL )
777         {
778                 VectorCopy( lm->plane, plane );
779                 plane[ 3 ] = lm->plane[ 3 ];
780         }
781         
782         /* otherwise make one from the points */
783         else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse )
784                 return qfalse;
785         
786         /* check to see if we need to calculate texture->world tangent vectors */
787         if( info->si->normalImage != NULL && CalcTangentVectors( 3, dv, stvStatic, ttvStatic ) )
788         {
789                 stv = stvStatic;
790                 ttv = ttvStatic;
791         }
792         else
793         {
794                 stv = NULL;
795                 ttv = NULL;
796         }
797         
798         VectorCopy( dv[ 0 ]->xyz, worldverts[ 0 ] );
799         VectorCopy( dv[ 1 ]->xyz, worldverts[ 1 ] );
800         VectorCopy( dv[ 2 ]->xyz, worldverts[ 2 ] );
801
802         /* map the vertexes */
803         MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, worldverts );
804         MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, worldverts );
805         MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, worldverts );
806         
807         /* 2002-11-20: prefer axial triangle edges */
808         if( mapNonAxial )
809         {
810                 /* subdivide the triangle */
811                 MapTriangle_r( lm, info, dv, plane, stv, ttv, worldverts );
812                 return qtrue;
813         }
814         
815         for( i = 0; i < 3; i++ )
816         {
817                 float                   *a, *b;
818                 bspDrawVert_t   *dv2[ 3 ];
819                 
820                 
821                 /* get verts */
822                 a = dv[ i ]->lightmap[ 0 ];
823                 b = dv[ (i + 1) % 3 ]->lightmap[ 0 ];
824                 
825                 /* make degenerate triangles for mapping edges */
826                 if( fabs( a[ 0 ] - b[ 0 ] ) < 0.01f || fabs( a[ 1 ] - b[ 1 ] ) < 0.01f )
827                 {
828                         dv2[ 0 ] = dv[ i ];
829                         dv2[ 1 ] = dv[ (i + 1) % 3 ];
830                         dv2[ 2 ] = dv[ (i + 1) % 3 ];
831                         
832                         /* map the degenerate triangle */
833                         MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts );
834                 }
835         }
836         
837         return qtrue;
838 }
839
840
841
842 /*
843 MapQuad_r()
844 recursively subdivides a quad until its edges are shorter
845 than the distance between two luxels
846 */
847
848 static void MapQuad_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ], vec4_t plane, vec3_t stv[ 4 ], vec3_t ttv[ 4 ] )
849 {
850         bspDrawVert_t   mid[ 2 ], *dv2[ 4 ];
851         int                             max;
852         
853         
854         /* subdivide calc */
855         {
856                 int                     i;
857                 float           *a, *b, dx, dy, dist, maxDist;
858                 
859                 
860                 /* find the longest edge and split it */
861                 max = -1;
862                 maxDist = 0;
863                 for( i = 0; i < 4; i++ )
864                 {
865                         /* get verts */
866                         a = dv[ i ]->lightmap[ 0 ];
867                         b = dv[ (i + 1) % 4 ]->lightmap[ 0 ];
868                         
869                         /* get dists */
870                         dx = a[ 0 ] - b[ 0 ];
871                         dy = a[ 1 ] - b[ 1 ];
872                         dist = (dx * dx) + (dy * dy);   //% sqrt( (dx * dx) + (dy * dy) );
873                         
874                         /* longer? */
875                         if( dist > maxDist )
876                         {
877                                 maxDist = dist;
878                                 max = i;
879                         }
880                 }
881                 
882                 /* try to early out */
883                 if( max < 0 || maxDist <= subdivideThreshold )
884                         return;
885         }
886         
887         /* we only care about even/odd edges */
888         max &= 1;
889         
890         /* split the longest edges */
891         LerpDrawVert( dv[ max ], dv[ (max + 1) % 4 ], &mid[ 0 ] );
892         LerpDrawVert( dv[ max + 2 ], dv[ (max + 3) % 4 ], &mid[ 1 ] );
893         
894         /* map the vertexes */
895         MapSingleLuxel( lm, info, &mid[ 0 ], plane, 1, stv, ttv, NULL );
896         MapSingleLuxel( lm, info, &mid[ 1 ], plane, 1, stv, ttv, NULL );
897         
898         /* 0 and 2 */
899         if( max == 0 )
900         {
901                 /* recurse to first quad */
902                 dv2[ 0 ] = dv[ 0 ];
903                 dv2[ 1 ] = &mid[ 0 ];
904                 dv2[ 2 ] = &mid[ 1 ];
905                 dv2[ 3 ] = dv[ 3 ];
906                 MapQuad_r( lm, info, dv2, plane, stv, ttv );
907                 
908                 /* recurse to second quad */
909                 dv2[ 0 ] = &mid[ 0 ];
910                 dv2[ 1 ] = dv[ 1 ];
911                 dv2[ 2 ] = dv[ 2 ];
912                 dv2[ 3 ] = &mid[ 1 ];
913                 MapQuad_r( lm, info, dv2, plane, stv, ttv );
914         }
915         
916         /* 1 and 3 */
917         else
918         {
919                 /* recurse to first quad */
920                 dv2[ 0 ] = dv[ 0 ];
921                 dv2[ 1 ] = dv[ 1 ];
922                 dv2[ 2 ] = &mid[ 0 ];
923                 dv2[ 3 ] = &mid[ 1 ];
924                 MapQuad_r( lm, info, dv2, plane, stv, ttv );
925                 
926                 /* recurse to second quad */
927                 dv2[ 0 ] = &mid[ 1 ];
928                 dv2[ 1 ] = &mid[ 0 ];
929                 dv2[ 2 ] = dv[ 2 ];
930                 dv2[ 3 ] = dv[ 3 ];
931                 MapQuad_r( lm, info, dv2, plane, stv, ttv );
932         }
933 }
934
935
936
937 /*
938 MapQuad()
939 seed function for MapQuad_r()
940 requires a cw ordered triangle quad
941 */
942
943 #define QUAD_PLANAR_EPSILON             0.5f
944
945 static qboolean MapQuad( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ] )
946 {
947         float                   dist;
948         vec4_t                  plane;
949         vec3_t                  *stv, *ttv, stvStatic[ 4 ], ttvStatic[ 4 ];
950         
951         
952         /* get plane if possible */
953         if( lm->plane != NULL )
954         {
955                 VectorCopy( lm->plane, plane );
956                 plane[ 3 ] = lm->plane[ 3 ];
957         }
958         
959         /* otherwise make one from the points */
960         else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse )
961                 return qfalse;
962         
963         /* 4th point must fall on the plane */
964         dist = DotProduct( plane, dv[ 3 ]->xyz ) - plane[ 3 ];
965         if( fabs( dist ) > QUAD_PLANAR_EPSILON )
966                 return qfalse;
967         
968         /* check to see if we need to calculate texture->world tangent vectors */
969         if( info->si->normalImage != NULL && CalcTangentVectors( 4, dv, stvStatic, ttvStatic ) )
970         {
971                 stv = stvStatic;
972                 ttv = ttvStatic;
973         }
974         else
975         {
976                 stv = NULL;
977                 ttv = NULL;
978         }
979         
980         /* map the vertexes */
981         MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, NULL );
982         MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, NULL );
983         MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, NULL );
984         MapSingleLuxel( lm, info, dv[ 3 ], plane, 1, stv, ttv, NULL );
985         
986         /* subdivide the quad */
987         MapQuad_r( lm, info, dv, plane, stv, ttv );
988         return qtrue;
989 }
990
991
992
993 /*
994 MapRawLightmap()
995 maps the locations, normals, and pvs clusters for a raw lightmap
996 */
997
998 #define VectorDivide( in, d, out )      VectorScale( in, (1.0f / (d)), out )    //%     (out)[ 0 ] = (in)[ 0 ] / (d), (out)[ 1 ] = (in)[ 1 ] / (d), (out)[ 2 ] = (in)[ 2 ] / (d)
999
1000 void MapRawLightmap( int rawLightmapNum )
1001 {
1002         int                                     n, num, i, x, y, sx, sy, pw[ 5 ], r, *cluster, mapNonAxial;
1003         float                           *luxel, *origin, *normal, samples, radius, pass;
1004         rawLightmap_t           *lm;
1005         bspDrawSurface_t        *ds;
1006         surfaceInfo_t           *info;
1007         mesh_t                          src, *subdivided, *mesh;
1008         bspDrawVert_t           *verts, *dv[ 4 ], fake;
1009         
1010         
1011         /* bail if this number exceeds the number of raw lightmaps */
1012         if( rawLightmapNum >= numRawLightmaps )
1013                 return;
1014         
1015         /* get lightmap */
1016         lm = &rawLightmaps[ rawLightmapNum ];
1017         
1018         /* -----------------------------------------------------------------
1019            map referenced surfaces onto the raw lightmap
1020            ----------------------------------------------------------------- */
1021         
1022         /* walk the list of surfaces on this raw lightmap */
1023         for( n = 0; n < lm->numLightSurfaces; n++ )
1024         {
1025                 /* with > 1 surface per raw lightmap, clear occluded */
1026                 if( n > 0 )
1027                 {
1028                         for( y = 0; y < lm->sh; y++ )
1029                         {
1030                                 for( x = 0; x < lm->sw; x++ )
1031                                 {
1032                                         /* get cluster */
1033                                         cluster = SUPER_CLUSTER( x, y );
1034                                         if( *cluster < 0 )
1035                                                 *cluster = CLUSTER_UNMAPPED;
1036                                 }
1037                         }
1038                 }
1039                 
1040                 /* get surface */
1041                 num = lightSurfaces[ lm->firstLightSurface + n ];
1042                 ds = &bspDrawSurfaces[ num ];
1043                 info = &surfaceInfos[ num ];
1044                 
1045                 /* bail if no lightmap to calculate */
1046                 if( info->lm != lm )
1047                 {
1048                         Sys_Printf( "!" );
1049                         continue;
1050                 }
1051                 
1052                 /* map the surface onto the lightmap origin/cluster/normal buffers */
1053                 switch( ds->surfaceType )
1054                 {
1055                         case MST_PLANAR:
1056                                 /* get verts */
1057                                 verts = yDrawVerts + ds->firstVert;
1058                                 
1059                                 /* map the triangles */
1060                                 for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ )
1061                                 {
1062                                         for( i = 0; i < ds->numIndexes; i += 3 )
1063                                         {
1064                                                 dv[ 0 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i ] ];
1065                                                 dv[ 1 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 1 ] ];
1066                                                 dv[ 2 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 2 ] ];
1067                                                 MapTriangle( lm, info, dv, mapNonAxial );
1068                                         }
1069                                 }
1070                                 break;
1071                         
1072                         case MST_PATCH:
1073                                 /* make a mesh from the drawsurf */ 
1074                                 src.width = ds->patchWidth;
1075                                 src.height = ds->patchHeight;
1076                                 src.verts = &yDrawVerts[ ds->firstVert ];
1077                                 //%     subdivided = SubdivideMesh( src, 8, 512 );
1078                                 subdivided = SubdivideMesh2( src, info->patchIterations );
1079                                 
1080                                 /* fit it to the curve and remove colinear verts on rows/columns */
1081                                 PutMeshOnCurve( *subdivided );
1082                                 mesh = RemoveLinearMeshColumnsRows( subdivided );
1083                                 FreeMesh( subdivided );
1084                                 
1085                                 /* get verts */
1086                                 verts = mesh->verts;
1087                                 
1088                                 /* debug code */
1089                                 #if 0
1090                                         if( lm->plane )
1091                                         {
1092                                                 Sys_Printf( "Planar patch: [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f]\n",
1093                                                         lm->plane[ 0 ], lm->plane[ 1 ], lm->plane[ 2 ],
1094                                                         lm->vecs[ 0 ][ 0 ], lm->vecs[ 0 ][ 1 ], lm->vecs[ 0 ][ 2 ],
1095                                                         lm->vecs[ 1 ][ 0 ], lm->vecs[ 1 ][ 1 ], lm->vecs[ 1 ][ 2 ] );
1096                                         }
1097                                 #endif
1098                                 
1099                                 /* map the mesh quads */
1100                                 #if 0
1101
1102                                 for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ )
1103                                 {
1104                                         for( y = 0; y < (mesh->height - 1); y++ )
1105                                         {
1106                                                 for( x = 0; x < (mesh->width - 1); x++ )
1107                                                 {
1108                                                         /* set indexes */
1109                                                         pw[ 0 ] = x + (y * mesh->width);
1110                                                         pw[ 1 ] = x + ((y + 1) * mesh->width);
1111                                                         pw[ 2 ] = x + 1 + ((y + 1) * mesh->width);
1112                                                         pw[ 3 ] = x + 1 + (y * mesh->width);
1113                                                         pw[ 4 ] = x + (y * mesh->width);        /* same as pw[ 0 ] */
1114                                                         
1115                                                         /* set radix */
1116                                                         r = (x + y) & 1;
1117                                                         
1118                                                         /* get drawverts and map first triangle */
1119                                                         dv[ 0 ] = &verts[ pw[ r + 0 ] ];
1120                                                         dv[ 1 ] = &verts[ pw[ r + 1 ] ];
1121                                                         dv[ 2 ] = &verts[ pw[ r + 2 ] ];
1122                                                         MapTriangle( lm, info, dv, mapNonAxial );
1123                                                         
1124                                                         /* get drawverts and map second triangle */
1125                                                         dv[ 0 ] = &verts[ pw[ r + 0 ] ];
1126                                                         dv[ 1 ] = &verts[ pw[ r + 2 ] ];
1127                                                         dv[ 2 ] = &verts[ pw[ r + 3 ] ];
1128                                                         MapTriangle( lm, info, dv, mapNonAxial );
1129                                                 }
1130                                         }
1131                                 }
1132                                 
1133                                 #else
1134                                 
1135                                 for( y = 0; y < (mesh->height - 1); y++ )
1136                                 {
1137                                         for( x = 0; x < (mesh->width - 1); x++ )
1138                                         {
1139                                                 /* set indexes */
1140                                                 pw[ 0 ] = x + (y * mesh->width);
1141                                                 pw[ 1 ] = x + ((y + 1) * mesh->width);
1142                                                 pw[ 2 ] = x + 1 + ((y + 1) * mesh->width);
1143                                                 pw[ 3 ] = x + 1 + (y * mesh->width);
1144                                                 pw[ 4 ] = pw[ 0 ];
1145                                                 
1146                                                 /* set radix */
1147                                                 r = (x + y) & 1;
1148                                                 
1149                                                 /* attempt to map quad first */
1150                                                 dv[ 0 ] = &verts[ pw[ r + 0 ] ];
1151                                                 dv[ 1 ] = &verts[ pw[ r + 1 ] ];
1152                                                 dv[ 2 ] = &verts[ pw[ r + 2 ] ];
1153                                                 dv[ 3 ] = &verts[ pw[ r + 3 ] ];
1154                                                 if( MapQuad( lm, info, dv ) )
1155                                                         continue;
1156                                                 
1157                                                 /* get drawverts and map first triangle */
1158                                                 MapTriangle( lm, info, dv, mapNonAxial );
1159                                                 
1160                                                 /* get drawverts and map second triangle */
1161                                                 dv[ 1 ] = &verts[ pw[ r + 2 ] ];
1162                                                 dv[ 2 ] = &verts[ pw[ r + 3 ] ];
1163                                                 MapTriangle( lm, info, dv, mapNonAxial );
1164                                         }
1165                                 }
1166                                 
1167                                 #endif
1168                                 
1169                                 /* free the mesh */
1170                                 FreeMesh( mesh );
1171                                 break;
1172                         
1173                         default:
1174                                 break;
1175                 }
1176         }
1177         
1178         /* -----------------------------------------------------------------
1179            average and clean up luxel normals
1180            ----------------------------------------------------------------- */
1181         
1182         /* walk the luxels */
1183         for( y = 0; y < lm->sh; y++ )
1184         {
1185                 for( x = 0; x < lm->sw; x++ )
1186                 {
1187                         /* get luxel */
1188                         luxel = SUPER_LUXEL( 0, x, y );
1189                         normal = SUPER_NORMAL( x, y );
1190                         cluster = SUPER_CLUSTER( x, y );
1191
1192                         /* only look at mapped luxels */
1193                         if( *cluster < 0 )
1194                                 continue;
1195                         
1196                         /* the normal data could be the sum of multiple samples */
1197                         if( luxel[ 3 ] > 1.0f )
1198                                 VectorNormalize( normal, normal );
1199                         
1200                         /* mark this luxel as having only one normal */
1201                         luxel[ 3 ] = 1.0f;
1202                 }
1203         }
1204         
1205         /* non-planar surfaces stop here */
1206         if( lm->plane == NULL )
1207                 return;
1208         
1209         /* -----------------------------------------------------------------
1210            map occluded or unuxed luxels
1211            ----------------------------------------------------------------- */
1212         
1213         /* walk the luxels */
1214         radius = floor( superSample / 2 );
1215         radius = radius > 0 ? radius : 1.0f;
1216         radius += 1.0f;
1217         for( pass = 2.0f; pass <= radius; pass += 1.0f )
1218         {
1219                 for( y = 0; y < lm->sh; y++ )
1220                 {
1221                         for( x = 0; x < lm->sw; x++ )
1222                         {
1223                                 /* get luxel */
1224                                 luxel = SUPER_LUXEL( 0, x, y );
1225                                 normal = SUPER_NORMAL( x, y );
1226                                 cluster = SUPER_CLUSTER( x, y );
1227                                 
1228                                 /* only look at unmapped luxels */
1229                                 if( *cluster != CLUSTER_UNMAPPED )
1230                                         continue;
1231                                 
1232                                 /* divine a normal and origin from neighboring luxels */
1233                                 VectorClear( fake.xyz );
1234                                 VectorClear( fake.normal );
1235                                 fake.lightmap[ 0 ][ 0 ] = x;    //% 0.0001 + x;
1236                                 fake.lightmap[ 0 ][ 1 ] = y;    //% 0.0001 + y;
1237                                 samples = 0.0f;
1238                                 for( sy = (y - 1); sy <= (y + 1); sy++ )
1239                                 {
1240                                         if( sy < 0 || sy >= lm->sh )
1241                                                 continue;
1242                                         
1243                                         for( sx = (x - 1); sx <= (x + 1); sx++ )
1244                                         {
1245                                                 if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) )
1246                                                         continue;
1247                                                 
1248                                                 /* get neighboring luxel */
1249                                                 luxel = SUPER_LUXEL( 0, sx, sy );
1250                                                 origin = SUPER_ORIGIN( sx, sy );
1251                                                 normal = SUPER_NORMAL( sx, sy );
1252                                                 cluster = SUPER_CLUSTER( sx, sy );
1253                                                 
1254                                                 /* only consider luxels mapped in previous passes */
1255                                                 if( *cluster < 0 || luxel[ 0 ] >= pass )
1256                                                         continue;
1257                                                 
1258                                                 /* add its distinctiveness to our own */
1259                                                 VectorAdd( fake.xyz, origin, fake.xyz );
1260                                                 VectorAdd( fake.normal, normal, fake.normal );
1261                                                 samples += luxel[ 3 ];
1262                                         }
1263                                 }
1264                                 
1265                                 /* any samples? */
1266                                 if( samples == 0.0f )
1267                                         continue;
1268                                 
1269                                 /* average */
1270                                 VectorDivide( fake.xyz, samples, fake.xyz );
1271                                 //%     VectorDivide( fake.normal, samples, fake.normal );
1272                                 if( VectorNormalize( fake.normal, fake.normal ) == 0.0f )
1273                                         continue;
1274                                 
1275                                 /* map the fake vert */
1276                                 MapSingleLuxel( lm, NULL, &fake, lm->plane, pass, NULL, NULL, NULL );
1277                         }
1278                 }
1279         }
1280         
1281         /* -----------------------------------------------------------------
1282            average and clean up luxel normals
1283            ----------------------------------------------------------------- */
1284         
1285         /* walk the luxels */
1286         for( y = 0; y < lm->sh; y++ )
1287         {
1288                 for( x = 0; x < lm->sw; x++ )
1289                 {
1290                         /* get luxel */
1291                         luxel = SUPER_LUXEL( 0, x, y );
1292                         normal = SUPER_NORMAL( x, y );
1293                         cluster = SUPER_CLUSTER( x, y );
1294                         
1295                         /* only look at mapped luxels */
1296                         if( *cluster < 0 )
1297                                 continue;
1298                         
1299                         /* the normal data could be the sum of multiple samples */
1300                         if( luxel[ 3 ] > 1.0f )
1301                                 VectorNormalize( normal, normal );
1302                         
1303                         /* mark this luxel as having only one normal */
1304                         luxel[ 3 ] = 1.0f;
1305                 }
1306         }
1307         
1308         /* debug code */
1309         #if 0
1310                 Sys_Printf( "\n" );
1311                 for( y = 0; y < lm->sh; y++ )
1312                 {
1313                         for( x = 0; x < lm->sw; x++ )
1314                         {
1315                                 vec3_t  mins, maxs;
1316                                 
1317
1318                                 cluster = SUPER_CLUSTER( x, y );
1319                                 origin = SUPER_ORIGIN( x, y );
1320                                 normal = SUPER_NORMAL( x, y );
1321                                 luxel = SUPER_LUXEL( x, y );
1322                                 
1323                                 if( *cluster < 0 )
1324                                         continue;
1325                                 
1326                                 /* check if within the bounding boxes of all surfaces referenced */
1327                                 ClearBounds( mins, maxs );
1328                                 for( n = 0; n < lm->numLightSurfaces; n++ )
1329                                 {
1330                                         int TOL;
1331                                         info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + n ] ];
1332                                         TOL = info->sampleSize + 2;
1333                                         AddPointToBounds( info->mins, mins, maxs );
1334                                         AddPointToBounds( info->maxs, mins, maxs );
1335                                         if( origin[ 0 ] > (info->mins[ 0 ] - TOL) && origin[ 0 ] < (info->maxs[ 0 ] + TOL) &&
1336                                                 origin[ 1 ] > (info->mins[ 1 ] - TOL) && origin[ 1 ] < (info->maxs[ 1 ] + TOL) &&
1337                                                 origin[ 2 ] > (info->mins[ 2 ] - TOL) && origin[ 2 ] < (info->maxs[ 2 ] + TOL) )
1338                                                 break;
1339                                 }
1340                                 
1341                                 /* inside? */
1342                                 if( n < lm->numLightSurfaces )
1343                                         continue;
1344                                 
1345                                 /* report bogus origin */
1346                                 Sys_Printf( "%6d [%2d,%2d] (%4d): XYZ(%+4.1f %+4.1f %+4.1f) LO(%+4.1f %+4.1f %+4.1f) HI(%+4.1f %+4.1f %+4.1f) <%3.0f>\n",
1347                                         rawLightmapNum, x, y, *cluster,
1348                                         origin[ 0 ], origin[ 1 ], origin[ 2 ],
1349                                         mins[ 0 ], mins[ 1 ], mins[ 2 ],
1350                                         maxs[ 0 ], maxs[ 1 ], maxs[ 2 ],
1351                                         luxel[ 3 ] );
1352                         }
1353                 }
1354         #endif
1355 }
1356
1357
1358
1359 /*
1360 SetupDirt()
1361 sets up dirtmap (ambient occlusion)
1362 */
1363
1364 #define DIRT_CONE_ANGLE                         88      /* degrees */
1365 #define DIRT_NUM_ANGLE_STEPS            16
1366 #define DIRT_NUM_ELEVATION_STEPS        3
1367 #define DIRT_NUM_VECTORS                        (DIRT_NUM_ANGLE_STEPS * DIRT_NUM_ELEVATION_STEPS)
1368
1369 static vec3_t           dirtVectors[ DIRT_NUM_VECTORS ];
1370 static int                      numDirtVectors = 0;
1371
1372 void SetupDirt( void )
1373 {
1374         int             i, j;
1375         float   angle, elevation, angleStep, elevationStep;
1376         
1377         
1378         /* note it */
1379         Sys_FPrintf( SYS_VRB, "--- SetupDirt ---\n" );
1380         
1381         /* calculate angular steps */
1382         angleStep = DEG2RAD( 360.0f / DIRT_NUM_ANGLE_STEPS );
1383         elevationStep = DEG2RAD( DIRT_CONE_ANGLE / DIRT_NUM_ELEVATION_STEPS );
1384         
1385         /* iterate angle */
1386         angle = 0.0f;
1387         for( i = 0, angle = 0.0f; i < DIRT_NUM_ANGLE_STEPS; i++, angle += angleStep )
1388         {
1389                 /* iterate elevation */
1390                 for( j = 0, elevation = elevationStep * 0.5f; j < DIRT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep )
1391                 {
1392                         dirtVectors[ numDirtVectors ][ 0 ] = sin( elevation ) * cos( angle );
1393                         dirtVectors[ numDirtVectors ][ 1 ] = sin( elevation ) * sin( angle );
1394                         dirtVectors[ numDirtVectors ][ 2 ] = cos( elevation );
1395                         numDirtVectors++;
1396                 }
1397         }
1398         
1399         /* emit some statistics */
1400         Sys_FPrintf( SYS_VRB, "%9d dirtmap vectors\n", numDirtVectors );
1401 }
1402
1403
1404 /*
1405 DirtForSample()
1406 calculates dirt value for a given sample
1407 */
1408
1409 float DirtForSample( trace_t *trace )
1410 {
1411         int             i;
1412         float   gatherDirt, outDirt, angle, elevation, ooDepth;
1413         vec3_t  normal, worldUp, myUp, myRt, temp, direction, displacement;
1414         
1415         
1416         /* dummy check */
1417         if( !dirty )
1418                 return 1.0f;
1419         if( trace == NULL || trace->cluster < 0 )
1420                 return 0.0f;
1421         
1422         /* setup */
1423         gatherDirt = 0.0f;
1424         ooDepth = 1.0f / dirtDepth;
1425         VectorCopy( trace->normal, normal );
1426         
1427         /* check if the normal is aligned to the world-up */
1428         if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) )
1429         {
1430                 if( normal[ 2 ] == 1.0f )               
1431                 {
1432                         VectorSet( myRt, 1.0f, 0.0f, 0.0f );
1433                         VectorSet( myUp, 0.0f, 1.0f, 0.0f );
1434                 }
1435                 else if( normal[ 2 ] == -1.0f )
1436                 {
1437                         VectorSet( myRt, -1.0f, 0.0f, 0.0f );
1438                         VectorSet( myUp,  0.0f, 1.0f, 0.0f );
1439                 }
1440         }
1441         else
1442         {
1443                 VectorSet( worldUp, 0.0f, 0.0f, 1.0f );
1444                 CrossProduct( normal, worldUp, myRt );
1445                 VectorNormalize( myRt, myRt );
1446                 CrossProduct( myRt, normal, myUp );
1447                 VectorNormalize( myUp, myUp );
1448         }
1449         
1450         /* 1 = random mode, 0 (well everything else) = non-random mode */
1451         if( dirtMode == 1 )
1452         {
1453                 /* iterate */
1454                 for( i = 0; i < numDirtVectors; i++ )
1455                 {
1456                         /* get random vector */
1457                         angle = Random() * DEG2RAD( 360.0f );
1458                         elevation = Random() * DEG2RAD( DIRT_CONE_ANGLE );
1459                         temp[ 0 ] = cos( angle ) * sin( elevation );
1460                         temp[ 1 ] = sin( angle ) * sin( elevation );
1461                         temp[ 2 ] = cos( elevation );
1462                         
1463                         /* transform into tangent space */
1464                         direction[ 0 ] = myRt[ 0 ] * temp[ 0 ] + myUp[ 0 ] * temp[ 1 ] + normal[ 0 ] * temp[ 2 ];
1465                         direction[ 1 ] = myRt[ 1 ] * temp[ 0 ] + myUp[ 1 ] * temp[ 1 ] + normal[ 1 ] * temp[ 2 ];
1466                         direction[ 2 ] = myRt[ 2 ] * temp[ 0 ] + myUp[ 2 ] * temp[ 1 ] + normal[ 2 ] * temp[ 2 ];
1467                         
1468                         /* set endpoint */
1469                         VectorMA( trace->origin, dirtDepth, direction, trace->end );
1470                         SetupTrace( trace );
1471                         
1472                         /* trace */
1473                         TraceLine( trace );
1474                         if( trace->opaque )
1475                         {
1476                                 VectorSubtract( trace->hit, trace->origin, displacement );
1477                                 gatherDirt += 1.0f - ooDepth * VectorLength( displacement );
1478                         }
1479                 }
1480         }
1481         else
1482         {
1483                 /* iterate through ordered vectors */
1484                 for( i = 0; i < numDirtVectors; i++ )
1485                 {
1486                         /* transform vector into tangent space */
1487                         direction[ 0 ] = myRt[ 0 ] * dirtVectors[ i ][ 0 ] + myUp[ 0 ] * dirtVectors[ i ][ 1 ] + normal[ 0 ] * dirtVectors[ i ][ 2 ];
1488                         direction[ 1 ] = myRt[ 1 ] * dirtVectors[ i ][ 0 ] + myUp[ 1 ] * dirtVectors[ i ][ 1 ] + normal[ 1 ] * dirtVectors[ i ][ 2 ];
1489                         direction[ 2 ] = myRt[ 2 ] * dirtVectors[ i ][ 0 ] + myUp[ 2 ] * dirtVectors[ i ][ 1 ] + normal[ 2 ] * dirtVectors[ i ][ 2 ];
1490                         
1491                         /* set endpoint */
1492                         VectorMA( trace->origin, dirtDepth, direction, trace->end );
1493                         SetupTrace( trace );
1494                         
1495                         /* trace */
1496                         TraceLine( trace );
1497                         if( trace->opaque )
1498                         {
1499                                 VectorSubtract( trace->hit, trace->origin, displacement );
1500                                 gatherDirt += 1.0f - ooDepth * VectorLength( displacement );
1501                         }
1502                 }
1503         }
1504         
1505         /* direct ray */
1506         VectorMA( trace->origin, dirtDepth, normal, trace->end );
1507         SetupTrace( trace );
1508         
1509         /* trace */
1510         TraceLine( trace );
1511         if( trace->opaque )
1512         {
1513                 VectorSubtract( trace->hit, trace->origin, displacement );
1514                 gatherDirt += 1.0f - ooDepth * VectorLength( displacement );
1515         }
1516         
1517         /* early out */
1518         if( gatherDirt <= 0.0f )
1519                 return 1.0f;
1520         
1521         /* apply gain (does this even do much? heh) */
1522         outDirt = pow( gatherDirt / (numDirtVectors + 1), dirtGain );
1523         if( outDirt > 1.0f )
1524                 outDirt = 1.0f;
1525         
1526         /* apply scale */
1527         outDirt *= dirtScale;
1528         if( outDirt > 1.0f )
1529                 outDirt = 1.0f;
1530         
1531         /* return to sender */
1532         return 1.0f - outDirt;
1533 }
1534
1535
1536
1537 /*
1538 DirtyRawLightmap()
1539 calculates dirty fraction for each luxel
1540 */
1541
1542 void DirtyRawLightmap( int rawLightmapNum )
1543 {
1544         int                                     i, x, y, sx, sy, *cluster;
1545         float                           *origin, *normal, *dirt, *dirt2, average, samples;
1546         rawLightmap_t           *lm;
1547         surfaceInfo_t           *info;
1548         trace_t                         trace;
1549         qboolean                        noDirty;
1550
1551         
1552         /* bail if this number exceeds the number of raw lightmaps */
1553         if( rawLightmapNum >= numRawLightmaps )
1554                 return;
1555         
1556         /* get lightmap */
1557         lm = &rawLightmaps[ rawLightmapNum ];
1558         
1559         /* setup trace */
1560         trace.testOcclusion = qtrue;
1561         trace.forceSunlight = qfalse;
1562         trace.recvShadows = lm->recvShadows;
1563         trace.numSurfaces = lm->numLightSurfaces;
1564         trace.surfaces = &lightSurfaces[ lm->firstLightSurface ];
1565         trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS;
1566         trace.testAll = qtrue;
1567         
1568         /* twosided lighting (may or may not be a good idea for lightmapped stuff) */
1569         trace.twoSided = qfalse;
1570         for( i = 0; i < trace.numSurfaces; i++ )
1571         {
1572                 /* get surface */
1573                 info = &surfaceInfos[ trace.surfaces[ i ] ];
1574                 
1575                 /* check twosidedness */
1576                 if( info->si->twoSided )
1577                 {
1578                         trace.twoSided = qtrue;
1579                         break;
1580                 }
1581         }
1582
1583         noDirty = qfalse;\r
1584         for( i = 0; i < trace.numSurfaces; i++ )\r
1585         {\r
1586                 /* get surface */\r
1587                 info = &surfaceInfos[ trace.surfaces[ i ] ];\r
1588 \r
1589                 /* check twosidedness */\r
1590                 if( info->si->noDirty )\r
1591                 {\r
1592                         noDirty = qtrue;\r
1593                         break;\r
1594                 }\r
1595         }
1596         
1597         /* gather dirt */
1598         for( y = 0; y < lm->sh; y++ )
1599         {
1600                 for( x = 0; x < lm->sw; x++ )
1601                 {
1602                         /* get luxel */
1603                         cluster = SUPER_CLUSTER( x, y );
1604                         origin = SUPER_ORIGIN( x, y );
1605                         normal = SUPER_NORMAL( x, y );
1606                         dirt = SUPER_DIRT( x, y );
1607                         
1608                         /* set default dirt */
1609                         *dirt = 0.0f;
1610                         
1611                         /* only look at mapped luxels */
1612                         if( *cluster < 0 )
1613                                 continue;
1614
1615                         /* don't apply dirty on this surface */\r
1616                         if( noDirty )\r
1617                         {\r
1618                                 *dirt = 1.0f;\r
1619                                 continue;\r
1620                         }
1621                         
1622                         /* copy to trace */
1623                         trace.cluster = *cluster;
1624                         VectorCopy( origin, trace.origin );
1625                         VectorCopy( normal, trace.normal );
1626                         
1627                         /* get dirt */
1628                         *dirt = DirtForSample( &trace );
1629                 }
1630         }
1631         
1632         /* testing no filtering */
1633         //%     return;
1634         
1635         /* filter dirt */
1636         for( y = 0; y < lm->sh; y++ )
1637         {
1638                 for( x = 0; x < lm->sw; x++ )
1639                 {
1640                         /* get luxel */
1641                         cluster = SUPER_CLUSTER( x, y );
1642                         dirt = SUPER_DIRT( x, y );
1643                         
1644                         /* filter dirt by adjacency to unmapped luxels */
1645                         average = *dirt;
1646                         samples = 1.0f;
1647                         for( sy = (y - 1); sy <= (y + 1); sy++ )
1648                         {
1649                                 if( sy < 0 || sy >= lm->sh )
1650                                         continue;
1651                                 
1652                                 for( sx = (x - 1); sx <= (x + 1); sx++ )
1653                                 {
1654                                         if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) )
1655                                                 continue;
1656                                         
1657                                         /* get neighboring luxel */
1658                                         cluster = SUPER_CLUSTER( sx, sy );
1659                                         dirt2 = SUPER_DIRT( sx, sy );
1660                                         if( *cluster < 0 || *dirt2 <= 0.0f )
1661                                                 continue;
1662                                         
1663                                         /* add it */
1664                                         average += *dirt2;
1665                                         samples += 1.0f;
1666                                 }
1667                                 
1668                                 /* bail */
1669                                 if( samples <= 0.0f )
1670                                         break;
1671                         }
1672                         
1673                         /* bail */
1674                         if( samples <= 0.0f )
1675                                 continue;
1676                         
1677                         /* scale dirt */
1678                         *dirt = average / samples;
1679                 }
1680         }
1681 }
1682
1683
1684
1685 /*
1686 SubmapRawLuxel()
1687 calculates the pvs cluster, origin, normal of a sub-luxel
1688 */
1689
1690 static qboolean SubmapRawLuxel( rawLightmap_t *lm, int x, int y, float bx, float by, int *sampleCluster, vec3_t sampleOrigin, vec3_t sampleNormal )
1691 {
1692         int                     i, *cluster, *cluster2;
1693         float           *origin, *origin2, *normal;     //%     , *normal2;
1694         vec3_t          originVecs[ 2 ];                        //%     , normalVecs[ 2 ];
1695         
1696         
1697         /* calulate x vector */
1698         if( (x < (lm->sw - 1) && bx >= 0.0f) || (x == 0 && bx <= 0.0f) )
1699         {
1700                 cluster = SUPER_CLUSTER( x, y );
1701                 origin = SUPER_ORIGIN( x, y );
1702                 //%     normal = SUPER_NORMAL( x, y );
1703                 cluster2 = SUPER_CLUSTER( x + 1, y );
1704                 origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x + 1, y );
1705                 //%     normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x + 1, y );
1706         }
1707         else if( (x > 0 && bx <= 0.0f) || (x == (lm->sw - 1) && bx >= 0.0f) )
1708         {
1709                 cluster = SUPER_CLUSTER( x - 1, y );
1710                 origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x - 1, y );
1711                 //%     normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x - 1, y );
1712                 cluster2 = SUPER_CLUSTER( x, y );
1713                 origin2 = SUPER_ORIGIN( x, y );
1714                 //%     normal2 = SUPER_NORMAL( x, y );
1715         }
1716         else
1717                 Sys_Printf( "WARNING: Spurious lightmap S vector\n" );
1718         
1719         VectorSubtract( origin2, origin, originVecs[ 0 ] );
1720         //%     VectorSubtract( normal2, normal, normalVecs[ 0 ] );
1721         
1722         /* calulate y vector */
1723         if( (y < (lm->sh - 1) && bx >= 0.0f) || (y == 0 && bx <= 0.0f) )
1724         {
1725                 cluster = SUPER_CLUSTER( x, y );
1726                 origin = SUPER_ORIGIN( x, y );
1727                 //%     normal = SUPER_NORMAL( x, y );
1728                 cluster2 = SUPER_CLUSTER( x, y + 1 );
1729                 origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y + 1 );
1730                 //%     normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y + 1 );
1731         }
1732         else if( (y > 0 && bx <= 0.0f) || (y == (lm->sh - 1) && bx >= 0.0f) )
1733         {
1734                 cluster = SUPER_CLUSTER( x, y - 1 );
1735                 origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y - 1 );
1736                 //%     normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y - 1 );
1737                 cluster2 = SUPER_CLUSTER( x, y );
1738                 origin2 = SUPER_ORIGIN( x, y );
1739                 //%     normal2 = SUPER_NORMAL( x, y );
1740         }
1741         else
1742                 Sys_Printf( "WARNING: Spurious lightmap T vector\n" );
1743         
1744         VectorSubtract( origin2, origin, originVecs[ 1 ] );
1745         //%     VectorSubtract( normal2, normal, normalVecs[ 1 ] );
1746         
1747         /* calculate new origin */
1748         //%     VectorMA( origin, bx, originVecs[ 0 ], sampleOrigin );
1749         //%     VectorMA( sampleOrigin, by, originVecs[ 1 ], sampleOrigin );
1750         for( i = 0; i < 3; i++ )
1751                 sampleOrigin[ i ] = sampleOrigin[ i ] + (bx * originVecs[ 0 ][ i ]) + (by * originVecs[ 1 ][ i ]);
1752         
1753         /* get cluster */
1754         *sampleCluster = ClusterForPointExtFilter( sampleOrigin, (LUXEL_EPSILON * 2), lm->numLightClusters, lm->lightClusters );
1755         if( *sampleCluster < 0 )
1756                 return qfalse;
1757         
1758         /* calculate new normal */
1759         //%     VectorMA( normal, bx, normalVecs[ 0 ], sampleNormal );
1760         //%     VectorMA( sampleNormal, by, normalVecs[ 1 ], sampleNormal );
1761         //%     if( VectorNormalize( sampleNormal, sampleNormal ) <= 0.0f )
1762         //%             return qfalse;
1763         normal = SUPER_NORMAL( x, y );
1764         VectorCopy( normal, sampleNormal );
1765         
1766         /* return ok */
1767         return qtrue;
1768 }
1769
1770
1771 /*
1772 SubsampleRawLuxel_r()
1773 recursively subsamples a luxel until its color gradient is low enough or subsampling limit is reached
1774 */
1775
1776 static void SubsampleRawLuxel_r( rawLightmap_t *lm, trace_t *trace, vec3_t sampleOrigin, int x, int y, float bias, float *lightLuxel )
1777 {
1778         int                     b, samples, mapped, lighted;
1779         int                     cluster[ 4 ];
1780         vec4_t          luxel[ 4 ];
1781         vec3_t          origin[ 4 ], normal[ 4 ];
1782         float           biasDirs[ 4 ][ 2 ] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { -1.0f, 1.0f }, { 1.0f, 1.0f } };
1783         vec3_t          color, total;
1784         
1785         
1786         /* limit check */
1787         if( lightLuxel[ 3 ] >= lightSamples )
1788                 return;
1789         
1790         /* setup */
1791         VectorClear( total );
1792         mapped = 0;
1793         lighted = 0;
1794         
1795         /* make 2x2 subsample stamp */
1796         for( b = 0; b < 4; b++ )
1797         {
1798                 /* set origin */
1799                 VectorCopy( sampleOrigin, origin[ b ] );
1800                 
1801                 /* calculate position */
1802                 if( !SubmapRawLuxel( lm, x, y, (bias * biasDirs[ b ][ 0 ]), (bias * biasDirs[ b ][ 1 ]), &cluster[ b ], origin[ b ], normal[ b ] ) )
1803                 {
1804                         cluster[ b ] = -1;
1805                         continue;
1806                 }
1807                 mapped++;
1808                 
1809                 /* increment sample count */
1810                 luxel[ b ][ 3 ] = lightLuxel[ 3 ] + 1.0f;
1811                 
1812                 /* setup trace */
1813                 trace->cluster = *cluster;
1814                 VectorCopy( origin[ b ], trace->origin );
1815                 VectorCopy( normal[ b ], trace->normal );
1816                 
1817                 /* sample light */
1818
1819                 LightContributionToSample( trace );
1820                 
1821                 /* add to totals (fixme: make contrast function) */
1822                 VectorCopy( trace->color, luxel[ b ] );
1823                 VectorAdd( total, trace->color, total );
1824                 if( (luxel[ b ][ 0 ] + luxel[ b ][ 1 ] + luxel[ b ][ 2 ]) > 0.0f )
1825                         lighted++;
1826         }
1827         
1828         /* subsample further? */
1829         if( (lightLuxel[ 3 ] + 1.0f) < lightSamples &&
1830                 (total[ 0 ] > 4.0f || total[ 1 ] > 4.0f || total[ 2 ] > 4.0f) &&
1831                 lighted != 0 && lighted != mapped )
1832         {
1833                 for( b = 0; b < 4; b++ )
1834                 {
1835                         if( cluster[ b ] < 0 )
1836                                 continue;
1837                         SubsampleRawLuxel_r( lm, trace, origin[ b ], x, y, (bias * 0.25f), luxel[ b ] );
1838                 }
1839         }
1840         
1841         /* average */
1842         //%     VectorClear( color );
1843         //%     samples = 0;
1844         VectorCopy( lightLuxel, color );
1845         samples = 1;
1846         for( b = 0; b < 4; b++ )
1847         {
1848                 if( cluster[ b ] < 0 )
1849                         continue;
1850                 VectorAdd( color, luxel[ b ], color );
1851                 samples++;
1852         }
1853         
1854         /* add to luxel */
1855         if( samples > 0 )
1856         {
1857                 /* average */
1858                 color[ 0 ] /= samples;
1859                 color[ 1 ] /= samples;
1860                 color[ 2 ] /= samples;
1861                 
1862                 /* add to color */
1863                 VectorCopy( color, lightLuxel );
1864                 lightLuxel[ 3 ] += 1.0f;
1865         }
1866 }
1867
1868
1869
1870 /*
1871 IlluminateRawLightmap()
1872 illuminates the luxels
1873 */
1874
1875 #define STACK_LL_SIZE                   (SUPER_LUXEL_SIZE * 64 * 64)
1876 #define LIGHT_LUXEL( x, y )             (lightLuxels + ((((y) * lm->sw) + (x)) * SUPER_LUXEL_SIZE))
1877
1878 void IlluminateRawLightmap( int rawLightmapNum )
1879 {
1880         int                                     i, t, x, y, sx, sy, size, llSize, luxelFilterRadius, lightmapNum;
1881         int                                     *cluster, *cluster2, mapped, lighted, totalLighted;
1882         rawLightmap_t           *lm;
1883         surfaceInfo_t           *info;
1884         qboolean                        filterColor, filterDir;
1885         float                           brightness;
1886         float                           *origin, *normal, *dirt, *luxel, *luxel2, *deluxel, *deluxel2;
1887         float                           *lightLuxels, *lightLuxel, samples, filterRadius, weight;
1888         vec3_t                          color, averageColor, averageDir, total, temp, temp2;
1889         float                           tests[ 4 ][ 2 ] = { { 0.0f, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } };
1890         trace_t                         trace;
1891         float                           stackLightLuxels[ STACK_LL_SIZE ];
1892         
1893         
1894         /* bail if this number exceeds the number of raw lightmaps */
1895         if( rawLightmapNum >= numRawLightmaps )
1896                 return;
1897         
1898         /* get lightmap */
1899         lm = &rawLightmaps[ rawLightmapNum ];
1900         
1901         /* setup trace */
1902         trace.testOcclusion = !noTrace;
1903         trace.forceSunlight = qfalse;
1904         trace.recvShadows = lm->recvShadows;
1905         trace.numSurfaces = lm->numLightSurfaces;
1906         trace.surfaces = &lightSurfaces[ lm->firstLightSurface ];
1907         trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS;
1908         
1909         /* twosided lighting (may or may not be a good idea for lightmapped stuff) */
1910         trace.twoSided = qfalse;
1911         for( i = 0; i < trace.numSurfaces; i++ )
1912         {
1913                 /* get surface */
1914                 info = &surfaceInfos[ trace.surfaces[ i ] ];
1915                 
1916                 /* check twosidedness */
1917                 if( info->si->twoSided )
1918                 {
1919                         trace.twoSided = qtrue;
1920                         break;
1921                 }
1922         }
1923         
1924         /* create a culled light list for this raw lightmap */
1925         CreateTraceLightsForBounds( lm->mins, lm->maxs, lm->plane, lm->numLightClusters, lm->lightClusters, LIGHT_SURFACES, &trace );
1926         
1927         /* -----------------------------------------------------------------
1928            fill pass
1929            ----------------------------------------------------------------- */
1930         
1931         /* set counts */
1932         numLuxelsIlluminated += (lm->sw * lm->sh);
1933         
1934         /* test debugging state */
1935         if( debugSurfaces || debugAxis || debugCluster || debugOrigin || dirtDebug || normalmap )
1936         {
1937                 /* debug fill the luxels */
1938                 for( y = 0; y < lm->sh; y++ )
1939                 {
1940                         for( x = 0; x < lm->sw; x++ )
1941                         {
1942                                 /* get cluster */
1943                                 cluster = SUPER_CLUSTER( x, y );
1944
1945                                 /* only fill mapped luxels */
1946                                 if( *cluster < 0 )
1947                                         continue;
1948                                 
1949                                 /* get particulars */
1950                                 luxel = SUPER_LUXEL( 0, x, y );
1951                                 origin = SUPER_ORIGIN( x, y );
1952                                 normal = SUPER_NORMAL( x, y );
1953                                 
1954                                 /* color the luxel with raw lightmap num? */
1955                                 if( debugSurfaces )
1956                                         VectorCopy( debugColors[ rawLightmapNum % 12 ], luxel );
1957                                 
1958                                 /* color the luxel with lightmap axis? */
1959                                 else if( debugAxis )
1960                                 {
1961                                         luxel[ 0 ] = (lm->axis[ 0 ] + 1.0f) * 127.5f;
1962                                         luxel[ 1 ] = (lm->axis[ 1 ] + 1.0f) * 127.5f;
1963                                         luxel[ 2 ] = (lm->axis[ 2 ] + 1.0f) * 127.5f;
1964                                 }
1965                                 
1966                                 /* color the luxel with luxel cluster? */
1967                                 else if( debugCluster )
1968                                         VectorCopy( debugColors[ *cluster % 12 ], luxel );
1969                                 
1970                                 /* color the luxel with luxel origin? */
1971                                 else if( debugOrigin )
1972                                 {
1973                                         VectorSubtract( lm->maxs, lm->mins, temp );
1974                                         VectorScale( temp, (1.0f / 255.0f), temp );
1975                                         VectorSubtract( origin, lm->mins, temp2 );
1976                                         luxel[ 0 ] = lm->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]);
1977                                         luxel[ 1 ] = lm->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]);
1978                                         luxel[ 2 ] = lm->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]);
1979                                 }
1980                                 
1981                                 /* color the luxel with the normal */
1982                                 else if( normalmap )
1983                                 {
1984                                         luxel[ 0 ] = (normal[ 0 ] + 1.0f) * 127.5f;
1985                                         luxel[ 1 ] = (normal[ 1 ] + 1.0f) * 127.5f;
1986                                         luxel[ 2 ] = (normal[ 2 ] + 1.0f) * 127.5f;
1987                                 }
1988                                 
1989                                 /* otherwise clear it */
1990                                 else
1991                                         VectorClear( luxel );
1992                                 
1993                                 /* add to counts */
1994                                 luxel[ 3 ] = 1.0f;
1995                         }
1996                 }
1997         }
1998         else
1999         {
2000                 /* allocate temporary per-light luxel storage */
2001                 llSize = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float );
2002                 if( llSize <= (STACK_LL_SIZE * sizeof( float )) )
2003                         lightLuxels = stackLightLuxels;
2004                 else
2005                         lightLuxels = safe_malloc( llSize );
2006                 
2007                 /* clear luxels */
2008                 //%     memset( lm->superLuxels[ 0 ], 0, llSize );
2009                 
2010                 /* set ambient color */
2011                 for( y = 0; y < lm->sh; y++ )
2012                 {
2013                         for( x = 0; x < lm->sw; x++ )
2014                         {
2015                                 /* get cluster */
2016                                 cluster = SUPER_CLUSTER( x, y );
2017                                 luxel = SUPER_LUXEL( 0, x, y );
2018                                 normal = SUPER_NORMAL( x, y );
2019                                 deluxel = SUPER_DELUXEL( x, y );
2020                                 
2021                                 /* blacken unmapped clusters */
2022                                 if( *cluster < 0 )
2023                                         VectorClear( luxel );
2024                                 
2025                                 /* set ambient */
2026                                 else
2027                                 {
2028                                         VectorCopy( ambientColor, luxel );
2029                                         if( deluxemap )
2030                                         {
2031                                                 brightness = RGBTOGRAY( ambientColor ) * ( 1.0f/255.0f );
2032
2033                                                 // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light
2034                                                 if(brightness < 0.00390625f)
2035                                                         brightness = 0.00390625f;
2036
2037                                                 VectorScale( normal, brightness, deluxel );
2038                                         }
2039                                         luxel[ 3 ] = 1.0f;
2040                                 }
2041                         }
2042                 }
2043                 
2044                 /* clear styled lightmaps */
2045                 size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float );
2046                 for( lightmapNum = 1; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2047                 {
2048                         if( lm->superLuxels[ lightmapNum ] != NULL )
2049                                 memset( lm->superLuxels[ lightmapNum ], 0, size );
2050                 }
2051                 
2052                 /* debugging code */
2053                 //%     if( trace.numLights <= 0 )
2054                 //%             Sys_Printf( "Lightmap %9d: 0 lights, axis: %.2f, %.2f, %.2f\n", rawLightmapNum, lm->axis[ 0 ], lm->axis[ 1 ], lm->axis[ 2 ] );
2055                 
2056                 /* walk light list */
2057                 for( i = 0; i < trace.numLights; i++ )
2058                 {
2059                         /* setup trace */
2060                         trace.light = trace.lights[ i ];
2061                         
2062                         /* style check */
2063                         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2064                         {
2065                                 if( lm->styles[ lightmapNum ] == trace.light->style ||
2066                                         lm->styles[ lightmapNum ] == LS_NONE )
2067                                         break;
2068                         }
2069                         
2070                         /* max of MAX_LIGHTMAPS (4) styles allowed to hit a surface/lightmap */
2071                         if( lightmapNum >= MAX_LIGHTMAPS )
2072                         {
2073                                 Sys_Printf( "WARNING: Hit per-surface style limit (%d)\n", MAX_LIGHTMAPS );
2074                                 continue;
2075                         }
2076                         
2077                         /* setup */
2078                         memset( lightLuxels, 0, llSize );
2079                         totalLighted = 0;
2080                         
2081                         /* initial pass, one sample per luxel */
2082                         for( y = 0; y < lm->sh; y++ )
2083                         {
2084                                 for( x = 0; x < lm->sw; x++ )
2085                                 {
2086                                         /* get cluster */
2087                                         cluster = SUPER_CLUSTER( x, y );
2088                                         if( *cluster < 0 )
2089                                                 continue;
2090                                         
2091                                         /* get particulars */
2092                                         lightLuxel = LIGHT_LUXEL( x, y );
2093                                         deluxel = SUPER_DELUXEL( x, y );
2094                                         origin = SUPER_ORIGIN( x, y );
2095                                         normal = SUPER_NORMAL( x, y );
2096
2097 #if 0
2098                                         ////////// 27's temp hack for testing edge clipping ////
2099                                         if( origin[0]==0 && origin[1]==0 && origin[2]==0 )
2100                                         {
2101                                                 lightLuxel[ 1 ] = 255;
2102                                                 lightLuxel[ 3 ] = 1.0f;
2103                                                 totalLighted++;
2104                                         }
2105                                         else
2106 #endif
2107                                         {
2108                                                 /* set contribution count */
2109                                                 lightLuxel[ 3 ] = 1.0f;
2110
2111                                                 /* setup trace */
2112                                                 trace.cluster = *cluster;
2113                                                 VectorCopy( origin, trace.origin );
2114                                                 VectorCopy( normal, trace.normal );
2115
2116                                                 /* get light for this sample */
2117                                                 LightContributionToSample( &trace );
2118                                                 VectorCopy( trace.color, lightLuxel );
2119
2120                                                 /* add the contribution to the deluxemap */\r
2121                                                 if( deluxemap )\r
2122                                                         VectorAdd( deluxel, trace.directionContribution, deluxel );
2123
2124                                                 /* add to count */
2125                                                 if( trace.color[ 0 ] || trace.color[ 1 ] || trace.color[ 2 ] )
2126                                                         totalLighted++;
2127                                         }
2128                                 }
2129                         }
2130                         
2131                         /* don't even bother with everything else if nothing was lit */
2132                         if( totalLighted == 0 )
2133                                 continue;
2134                         
2135                         /* determine filter radius */
2136                         filterRadius = lm->filterRadius > trace.light->filterRadius
2137                                 ? lm->filterRadius
2138                                 : trace.light->filterRadius;
2139                         if( filterRadius < 0.0f )
2140                                 filterRadius = 0.0f;
2141                         
2142                         /* set luxel filter radius */
2143                         luxelFilterRadius = superSample * filterRadius / lm->sampleSize;
2144                         if( luxelFilterRadius == 0 && (filterRadius > 0.0f || filter) )
2145                                 luxelFilterRadius = 1;
2146                         
2147                         /* secondary pass, adaptive supersampling (fixme: use a contrast function to determine if subsampling is necessary) */
2148                         /* 2003-09-27: changed it so filtering disamples supersampling, as it would waste time */
2149                         if( lightSamples > 1 && luxelFilterRadius == 0 )
2150                         {
2151                                 /* walk luxels */
2152                                 for( y = 0; y < (lm->sh - 1); y++ )
2153                                 {
2154                                         for( x = 0; x < (lm->sw - 1); x++ )
2155                                         {
2156                                                 /* setup */
2157                                                 mapped = 0;
2158                                                 lighted = 0;
2159                                                 VectorClear( total );
2160                                                 
2161                                                 /* test 2x2 stamp */
2162                                                 for( t = 0; t < 4; t++ )
2163                                                 {
2164                                                         /* set sample coords */
2165                                                         sx = x + tests[ t ][ 0 ];
2166                                                         sy = y + tests[ t ][ 1 ];
2167                                                         
2168                                                         /* get cluster */
2169                                                         cluster = SUPER_CLUSTER( sx, sy );
2170                                                         if( *cluster < 0 )
2171                                                                 continue;
2172                                                         mapped++;
2173                                                         
2174                                                         /* get luxel */
2175                                                         lightLuxel = LIGHT_LUXEL( sx, sy );
2176                                                         VectorAdd( total, lightLuxel, total );
2177                                                         if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) > 0.0f )
2178                                                                 lighted++;
2179                                                 }
2180                                                 
2181                                                 /* if total color is under a certain amount, then don't bother subsampling */
2182                                                 if( total[ 0 ] <= 4.0f && total[ 1 ] <= 4.0f && total[ 2 ] <= 4.0f )
2183                                                         continue;
2184                                                 
2185                                                 /* if all 4 pixels are either in shadow or light, then don't subsample */
2186                                                 if( lighted != 0 && lighted != mapped )
2187                                                 {
2188                                                         for( t = 0; t < 4; t++ )
2189                                                         {
2190                                                                 /* set sample coords */
2191                                                                 sx = x + tests[ t ][ 0 ];
2192                                                                 sy = y + tests[ t ][ 1 ];
2193                                                                 
2194                                                                 /* get luxel */
2195                                                                 cluster = SUPER_CLUSTER( sx, sy );
2196                                                                 if( *cluster < 0 )
2197                                                                         continue;
2198                                                                 lightLuxel = LIGHT_LUXEL( sx, sy );
2199                                                                 origin = SUPER_ORIGIN( sx, sy );
2200                                                                 
2201                                                                 /* only subsample shadowed luxels */
2202                                                                 //%     if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) <= 0.0f )
2203                                                                 //%             continue;
2204                                                                 
2205                                                                 /* subsample it */
2206                                                                 SubsampleRawLuxel_r( lm, &trace, origin, sx, sy, 0.25f, lightLuxel );
2207                                                                 
2208                                                                 /* debug code to colorize subsampled areas to yellow */
2209                                                                 //%     luxel = SUPER_LUXEL( lightmapNum, sx, sy );
2210                                                                 //%     VectorSet( luxel, 255, 204, 0 );
2211                                                         }
2212                                                 }
2213                                         }
2214                                 }
2215                         }
2216                         
2217                         /* tertiary pass, apply dirt map (ambient occlusion) */
2218                         if( 0 && dirty )
2219                         {
2220                                 /* walk luxels */
2221                                 for( y = 0; y < lm->sh; y++ )
2222                                 {
2223                                         for( x = 0; x < lm->sw; x++ )
2224                                         {
2225                                                 /* get cluster  */
2226                                                 cluster = SUPER_CLUSTER( x, y );
2227                                                 if( *cluster < 0 )
2228                                                         continue;
2229                                                 
2230                                                 /* get particulars */
2231                                                 lightLuxel = LIGHT_LUXEL( x, y );
2232                                                 dirt = SUPER_DIRT( x, y );
2233                                                 
2234                                                 /* scale light value */
2235                                                 VectorScale( lightLuxel, *dirt, lightLuxel );
2236                                         }
2237                                 }
2238                         }
2239                         
2240                         /* allocate sampling lightmap storage */
2241                         if( lm->superLuxels[ lightmapNum ] == NULL )
2242                         {
2243                                 /* allocate sampling lightmap storage */
2244                                 size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float );
2245                                 lm->superLuxels[ lightmapNum ] = safe_malloc( size );
2246                                 memset( lm->superLuxels[ lightmapNum ], 0, size );
2247                         }
2248                         
2249                         /* set style */
2250                         if( lightmapNum > 0 )
2251                         {
2252                                 lm->styles[ lightmapNum ] = trace.light->style;
2253                                 //%     Sys_Printf( "Surface %6d has lightstyle %d\n", rawLightmapNum, trace.light->style );
2254                         }
2255                         
2256                         /* copy to permanent luxels */
2257                         for( y = 0; y < lm->sh; y++ )
2258                         {
2259                                 for( x = 0; x < lm->sw; x++ )
2260                                 {
2261                                         /* get cluster and origin */
2262                                         cluster = SUPER_CLUSTER( x, y );
2263                                         if( *cluster < 0 )
2264                                                 continue;
2265                                         origin = SUPER_ORIGIN( x, y );
2266                                         
2267                                         /* filter? */
2268                                         if( luxelFilterRadius )
2269                                         {
2270                                                 /* setup */
2271                                                 VectorClear( averageColor );
2272                                                 samples = 0.0f;
2273                                                 
2274                                                 /* cheaper distance-based filtering */
2275                                                 for( sy = (y - luxelFilterRadius); sy <= (y + luxelFilterRadius); sy++ )
2276                                                 {
2277                                                         if( sy < 0 || sy >= lm->sh )
2278                                                                 continue;
2279                                                         
2280                                                         for( sx = (x - luxelFilterRadius); sx <= (x + luxelFilterRadius); sx++ )
2281                                                         {
2282                                                                 if( sx < 0 || sx >= lm->sw )
2283                                                                         continue;
2284                                                                 
2285                                                                 /* get particulars */
2286                                                                 cluster = SUPER_CLUSTER( sx, sy );
2287                                                                 if( *cluster < 0 )
2288                                                                         continue;
2289                                                                 lightLuxel = LIGHT_LUXEL( sx, sy );
2290                                                                 
2291                                                                 /* create weight */
2292                                                                 weight = (abs( sx - x ) == luxelFilterRadius ? 0.5f : 1.0f);
2293                                                                 weight *= (abs( sy - y ) == luxelFilterRadius ? 0.5f : 1.0f);
2294                                                                 
2295                                                                 /* scale luxel by filter weight */
2296                                                                 VectorScale( lightLuxel, weight, color );
2297                                                                 VectorAdd( averageColor, color, averageColor );
2298                                                                 samples += weight;
2299                                                         }
2300                                                 }
2301                                                 
2302                                                 /* any samples? */
2303                                                 if( samples <= 0.0f     )
2304                                                         continue;
2305                                                 
2306                                                 /* scale into luxel */
2307                                                 luxel = SUPER_LUXEL( lightmapNum, x, y );
2308                                                 luxel[ 3 ] = 1.0f;
2309                                                 
2310                                                 /* handle negative light */
2311                                                 if( trace.light->flags & LIGHT_NEGATIVE )
2312                                                 { 
2313                                                         luxel[ 0 ] -= averageColor[ 0 ] / samples;
2314                                                         luxel[ 1 ] -= averageColor[ 1 ] / samples;
2315                                                         luxel[ 2 ] -= averageColor[ 2 ] / samples;
2316                                                 }
2317                                                 
2318                                                 /* handle normal light */
2319                                                 else
2320                                                 { 
2321                                                         luxel[ 0 ] += averageColor[ 0 ] / samples;
2322                                                         luxel[ 1 ] += averageColor[ 1 ] / samples;
2323                                                         luxel[ 2 ] += averageColor[ 2 ] / samples;
2324                                                 }
2325                                         }
2326                                         
2327                                         /* single sample */
2328                                         else
2329                                         {
2330                                                 /* get particulars */
2331                                                 lightLuxel = LIGHT_LUXEL( x, y );
2332                                                 luxel = SUPER_LUXEL( lightmapNum, x, y );
2333                                                 
2334                                                 /* handle negative light */
2335                                                 if( trace.light->flags & LIGHT_NEGATIVE )
2336                                                         VectorScale( averageColor, -1.0f, averageColor );
2337
2338                                                 /* add color */
2339                                                 luxel[ 3 ] = 1.0f;
2340                                                 
2341                                                 /* handle negative light */
2342                                                 if( trace.light->flags & LIGHT_NEGATIVE )
2343                                                         VectorSubtract( luxel, lightLuxel, luxel );
2344                                                 
2345                                                 /* handle normal light */
2346                                                 else
2347                                                         VectorAdd( luxel, lightLuxel, luxel );
2348                                         }
2349                                 }
2350                         }
2351                 }
2352                 
2353                 /* free temporary luxels */
2354                 if( lightLuxels != stackLightLuxels )
2355                         free( lightLuxels );
2356         }
2357         
2358         /* free light list */
2359         FreeTraceLights( &trace );
2360         
2361         /* floodlight pass */
2362         FloodlightIlluminateLightmap(lm);
2363
2364         if (debugnormals)
2365         {
2366                 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2367                 {
2368                         /* early out */
2369                         if( lm->superLuxels[ lightmapNum ] == NULL )
2370                                 continue;
2371                         
2372                         for( y = 0; y < lm->sh; y++ )
2373                         {
2374                                 for( x = 0; x < lm->sw; x++ )
2375                                 {
2376                                         /* get cluster */
2377                                         cluster = SUPER_CLUSTER( x, y );
2378                                         //%     if( *cluster < 0 )
2379                                         //%             continue;
2380                                         
2381                                         /* get particulars */
2382                                         luxel = SUPER_LUXEL( lightmapNum, x, y );
2383                                         normal = SUPER_NORMAL (  x, y );
2384                
2385                                         luxel[0]=(normal[0]*127)+127;
2386                                         luxel[1]=(normal[1]*127)+127;
2387                                         luxel[2]=(normal[2]*127)+127;
2388                                 }
2389                         }
2390                 }
2391         }
2392         
2393         /*      -----------------------------------------------------------------
2394                 dirt pass
2395                 ----------------------------------------------------------------- */
2396         
2397         if( dirty )
2398         {
2399                 /* walk lightmaps */
2400                 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2401                 {
2402                         /* early out */
2403                         if( lm->superLuxels[ lightmapNum ] == NULL )
2404                                 continue;
2405                         
2406                         /* apply dirt to each luxel */
2407                         for( y = 0; y < lm->sh; y++ )
2408                         {
2409                                 for( x = 0; x < lm->sw; x++ )
2410                                 {
2411                                         /* get cluster */
2412                                         cluster = SUPER_CLUSTER( x, y );
2413                                         //%     if( *cluster < 0 ) // TODO why not do this check? These pixels should be zero anyway
2414                                         //%             continue;
2415                                         
2416                                         /* get particulars */
2417                                         luxel = SUPER_LUXEL( lightmapNum, x, y );
2418                                         dirt = SUPER_DIRT( x, y );
2419                                         
2420                                         /* apply dirt */
2421                                         VectorScale( luxel, *dirt, luxel );
2422                                         
2423                                         /* debugging */
2424                                         if( dirtDebug )
2425                                                 VectorSet( luxel, *dirt * 255.0f, *dirt * 255.0f, *dirt * 255.0f );
2426                                 }
2427                         }
2428                 }
2429         }
2430         
2431         /* -----------------------------------------------------------------
2432            filter pass
2433            ----------------------------------------------------------------- */
2434         
2435         /* walk lightmaps */
2436         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2437         {
2438                 /* early out */
2439                 if( lm->superLuxels[ lightmapNum ] == NULL )
2440                         continue;
2441                 
2442                 /* average occluded luxels from neighbors */
2443                 for( y = 0; y < lm->sh; y++ )
2444                 {
2445                         for( x = 0; x < lm->sw; x++ )
2446                         {
2447                                 /* get particulars */
2448                                 cluster = SUPER_CLUSTER( x, y );
2449                                 luxel = SUPER_LUXEL( lightmapNum, x, y );
2450                                 deluxel = SUPER_DELUXEL( x, y );
2451                                 normal = SUPER_NORMAL( x, y );
2452                                 
2453                                 /* determine if filtering is necessary */
2454                                 filterColor = qfalse;
2455                                 filterDir = qfalse;
2456                                 if( *cluster < 0 ||
2457                                         (lm->splotchFix && (luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ])) )
2458                                         filterColor = qtrue;
2459
2460                                 if( deluxemap && lightmapNum == 0 && (*cluster < 0 || filter) )
2461                                         filterDir = qtrue;
2462                                 
2463                                 if( !filterColor && !filterDir )
2464                                         continue;
2465                                 
2466                                 /* choose seed amount */
2467                                 VectorClear( averageColor );
2468                                 VectorClear( averageDir );
2469                                 samples = 0.0f;
2470                                 
2471                                 /* walk 3x3 matrix */
2472                                 for( sy = (y - 1); sy <= (y + 1); sy++ )
2473                                 {
2474                                         if( sy < 0 || sy >= lm->sh )
2475                                                 continue;
2476                                         
2477                                         for( sx = (x - 1); sx <= (x + 1); sx++ )
2478                                         {
2479                                                 if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) )
2480                                                         continue;
2481                                                 
2482                                                 /* get neighbor's particulars */
2483                                                 cluster2 = SUPER_CLUSTER( sx, sy );
2484                                                 luxel2 = SUPER_LUXEL( lightmapNum, sx, sy );
2485                                                 deluxel2 = SUPER_DELUXEL( sx, sy );
2486                                                 
2487                                                 /* ignore unmapped/unlit luxels */
2488                                                 if( *cluster2 < 0 || luxel2[ 3 ] == 0.0f ||
2489                                                         (lm->splotchFix && VectorCompare( luxel2, ambientColor )) )
2490                                                         continue;
2491                                                 
2492                                                 /* add its distinctiveness to our own */
2493                                                 VectorAdd( averageColor, luxel2, averageColor );
2494                                                 samples += luxel2[ 3 ];
2495                                                 if( filterDir )
2496                                                         VectorAdd( averageDir, deluxel2, averageDir );
2497                                         }
2498                                 }
2499                                 
2500                                 /* fall through */
2501                                 if( samples <= 0.0f )
2502                                         continue;
2503                                 
2504                                 /* dark lightmap seams */
2505                                 if( dark )
2506                                 {
2507                                         if( lightmapNum == 0 )
2508                                                 VectorMA( averageColor, 2.0f, ambientColor, averageColor );
2509                                         samples += 2.0f;
2510                                 }
2511                                 
2512                                 /* average it */
2513                                 if( filterColor )
2514                                 {
2515                                         VectorDivide( averageColor, samples, luxel );
2516                                         luxel[ 3 ] = 1.0f;
2517                                 }
2518                                 if( filterDir )
2519                                         VectorDivide( averageDir, samples, deluxel );
2520                                 
2521                                 /* set cluster to -3 */
2522                                 if( *cluster < 0 )
2523                                         *cluster = CLUSTER_FLOODED;
2524                         }
2525                 }
2526         }
2527
2528
2529 #if 0
2530         // audit pass
2531         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2532         {
2533                 /* early out */
2534                 if( lm->superLuxels[ lightmapNum ] == NULL )
2535                         continue;
2536                 for( y = 0; y < lm->sh; y++ )
2537                         for( x = 0; x < lm->sw; x++ )
2538                         {
2539                                 /* get cluster */
2540                                 cluster = SUPER_CLUSTER( x, y );
2541                                 luxel = SUPER_LUXEL( lightmapNum, x, y );
2542                                 deluxel = SUPER_DELUXEL( x, y );
2543                                 if(!luxel || !deluxel || !cluster)
2544                                 {
2545                                         Sys_FPrintf(SYS_VRB, "WARNING: I got NULL'd.\n");
2546                                         continue;
2547                                 }
2548                                 else if(*cluster < 0)
2549                                 {
2550                                         // unmapped pixel
2551                                         // should have neither deluxemap nor lightmap
2552                                         if(deluxel[3])
2553                                                 Sys_FPrintf(SYS_VRB, "WARNING: I have written deluxe to an unmapped luxel. Sorry.\n");
2554                                 }
2555                                 else
2556                                 {
2557                                         // mapped pixel
2558                                         // should have both deluxemap and lightmap
2559                                         if(deluxel[3])
2560                                                 Sys_FPrintf(SYS_VRB, "WARNING: I forgot to write deluxe to a mapped luxel. Sorry.\n");
2561                                 }
2562                         }
2563         }
2564 #endif
2565 }
2566
2567
2568
2569 /*
2570 IlluminateVertexes()
2571 light the surface vertexes
2572 */
2573
2574 #define VERTEX_NUDGE    4.0f
2575
2576 void IlluminateVertexes( int num )
2577 {
2578         int                                     i, x, y, z, x1, y1, z1, sx, sy, radius, maxRadius, *cluster;
2579         int                                     lightmapNum, numAvg;
2580         float                           samples, *vertLuxel, *radVertLuxel, *luxel, dirt;
2581         vec3_t                          origin, temp, temp2, colors[ MAX_LIGHTMAPS ], avgColors[ MAX_LIGHTMAPS ];
2582         bspDrawSurface_t        *ds;
2583         surfaceInfo_t           *info;
2584         rawLightmap_t           *lm;
2585         bspDrawVert_t           *verts;
2586         trace_t                         trace;
2587         
2588         
2589         /* get surface, info, and raw lightmap */
2590         ds = &bspDrawSurfaces[ num ];
2591         info = &surfaceInfos[ num ];
2592         lm = info->lm;
2593         
2594         /* -----------------------------------------------------------------
2595            illuminate the vertexes
2596            ----------------------------------------------------------------- */
2597         
2598         /* calculate vertex lighting for surfaces without lightmaps */
2599         if( lm == NULL || cpmaHack )
2600         {
2601                 /* setup trace */
2602                 trace.testOcclusion = (cpmaHack && lm != NULL) ? qfalse : !noTrace;
2603                 trace.forceSunlight = info->si->forceSunlight;
2604                 trace.recvShadows = info->recvShadows;
2605                 trace.numSurfaces = 1;
2606                 trace.surfaces = &num;
2607                 trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS;
2608                 
2609                 /* twosided lighting */
2610                 trace.twoSided = info->si->twoSided;
2611                 
2612                 /* make light list for this surface */
2613                 CreateTraceLightsForSurface( num, &trace );
2614                 
2615                 /* setup */
2616                 verts = yDrawVerts + ds->firstVert;
2617                 numAvg = 0;
2618                 memset( avgColors, 0, sizeof( avgColors ) );
2619                 
2620                 /* walk the surface verts */
2621                 for( i = 0; i < ds->numVerts; i++ )
2622                 {
2623                         /* get vertex luxel */
2624                         radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i );
2625                         
2626                         /* color the luxel with raw lightmap num? */
2627                         if( debugSurfaces )
2628                                 VectorCopy( debugColors[ num % 12 ], radVertLuxel );
2629                         
2630                         /* color the luxel with luxel origin? */
2631                         else if( debugOrigin )
2632                         {
2633                                 VectorSubtract( info->maxs, info->mins, temp );
2634                                 VectorScale( temp, (1.0f / 255.0f), temp );
2635                                 VectorSubtract( origin, lm->mins, temp2 );
2636                                 radVertLuxel[ 0 ] = info->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]);
2637                                 radVertLuxel[ 1 ] = info->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]);
2638                                 radVertLuxel[ 2 ] = info->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]);
2639                         }
2640                         
2641                         /* color the luxel with the normal */
2642                         else if( normalmap )
2643                         {
2644                                 radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f;
2645                                 radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f;
2646                                 radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f;
2647                         }
2648                         
2649                         /* illuminate the vertex */
2650                         else
2651                         {
2652                                 /* clear vertex luxel */
2653                                 VectorSet( radVertLuxel, -1.0f, -1.0f, -1.0f );
2654                                 
2655                                 /* try at initial origin */
2656                                 trace.cluster = ClusterForPointExtFilter( verts[ i ].xyz, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] );
2657                                 if( trace.cluster >= 0 )
2658                                 {
2659                                         /* setup trace */
2660                                         VectorCopy( verts[ i ].xyz, trace.origin );
2661                                         VectorCopy( verts[ i ].normal, trace.normal );
2662                                         
2663                                         /* r7 dirt */
2664                                         if( dirty )
2665                                                 dirt = DirtForSample( &trace );
2666                                         else
2667                                                 dirt = 1.0f;
2668
2669                                         /* trace */
2670                                         LightingAtSample( &trace, ds->vertexStyles, colors );
2671                                         
2672                                         /* store */
2673                                         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2674                                         {
2675                                                 /* r7 dirt */
2676                                                 VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] );
2677                                                 
2678                                                 /* store */
2679                                                 radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2680                                                 VectorCopy( colors[ lightmapNum ], radVertLuxel );
2681                                                 VectorAdd( avgColors[ lightmapNum ], colors[ lightmapNum ], colors[ lightmapNum ] );
2682                                         }
2683                                 }
2684                                 
2685                                 /* is this sample bright enough? */
2686                                 radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i );
2687                                 if( radVertLuxel[ 0 ] <= ambientColor[ 0 ] &&
2688                                         radVertLuxel[ 1 ] <= ambientColor[ 1 ] &&
2689                                         radVertLuxel[ 2 ] <= ambientColor[ 2 ] )
2690                                 {
2691                                         /* nudge the sample point around a bit */
2692                                         for( x = 0; x < 4; x++ )
2693                                         {
2694                                                 /* two's complement 0, 1, -1, 2, -2, etc */
2695                                                 x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1);
2696                                                 
2697                                                 for( y = 0; y < 4; y++ )
2698                                                 {
2699                                                         y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1);
2700                                                         
2701                                                         for( z = 0; z < 4; z++ )
2702                                                         {
2703                                                                 z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1);
2704                                                                 
2705                                                                 /* nudge origin */
2706                                                                 trace.origin[ 0 ] = verts[ i ].xyz[ 0 ] + (VERTEX_NUDGE * x1);
2707                                                                 trace.origin[ 1 ] = verts[ i ].xyz[ 1 ] + (VERTEX_NUDGE * y1);
2708                                                                 trace.origin[ 2 ] = verts[ i ].xyz[ 2 ] + (VERTEX_NUDGE * z1);
2709                                                                 
2710                                                                 /* try at nudged origin */
2711                                                                 trace.cluster = ClusterForPointExtFilter( origin, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] );
2712                                                                 if( trace.cluster < 0 )
2713                                                                         continue;
2714                                                                                                                         
2715                                                                 /* trace */
2716                                                                 LightingAtSample( &trace, ds->vertexStyles, colors );
2717                                                                 
2718                                                                 /* store */
2719                                                                 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2720                                                                 {
2721                                                                         /* r7 dirt */
2722                                                                         VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] );
2723                                                                         
2724                                                                         /* store */
2725                                                                         radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2726                                                                         VectorCopy( colors[ lightmapNum ], radVertLuxel );
2727                                                                 }
2728                                                                 
2729                                                                 /* bright enough? */
2730                                                                 radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i );
2731                                                                 if( radVertLuxel[ 0 ] > ambientColor[ 0 ] ||
2732                                                                         radVertLuxel[ 1 ] > ambientColor[ 1 ] ||
2733                                                                         radVertLuxel[ 2 ] > ambientColor[ 2 ] )
2734                                                                         x = y = z = 1000;
2735                                                         }
2736                                                 }
2737                                         }
2738                                 }
2739                                 
2740                                 /* add to average? */
2741                                 radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i );
2742                                 if( radVertLuxel[ 0 ] > ambientColor[ 0 ] ||
2743                                         radVertLuxel[ 1 ] > ambientColor[ 1 ] ||
2744                                         radVertLuxel[ 2 ] > ambientColor[ 2 ] )
2745                                 {
2746                                         numAvg++;
2747                                         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2748                                         {
2749                                                 radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2750                                                 VectorAdd( avgColors[ lightmapNum ], radVertLuxel, avgColors[ lightmapNum ] );
2751                                         }
2752                                 }
2753                         }
2754                         
2755                         /* another happy customer */
2756                         numVertsIlluminated++;
2757                 }
2758                 
2759                 /* set average color */
2760                 if( numAvg > 0 )
2761                 {
2762                         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2763                                 VectorScale( avgColors[ lightmapNum ], (1.0f / numAvg), avgColors[ lightmapNum ] );
2764                 }
2765                 else
2766                 {
2767                         VectorCopy( ambientColor, avgColors[ 0 ] );
2768                 }
2769                 
2770                 /* clean up and store vertex color */
2771                 for( i = 0; i < ds->numVerts; i++ )
2772                 {
2773                         /* get vertex luxel */
2774                         radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i );
2775                         
2776                         /* store average in occluded vertexes */
2777                         if( radVertLuxel[ 0 ] < 0.0f )
2778                         {
2779                                 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2780                                 {
2781                                         radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2782                                         VectorCopy( avgColors[ lightmapNum ], radVertLuxel );
2783                                         
2784                                         /* debug code */
2785                                         //%     VectorSet( radVertLuxel, 255.0f, 0.0f, 0.0f );
2786                                 }
2787                         }
2788                         
2789                         /* store it */
2790                         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2791                         {
2792                                 /* get luxels */
2793                                 vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2794                                 radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2795                                 
2796                                 /* store */
2797                                 if( bouncing || bounce == 0 || !bounceOnly )
2798                                         VectorAdd( vertLuxel, radVertLuxel, vertLuxel );
2799                                 if( !info->si->noVertexLight )
2800                                         ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], info->si->vertexScale );
2801                         }
2802                 }
2803                 
2804                 /* free light list */
2805                 FreeTraceLights( &trace );
2806                 
2807                 /* return to sender */
2808                 return;
2809         }
2810         
2811         /* -----------------------------------------------------------------
2812            reconstitute vertex lighting from the luxels
2813            ----------------------------------------------------------------- */
2814         
2815         /* set styles from lightmap */
2816         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2817                 ds->vertexStyles[ lightmapNum ] = lm->styles[ lightmapNum ];
2818         
2819         /* get max search radius */
2820         maxRadius = lm->sw;
2821         maxRadius = maxRadius > lm->sh ? maxRadius : lm->sh;
2822         
2823         /* walk the surface verts */
2824         verts = yDrawVerts + ds->firstVert;
2825         for( i = 0; i < ds->numVerts; i++ )
2826         {
2827                 /* do each lightmap */
2828                 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
2829                 {
2830                         /* early out */
2831                         if( lm->superLuxels[ lightmapNum ] == NULL )
2832                                 continue;
2833                         
2834                         /* get luxel coords */
2835                         x = verts[ i ].lightmap[ lightmapNum ][ 0 ];
2836                         y = verts[ i ].lightmap[ lightmapNum ][ 1 ];
2837                         if( x < 0 )
2838                                 x = 0;
2839                         else if( x >= lm->sw )
2840                                 x = lm->sw - 1;
2841                         if( y < 0 )
2842                                 y = 0;
2843                         else if( y >= lm->sh )
2844                                 y = lm->sh - 1;
2845                         
2846                         /* get vertex luxels */
2847                         vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2848                         radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i );
2849                         
2850                         /* color the luxel with the normal? */
2851                         if( normalmap )
2852                         {
2853                                 radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f;
2854                                 radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f;
2855                                 radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f;
2856                         }
2857                         
2858                         /* color the luxel with surface num? */
2859                         else if( debugSurfaces )
2860                                 VectorCopy( debugColors[ num % 12 ], radVertLuxel );
2861                         
2862                         /* divine color from the superluxels */
2863                         else
2864                         {
2865                                 /* increasing radius */
2866                                 VectorClear( radVertLuxel );
2867                                 samples = 0.0f;
2868                                 for( radius = 0; radius < maxRadius && samples <= 0.0f; radius++ )
2869                                 {
2870                                         /* sample within radius */
2871                                         for( sy = (y - radius); sy <= (y + radius); sy++ )
2872                                         {
2873                                                 if( sy < 0 || sy >= lm->sh )
2874                                                         continue;
2875                                                 
2876                                                 for( sx = (x - radius); sx <= (x + radius); sx++ )
2877                                                 {
2878                                                         if( sx < 0 || sx >= lm->sw )
2879                                                                 continue;
2880                                                         
2881                                                         /* get luxel particulars */
2882                                                         luxel = SUPER_LUXEL( lightmapNum, sx, sy );
2883                                                         cluster = SUPER_CLUSTER( sx, sy );
2884                                                         if( *cluster < 0 )
2885                                                                 continue;
2886                                                         
2887                                                         /* testing: must be brigher than ambient color */
2888                                                         //%     if( luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ] )
2889                                                         //%             continue;
2890                                                         
2891                                                         /* add its distinctiveness to our own */
2892                                                         VectorAdd( radVertLuxel, luxel, radVertLuxel );
2893                                                         samples += luxel[ 3 ];
2894                                                 }
2895                                         }
2896                                 }
2897                                 
2898                                 /* any color? */
2899                                 if( samples > 0.0f )
2900                                         VectorDivide( radVertLuxel, samples, radVertLuxel );
2901                                 else
2902                                         VectorCopy( ambientColor, radVertLuxel );
2903                         }
2904                         
2905                         /* store into floating point storage */
2906                         VectorAdd( vertLuxel, radVertLuxel, vertLuxel );
2907                         numVertsIlluminated++;
2908                         
2909                         /* store into bytes (for vertex approximation) */
2910                         if( !info->si->noVertexLight )
2911                                 ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], 1.0f );
2912                 }
2913         }
2914 }
2915
2916
2917
2918 /* -------------------------------------------------------------------------------
2919
2920 light optimization (-fast)
2921
2922 creates a list of lights that will affect a surface and stores it in tw
2923 this is to optimize surface lighting by culling out as many of the
2924 lights in the world as possible from further calculation
2925
2926 ------------------------------------------------------------------------------- */
2927
2928 /*
2929 SetupBrushes()
2930 determines opaque brushes in the world and find sky shaders for sunlight calculations
2931 */
2932
2933 void SetupBrushes( void )
2934 {
2935         int                             i, j, b, compileFlags;
2936         qboolean                inside;
2937         bspBrush_t              *brush;
2938         bspBrushSide_t  *side;
2939         bspShader_t             *shader;
2940         shaderInfo_t    *si;
2941         
2942         
2943         /* note it */
2944         Sys_FPrintf( SYS_VRB, "--- SetupBrushes ---\n" );
2945         
2946         /* allocate */
2947         if( opaqueBrushes == NULL )
2948                 opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 );
2949         
2950         /* clear */
2951         memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 );
2952         numOpaqueBrushes = 0;
2953         
2954         /* walk the list of worldspawn brushes */
2955         for( i = 0; i < bspModels[ 0 ].numBSPBrushes; i++ )
2956         {
2957                 /* get brush */
2958                 b = bspModels[ 0 ].firstBSPBrush + i;
2959                 brush = &bspBrushes[ b ];
2960                 
2961                 /* check all sides */
2962                 inside = qtrue;
2963                 compileFlags = 0;
2964                 for( j = 0; j < brush->numSides && inside; j++ )
2965                 {
2966                         /* do bsp shader calculations */
2967                         side = &bspBrushSides[ brush->firstSide + j ];
2968                         shader = &bspShaders[ side->shaderNum ];
2969                         
2970                         /* get shader info */
2971                         si = ShaderInfoForShader( shader->shader );
2972                         if( si == NULL )
2973                                 continue;
2974                         
2975                         /* or together compile flags */
2976                         compileFlags |= si->compileFlags;
2977                 }
2978                 
2979                 /* determine if this brush is opaque to light */
2980                 if( !(compileFlags & C_TRANSLUCENT) )
2981                 {
2982                         opaqueBrushes[ b >> 3 ] |= (1 << (b & 7));
2983                         numOpaqueBrushes++;
2984                         maxOpaqueBrush = i;
2985                 }
2986         }
2987         
2988         /* emit some statistics */
2989         Sys_FPrintf( SYS_VRB, "%9d opaque brushes\n", numOpaqueBrushes );
2990 }
2991
2992
2993
2994 /*
2995 ClusterVisible()
2996 determines if two clusters are visible to each other using the PVS
2997 */
2998
2999 qboolean ClusterVisible( int a, int b )
3000 {
3001         int                     portalClusters, leafBytes;
3002         byte            *pvs;
3003         
3004         
3005         /* dummy check */
3006         if( a < 0 || b < 0 )
3007                 return qfalse;
3008         
3009         /* early out */
3010         if( a == b )
3011                 return qtrue;
3012         
3013         /* not vised? */
3014         if( numBSPVisBytes <=8 )
3015                 return qtrue;
3016         
3017         /* get pvs data */
3018         portalClusters = ((int *) bspVisBytes)[ 0 ];
3019         leafBytes = ((int*) bspVisBytes)[ 1 ];
3020         pvs = bspVisBytes + VIS_HEADER_SIZE + (a * leafBytes);
3021         
3022         /* check */
3023         if( (pvs[ b >> 3 ] & (1 << (b & 7))) )
3024                 return qtrue;
3025         return qfalse;
3026 }
3027
3028
3029
3030 /*
3031 PointInLeafNum_r()
3032 borrowed from vlight.c
3033 */
3034
3035 int     PointInLeafNum_r( vec3_t point, int nodenum )
3036 {
3037         int                     leafnum;
3038         vec_t           dist;
3039         bspNode_t               *node;
3040         bspPlane_t      *plane;
3041         
3042         
3043         while( nodenum >= 0 )
3044         {
3045                 node = &bspNodes[ nodenum ];
3046                 plane = &bspPlanes[ node->planeNum ];
3047                 dist = DotProduct( point, plane->normal ) - plane->dist;
3048                 if( dist > 0.1 )
3049                         nodenum = node->children[ 0 ];
3050                 else if( dist < -0.1 )
3051                         nodenum = node->children[ 1 ];
3052                 else
3053                 {
3054                         leafnum = PointInLeafNum_r( point, node->children[ 0 ] );
3055                         if( bspLeafs[ leafnum ].cluster != -1 )
3056                                 return leafnum;
3057                         nodenum = node->children[ 1 ];
3058                 }
3059         }
3060         
3061         leafnum = -nodenum - 1;
3062         return leafnum;
3063 }
3064
3065
3066
3067 /*
3068 PointInLeafnum()
3069 borrowed from vlight.c
3070 */
3071
3072 int     PointInLeafNum( vec3_t point )
3073 {
3074         return PointInLeafNum_r( point, 0 );
3075 }
3076
3077
3078
3079 /*
3080 ClusterVisibleToPoint() - ydnar
3081 returns qtrue if point can "see" cluster
3082 */
3083
3084 qboolean ClusterVisibleToPoint( vec3_t point, int cluster )
3085 {
3086         int             pointCluster;
3087         
3088
3089         /* get leafNum for point */
3090         pointCluster = ClusterForPoint( point );
3091         if( pointCluster < 0 )
3092                 return qfalse;
3093         
3094         /* check pvs */
3095         return ClusterVisible( pointCluster, cluster );
3096 }
3097
3098
3099
3100 /*
3101 ClusterForPoint() - ydnar
3102 returns the pvs cluster for point
3103 */
3104
3105 int ClusterForPoint( vec3_t point )
3106 {
3107         int             leafNum;
3108         
3109
3110         /* get leafNum for point */
3111         leafNum = PointInLeafNum( point );
3112         if( leafNum < 0 )
3113                 return -1;
3114         
3115         /* return the cluster */
3116         return bspLeafs[ leafNum ].cluster;
3117 }
3118
3119
3120
3121 /*
3122 ClusterForPointExt() - ydnar
3123 also takes brushes into account for occlusion testing
3124 */
3125
3126 int ClusterForPointExt( vec3_t point, float epsilon )
3127 {
3128         int                             i, j, b, leafNum, cluster;
3129         float                   dot;
3130         qboolean                inside;
3131         int                             *brushes, numBSPBrushes;
3132         bspLeaf_t               *leaf;
3133         bspBrush_t              *brush;
3134         bspPlane_t              *plane;
3135         
3136         
3137         /* get leaf for point */
3138         leafNum = PointInLeafNum( point );
3139         if( leafNum < 0 )
3140                 return -1;
3141         leaf = &bspLeafs[ leafNum ];
3142         
3143         /* get the cluster */
3144         cluster = leaf->cluster;
3145         if( cluster < 0 )
3146                 return -1;
3147         
3148         /* transparent leaf, so check point against all brushes in the leaf */
3149         brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ];
3150         numBSPBrushes = leaf->numBSPLeafBrushes;
3151         for( i = 0; i < numBSPBrushes; i++ )
3152         {
3153                 /* get parts */
3154                 b = brushes[ i ];
3155                 if( b > maxOpaqueBrush )
3156                         continue;
3157                 brush = &bspBrushes[ b ];
3158                 if( !(opaqueBrushes[ b >> 3 ] & (1 << (b & 7))) )
3159                         continue;
3160                 
3161                 /* check point against all planes */
3162                 inside = qtrue;
3163                 for( j = 0; j < brush->numSides && inside; j++ )
3164                 {
3165                         plane = &bspPlanes[ bspBrushSides[ brush->firstSide + j ].planeNum ];
3166                         dot = DotProduct( point, plane->normal );
3167                         dot -= plane->dist;
3168                         if( dot > epsilon )
3169                                 inside = qfalse;
3170                 }
3171                 
3172                 /* if inside, return bogus cluster */
3173                 if( inside )
3174                         return -1 - b;
3175         }
3176         
3177         /* if the point made it this far, it's not inside any opaque brushes */
3178         return cluster;
3179 }
3180
3181
3182
3183 /*
3184 ClusterForPointExtFilter() - ydnar
3185 adds cluster checking against a list of known valid clusters
3186 */
3187
3188 int ClusterForPointExtFilter( vec3_t point, float epsilon, int numClusters, int *clusters )
3189 {
3190         int             i, cluster;
3191         
3192         
3193         /* get cluster for point */
3194         cluster = ClusterForPointExt( point, epsilon );
3195         
3196         /* check if filtering is necessary */
3197         if( cluster < 0 || numClusters <= 0 || clusters == NULL )
3198                 return cluster;
3199         
3200         /* filter */
3201         for( i = 0; i < numClusters; i++ )
3202         {
3203                 if( cluster == clusters[ i ] || ClusterVisible( cluster, clusters[ i ] ) )
3204                         return cluster;
3205         }
3206         
3207         /* failed */
3208         return -1;
3209 }
3210
3211
3212
3213 /*
3214 ShaderForPointInLeaf() - ydnar
3215 checks a point against all brushes in a leaf, returning the shader of the brush
3216 also sets the cumulative surface and content flags for the brush hit
3217 */
3218
3219 int ShaderForPointInLeaf( vec3_t point, int leafNum, float epsilon, int wantContentFlags, int wantSurfaceFlags, int *contentFlags, int *surfaceFlags )
3220 {
3221         int                             i, j;
3222         float                   dot;
3223         qboolean                inside;
3224         int                             *brushes, numBSPBrushes;
3225         bspLeaf_t                       *leaf;
3226         bspBrush_t              *brush;
3227         bspBrushSide_t  *side;
3228         bspPlane_t              *plane;
3229         bspShader_t             *shader;
3230         int                             allSurfaceFlags, allContentFlags;
3231
3232         
3233         /* clear things out first */
3234         *surfaceFlags = 0;
3235         *contentFlags = 0;
3236         
3237         /* get leaf */
3238         if( leafNum < 0 )
3239                 return -1;
3240         leaf = &bspLeafs[ leafNum ];
3241         
3242         /* transparent leaf, so check point against all brushes in the leaf */
3243         brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ];
3244         numBSPBrushes = leaf->numBSPLeafBrushes;
3245         for( i = 0; i < numBSPBrushes; i++ )
3246         {
3247                 /* get parts */
3248                 brush = &bspBrushes[ brushes[ i ] ];
3249                 
3250                 /* check point against all planes */
3251                 inside = qtrue;
3252                 allSurfaceFlags = 0;
3253                 allContentFlags = 0;
3254                 for( j = 0; j < brush->numSides && inside; j++ )
3255                 {
3256                         side = &bspBrushSides[ brush->firstSide + j ];
3257                         plane = &bspPlanes[ side->planeNum ];
3258                         dot = DotProduct( point, plane->normal );
3259                         dot -= plane->dist;
3260                         if( dot > epsilon )
3261                                 inside = qfalse;
3262                         else
3263                         {
3264                                 shader = &bspShaders[ side->shaderNum ];
3265                                 allSurfaceFlags |= shader->surfaceFlags;
3266                                 allContentFlags |= shader->contentFlags;
3267                         }
3268                 }
3269                 
3270                 /* handle if inside */
3271                 if( inside )
3272                 {
3273                         /* if there are desired flags, check for same and continue if they aren't matched */
3274                         if( wantContentFlags && !(wantContentFlags & allContentFlags) )
3275                                 continue;
3276                         if( wantSurfaceFlags && !(wantSurfaceFlags & allSurfaceFlags) )
3277                                 continue;
3278                         
3279                         /* store the cumulative flags and return the brush shader (which is mostly useless) */
3280                         *surfaceFlags = allSurfaceFlags;
3281                         *contentFlags = allContentFlags;
3282                         return brush->shaderNum;
3283                 }
3284         }
3285         
3286         /* if the point made it this far, it's not inside any brushes */
3287         return -1;
3288 }
3289
3290
3291
3292 /*
3293 ChopBounds()
3294 chops a bounding box by the plane defined by origin and normal
3295 returns qfalse if the bounds is entirely clipped away
3296
3297 this is not exactly the fastest way to do this...
3298 */
3299
3300 qboolean ChopBounds( vec3_t mins, vec3_t maxs, vec3_t origin, vec3_t normal )
3301 {
3302         /* FIXME: rewrite this so it doesn't use bloody brushes */
3303         return qtrue;
3304 }
3305
3306
3307
3308 /*
3309 SetupEnvelopes()
3310 calculates each light's effective envelope,
3311 taking into account brightness, type, and pvs.
3312 */
3313
3314 #define LIGHT_EPSILON   0.125f
3315 #define LIGHT_NUDGE             2.0f
3316
3317 void SetupEnvelopes( qboolean forGrid, qboolean fastFlag )
3318 {
3319         int                     i, x, y, z, x1, y1, z1;
3320         light_t         *light, *light2, **owner;
3321         bspLeaf_t       *leaf;
3322         vec3_t          origin, dir, mins, maxs, nullVector = { 0, 0, 0 };
3323         float           radius, intensity;
3324         light_t         *buckets[ 256 ];
3325         
3326         
3327         /* early out for weird cases where there are no lights */
3328         if( lights == NULL )
3329                 return;
3330         
3331         /* note it */
3332         Sys_FPrintf( SYS_VRB, "--- SetupEnvelopes%s ---\n", fastFlag ? " (fast)" : "" );
3333         
3334         /* count lights */
3335         numLights = 0;
3336         numCulledLights = 0;
3337         owner = &lights;
3338         while( *owner != NULL )
3339         {
3340                 /* get light */
3341                 light = *owner;
3342                 
3343                 /* handle negative lights */
3344                 if( light->photons < 0.0f || light->add < 0.0f )
3345                 {
3346                         light->photons *= -1.0f;
3347                         light->add *= -1.0f;
3348                         light->flags |= LIGHT_NEGATIVE;
3349                 }
3350                 
3351                 /* sunlight? */
3352                 if( light->type == EMIT_SUN )
3353                 {
3354                         /* special cased */
3355                         light->cluster = 0;
3356                         light->envelope = MAX_WORLD_COORD * 8.0f;
3357                         VectorSet( light->mins, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f );
3358                         VectorSet( light->maxs, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f );
3359                 }
3360                 
3361                 /* everything else */
3362                 else
3363                 {
3364                         /* get pvs cluster for light */
3365                         light->cluster = ClusterForPointExt( light->origin, LIGHT_EPSILON );
3366                         
3367                         /* invalid cluster? */
3368                         if( light->cluster < 0 )
3369                         {
3370                                 /* nudge the sample point around a bit */
3371                                 for( x = 0; x < 4; x++ )
3372                                 {
3373                                         /* two's complement 0, 1, -1, 2, -2, etc */
3374                                         x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1);
3375                                         
3376                                         for( y = 0; y < 4; y++ )
3377                                         {
3378                                                 y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1);
3379                                                 
3380                                                 for( z = 0; z < 4; z++ )
3381                                                 {
3382                                                         z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1);
3383                                                         
3384                                                         /* nudge origin */
3385                                                         origin[ 0 ] = light->origin[ 0 ] + (LIGHT_NUDGE * x1);
3386                                                         origin[ 1 ] = light->origin[ 1 ] + (LIGHT_NUDGE * y1);
3387                                                         origin[ 2 ] = light->origin[ 2 ] + (LIGHT_NUDGE * z1);
3388                                                         
3389                                                         /* try at nudged origin */
3390                                                         light->cluster = ClusterForPointExt( origin, LIGHT_EPSILON );
3391                                                         if( light->cluster < 0 )
3392                                                                 continue;
3393                                                                         
3394                                                         /* set origin */
3395                                                         VectorCopy( origin, light->origin );
3396                                                 }
3397                                         }
3398                                 }
3399                         }
3400                         
3401                         /* only calculate for lights in pvs and outside of opaque brushes */
3402                         if( light->cluster >= 0 )
3403                         {
3404                                 /* set light fast flag */
3405                                 if( fastFlag )
3406                                         light->flags |= LIGHT_FAST_TEMP;
3407                                 else
3408                                         light->flags &= ~LIGHT_FAST_TEMP;
3409                                 if( light->si && light->si->noFast )
3410                                         light->flags &= ~(LIGHT_FAST | LIGHT_FAST_TEMP);
3411                                 
3412                                 /* clear light envelope */
3413                                 light->envelope = 0;
3414                                 
3415                                 /* handle area lights */
3416                                 if( exactPointToPolygon && light->type == EMIT_AREA && light->w != NULL )
3417                                 {
3418                                         /* ugly hack to calculate extent for area lights, but only done once */
3419                                         VectorScale( light->normal, -1.0f, dir );
3420                                         for( radius = 100.0f; radius < 130000.0f && light->envelope == 0; radius += 10.0f )
3421                                         {
3422                                                 float   factor;
3423                                                 
3424                                                 VectorMA( light->origin, radius, light->normal, origin );
3425                                                 factor = PointToPolygonFormFactor( origin, dir, light->w );
3426                                                 if( factor < 0.0f )
3427                                                         factor *= -1.0f;
3428                                                 if( (factor * light->add) <= light->falloffTolerance )
3429                                                         light->envelope = radius;
3430                                         }
3431                                         
3432                                         /* check for fast mode */
3433                                         if( !(light->flags & LIGHT_FAST) && !(light->flags & LIGHT_FAST_TEMP) )
3434                                                 light->envelope = MAX_WORLD_COORD * 8.0f;
3435                                 }
3436                                 else
3437                                 {
3438                                         radius = 0.0f;
3439                                         intensity = light->photons;
3440                                 }
3441                                 
3442                                 /* other calcs */
3443                                 if( light->envelope <= 0.0f )
3444                                 {
3445                                         /* solve distance for non-distance lights */
3446                                         if( !(light->flags & LIGHT_ATTEN_DISTANCE) )
3447                                                 light->envelope = MAX_WORLD_COORD * 8.0f;
3448                                         
3449                                         /* solve distance for linear lights */
3450                                         else if( (light->flags & LIGHT_ATTEN_LINEAR ) )
3451                                                 //% light->envelope = ((intensity / light->falloffTolerance) * linearScale - 1 + radius) / light->fade;
3452                                                 light->envelope = ((intensity * linearScale) - light->falloffTolerance) / light->fade;
3453
3454                                                 /*
3455                                                 add = angle * light->photons * linearScale - (dist * light->fade);
3456                                                 T = (light->photons * linearScale) - (dist * light->fade);
3457                                                 T + (dist * light->fade) = (light->photons * linearScale);
3458                                                 dist * light->fade = (light->photons * linearScale) - T;
3459                                                 dist = ((light->photons * linearScale) - T) / light->fade;
3460                                                 */
3461                                         
3462                                         /* solve for inverse square falloff */
3463                                         else
3464                                                 light->envelope = sqrt( intensity / light->falloffTolerance ) + radius;
3465                                                 
3466                                                 /*
3467                                                 add = light->photons / (dist * dist);
3468                                                 T = light->photons / (dist * dist);
3469                                                 T * (dist * dist) = light->photons;
3470                                                 dist = sqrt( light->photons / T );
3471                                                 */
3472                                 }
3473                                 
3474                                 /* chop radius against pvs */
3475                                 {
3476                                         /* clear bounds */
3477                                         ClearBounds( mins, maxs );
3478                                         
3479                                         /* check all leaves */
3480                                         for( i = 0; i < numBSPLeafs; i++ )
3481                                         {
3482                                                 /* get test leaf */
3483                                                 leaf = &bspLeafs[ i ];
3484                                                 
3485                                                 /* in pvs? */
3486                                                 if( leaf->cluster < 0 )
3487                                                         continue;
3488                                                 if( ClusterVisible( light->cluster, leaf->cluster ) == qfalse ) /* ydnar: thanks Arnout for exposing my stupid error (this never failed before) */
3489                                                         continue;
3490                                                 
3491                                                 /* add this leafs bbox to the bounds */
3492                                                 VectorCopy( leaf->mins, origin );
3493                                                 AddPointToBounds( origin, mins, maxs );
3494                                                 VectorCopy( leaf->maxs, origin );
3495                                                 AddPointToBounds( origin, mins, maxs );
3496                                         }
3497                                         
3498                                         /* test to see if bounds encompass light */
3499                                         for( i = 0; i < 3; i++ )
3500                                         {
3501                                                 if( mins[ i ] > light->origin[ i ] || maxs[ i ] < light->origin[ i ] )
3502                                                 {
3503                                                         //% Sys_Printf( "WARNING: Light PVS bounds (%.0f, %.0f, %.0f) -> (%.0f, %.0f, %.0f)\ndo not encompass light %d (%f, %f, %f)\n",
3504                                                         //%     mins[ 0 ], mins[ 1 ], mins[ 2 ],
3505                                                         //%     maxs[ 0 ], maxs[ 1 ], maxs[ 2 ],
3506                                                         //%     numLights, light->origin[ 0 ], light->origin[ 1 ], light->origin[ 2 ] );
3507                                                         AddPointToBounds( light->origin, mins, maxs );
3508                                                 }
3509                                         }
3510                                         
3511                                         /* chop the bounds by a plane for area lights and spotlights */
3512                                         if( light->type == EMIT_AREA || light->type == EMIT_SPOT )
3513                                                 ChopBounds( mins, maxs, light->origin, light->normal );
3514                                         
3515                                         /* copy bounds */
3516                                         VectorCopy( mins, light->mins );
3517                                         VectorCopy( maxs, light->maxs );
3518                                         
3519                                         /* reflect bounds around light origin */
3520                                         //%     VectorMA( light->origin, -1.0f, origin, origin );
3521                                         VectorScale( light->origin, 2, origin );
3522                                         VectorSubtract( origin, maxs, origin );
3523                                         AddPointToBounds( origin, mins, maxs );
3524                                         //%     VectorMA( light->origin, -1.0f, mins, origin );
3525                                         VectorScale( light->origin, 2, origin );
3526                                         VectorSubtract( origin, mins, origin );
3527                                         AddPointToBounds( origin, mins, maxs );
3528                                          
3529                                         /* calculate spherical bounds */
3530                                         VectorSubtract( maxs, light->origin, dir );
3531                                         radius = (float) VectorLength( dir );
3532                                         
3533                                         /* if this radius is smaller than the envelope, then set the envelope to it */
3534                                         if( radius < light->envelope )
3535                                         {
3536                                                 light->envelope = radius;
3537                                                 //%     Sys_FPrintf( SYS_VRB, "PVS Cull (%d): culled\n", numLights );
3538                                         }
3539                                         //%     else
3540                                         //%             Sys_FPrintf( SYS_VRB, "PVS Cull (%d): failed (%8.0f > %8.0f)\n", numLights, radius, light->envelope );
3541                                 }
3542                                 
3543                                 /* add grid/surface only check */
3544                                 if( forGrid )
3545                                 {
3546                                         if( !(light->flags & LIGHT_GRID) )
3547                                                 light->envelope = 0.0f;
3548                                 }
3549                                 else
3550                                 {
3551                                         if( !(light->flags & LIGHT_SURFACES) )
3552                                                 light->envelope = 0.0f;
3553                                 }
3554                         }
3555                         
3556                         /* culled? */
3557                         if( light->cluster < 0 || light->envelope <= 0.0f )
3558                         {
3559                                 /* debug code */
3560                                 //%     Sys_Printf( "Culling light: Cluster: %d Envelope: %f\n", light->cluster, light->envelope );
3561                                 
3562                                 /* delete the light */
3563                                 numCulledLights++;
3564                                 *owner = light->next;
3565                                 if( light->w != NULL )
3566                                         free( light->w );
3567                                 free( light );
3568                                 continue;
3569                         }
3570                 }
3571                 
3572                 /* square envelope */
3573                 light->envelope2 = (light->envelope * light->envelope);
3574                 
3575                 /* increment light count */
3576                 numLights++;
3577                 
3578                 /* set next light */
3579                 owner = &((**owner).next);
3580         }
3581         
3582         /* bucket sort lights by style */
3583         memset( buckets, 0, sizeof( buckets ) );
3584         light2 = NULL;
3585         for( light = lights; light != NULL; light = light2 )
3586         {
3587                 /* get next light */
3588                 light2 = light->next;
3589                 
3590                 /* filter into correct bucket */
3591                 light->next = buckets[ light->style ];
3592                 buckets[ light->style ] = light;
3593                 
3594                 /* if any styled light is present, automatically set nocollapse */
3595                 if( light->style != LS_NORMAL )
3596                         noCollapse = qtrue;
3597         }
3598         
3599         /* filter back into light list */
3600         lights = NULL;
3601         for( i = 255; i >= 0; i-- )
3602         {
3603                 light2 = NULL;
3604                 for( light = buckets[ i ]; light != NULL; light = light2 )
3605                 {
3606                         light2 = light->next;
3607                         light->next = lights;
3608                         lights = light;
3609                 }
3610         }
3611         
3612         /* emit some statistics */
3613         Sys_Printf( "%9d total lights\n", numLights );
3614         Sys_Printf( "%9d culled lights\n", numCulledLights );
3615 }
3616
3617
3618
3619 /*
3620 CreateTraceLightsForBounds()
3621 creates a list of lights that affect the given bounding box and pvs clusters (bsp leaves)
3622 */
3623
3624 void CreateTraceLightsForBounds( vec3_t mins, vec3_t maxs, vec3_t normal, int numClusters, int *clusters, int flags, trace_t *trace )
3625 {
3626         int                     i;
3627         light_t         *light;
3628         vec3_t          origin, dir, nullVector = { 0.0f, 0.0f, 0.0f };
3629         float           radius, dist, length;
3630         
3631         
3632         /* potential pre-setup  */
3633         if( numLights == 0 )
3634                 SetupEnvelopes( qfalse, fast );
3635         
3636         /* debug code */
3637         //% Sys_Printf( "CTWLFB: (%4.1f %4.1f %4.1f) (%4.1f %4.1f %4.1f)\n", mins[ 0 ], mins[ 1 ], mins[ 2 ], maxs[ 0 ], maxs[ 1 ], maxs[ 2 ] );
3638         
3639         /* allocate the light list */
3640         trace->lights = safe_malloc( sizeof( light_t* ) * (numLights + 1) );
3641         trace->numLights = 0;
3642         
3643         /* calculate spherical bounds */
3644         VectorAdd( mins, maxs, origin );
3645         VectorScale( origin, 0.5f, origin );
3646         VectorSubtract( maxs, origin, dir );
3647         radius = (float) VectorLength( dir );
3648         
3649         /* get length of normal vector */
3650         if( normal != NULL )
3651                 length = VectorLength( normal );
3652         else
3653         {
3654                 normal = nullVector;
3655                 length = 0;
3656         }
3657         
3658         /* test each light and see if it reaches the sphere */
3659         /* note: the attenuation code MUST match LightingAtSample() */
3660         for( light = lights; light; light = light->next )
3661         {
3662                 /* check zero sized envelope */
3663                 if( light->envelope <= 0 )
3664                 {
3665                         lightsEnvelopeCulled++;
3666                         continue;
3667                 }
3668                 
3669                 /* check flags */
3670                 if( !(light->flags & flags) )
3671                         continue;
3672                 
3673                 /* sunlight skips all this nonsense */
3674                 if( light->type != EMIT_SUN )
3675                 {
3676                         /* sun only? */
3677                         if( sunOnly )
3678                                 continue;
3679                         
3680                         /* check against pvs cluster */
3681                         if( numClusters > 0 && clusters != NULL )
3682                         {
3683                                 for( i = 0; i < numClusters; i++ )
3684                                 {
3685                                         if( ClusterVisible( light->cluster, clusters[ i ] ) )
3686                                                 break;
3687                                 }
3688                                 
3689                                 /* fixme! */
3690                                 if( i == numClusters )
3691                                 {
3692                                         lightsClusterCulled++;
3693                                         continue;
3694                                 }
3695                         }
3696                         
3697                         /* if the light's bounding sphere intersects with the bounding sphere then this light needs to be tested */
3698                         VectorSubtract( light->origin, origin, dir );
3699                         dist = VectorLength( dir );
3700                         dist -= light->envelope;
3701                         dist -= radius;
3702                         if( dist > 0 )
3703                         {
3704                                 lightsEnvelopeCulled++;
3705                                 continue;
3706                         }
3707                         
3708                         /* check bounding box against light's pvs envelope (note: this code never eliminated any lights, so disabling it) */
3709                         #if 0
3710                         skip = qfalse;
3711                         for( i = 0; i < 3; i++ )
3712                         {
3713                                 if( mins[ i ] > light->maxs[ i ] || maxs[ i ] < light->mins[ i ] )
3714                                         skip = qtrue;
3715                         }
3716                         if( skip )
3717                         {
3718                                 lightsBoundsCulled++;
3719                                 continue;
3720                         }
3721                         #endif
3722                 }
3723                 
3724                 /* planar surfaces (except twosided surfaces) have a couple more checks */
3725                 if( length > 0.0f && trace->twoSided == qfalse )
3726                 {
3727                         /* lights coplanar with a surface won't light it */
3728                         if( !(light->flags & LIGHT_TWOSIDED) && DotProduct( light->normal, normal ) > 0.999f )
3729                         {
3730                                 lightsPlaneCulled++;
3731                                 continue;
3732                         }
3733                         
3734                         /* check to see if light is behind the plane */
3735                         if( DotProduct( light->origin, normal ) - DotProduct( origin, normal ) < -1.0f )
3736                         {
3737                                 lightsPlaneCulled++;
3738                                 continue;
3739                         }
3740                 }
3741                 
3742                 /* add this light */
3743                 trace->lights[ trace->numLights++ ] = light;
3744         }
3745         
3746         /* make last night null */
3747         trace->lights[ trace->numLights ] = NULL;
3748 }
3749
3750
3751
3752 void FreeTraceLights( trace_t *trace )
3753 {
3754         if( trace->lights != NULL )
3755                 free( trace->lights );
3756 }
3757
3758
3759
3760 /*
3761 CreateTraceLightsForSurface()
3762 creates a list of lights that can potentially affect a drawsurface
3763 */
3764
3765 void CreateTraceLightsForSurface( int num, trace_t *trace )
3766 {
3767         int                                     i;
3768         vec3_t                          mins, maxs, normal;
3769         bspDrawVert_t           *dv;
3770         bspDrawSurface_t        *ds;
3771         surfaceInfo_t           *info;
3772         
3773         
3774         /* dummy check */
3775         if( num < 0 )
3776                 return;
3777         
3778         /* get drawsurface and info */
3779         ds = &bspDrawSurfaces[ num ];
3780         info = &surfaceInfos[ num ];
3781         
3782         /* get the mins/maxs for the dsurf */
3783         ClearBounds( mins, maxs );
3784         VectorCopy( bspDrawVerts[ ds->firstVert ].normal, normal );
3785         for( i = 0; i < ds->numVerts; i++ )
3786         {
3787                 dv = &yDrawVerts[ ds->firstVert + i ];
3788                 AddPointToBounds( dv->xyz, mins, maxs );
3789                 if( !VectorCompare( dv->normal, normal ) )
3790                         VectorClear( normal );
3791         }
3792         
3793         /* create the lights for the bounding box */
3794         CreateTraceLightsForBounds( mins, maxs, normal, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ], LIGHT_SURFACES, trace );
3795 }
3796
3797 /////////////////////////////////////////////////////////////
3798
3799 #define FLOODLIGHT_CONE_ANGLE                   88      /* degrees */
3800 #define FLOODLIGHT_NUM_ANGLE_STEPS              16
3801 #define FLOODLIGHT_NUM_ELEVATION_STEPS  4
3802 #define FLOODLIGHT_NUM_VECTORS                  (FLOODLIGHT_NUM_ANGLE_STEPS * FLOODLIGHT_NUM_ELEVATION_STEPS)
3803
3804 static vec3_t   floodVectors[ FLOODLIGHT_NUM_VECTORS ];
3805 static int              numFloodVectors = 0;
3806
3807 void SetupFloodLight( void )
3808 {
3809         int             i, j;
3810         float   angle, elevation, angleStep, elevationStep;
3811         const char      *value;
3812         double v1,v2,v3,v4,v5;
3813
3814         /* note it */
3815         Sys_FPrintf( SYS_VRB, "--- SetupFloodLight ---\n" );
3816
3817         /* calculate angular steps */
3818         angleStep = DEG2RAD( 360.0f / FLOODLIGHT_NUM_ANGLE_STEPS );
3819         elevationStep = DEG2RAD( FLOODLIGHT_CONE_ANGLE / FLOODLIGHT_NUM_ELEVATION_STEPS );
3820
3821         /* iterate angle */
3822         angle = 0.0f;
3823         for( i = 0, angle = 0.0f; i < FLOODLIGHT_NUM_ANGLE_STEPS; i++, angle += angleStep )
3824         {
3825                 /* iterate elevation */
3826                 for( j = 0, elevation = elevationStep * 0.5f; j < FLOODLIGHT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep )
3827                 {
3828                         floodVectors[ numFloodVectors ][ 0 ] = sin( elevation ) * cos( angle );
3829                         floodVectors[ numFloodVectors ][ 1 ] = sin( elevation ) * sin( angle );
3830                         floodVectors[ numFloodVectors ][ 2 ] = cos( elevation );
3831                         numFloodVectors++;
3832                 }
3833         }
3834
3835         /* emit some statistics */
3836         Sys_FPrintf( SYS_VRB, "%9d numFloodVectors\n", numFloodVectors );
3837
3838       /* floodlight */
3839         value = ValueForKey( &entities[ 0 ], "_floodlight" );
3840
3841         if( value[ 0 ] != '\0' )
3842         {
3843                 v1=v2=v3=0;
3844                 v4=floodlightDistance;
3845                 v5=floodlightIntensity;
3846
3847                 sscanf( value, "%lf %lf %lf %lf %lf", &v1, &v2, &v3, &v4, &v5);
3848
3849                 floodlightRGB[0]=v1;
3850                 floodlightRGB[1]=v2;
3851                 floodlightRGB[2]=v3;
3852
3853                 if (VectorLength(floodlightRGB)==0)
3854                 {
3855                         VectorSet(floodlightRGB,240,240,255);
3856                 }
3857
3858                 if (v4<1) v4=1024;
3859                 if (v5<1) v5=128;
3860
3861                 floodlightDistance=v4;
3862                 floodlightIntensity=v5;
3863
3864                 floodlighty = qtrue;
3865                 Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" );
3866         }
3867         else
3868         {
3869                 VectorSet(floodlightRGB,240,240,255);
3870                 //floodlighty = qtrue;
3871                 //Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" );
3872         }
3873         VectorNormalize(floodlightRGB,floodlightRGB);
3874 }
3875
3876 /*
3877 FloodLightForSample()
3878 calculates floodlight value for a given sample
3879 once again, kudos to the dirtmapping coder
3880 */
3881
3882 float FloodLightForSample( trace_t *trace , float floodLightDistance, qboolean floodLightLowQuality)
3883 {
3884         int             i;
3885         float   d;
3886         float   contribution;
3887         int     sub = 0;
3888         float   gatherLight, outLight;
3889         vec3_t  normal, worldUp, myUp, myRt, direction, displacement;
3890         float   dd;
3891         int     vecs = 0;
3892  
3893         gatherLight=0;
3894         /* dummy check */
3895         //if( !dirty )
3896         //      return 1.0f;
3897         if( trace == NULL || trace->cluster < 0 )
3898                 return 0.0f;
3899         
3900
3901         /* setup */
3902         dd = floodLightDistance;
3903         VectorCopy( trace->normal, normal );
3904         
3905         /* check if the normal is aligned to the world-up */
3906         if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) )
3907         {
3908                 if( normal[ 2 ] == 1.0f )               
3909                 {
3910                         VectorSet( myRt, 1.0f, 0.0f, 0.0f );
3911                         VectorSet( myUp, 0.0f, 1.0f, 0.0f );
3912                 }
3913                 else if( normal[ 2 ] == -1.0f )
3914                 {
3915                         VectorSet( myRt, -1.0f, 0.0f, 0.0f );
3916                         VectorSet( myUp,  0.0f, 1.0f, 0.0f );
3917                 }
3918         }
3919         else
3920         {
3921                 VectorSet( worldUp, 0.0f, 0.0f, 1.0f );
3922                 CrossProduct( normal, worldUp, myRt );
3923                 VectorNormalize( myRt, myRt );
3924                 CrossProduct( myRt, normal, myUp );
3925                 VectorNormalize( myUp, myUp );
3926         }
3927
3928         /* vortex: optimise floodLightLowQuality a bit */
3929         if ( floodLightLowQuality == qtrue )
3930     {
3931                 /* iterate through ordered vectors */
3932                 for( i = 0; i < numFloodVectors; i++ )
3933                         if (rand()%10 != 0 ) continue;
3934         }
3935         else
3936         {
3937                 /* iterate through ordered vectors */
3938                 for( i = 0; i < numFloodVectors; i++ )
3939                 {
3940                         vecs++;
3941                  
3942                         /* transform vector into tangent space */
3943                         direction[ 0 ] = myRt[ 0 ] * floodVectors[ i ][ 0 ] + myUp[ 0 ] * floodVectors[ i ][ 1 ] + normal[ 0 ] * floodVectors[ i ][ 2 ];
3944                         direction[ 1 ] = myRt[ 1 ] * floodVectors[ i ][ 0 ] + myUp[ 1 ] * floodVectors[ i ][ 1 ] + normal[ 1 ] * floodVectors[ i ][ 2 ];
3945                         direction[ 2 ] = myRt[ 2 ] * floodVectors[ i ][ 0 ] + myUp[ 2 ] * floodVectors[ i ][ 1 ] + normal[ 2 ] * floodVectors[ i ][ 2 ];
3946
3947                         /* set endpoint */
3948                         VectorMA( trace->origin, dd, direction, trace->end );
3949
3950                         //VectorMA( trace->origin, 1, direction, trace->origin );
3951                                 
3952                         SetupTrace( trace );
3953                         /* trace */
3954                         TraceLine( trace );
3955                         contribution=1;
3956
3957                         if (trace->compileFlags & C_SKY )
3958                         {
3959                                 contribution=1.0f;
3960                         }
3961                         else if ( trace->opaque )
3962                         {
3963                                 VectorSubtract( trace->hit, trace->origin, displacement );
3964                                 d=VectorLength( displacement );
3965
3966                                 // d=trace->distance;            
3967                                 //if (d>256) gatherDirt+=1;
3968                                 contribution=d/dd;
3969                                 if (contribution>1) contribution=1.0f; 
3970                      
3971                                 //gatherDirt += 1.0f - ooDepth * VectorLength( displacement );
3972                         }
3973                  
3974                         gatherLight+=contribution;
3975                 }
3976         }
3977    
3978         /* early out */
3979         if( gatherLight <= 0.0f )
3980                 return 0.0f;
3981         
3982         sub=vecs;
3983
3984         if (sub<1) sub=1;
3985         gatherLight/=(sub);
3986
3987         outLight=gatherLight;
3988         if( outLight > 1.0f )
3989                 outLight = 1.0f;
3990         
3991         /* return to sender */
3992         return outLight;
3993 }
3994
3995 /*
3996 FloodLightRawLightmap
3997 lighttracer style ambient occlusion light hack.
3998 Kudos to the dirtmapping author for most of this source.
3999 VorteX: modified to floodlight up custom surfaces (q3map_floodLight)
4000 VorteX: fixed problems with deluxemapping
4001 */
4002
4003 // floodlight pass on a lightmap
4004 void FloodLightRawLightmapPass( rawLightmap_t *lm , vec3_t lmFloodLightRGB, float lmFloodLightIntensity, float lmFloodLightDistance, qboolean lmFloodLightLowQuality, float floodlightDirectionScale)
4005 {
4006         int                                     i, x, y, *cluster;
4007         float                           *origin, *normal, *floodlight, floodLightAmount;
4008         surfaceInfo_t           *info;
4009         trace_t                         trace;
4010         // int sx, sy;
4011         // float samples, average, *floodlight2;
4012         
4013         memset(&trace,0,sizeof(trace_t));
4014
4015         /* setup trace */
4016         trace.testOcclusion = qtrue;
4017         trace.forceSunlight = qfalse;
4018         trace.twoSided = qtrue;
4019         trace.recvShadows = lm->recvShadows;
4020         trace.numSurfaces = lm->numLightSurfaces;
4021         trace.surfaces = &lightSurfaces[ lm->firstLightSurface ];
4022         trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS;
4023         trace.testAll = qfalse;
4024         trace.distance = 1024;
4025         
4026         /* twosided lighting (may or may not be a good idea for lightmapped stuff) */
4027         //trace.twoSided = qfalse;
4028         for( i = 0; i < trace.numSurfaces; i++ )
4029         {
4030                 /* get surface */
4031                 info = &surfaceInfos[ trace.surfaces[ i ] ];
4032                 
4033                 /* check twosidedness */
4034                 if( info->si->twoSided )
4035                 {
4036                         trace.twoSided = qtrue;
4037                         break;
4038                 }
4039         }
4040         
4041         /* gather floodlight */
4042         for( y = 0; y < lm->sh; y++ )
4043         {
4044                 for( x = 0; x < lm->sw; x++ )
4045                 {
4046                         /* get luxel */
4047                         cluster = SUPER_CLUSTER( x, y );
4048                         origin = SUPER_ORIGIN( x, y );
4049                         normal = SUPER_NORMAL( x, y );
4050                         floodlight = SUPER_FLOODLIGHT( x, y );
4051                         
4052                         /* set default dirt */
4053                         *floodlight = 0.0f;
4054                         
4055                         /* only look at mapped luxels */
4056                         if( *cluster < 0 )
4057                                 continue;
4058                         
4059                         /* copy to trace */
4060                         trace.cluster = *cluster;
4061                         VectorCopy( origin, trace.origin );
4062                         VectorCopy( normal, trace.normal );
4063    
4064                         /* get floodlight */
4065                         floodLightAmount = FloodLightForSample( &trace , lmFloodLightDistance, lmFloodLightLowQuality)*lmFloodLightIntensity;
4066                         
4067                         /* add floodlight */
4068                         floodlight[0] += lmFloodLightRGB[0]*floodLightAmount;
4069                         floodlight[1] += lmFloodLightRGB[1]*floodLightAmount;
4070                         floodlight[2] += lmFloodLightRGB[2]*floodLightAmount;
4071                         floodlight[3] += floodlightDirectionScale;
4072                 }
4073         }
4074         
4075         /* testing no filtering */
4076         return;
4077
4078 #if 0
4079         
4080         /* filter "dirt" */
4081         for( y = 0; y < lm->sh; y++ )
4082         {
4083                 for( x = 0; x < lm->sw; x++ )
4084                 {
4085                         /* get luxel */
4086                         cluster = SUPER_CLUSTER( x, y );
4087                         floodlight = SUPER_FLOODLIGHT(x, y );
4088                         
4089                         /* filter dirt by adjacency to unmapped luxels */
4090                         average = *floodlight;
4091                         samples = 1.0f;
4092                         for( sy = (y - 1); sy <= (y + 1); sy++ )
4093                         {
4094                                 if( sy < 0 || sy >= lm->sh )
4095                                         continue;
4096                                 
4097                                 for( sx = (x - 1); sx <= (x + 1); sx++ )
4098                                 {
4099                                         if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) )
4100                                                 continue;
4101                                         
4102                                         /* get neighboring luxel */
4103                                         cluster = SUPER_CLUSTER( sx, sy );
4104                                         floodlight2 = SUPER_FLOODLIGHT( sx, sy );
4105                                         if( *cluster < 0 || *floodlight2 <= 0.0f )
4106                                                 continue;
4107                                         
4108                                         /* add it */
4109                                         average += *floodlight2;
4110                                         samples += 1.0f;
4111                                 }
4112                                 
4113                                 /* bail */
4114                                 if( samples <= 0.0f )
4115                                         break;
4116                         }
4117                         
4118                         /* bail */
4119                         if( samples <= 0.0f )
4120                                 continue;
4121                         
4122                         /* scale dirt */
4123                         *floodlight = average / samples;
4124                 }
4125         }
4126 #endif
4127 }
4128
4129 void FloodLightRawLightmap( int rawLightmapNum )
4130 {
4131         rawLightmap_t           *lm;
4132
4133         /* bail if this number exceeds the number of raw lightmaps */
4134         if( rawLightmapNum >= numRawLightmaps )
4135                 return;
4136         /* get lightmap */
4137         lm = &rawLightmaps[ rawLightmapNum ];
4138
4139         /* global pass */
4140         if (floodlighty && floodlightIntensity)
4141                 FloodLightRawLightmapPass(lm, floodlightRGB, floodlightIntensity, floodlightDistance, floodlight_lowquality, 1.0f);
4142
4143         /* custom pass */
4144         if (lm->floodlightIntensity)
4145         {
4146                 FloodLightRawLightmapPass(lm, lm->floodlightRGB, lm->floodlightIntensity, lm->floodlightDistance, qfalse, lm->floodlightDirectionScale);
4147                 numSurfacesFloodlighten += 1;
4148         }
4149 }
4150
4151 void FloodlightRawLightmaps()
4152 {
4153         Sys_Printf( "--- FloodlightRawLightmap ---\n" );
4154         numSurfacesFloodlighten = 0;
4155         RunThreadsOnIndividual( numRawLightmaps, qtrue, FloodLightRawLightmap );
4156         Sys_Printf( "%9d custom lightmaps floodlighted\n", numSurfacesFloodlighten );
4157 }
4158
4159 /*
4160 FloodLightIlluminate()
4161 illuminate floodlight into lightmap luxels
4162 */
4163
4164 void FloodlightIlluminateLightmap( rawLightmap_t *lm )
4165 {
4166         float                           *luxel, *floodlight, *deluxel, *normal;
4167         int                                     *cluster;
4168         float                           brightness;
4169         int                                     x, y, lightmapNum;
4170
4171         /* walk lightmaps */
4172         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
4173         {
4174                 /* early out */
4175                 if( lm->superLuxels[ lightmapNum ] == NULL )
4176                         continue;
4177
4178                 /* apply floodlight to each luxel */
4179                 for( y = 0; y < lm->sh; y++ )
4180                 {
4181                         for( x = 0; x < lm->sw; x++ )
4182                         {
4183                                 /* get floodlight */
4184                                 floodlight = SUPER_FLOODLIGHT( x, y );
4185                                 if (!floodlight[0] && !floodlight[1] && !floodlight[2])
4186                                         continue;
4187                                                 
4188                                 /* get cluster */
4189                                 cluster = SUPER_CLUSTER( x, y );
4190
4191                                 /* only process mapped luxels */
4192                                 if( *cluster < 0 )
4193                                         continue;
4194
4195                                 /* get particulars */
4196                                 luxel = SUPER_LUXEL( lightmapNum, x, y );
4197                                 deluxel = SUPER_DELUXEL( x, y );
4198
4199                                 /* add to lightmap */
4200                                 luxel[0]+=floodlight[0];
4201                                 luxel[1]+=floodlight[1];
4202                                 luxel[2]+=floodlight[2];
4203
4204                                 if (luxel[3]==0) luxel[3]=1;
4205
4206                                 /* add to deluxemap */
4207                                 if (deluxemap && floodlight[3] > 0)\r
4208                                 {
4209                                         vec3_t                          lightvector;\r
4210 \r
4211                                         normal = SUPER_NORMAL( x, y );
4212                                         brightness = RGBTOGRAY( floodlight ) * ( 1.0f/255.0f ) * floodlight[3];\r
4213 \r
4214                                         // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light\r
4215                                         if(brightness < 0.00390625f)\r
4216                                                 brightness = 0.00390625f;\r
4217 \r
4218                                         VectorScale( normal, brightness, lightvector );
4219                                         VectorAdd( deluxel, lightvector, deluxel );
4220                                 }
4221                         }
4222                 }
4223         }
4224 }