ABToSVK commit
[xonotic/netradiant.git] / tools / quake3 / q3map2 / writebsp.c
1 /*
2 Copyright (C) 1999-2007 id Software, Inc. and contributors.
3 For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5 This file is part of GtkRadiant.
6
7 GtkRadiant is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 GtkRadiant is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GtkRadiant; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20
21 ----------------------------------------------------------------------------------
22
23 This code has been altered significantly from its original form, to support
24 several games based on the Quake III Arena engine, in the form of "Q3Map2."
25
26 ------------------------------------------------------------------------------- */
27
28
29
30 /* marker */
31 #define WRITEBSP_C
32
33
34
35 /* dependencies */
36 #include "q3map2.h"
37
38
39
40 /*
41 EmitShader()
42 emits a bsp shader entry
43 */
44
45 int     EmitShader( const char *shader, int *contentFlags, int *surfaceFlags )
46 {
47         int                             i;
48         shaderInfo_t    *si;
49         
50         
51         /* handle special cases */
52         if( shader == NULL )
53                 shader = "noshader";
54         
55         /* try to find an existing shader */
56         for( i = 0; i < numBSPShaders; i++ )
57         {
58                 /* ydnar: handle custom surface/content flags */
59                 if( surfaceFlags != NULL && bspShaders[ i ].surfaceFlags != *surfaceFlags )
60                         continue;
61                 if( contentFlags != NULL && bspShaders[ i ].contentFlags != *contentFlags )
62                         continue;
63                 
64                 /* compare name */
65                 if( !Q_stricmp( shader, bspShaders[ i ].shader ) )
66                         return i;
67         }
68         
69         /* get shaderinfo */
70         si = ShaderInfoForShader( shader );
71         
72         /* emit a new shader */
73         if( i == MAX_MAP_SHADERS )
74                 Error( "MAX_MAP_SHADERS" );
75         numBSPShaders++;
76         strcpy( bspShaders[ i ].shader, shader );
77         bspShaders[ i ].surfaceFlags = si->surfaceFlags;
78         bspShaders[ i ].contentFlags = si->contentFlags;
79         
80         /* handle custom content/surface flags */
81         if( surfaceFlags != NULL )
82                 bspShaders[ i ].surfaceFlags = *surfaceFlags;
83         if( contentFlags != NULL )
84                 bspShaders[ i ].contentFlags = *contentFlags;
85         
86         /* recursively emit any damage shaders */
87         if( si->damageShader[ 0 ] != '\0' )
88         {
89                 Sys_FPrintf( SYS_VRB, "Shader %s has damage shader %s\n", si->shader, si->damageShader );
90                 EmitShader( si->damageShader, NULL, NULL );
91         }
92         
93         /* return it */
94         return i;
95 }
96
97
98
99 /*
100 EmitPlanes()
101 there is no oportunity to discard planes, because all of the original
102 brushes will be saved in the map
103 */
104
105 void EmitPlanes( void )
106 {
107         int                     i;
108         bspPlane_t      *bp;
109         plane_t         *mp;
110         
111         
112         /* walk plane list */
113         mp = mapplanes;
114         for( i = 0; i < nummapplanes; i++, mp++ )
115         {
116                 bp = &bspPlanes[ numBSPPlanes ];
117                 VectorCopy( mp->normal, bp->normal );
118                 bp->dist = mp->dist;
119                 numBSPPlanes++;
120         }
121         
122         /* emit some statistics */
123         Sys_FPrintf( SYS_VRB, "%9d BSP planes\n", numBSPPlanes );
124 }
125
126
127
128 /*
129 EmitLeaf()
130 emits a leafnode to the bsp file
131 */
132
133 void EmitLeaf( node_t *node )
134 {
135         bspLeaf_t               *leaf_p;
136         brush_t                 *b;
137         drawSurfRef_t   *dsr;
138         int                             i = 0;
139
140         
141         /* check limits */
142         if( numBSPLeafs >= MAX_MAP_LEAFS )
143                 Error( "MAX_MAP_LEAFS" );
144
145         leaf_p = &bspLeafs[numBSPLeafs];
146         numBSPLeafs++;
147
148         leaf_p->cluster = node->cluster;
149         leaf_p->area = node->area;
150
151         /* emit bounding box */
152         VectorCopy( node->mins, leaf_p->mins );
153         VectorCopy( node->maxs, leaf_p->maxs );
154         
155         /* emit leaf brushes */
156         leaf_p->firstBSPLeafBrush = numBSPLeafBrushes;
157         for( b = node->brushlist; b; b = b->next )
158         {
159                 /* something is corrupting brushes */
160                 if( (int) b < 256 )
161                 {
162                         Sys_Printf( "WARNING: Node brush list corrupted (0x%08X)\n", b );
163                         break;
164                 }
165                 //%     if( b->guard != 0xDEADBEEF )
166                 //%             Sys_Printf( "Brush %6d: 0x%08X Guard: 0x%08X Next: 0x%08X Original: 0x%08X Sides: %d\n", b->brushNum, b, b, b->next, b->original, b->numsides );
167                 
168                 if( numBSPLeafBrushes >= MAX_MAP_LEAFBRUSHES )
169                         Error( "MAX_MAP_LEAFBRUSHES" );
170                 bspLeafBrushes[ numBSPLeafBrushes ] = b->original->outputNum;
171                 numBSPLeafBrushes++;
172         }
173         
174         leaf_p->numBSPLeafBrushes = numBSPLeafBrushes - leaf_p->firstBSPLeafBrush;
175         
176         /* emit leaf surfaces */
177         if( node->opaque )
178                 return;
179         
180         /* add the drawSurfRef_t drawsurfs */
181         leaf_p->firstBSPLeafSurface = numBSPLeafSurfaces;
182         for ( dsr = node->drawSurfReferences; dsr; dsr = dsr->nextRef )
183         {
184                 if( numBSPLeafSurfaces >= MAX_MAP_LEAFFACES )
185                         Error( "MAX_MAP_LEAFFACES" );
186                 bspLeafSurfaces[ numBSPLeafSurfaces ] = dsr->outputNum;
187                 numBSPLeafSurfaces++;                   
188         }
189         
190         leaf_p->numBSPLeafSurfaces = numBSPLeafSurfaces - leaf_p->firstBSPLeafSurface;
191 }
192
193
194 /*
195 EmitDrawNode_r()
196 recursively emit the bsp nodes
197 */
198
199 int EmitDrawNode_r( node_t *node )
200 {
201         bspNode_t       *n;
202         int                     i;
203         
204         
205         /* check for leafnode */
206         if( node->planenum == PLANENUM_LEAF )
207         {
208                 EmitLeaf( node );
209                 return -numBSPLeafs;
210         }
211         
212         /* emit a node */
213         if( numBSPNodes == MAX_MAP_NODES )
214                 Error( "MAX_MAP_NODES" );
215         n = &bspNodes[ numBSPNodes ];
216         numBSPNodes++;
217         
218         VectorCopy (node->mins, n->mins);
219         VectorCopy (node->maxs, n->maxs);
220
221         if (node->planenum & 1)
222                 Error ("WriteDrawNodes_r: odd planenum");
223         n->planeNum = node->planenum;
224
225         //
226         // recursively output the other nodes
227         //      
228         for (i=0 ; i<2 ; i++)
229         {
230                 if (node->children[i]->planenum == PLANENUM_LEAF)
231                 {
232                         n->children[i] = -(numBSPLeafs + 1);
233                         EmitLeaf (node->children[i]);
234                 }
235                 else
236                 {
237                         n->children[i] = numBSPNodes;   
238                         EmitDrawNode_r (node->children[i]);
239                 }
240         }
241
242         return n - bspNodes;
243 }
244
245
246
247 /*
248 ============
249 SetModelNumbers
250 ============
251 */
252 void SetModelNumbers (void)
253 {
254         int             i;
255         int             models;
256         char    value[10];
257
258         models = 1;
259         for ( i=1 ; i<numEntities ; i++ ) {
260                 if ( entities[i].brushes || entities[i].patches ) {
261                         sprintf ( value, "*%i", models );
262                         models++;
263                         SetKeyValue (&entities[i], "model", value);
264                 }
265         }
266
267 }
268
269
270
271
272 /*
273 SetLightStyles()
274 sets style keys for entity lights
275 */
276
277 void SetLightStyles( void )
278 {
279         int                     i, j, style, numStyles;
280         qboolean        keepLights;
281         const char      *t;
282         entity_t        *e;
283         epair_t         *ep, *next;
284         char            value[ 10 ];
285         char            lightTargets[ MAX_SWITCHED_LIGHTS ][ 64 ];
286         int                     lightStyles[ MAX_SWITCHED_LIGHTS ];
287         
288         
289         /* ydnar: determine if we keep lights in the bsp */
290         t = ValueForKey( &entities[ 0 ], "_keepLights" );
291         keepLights = (t[ 0 ] == '1') ? qtrue : qfalse;
292         
293         /* any light that is controlled (has a targetname) must have a unique style number generated for it */
294         numStyles = 0;
295         for( i = 1; i < numEntities; i++ )
296         {
297                 e = &entities[ i ];
298
299                 t = ValueForKey( e, "classname" );
300                 if( Q_strncasecmp( t, "light", 5 ) )
301                         continue;
302                 t = ValueForKey( e, "targetname" );
303                 if( t[ 0 ] == '\0' )
304                 {
305                         /* ydnar: strip the light from the BSP file */
306                         if( keepLights == qfalse )
307                         {
308                                 ep = e->epairs;
309                                 while( ep != NULL )
310                                 {
311                                         next = ep->next;
312                                         free( ep->key );
313                                         free( ep->value );
314                                         free( ep );
315                                         ep = next;
316                                 }
317                                 e->epairs = NULL;
318                                 numStrippedLights++;
319                         }
320                         
321                         /* next light */
322                         continue;
323                 }
324                 
325                 /* get existing style */
326                 style = IntForKey( e, "style" );
327                 if( style < LS_NORMAL || style > LS_NONE )
328                         Error( "Invalid lightstyle (%d) on entity %d", style, i );
329                 
330                 /* find this targetname */
331                 for( j = 0; j < numStyles; j++ )
332                         if( lightStyles[ j ] == style && !strcmp( lightTargets[ j ], t ) )
333                                 break;
334                 
335                 /* add a new style */
336                 if( j >= numStyles )
337                 {
338                         if( numStyles == MAX_SWITCHED_LIGHTS )
339                                 Error( "MAX_SWITCHED_LIGHTS (%d) exceeded, reduce the number of lights with targetnames", MAX_SWITCHED_LIGHTS );
340                         strcpy( lightTargets[ j ], t );
341                         lightStyles[ j ] = style;
342                         numStyles++;
343                 }
344                 
345                 /* set explicit style */
346                 sprintf( value, "%d", 32 + j );
347                 SetKeyValue( e, "style", value );
348                 
349                 /* set old style */
350                 if( style != LS_NORMAL )
351                 {
352                         sprintf( value, "%d", style );
353                         SetKeyValue( e, "switch_style", value );
354                 }
355         }
356         
357         /* emit some statistics */
358         Sys_FPrintf( SYS_VRB, "%9d light entities stripped\n", numStrippedLights );
359 }
360
361
362
363 /*
364 BeginBSPFile()
365 starts a new bsp file
366 */
367
368 void BeginBSPFile( void )
369 {
370         /* these values may actually be initialized if the file existed when loaded, so clear them explicitly */
371         numBSPModels = 0;
372         numBSPNodes = 0;
373         numBSPBrushSides = 0;
374         numBSPLeafSurfaces = 0;
375         numBSPLeafBrushes = 0;
376         
377         /* leave leaf 0 as an error, because leafs are referenced as negative number nodes */
378         numBSPLeafs = 1;
379         
380         
381         /* ydnar: gs mods: set the first 6 drawindexes to 0 1 2 2 1 3 for triangles and quads */
382         numBSPDrawIndexes = 6;
383         bspDrawIndexes[ 0 ] = 0;
384         bspDrawIndexes[ 1 ] = 1;
385         bspDrawIndexes[ 2 ] = 2;
386         bspDrawIndexes[ 3 ] = 0;
387         bspDrawIndexes[ 4 ] = 2;
388         bspDrawIndexes[ 5 ] = 3;
389 }
390
391
392
393 /*
394 EndBSPFile()
395 finishes a new bsp and writes to disk
396 */
397
398 void EndBSPFile( void )
399 {
400         char    path[ 1024 ];
401         
402
403         Sys_FPrintf( SYS_VRB, "--- EndBSPFile ---\n" );
404
405         EmitPlanes();
406         
407         numBSPEntities = numEntities;
408         UnparseEntities();
409         
410         /* write the surface extra file */
411         WriteSurfaceExtraFile( source );
412         
413         /* write the bsp */
414         sprintf( path, "%s.bsp", source );
415         Sys_Printf( "Writing %s\n", path );
416         WriteBSPFile( path );
417 }
418
419
420
421 /*
422 EmitBrushes()
423 writes the brush list to the bsp
424 */
425
426 void EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes )
427 {
428         int                             j;
429         brush_t                 *b;
430         bspBrush_t              *db;
431         bspBrushSide_t  *cp;
432         
433         
434         /* set initial brush */
435         if( firstBrush != NULL )
436                 *firstBrush = numBSPBrushes;
437         if( numBrushes != NULL )
438                 *numBrushes = 0;
439         
440         /* walk list of brushes */
441         for( b = brushes; b != NULL; b = b->next )
442         {
443                 /* check limits */
444                 if( numBSPBrushes == MAX_MAP_BRUSHES )
445                         Error( "MAX_MAP_BRUSHES (%d)", numBSPBrushes );
446                 
447                 /* get bsp brush */
448                 b->outputNum = numBSPBrushes;
449                 db = &bspBrushes[ numBSPBrushes ];
450                 numBSPBrushes++;
451                 if( numBrushes != NULL )
452                         (*numBrushes)++;
453                 
454                 db->shaderNum = EmitShader( b->contentShader->shader, &b->contentShader->contentFlags, &b->contentShader->surfaceFlags );
455                 db->firstSide = numBSPBrushSides;
456                 
457                 /* walk sides */
458                 db->numSides = 0;
459                 for( j = 0; j < b->numsides; j++ )
460                 {
461                         /* set output number to bogus initially */
462                         b->sides[ j ].outputNum = -1;
463                         
464                         /* don't emit generated backSide sides */
465                         if ( b->sides[ j ].backSide )
466                                 continue;
467                         
468                         /* check count */
469                         if( numBSPBrushSides == MAX_MAP_BRUSHSIDES )
470                                 Error( "MAX_MAP_BRUSHSIDES ");
471                         
472                         /* emit side */
473                         b->sides[ j ].outputNum = numBSPBrushSides;
474                         cp = &bspBrushSides[ numBSPBrushSides ];
475                         db->numSides++;
476                         numBSPBrushSides++;
477                         cp->planeNum = b->sides[ j ].planenum;
478                         
479                         /* emit shader */
480                         if( b->sides[ j ].shaderInfo )
481                                 cp->shaderNum = EmitShader( b->sides[ j ].shaderInfo->shader, &b->sides[ j ].shaderInfo->contentFlags, &b->sides[ j ].shaderInfo->surfaceFlags );
482                         else
483                                 cp->shaderNum = EmitShader( NULL, NULL, NULL );
484                 }
485         }
486 }
487
488
489
490 /*
491 EmitFogs() - ydnar
492 turns map fogs into bsp fogs
493 */
494
495 void EmitFogs( void )
496 {
497         int                     i, j;
498         
499         
500         /* setup */
501         numBSPFogs = numMapFogs;
502         
503         /* walk list */
504         for( i = 0; i < numMapFogs; i++ )
505         {
506                 /* set shader */
507                 strcpy( bspFogs[ i ].shader, mapFogs[ i ].si->shader );
508                 
509                 /* global fog doesn't have an associated brush */
510                 if( mapFogs[ i ].brush == NULL )
511                 {
512                         bspFogs[ i ].brushNum = -1;
513                         bspFogs[ i ].visibleSide = -1;
514                 }
515                 else
516                 {
517                         /* set brush */
518                         bspFogs[ i ].brushNum = mapFogs[ i ].brush->outputNum;
519                         
520                         /* try to use forced visible side */
521                         if( mapFogs[ i ].visibleSide >= 0 )
522                         {
523                                 bspFogs[ i ].visibleSide = mapFogs[ i ].visibleSide;
524                                 continue;
525                         }
526                         
527                         /* find visible side */
528                         for( j = 0; j < 6; j++ )
529                         {
530                                 if( mapFogs[ i ].brush->sides[ j ].visibleHull != NULL )
531                                 {
532                                         Sys_Printf( "Fog %d has visible side %d\n", i, j );
533                                         bspFogs[ i ].visibleSide = j;
534                                         break;
535                                 }
536                         }
537                 }
538         }
539 }
540
541
542
543 /*
544 BeginModel()
545 sets up a new brush model
546 */
547
548 void BeginModel( void )
549 {
550         bspModel_t      *mod;
551         brush_t         *b;
552         entity_t        *e;
553         vec3_t          mins, maxs;
554         vec3_t          lgMins, lgMaxs;         /* ydnar: lightgrid mins/maxs */
555         parseMesh_t     *p;
556         int                     i;
557         
558         
559         /* test limits */
560         if( numBSPModels == MAX_MAP_MODELS )
561                 Error( "MAX_MAP_MODELS" );
562         
563         /* get model and entity */
564         mod = &bspModels[ numBSPModels ];
565         e = &entities[ mapEntityNum ];
566         
567         /* ydnar: lightgrid mins/maxs */
568         ClearBounds( lgMins, lgMaxs );
569         
570         /* bound the brushes */
571         ClearBounds( mins, maxs );
572         for ( b = e->brushes; b; b = b->next )
573         {
574                 /* ignore non-real brushes (origin, etc) */
575                 if( b->numsides == 0 )
576                         continue;
577                 AddPointToBounds( b->mins, mins, maxs );
578                 AddPointToBounds( b->maxs, mins, maxs );
579                 
580                 /* ydnar: lightgrid bounds */
581                 if( b->compileFlags & C_LIGHTGRID )
582                 {
583                         AddPointToBounds( b->mins, lgMins, lgMaxs );
584                         AddPointToBounds( b->maxs, lgMins, lgMaxs );
585                 }
586         }
587         
588         /* bound patches */
589         for( p = e->patches; p; p = p->next )
590         {
591                 for( i = 0; i < (p->mesh.width * p->mesh.height); i++ )
592                         AddPointToBounds( p->mesh.verts[i].xyz, mins, maxs );
593         }
594         
595         /* ydnar: lightgrid mins/maxs */
596         if( lgMins[ 0 ] < 99999 )
597         {
598                 /* use lightgrid bounds */
599                 VectorCopy( lgMins, mod->mins );
600                 VectorCopy( lgMaxs, mod->maxs );
601         }
602         else
603         {
604                 /* use brush/patch bounds */
605                 VectorCopy( mins, mod->mins );
606                 VectorCopy( maxs, mod->maxs );
607         }
608         
609         /* note size */
610         Sys_FPrintf( SYS_VRB, "BSP bounds: { %f %f %f } { %f %f %f }\n", mins[ 0 ], mins[ 1 ], mins[ 2 ], maxs[ 0 ], maxs[ 1 ], maxs[ 2 ] );
611         Sys_FPrintf( SYS_VRB, "Lightgrid bounds: { %f %f %f } { %f %f %f }\n", lgMins[ 0 ], lgMins[ 1 ], lgMins[ 2 ], lgMaxs[ 0 ], lgMaxs[ 1 ], lgMaxs[ 2 ] );
612         
613         /* set firsts */
614         mod->firstBSPSurface = numBSPDrawSurfaces;
615         mod->firstBSPBrush = numBSPBrushes;
616 }
617
618
619
620
621 /*
622 EndModel()
623 finish a model's processing
624 */
625
626 void EndModel( entity_t *e, node_t *headnode )
627 {
628         bspModel_t      *mod;
629         
630         
631         /* note it */
632         Sys_FPrintf( SYS_VRB, "--- EndModel ---\n" );
633         
634         /* emit the bsp */
635         mod = &bspModels[ numBSPModels ];
636         EmitDrawNode_r( headnode );
637         
638         /* set surfaces and brushes */
639         mod->numBSPSurfaces = numBSPDrawSurfaces - mod->firstBSPSurface;
640         mod->firstBSPBrush = e->firstBrush;
641         mod->numBSPBrushes = e->numBrushes;
642         
643         /* increment model count */
644         numBSPModels++;
645 }
646
647
648