]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/light_bounce.c
Merge commit '87d5b6efe557ee73b613c030cca2374dd23bc1be' into garux-merge
[xonotic/netradiant.git] / tools / quake3 / q3map2 / light_bounce.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_BOUNCE_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /* functions */
42
43 /*
44    RadFreeLights()
45    deletes any existing lights, freeing up memory for the next bounce
46  */
47
48 void RadFreeLights( void ){
49         light_t     *light, *next;
50
51
52         /* delete lights */
53         for ( light = lights; light; light = next )
54         {
55                 next = light->next;
56                 if ( light->w != NULL ) {
57                         FreeWinding( light->w );
58                 }
59                 free( light );
60         }
61         numLights = 0;
62         lights = NULL;
63 }
64
65
66
67 /*
68    RadClipWindingEpsilon()
69    clips a rad winding by a plane
70    based off the regular clip winding code
71  */
72
73 static void RadClipWindingEpsilon( radWinding_t *in, vec3_t normal, vec_t dist,
74                                                                    vec_t epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw ){
75         vec_t           *dists;
76         int             *sides;
77         int counts[ 3 ];
78         vec_t dot;                  /* ydnar: changed from static b/c of threading */ /* VC 4.2 optimizer bug if not static? */
79         int i, j, k;
80         radVert_t       *v1, *v2, mid;
81         int maxPoints;
82
83
84         /* crutch */
85         dists = cw->dists;
86         sides = cw->sides;
87
88         /* clear counts */
89         counts[ 0 ] = counts[ 1 ] = counts[ 2 ] = 0;
90
91         /* determine sides for each point */
92         for ( i = 0; i < in->numVerts; i++ )
93         {
94                 dot = DotProduct( in->verts[ i ].xyz, normal );
95                 dot -= dist;
96                 dists[ i ] = dot;
97                 if ( dot > epsilon ) {
98                         sides[ i ] = SIDE_FRONT;
99                 }
100                 else if ( dot < -epsilon ) {
101                         sides[ i ] = SIDE_BACK;
102                 }
103                 else{
104                         sides[ i ] = SIDE_ON;
105                 }
106                 counts[ sides[ i ] ]++;
107         }
108         sides[ i ] = sides[ 0 ];
109         dists[ i ] = dists[ 0 ];
110
111         /* clear front and back */
112         front->numVerts = back->numVerts = 0;
113
114         /* handle all on one side cases */
115         if ( counts[ 0 ] == 0 ) {
116                 memcpy( back, in, sizeof( radWinding_t ) );
117                 return;
118         }
119         if ( counts[ 1 ] == 0 ) {
120                 memcpy( front, in, sizeof( radWinding_t ) );
121                 return;
122         }
123
124         /* setup windings */
125         maxPoints = in->numVerts + 4;
126
127         /* do individual verts */
128         for ( i = 0; i < in->numVerts; i++ )
129         {
130                 /* do simple vertex copies first */
131                 v1 = &in->verts[ i ];
132
133                 if ( sides[ i ] == SIDE_ON ) {
134                         memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) );
135                         memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) );
136                         continue;
137                 }
138
139                 if ( sides[ i ] == SIDE_FRONT ) {
140                         memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) );
141                 }
142
143                 if ( sides[ i ] == SIDE_BACK ) {
144                         memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) );
145                 }
146
147                 if ( sides[ i + 1 ] == SIDE_ON || sides[ i + 1 ] == sides[ i ] ) {
148                         continue;
149                 }
150
151                 /* generate a split vertex */
152                 v2 = &in->verts[ ( i + 1 ) % in->numVerts ];
153
154                 dot = dists[ i ] / ( dists[ i ] - dists[ i + 1 ] );
155
156                 /* average vertex values */
157                 for ( j = 0; j < 4; j++ )
158                 {
159                         /* color */
160                         if ( j < 4 ) {
161                                 for ( k = 0; k < MAX_LIGHTMAPS; k++ )
162                                         mid.color[ k ][ j ] = v1->color[ k ][ j ] + dot * ( v2->color[ k ][ j ] - v1->color[ k ][ j ] );
163                         }
164
165                         /* xyz, normal */
166                         if ( j < 3 ) {
167                                 mid.xyz[ j ] = v1->xyz[ j ] + dot * ( v2->xyz[ j ] - v1->xyz[ j ] );
168                                 mid.normal[ j ] = v1->normal[ j ] + dot * ( v2->normal[ j ] - v1->normal[ j ] );
169                         }
170
171                         /* st, lightmap */
172                         if ( j < 2 ) {
173                                 mid.st[ j ] = v1->st[ j ] + dot * ( v2->st[ j ] - v1->st[ j ] );
174                                 for ( k = 0; k < MAX_LIGHTMAPS; k++ )
175                                         mid.lightmap[ k ][ j ] = v1->lightmap[ k ][ j ] + dot * ( v2->lightmap[ k ][ j ] - v1->lightmap[ k ][ j ] );
176                         }
177                 }
178
179                 /* normalize the averaged normal */
180                 VectorNormalize( mid.normal, mid.normal );
181
182                 /* copy the midpoint to both windings */
183                 memcpy( &front->verts[ front->numVerts++ ], &mid, sizeof( radVert_t ) );
184                 memcpy( &back->verts[ back->numVerts++ ], &mid, sizeof( radVert_t ) );
185         }
186
187         /* error check */
188         if ( front->numVerts > maxPoints ) {
189                 Error( "RadClipWindingEpsilon: points exceeded estimate" );
190         }
191         if ( front->numVerts > MAX_POINTS_ON_WINDING ) {
192                 Error( "RadClipWindingEpsilon: MAX_POINTS_ON_WINDING" );
193         }
194 }
195
196
197
198
199
200 /*
201    RadSampleImage()
202    samples a texture image for a given color
203    returns qfalse if pixels are bad
204  */
205
206 qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] ){
207         float sto[ 2 ];
208         int x, y;
209
210
211         /* clear color first */
212         color[ 0 ] = color[ 1 ] = color[ 2 ] = color[ 3 ] = 255;
213
214         /* dummy check */
215         if ( pixels == NULL || width < 1 || height < 1 ) {
216                 return qfalse;
217         }
218
219         /* bias st */
220         sto[ 0 ] = st[ 0 ];
221         while ( sto[ 0 ] < 0.0f )
222                 sto[ 0 ] += 1.0f;
223         sto[ 1 ] = st[ 1 ];
224         while ( sto[ 1 ] < 0.0f )
225                 sto[ 1 ] += 1.0f;
226
227         /* get offsets */
228         x = ( (float) width * sto[ 0 ] ) + 0.5f;
229         x %= width;
230         y = ( (float) height * sto[ 1 ] )  + 0.5f;
231         y %= height;
232
233         /* get pixel */
234         pixels += ( y * width * 4 ) + ( x * 4 );
235         VectorCopy( pixels, color );
236         color[ 3 ] = pixels[ 3 ];
237
238         if ( texturesRGB ) {
239                 color[0] = Image_LinearFloatFromsRGBFloat( color[0] * ( 1.0 / 255.0 ) ) * 255.0;
240                 color[1] = Image_LinearFloatFromsRGBFloat( color[1] * ( 1.0 / 255.0 ) ) * 255.0;
241                 color[2] = Image_LinearFloatFromsRGBFloat( color[2] * ( 1.0 / 255.0 ) ) * 255.0;
242         }
243
244         return qtrue;
245 }
246
247
248
249 /*
250    RadSample()
251    samples a fragment's lightmap or vertex color and returns an
252    average color and a color gradient for the sample
253  */
254
255 #define MAX_SAMPLES         150
256 #define SAMPLE_GRANULARITY  6
257
258 static void RadSample( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, radWinding_t *rw, vec3_t average, vec3_t gradient, int *style ){
259         int i, j, k, l, v, x, y, samples, avgcolor;
260         vec3_t color, mins, maxs;
261         vec4_t textureColor;
262         float alpha, alphaI, bf;
263         vec3_t blend;
264         float st[ 2 ], lightmap[ 2 ], *radLuxel;
265         radVert_t   *rv[ 3 ];
266
267         if (!bouncing)
268                 Sys_Printf( "BUG: RadSample: !bouncing shouldn't happen\n" );
269
270         /* initial setup */
271         ClearBounds( mins, maxs );
272         VectorClear( average );
273         VectorClear( gradient );
274         alpha = 0;
275
276         /* dummy check */
277         if ( rw == NULL || rw->numVerts < 3 ) {
278                 return;
279         }
280
281         /* start sampling */
282         samples = 0;
283
284         /* sample vertex colors if no lightmap or this is the initial pass */
285         if ( lm == NULL || lm->radLuxels[ lightmapNum ] == NULL || bouncing == qfalse ) {
286                 for ( samples = 0; samples < rw->numVerts; samples++ )
287                 {
288                         /* multiply by texture color */
289                         if ( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, rw->verts[ samples ].st, textureColor ) ) {
290                                 VectorCopy( si->averageColor, textureColor );
291                                 textureColor[ 3 ] = 255.0f;
292                         }
293                         avgcolor = ( textureColor[ 0 ] + textureColor[ 1 ] + textureColor[ 2 ] ) / 3;
294                         for ( i = 0; i < 3; i++ )
295                                 color[ i ] = ( ( textureColor[ i ] * bounceColorRatio + ( avgcolor * ( 1 - bounceColorRatio ) ) ) / 255 ) * ( rw->verts[ samples ].color[ lightmapNum ][ i ] / 255.0f );
296 //                              color[ i ] = ( textureColor[ i ] / 255 ) * ( rw->verts[ samples ].color[ lightmapNum ][ i ] / 255.0f );
297
298                         AddPointToBounds( color, mins, maxs );
299                         VectorAdd( average, color, average );
300
301                         /* get alpha */
302                         alpha += ( textureColor[ 3 ] / 255.0f ) * ( rw->verts[ samples ].color[ lightmapNum ][ 3 ] / 255.0f );
303                 }
304
305                 /* set style */
306                 *style = ds->vertexStyles[ lightmapNum ];
307         }
308
309         /* sample lightmap */
310         else
311         {
312                 /* fracture the winding into a fan (including degenerate tris) */
313                 for ( v = 1; v < ( rw->numVerts - 1 ) && samples < MAX_SAMPLES; v++ )
314                 {
315                         /* get a triangle */
316                         rv[ 0 ] = &rw->verts[ 0 ];
317                         rv[ 1 ] = &rw->verts[ v ];
318                         rv[ 2 ] = &rw->verts[ v + 1 ];
319
320                         /* this code is embarassing (really should just rasterize the triangle) */
321                         for ( i = 1; i < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; i++ )
322                         {
323                                 for ( j = 1; j < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; j++ )
324                                 {
325                                         for ( k = 1; k < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; k++ )
326                                         {
327                                                 /* create a blend vector (barycentric coordinates) */
328                                                 blend[ 0 ] = i;
329                                                 blend[ 1 ] = j;
330                                                 blend[ 2 ] = k;
331                                                 bf = ( 1.0 / ( blend[ 0 ] + blend[ 1 ] + blend[ 2 ] ) );
332                                                 VectorScale( blend, bf, blend );
333
334                                                 /* create a blended sample */
335                                                 st[ 0 ] = st[ 1 ] = 0.0f;
336                                                 lightmap[ 0 ] = lightmap[ 1 ] = 0.0f;
337                                                 alphaI = 0.0f;
338                                                 for ( l = 0; l < 3; l++ )
339                                                 {
340                                                         st[ 0 ] += ( rv[ l ]->st[ 0 ] * blend[ l ] );
341                                                         st[ 1 ] += ( rv[ l ]->st[ 1 ] * blend[ l ] );
342                                                         lightmap[ 0 ] += ( rv[ l ]->lightmap[ lightmapNum ][ 0 ] * blend[ l ] );
343                                                         lightmap[ 1 ] += ( rv[ l ]->lightmap[ lightmapNum ][ 1 ] * blend[ l ] );
344                                                         alphaI += ( rv[ l ]->color[ lightmapNum ][ 3 ] * blend[ l ] );
345                                                 }
346
347                                                 /* get lightmap xy coords */
348                                                 x = lightmap[ 0 ] / (float) superSample;
349                                                 y = lightmap[ 1 ] / (float) superSample;
350                                                 if ( x < 0 ) {
351                                                         x = 0;
352                                                 }
353                                                 else if ( x >= lm->w ) {
354                                                         x = lm->w - 1;
355                                                 }
356                                                 if ( y < 0 ) {
357                                                         y = 0;
358                                                 }
359                                                 else if ( y >= lm->h ) {
360                                                         y = lm->h - 1;
361                                                 }
362
363                                                 /* get radiosity luxel */
364                                                 radLuxel = RAD_LUXEL( lightmapNum, x, y );
365
366                                                 /* ignore unlit/unused luxels */
367                                                 if ( radLuxel[ 0 ] < 0.0f ) {
368                                                         continue;
369                                                 }
370
371                                                 /* inc samples */
372                                                 samples++;
373
374                                                 /* multiply by texture color */
375                                                 if ( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, st, textureColor ) ) {
376                                                         VectorCopy( si->averageColor, textureColor );
377                                                         textureColor[ 3 ] = 255;
378                                                 }
379                                                 avgcolor = ( textureColor[ 0 ] + textureColor[ 1 ] + textureColor[ 2 ] ) / 3;
380                                                 for ( l = 0; l < 3; l++ ){
381                                                         color[ l ] = ( ( textureColor[ l ] * bounceColorRatio + ( avgcolor * ( 1 - bounceColorRatio ) ) ) / 255 ) * ( radLuxel[ l ] / 255 );
382                                                 //Sys_Printf( "%i %i %i %i %i \n", (int) textureColor[ 0 ], (int) textureColor[ 1 ], (int) textureColor[ 2 ], (int) avgcolor, (int) color[ i ] );
383                                                 }
384                                                 AddPointToBounds( color, mins, maxs );
385                                                 VectorAdd( average, color, average );
386
387                                                 /* get alpha */
388                                                 alpha += ( textureColor[ 3 ] / 255 ) * ( alphaI / 255 );
389                                         }
390                                 }
391                         }
392                 }
393
394                 /* set style */
395                 *style = ds->lightmapStyles[ lightmapNum ];
396         }
397
398         /* any samples? */
399         if ( samples <= 0 ) {
400                 return;
401         }
402
403         /* average the color */
404         VectorScale( average, ( 1.0 / samples ), average );
405
406         /* create the color gradient */
407         //%     VectorSubtract( maxs, mins, delta );
408
409         /* new: color gradient will always be 0-1.0, expressed as the range of light relative to overall light */
410         //%     gradient[ 0 ] = maxs[ 0 ] > 0.0f ? (maxs[ 0 ] - mins[ 0 ]) / maxs[ 0 ] : 0.0f;
411         //%     gradient[ 1 ] = maxs[ 1 ] > 0.0f ? (maxs[ 1 ] - mins[ 1 ]) / maxs[ 1 ] : 0.0f;
412         //%     gradient[ 2 ] = maxs[ 2 ] > 0.0f ? (maxs[ 2 ] - mins[ 2 ]) / maxs[ 2 ] : 0.0f;
413
414         /* newer: another contrast function */
415         for ( i = 0; i < 3; i++ )
416                 gradient[ i ] = ( maxs[ i ] - mins[ i ] ) * maxs[ i ];
417 }
418
419
420
421 /*
422    RadSubdivideDiffuseLight()
423    subdivides a radiosity winding until it is smaller than subdivide, then generates an area light
424  */
425
426 #define RADIOSITY_MAX_GRADIENT      0.75f   //% 0.25f
427 #define RADIOSITY_VALUE             500.0f
428 #define RADIOSITY_MIN               0.0001f
429 #define RADIOSITY_CLIP_EPSILON      0.125f
430
431
432
433 static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si,
434                                                                           float scale, float subdivide, radWinding_t *rw, clipWork_t *cw ){
435         int i, style = 0;
436         float dist, area, value;
437         vec3_t mins, maxs, normal, d1, d2, cross, color, gradient;
438         light_t         *light, *splash;
439         winding_t       *w, *splash_w;
440
441
442         /* dummy check */
443         if ( rw == NULL || rw->numVerts < 3 ) {
444                 return;
445         }
446
447         /* get bounds for winding */
448         ClearBounds( mins, maxs );
449         for ( i = 0; i < rw->numVerts; i++ )
450                 AddPointToBounds( rw->verts[ i ].xyz, mins, maxs );
451
452         /* subdivide if necessary */
453         for ( i = 0; i < 3; i++ )
454         {
455                 if ( maxs[ i ] - mins[ i ] > subdivide ) {
456                         radWinding_t front, back;
457
458
459                         /* make axial plane */
460                         VectorClear( normal );
461                         normal[ i ] = 1;
462                         dist = ( maxs[ i ] + mins[ i ] ) * 0.5f;
463
464                         /* clip the winding */
465                         RadClipWindingEpsilon( rw, normal, dist, RADIOSITY_CLIP_EPSILON, &front, &back, cw );
466
467                         /* recurse */
468                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, &front, cw );
469                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, &back, cw );
470                         return;
471                 }
472         }
473
474         /* check area */
475         area = 0.0f;
476         for ( i = 2; i < rw->numVerts; i++ )
477         {
478                 VectorSubtract( rw->verts[ i - 1 ].xyz, rw->verts[ 0 ].xyz, d1 );
479                 VectorSubtract( rw->verts[ i ].xyz, rw->verts[ 0 ].xyz, d2 );
480                 CrossProduct( d1, d2, cross );
481                 area += 0.5f * VectorLength( cross );
482         }
483         if ( area < 1.0f || area > 20000000.0f ) {
484                 return;
485         }
486
487         /* more subdivision may be necessary */
488         if ( bouncing ) {
489                 /* get color sample for the surface fragment */
490                 RadSample( lightmapNum, ds, lm, si, rw, color, gradient, &style );
491
492                 /* if color gradient is too high, subdivide again */
493                 if ( subdivide > minDiffuseSubdivide &&
494                          ( gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT ) ) {
495                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, ( subdivide / 2.0f ), rw, cw );
496                         return;
497                 }
498         }
499
500         /* create a regular winding and an average normal */
501         w = AllocWinding( rw->numVerts );
502         w->numpoints = rw->numVerts;
503         VectorClear( normal );
504         for ( i = 0; i < rw->numVerts; i++ )
505         {
506                 VectorCopy( rw->verts[ i ].xyz, w->p[ i ] );
507                 VectorAdd( normal, rw->verts[ i ].normal, normal );
508         }
509         VectorScale( normal, ( 1.0f / rw->numVerts ), normal );
510         if ( VectorNormalize( normal, normal ) == 0.0f ) {
511                 return;
512         }
513
514         /* early out? */
515         if ( bouncing && VectorLength( color ) < RADIOSITY_MIN ) {
516                 return;
517         }
518
519         /* debug code */
520         //%     Sys_Printf( "Size: %d %d %d\n", (int) (maxs[ 0 ] - mins[ 0 ]), (int) (maxs[ 1 ] - mins[ 1 ]), (int) (maxs[ 2 ] - mins[ 2 ]) );
521         //%     Sys_Printf( "Grad: %f %f %f\n", gradient[ 0 ], gradient[ 1 ], gradient[ 2 ] );
522
523         /* increment counts */
524         numDiffuseLights++;
525         switch ( ds->surfaceType )
526         {
527         case MST_PLANAR:
528                 numBrushDiffuseLights++;
529                 break;
530
531         case MST_TRIANGLE_SOUP:
532                 numTriangleDiffuseLights++;
533                 break;
534
535         case MST_PATCH:
536                 numPatchDiffuseLights++;
537                 break;
538         }
539
540         /* create a light */
541         light = safe_malloc( sizeof( *light ) );
542         memset( light, 0, sizeof( *light ) );
543
544         /* attach it */
545         ThreadLock();
546         light->next = lights;
547         lights = light;
548         ThreadUnlock();
549
550         /* initialize the light */
551         light->flags = LIGHT_AREA_DEFAULT;
552         light->type = EMIT_AREA;
553         light->si = si;
554         light->fade = 1.0f;
555         light->w = w;
556
557         /* set falloff threshold */
558         light->falloffTolerance = falloffTolerance;
559
560         /* bouncing light? */
561         if ( bouncing == qfalse ) {
562                 /* This is weird. This actually handles surfacelight and not
563                  * bounces. */
564
565                 /* handle first-pass lights in normal q3a style */
566                 value = si->value;
567                 light->photons = value * area * areaScale;
568                 light->add = value * formFactorValueScale * areaScale;
569                 VectorCopy( si->color, light->color );
570                 VectorScale( light->color, light->add, light->emitColor );
571                 light->style = noStyles ? LS_NORMAL : si->lightStyle;
572                 if ( light->style < LS_NORMAL || light->style >= LS_NONE ) {
573                         light->style = LS_NORMAL;
574                 }
575
576                 /* set origin */
577                 VectorAdd( mins, maxs, light->origin );
578                 VectorScale( light->origin, 0.5f, light->origin );
579
580                 /* nudge it off the plane a bit */
581                 VectorCopy( normal, light->normal );
582                 VectorMA( light->origin, 1.0f, light->normal, light->origin );
583                 light->dist = DotProduct( light->origin, normal );
584
585 #if 0
586                 /* optionally create a point backsplash light */
587                 if ( si->backsplashFraction > 0 ) {
588
589                         /* allocate a new point light */
590                         splash = safe_malloc( sizeof( *splash ) );
591                         memset( splash, 0, sizeof( *splash ) );
592
593                         splash->next = lights;
594                         lights = splash;
595
596
597                         /* set it up */
598                         splash->flags = LIGHT_Q3A_DEFAULT;
599                         splash->type = EMIT_POINT;
600                         splash->photons = light->photons * si->backsplashFraction;
601
602                         splash->fade = 1.0f;
603                         splash->si = si;
604                         VectorMA( light->origin, si->backsplashDistance, normal, splash->origin );
605                         VectorCopy( si->color, splash->color );
606
607                         splash->falloffTolerance = falloffTolerance;
608                         splash->style = noStyles ? LS_NORMAL : light->style;
609
610                         /* add to counts */
611                         numPointLights++;
612                 }
613 #endif
614
615 #if 1
616                 /* optionally create area backsplash light */
617                 //if ( original && si->backsplashFraction > 0 ) {
618                 if ( si->backsplashFraction > 0 && !( si->compileFlags & C_SKY ) ) {
619                         /* allocate a new area light */
620                         splash = safe_malloc( sizeof( *splash ) );
621                         memset( splash, 0, sizeof( *splash ) );
622                         ThreadLock();
623                         splash->next = lights;
624                         lights = splash;
625                         ThreadUnlock();
626
627                         /* set it up */
628                         splash->flags = LIGHT_AREA_DEFAULT;
629                         splash->type = EMIT_AREA;
630                         splash->photons = light->photons * 7.0f * si->backsplashFraction;
631                         splash->add = light->add * 7.0f * si->backsplashFraction;
632                         splash->fade = 1.0f;
633                         splash->si = si;
634                         VectorCopy( si->color, splash->color );
635                         VectorScale( splash->color, splash->add, splash->emitColor );
636                         splash->falloffTolerance = falloffTolerance;
637                         splash->style = noStyles ? LS_NORMAL : si->lightStyle;
638                         if ( splash->style < LS_NORMAL || splash->style >= LS_NONE ) {
639                                 splash->style = LS_NORMAL;
640                         }
641
642                         /* create a regular winding */
643                         splash_w = AllocWinding( rw->numVerts );
644                         splash_w->numpoints = rw->numVerts;
645                         for ( i = 0; i < rw->numVerts; i++ )
646                                 VectorMA( rw->verts[rw->numVerts - 1 - i].xyz, si->backsplashDistance, normal, splash_w->p[ i ] );
647                         splash->w = splash_w;
648
649                         VectorMA( light->origin, si->backsplashDistance, normal, splash->origin );
650                         VectorNegate( normal, splash->normal );
651             splash->dist = DotProduct( splash->origin, splash->normal );
652
653 //                      splash->flags |= LIGHT_TWOSIDED;
654                 }
655 #endif
656
657         }
658         else
659         {
660                 /* handle bounced light (radiosity) a little differently */
661                 value = RADIOSITY_VALUE * si->bounceScale * 0.375f;
662                 light->photons = value * area * bounceScale;
663                 light->add = value * formFactorValueScale * bounceScale;
664                 VectorCopy( color, light->color );
665                 VectorScale( light->color, light->add, light->emitColor );
666                 light->style = noStyles ? LS_NORMAL : style;
667                 if ( light->style < LS_NORMAL || light->style >= LS_NONE ) {
668                         light->style = LS_NORMAL;
669                 }
670
671                 /* set origin */
672                 WindingCenter( w, light->origin );
673
674                 /* nudge it off the plane a bit */
675                 VectorCopy( normal, light->normal );
676                 VectorMA( light->origin, 1.0f, light->normal, light->origin );
677                 light->dist = DotProduct( light->origin, normal );
678         }
679
680         if (light->photons < 0 || light->add < 0 || light->color[0] < 0 || light->color[1] < 0 || light->color[2] < 0)
681                 Sys_Printf( "BUG: RadSubdivideDiffuseLight created a darkbulb\n" );
682
683         /* emit light from both sides? */
684         if ( si->compileFlags & C_FOG || si->twoSided ) {
685                 light->flags |= LIGHT_TWOSIDED;
686         }
687
688         //%     Sys_Printf( "\nAL: C: (%6f, %6f, %6f) [%6f] N: (%6f, %6f, %6f) %s\n",
689         //%             light->color[ 0 ], light->color[ 1 ], light->color[ 2 ], light->add,
690         //%             light->normal[ 0 ], light->normal[ 1 ], light->normal[ 2 ],
691         //%             light->si->shader );
692 }
693
694
695 /*
696    RadLightForTriangles()
697    creates unbounced diffuse lights for triangle soup (misc_models, etc)
698  */
699
700 void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ){
701         int i, j, k, v;
702         bspDrawSurface_t    *ds;
703         float               *radVertexLuxel;
704         radWinding_t rw;
705
706
707         /* get surface */
708         ds = &bspDrawSurfaces[ num ];
709
710         /* each triangle is a potential emitter */
711         rw.numVerts = 3;
712         for ( i = 0; i < ds->numIndexes; i += 3 )
713         {
714                 /* copy each vert */
715                 for ( j = 0; j < 3; j++ )
716                 {
717                         /* get vertex index and rad vertex luxel */
718                         v = ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ];
719
720                         /* get most everything */
721                         memcpy( &rw.verts[ j ], &yDrawVerts[ v ], sizeof( bspDrawVert_t ) );
722
723                         /* fix colors */
724                         for ( k = 0; k < MAX_LIGHTMAPS; k++ )
725                         {
726                                 radVertexLuxel = RAD_VERTEX_LUXEL( k, ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ] );
727                                 VectorCopy( radVertexLuxel, rw.verts[ j ].color[ k ] );
728                                 rw.verts[ j ].color[ k ][ 3 ] = yDrawVerts[ v ].color[ k ][ 3 ];
729                         }
730                 }
731
732                 /* subdivide into area lights */
733                 RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, &rw, cw );
734         }
735 }
736
737
738
739 /*
740    RadLightForPatch()
741    creates unbounced diffuse lights for patches
742  */
743
744 #define PLANAR_EPSILON  0.1f
745
746 void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ){
747         int i, x, y, v, t, pw[ 5 ], r;
748         bspDrawSurface_t    *ds;
749         surfaceInfo_t       *info;
750         bspDrawVert_t       *bogus;
751         bspDrawVert_t       *dv[ 4 ];
752         mesh_t src, *subdivided, *mesh;
753         float               *radVertexLuxel;
754         float dist;
755         vec4_t plane;
756         qboolean planar;
757         radWinding_t rw;
758
759
760         /* get surface */
761         ds = &bspDrawSurfaces[ num ];
762         info = &surfaceInfos[ num ];
763
764         /* construct a bogus vert list with color index stuffed into color[ 0 ] */
765         bogus = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
766         memcpy( bogus, &yDrawVerts[ ds->firstVert ], ds->numVerts * sizeof( bspDrawVert_t ) );
767         for ( i = 0; i < ds->numVerts; i++ )
768                 bogus[ i ].color[ 0 ][ 0 ] = i;
769
770         /* build a subdivided mesh identical to shadow facets for this patch */
771         /* this MUST MATCH FacetsForPatch() identically! */
772         src.width = ds->patchWidth;
773         src.height = ds->patchHeight;
774         src.verts = bogus;
775         //%     subdivided = SubdivideMesh( src, 8, 512 );
776         subdivided = SubdivideMesh2( src, info->patchIterations );
777         PutMeshOnCurve( *subdivided );
778         //%     MakeMeshNormals( *subdivided );
779         mesh = RemoveLinearMeshColumnsRows( subdivided );
780         FreeMesh( subdivided );
781         free( bogus );
782
783         /* FIXME: build interpolation table into color[ 1 ] */
784
785         /* fix up color indexes */
786         for ( i = 0; i < ( mesh->width * mesh->height ); i++ )
787         {
788                 dv[ 0 ] = &mesh->verts[ i ];
789                 if ( dv[ 0 ]->color[ 0 ][ 0 ] >= ds->numVerts ) {
790                         dv[ 0 ]->color[ 0 ][ 0 ] = ds->numVerts - 1;
791                 }
792         }
793
794         /* iterate through the mesh quads */
795         for ( y = 0; y < ( mesh->height - 1 ); y++ )
796         {
797                 for ( x = 0; x < ( mesh->width - 1 ); x++ )
798                 {
799                         /* set indexes */
800                         pw[ 0 ] = x + ( y * mesh->width );
801                         pw[ 1 ] = x + ( ( y + 1 ) * mesh->width );
802                         pw[ 2 ] = x + 1 + ( ( y + 1 ) * mesh->width );
803                         pw[ 3 ] = x + 1 + ( y * mesh->width );
804                         pw[ 4 ] = x + ( y * mesh->width );    /* same as pw[ 0 ] */
805
806                         /* set radix */
807                         r = ( x + y ) & 1;
808
809                         /* get drawverts */
810                         dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ];
811                         dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ];
812                         dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ];
813                         dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ];
814
815                         /* planar? */
816                         planar = PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz );
817                         if ( planar ) {
818                                 dist = DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ];
819                                 if ( fabs( dist ) > PLANAR_EPSILON ) {
820                                         planar = qfalse;
821                                 }
822                         }
823
824                         /* generate a quad */
825                         if ( planar ) {
826                                 rw.numVerts = 4;
827                                 for ( v = 0; v < 4; v++ )
828                                 {
829                                         /* get most everything */
830                                         memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) );
831
832                                         /* fix colors */
833                                         for ( i = 0; i < MAX_LIGHTMAPS; i++ )
834                                         {
835                                                 radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] );
836                                                 VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] );
837                                                 rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ];
838                                         }
839                                 }
840
841                                 /* subdivide into area lights */
842                                 RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, &rw, cw );
843                         }
844
845                         /* generate 2 tris */
846                         else
847                         {
848                                 rw.numVerts = 3;
849                                 for ( t = 0; t < 2; t++ )
850                                 {
851                                         for ( v = 0; v < 3 + t; v++ )
852                                         {
853                                                 /* get "other" triangle (stupid hacky logic, but whatevah) */
854                                                 if ( v == 1 && t == 1 ) {
855                                                         v++;
856                                                 }
857
858                                                 /* get most everything */
859                                                 memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) );
860
861                                                 /* fix colors */
862                                                 for ( i = 0; i < MAX_LIGHTMAPS; i++ )
863                                                 {
864                                                         radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] );
865                                                         VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] );
866                                                         rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ];
867                                                 }
868                                         }
869
870                                         /* subdivide into area lights */
871                                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, &rw, cw );
872                                 }
873                         }
874                 }
875         }
876
877         /* free the mesh */
878         FreeMesh( mesh );
879 }
880
881
882
883
884 /*
885    RadLight()
886    creates unbounced diffuse lights for a given surface
887  */
888
889 void RadLight( int num ){
890         int lightmapNum;
891         float scale, subdivide;
892         int contentFlags, surfaceFlags, compileFlags;
893         bspDrawSurface_t    *ds;
894         surfaceInfo_t       *info;
895         rawLightmap_t       *lm;
896         shaderInfo_t        *si;
897         clipWork_t cw;
898
899
900         /* get drawsurface, lightmap, and shader info */
901         ds = &bspDrawSurfaces[ num ];
902         info = &surfaceInfos[ num ];
903         lm = info->lm;
904         si = info->si;
905         scale = si->bounceScale;
906
907         /* find nodraw bit */
908         contentFlags = surfaceFlags = compileFlags = 0;
909         ApplySurfaceParm( "nodraw", &contentFlags, &surfaceFlags, &compileFlags );
910
911         // jal : avoid bouncing on trans surfaces
912         ApplySurfaceParm( "trans", &contentFlags, &surfaceFlags, &compileFlags );
913
914         /* early outs? */
915         if ( scale <= 0.0f || ( si->compileFlags & C_SKY ) || si->autosprite ||
916                  ( bspShaders[ ds->shaderNum ].contentFlags & contentFlags ) || ( bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags ) ||
917                  ( si->compileFlags & compileFlags ) ) {
918                 return;
919         }
920
921         /* determine how much we need to chop up the surface */
922         if ( si->lightSubdivide ) {
923                 subdivide = si->lightSubdivide;
924         }
925         else{
926                 subdivide = diffuseSubdivide;
927         }
928
929         /* inc counts */
930         numDiffuseSurfaces++;
931
932         /* iterate through styles (this could be more efficient, yes) */
933         for ( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
934         {
935                 /* switch on type */
936                 if ( ds->lightmapStyles[ lightmapNum ] != LS_NONE && ds->lightmapStyles[ lightmapNum ] != LS_UNUSED ) {
937                         switch ( ds->surfaceType )
938                         {
939                         case MST_PLANAR:
940                         case MST_TRIANGLE_SOUP:
941                                 RadLightForTriangles( num, lightmapNum, lm, si, scale, subdivide, &cw );
942                                 break;
943
944                         case MST_PATCH:
945                                 RadLightForPatch( num, lightmapNum, lm, si, scale, subdivide, &cw );
946                                 break;
947
948                         default:
949                                 break;
950                         }
951                 }
952         }
953 }
954
955
956
957 /*
958    RadCreateDiffuseLights()
959    creates lights for unbounced light on surfaces in the bsp
960  */
961
962 int iterations = 0;
963
964 void RadCreateDiffuseLights( void ){
965         /* startup */
966         Sys_FPrintf( SYS_VRB, "--- RadCreateDiffuseLights ---\n" );
967         numDiffuseSurfaces = 0;
968         numDiffuseLights = 0;
969         numBrushDiffuseLights = 0;
970         numTriangleDiffuseLights = 0;
971         numPatchDiffuseLights = 0;
972         numAreaLights = 0;
973
974         /* hit every surface (threaded) */
975         RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, RadLight );
976
977         /* dump the lights generated to a file */
978         if ( dump ) {
979                 char dumpName[ 1024 ], ext[ 64 ];
980                 FILE    *file;
981                 light_t *light;
982
983                 strcpy( dumpName, source );
984                 StripExtension( dumpName );
985                 sprintf( ext, "_bounce_%03d.map", iterations );
986                 strcat( dumpName, ext );
987                 file = fopen( dumpName, "wb" );
988                 Sys_Printf( "Writing %s...\n", dumpName );
989                 if ( file ) {
990                         for ( light = lights; light; light = light->next )
991                         {
992                                 fprintf( file,
993                                                  "{\n"
994                                                  "\"classname\" \"light\"\n"
995                                                  "\"light\" \"%d\"\n"
996                                                  "\"origin\" \"%.0f %.0f %.0f\"\n"
997                                                  "\"_color\" \"%.3f %.3f %.3f\"\n"
998                                                  "}\n",
999
1000                                                  (int) light->add,
1001
1002                                                  light->origin[ 0 ],
1003                                                  light->origin[ 1 ],
1004                                                  light->origin[ 2 ],
1005
1006                                                  light->color[ 0 ],
1007                                                  light->color[ 1 ],
1008                                                  light->color[ 2 ] );
1009                         }
1010                         fclose( file );
1011                 }
1012         }
1013
1014         /* increment */
1015         iterations++;
1016
1017         /* print counts */
1018         Sys_Printf( "%8d diffuse surfaces\n", numDiffuseSurfaces );
1019         Sys_FPrintf( SYS_VRB, "%8d total diffuse lights\n", numDiffuseLights );
1020         Sys_FPrintf( SYS_VRB, "%8d brush diffuse lights\n", numBrushDiffuseLights );
1021         Sys_FPrintf( SYS_VRB, "%8d patch diffuse lights\n", numPatchDiffuseLights );
1022         Sys_FPrintf( SYS_VRB, "%8d triangle diffuse lights\n", numTriangleDiffuseLights );
1023 }