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