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