q3map2: fix not displaying default args for some q3map2 stages
[xonotic/netradiant.git] / tools / quake3 / q3map2 / bsp.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 BSP_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /* -------------------------------------------------------------------------------
42
43    functions
44
45    ------------------------------------------------------------------------------- */
46
47
48 /*
49    ProcessAdvertisements()
50    copies advertisement info into the BSP structures
51  */
52
53 static void ProcessAdvertisements( void ) {
54         int i;
55         const char*         className;
56         const char*         modelKey;
57         int modelNum;
58         bspModel_t*         adModel;
59         bspDrawSurface_t*   adSurface;
60
61         Sys_FPrintf( SYS_VRB, "--- ProcessAdvertisements ---\n" );
62
63         for ( i = 0; i < numEntities; i++ ) {
64
65                 /* is an advertisement? */
66                 className = ValueForKey( &entities[ i ], "classname" );
67
68                 if ( !Q_stricmp( "advertisement", className ) ) {
69
70                         modelKey = ValueForKey( &entities[ i ], "model" );
71
72                         if ( strlen( modelKey ) > MAX_QPATH - 1 ) {
73                                 Error( "Model Key for entity exceeds ad struct string length." );
74                         }
75                         else {
76                                 if ( numBSPAds < MAX_MAP_ADVERTISEMENTS ) {
77                                         bspAds[numBSPAds].cellId = IntForKey( &entities[ i ], "cellId" );
78                                         strncpy( bspAds[numBSPAds].model, modelKey, sizeof( bspAds[numBSPAds].model ) );
79
80                                         modelKey++;
81                                         modelNum = atoi( modelKey );
82                                         adModel = &bspModels[modelNum];
83
84                                         if ( adModel->numBSPSurfaces != 1 ) {
85                                                 Error( "Ad cell id %d has more than one surface.", bspAds[numBSPAds].cellId );
86                                         }
87
88                                         adSurface = &bspDrawSurfaces[adModel->firstBSPSurface];
89
90                                         // store the normal for use at run time.. all ad verts are assumed to
91                                         // have identical normals (because they should be a simple rectangle)
92                                         // so just use the first vert's normal
93                                         VectorCopy( bspDrawVerts[adSurface->firstVert].normal, bspAds[numBSPAds].normal );
94
95                                         // store the ad quad for quick use at run time
96                                         if ( adSurface->surfaceType == MST_PATCH ) {
97                                                 int v0 = adSurface->firstVert + adSurface->patchHeight - 1;
98                                                 int v1 = adSurface->firstVert + adSurface->numVerts - 1;
99                                                 int v2 = adSurface->firstVert + adSurface->numVerts - adSurface->patchWidth;
100                                                 int v3 = adSurface->firstVert;
101                                                 VectorCopy( bspDrawVerts[v0].xyz, bspAds[numBSPAds].rect[0] );
102                                                 VectorCopy( bspDrawVerts[v1].xyz, bspAds[numBSPAds].rect[1] );
103                                                 VectorCopy( bspDrawVerts[v2].xyz, bspAds[numBSPAds].rect[2] );
104                                                 VectorCopy( bspDrawVerts[v3].xyz, bspAds[numBSPAds].rect[3] );
105                                         }
106                                         else {
107                                                 Error( "Ad cell %d has an unsupported Ad Surface type.", bspAds[numBSPAds].cellId );
108                                         }
109
110                                         numBSPAds++;
111                                 }
112                                 else {
113                                         Error( "Maximum number of map advertisements exceeded." );
114                                 }
115                         }
116                 }
117         }
118
119         Sys_FPrintf( SYS_VRB, "%9d in-game advertisements\n", numBSPAds );
120 }
121
122 /*
123    SetCloneModelNumbers() - ydnar
124    sets the model numbers for brush entities
125  */
126
127 static void SetCloneModelNumbers( void ){
128         int i, j;
129         int models;
130         char modelValue[ 10 ];
131         const char  *value, *value2, *value3;
132
133
134         /* start with 1 (worldspawn is model 0) */
135         models = 1;
136         for ( i = 1; i < numEntities; i++ )
137         {
138                 /* only entities with brushes or patches get a model number */
139                 if ( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) {
140                         continue;
141                 }
142
143                 /* is this a clone? */
144                 value = ValueForKey( &entities[ i ], "_ins" );
145                 if ( value[ 0 ] == '\0' ) {
146                         value = ValueForKey( &entities[ i ], "_instance" );
147                 }
148                 if ( value[ 0 ] == '\0' ) {
149                         value = ValueForKey( &entities[ i ], "_clone" );
150                 }
151                 if ( value[ 0 ] != '\0' ) {
152                         continue;
153                 }
154
155                 /* add the model key */
156                 sprintf( modelValue, "*%d", models );
157                 SetKeyValue( &entities[ i ], "model", modelValue );
158
159                 /* increment model count */
160                 models++;
161         }
162
163         /* fix up clones */
164         for ( i = 1; i < numEntities; i++ )
165         {
166                 /* only entities with brushes or patches get a model number */
167                 if ( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) {
168                         continue;
169                 }
170
171                 /* is this a clone? */
172                 value = ValueForKey( &entities[ i ], "_ins" );
173                 if ( value[ 0 ] == '\0' ) {
174                         value = ValueForKey( &entities[ i ], "_instance" );
175                 }
176                 if ( value[ 0 ] == '\0' ) {
177                         value = ValueForKey( &entities[ i ], "_clone" );
178                 }
179                 if ( value[ 0 ] == '\0' ) {
180                         continue;
181                 }
182
183                 /* find an entity with matching clone name */
184                 for ( j = 0; j < numEntities; j++ )
185                 {
186                         /* is this a clone parent? */
187                         value2 = ValueForKey( &entities[ j ], "_clonename" );
188                         if ( value2[ 0 ] == '\0' ) {
189                                 continue;
190                         }
191
192                         /* do they match? */
193                         if ( strcmp( value, value2 ) == 0 ) {
194                                 /* get the model num */
195                                 value3 = ValueForKey( &entities[ j ], "model" );
196                                 if ( value3[ 0 ] == '\0' ) {
197                                         Sys_FPrintf( SYS_WRN, "WARNING: Cloned entity %s referenced entity without model\n", value2 );
198                                         continue;
199                                 }
200                                 models = atoi( &value2[ 1 ] );
201
202                                 /* add the model key */
203                                 sprintf( modelValue, "*%d", models );
204                                 SetKeyValue( &entities[ i ], "model", modelValue );
205
206                                 /* nuke the brushes/patches for this entity (fixme: leak!) */
207                                 entities[ i ].brushes = NULL;
208                                 entities[ i ].patches = NULL;
209                         }
210                 }
211         }
212 }
213
214
215
216 /*
217    FixBrushSides() - ydnar
218    matches brushsides back to their appropriate drawsurface and shader
219  */
220
221 static void FixBrushSides( entity_t *e ){
222         int i;
223         mapDrawSurface_t    *ds;
224         sideRef_t           *sideRef;
225         bspBrushSide_t      *side;
226
227
228         /* note it */
229         Sys_FPrintf( SYS_VRB, "--- FixBrushSides ---\n" );
230
231         /* walk list of drawsurfaces */
232         for ( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ )
233         {
234                 /* get surface and try to early out */
235                 ds = &mapDrawSurfs[ i ];
236                 if ( ds->outputNum < 0 ) {
237                         continue;
238                 }
239
240                 /* walk sideref list */
241                 for ( sideRef = ds->sideRef; sideRef != NULL; sideRef = sideRef->next )
242                 {
243                         /* get bsp brush side */
244                         if ( sideRef->side == NULL || sideRef->side->outputNum < 0 ) {
245                                 continue;
246                         }
247                         side = &bspBrushSides[ sideRef->side->outputNum ];
248
249                         /* set drawsurface */
250                         side->surfaceNum = ds->outputNum;
251                         //%     Sys_FPrintf( SYS_VRB, "DS: %7d Side: %7d     ", ds->outputNum, sideRef->side->outputNum );
252
253                         /* set shader */
254                         if ( strcmp( bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader ) ) {
255                                 //%     Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader );
256                                 side->shaderNum = EmitShader( ds->shaderInfo->shader, &ds->shaderInfo->contentFlags, &ds->shaderInfo->surfaceFlags );
257                         }
258                 }
259         }
260 }
261
262
263
264 /*
265    ProcessWorldModel()
266    creates a full bsp + surfaces for the worldspawn entity
267  */
268
269 void ProcessWorldModel( const char *portalFilePath, const char *lineFilePath ){
270         int i, s;
271         entity_t    *e;
272         tree_t      *tree;
273         face_t      *faces;
274         qboolean ignoreLeaks, leaked;
275         xmlNodePtr polyline, leaknode;
276         char level[ 2 ], shader[ 1024 ];
277         const char  *value;
278         int leakStatus;
279
280         /* sets integer blockSize from worldspawn "_blocksize" key if it exists */
281         value = ValueForKey( &entities[ 0 ], "_blocksize" );
282         if ( value[ 0 ] == '\0' ) {
283                 value = ValueForKey( &entities[ 0 ], "blocksize" );
284         }
285         if ( value[ 0 ] == '\0' ) {
286                 value = ValueForKey( &entities[ 0 ], "chopsize" );  /* sof2 */
287         }
288         if ( value[ 0 ] != '\0' ) {
289                 /* scan 3 numbers */
290                 s = sscanf( value, "%d %d %d", &blockSize[ 0 ], &blockSize[ 1 ], &blockSize[ 2 ] );
291
292                 /* handle legacy case */
293                 if ( s == 1 ) {
294                         blockSize[ 1 ] = blockSize[ 0 ];
295                         blockSize[ 2 ] = blockSize[ 0 ];
296                 }
297         }
298         Sys_Printf( "block size = { %d %d %d }\n", blockSize[ 0 ], blockSize[ 1 ], blockSize[ 2 ] );
299
300         /* sof2: ignore leaks? */
301         value = ValueForKey( &entities[ 0 ], "_ignoreleaks" );  /* ydnar */
302         if ( value[ 0 ] == '\0' ) {
303                 value = ValueForKey( &entities[ 0 ], "ignoreleaks" );
304         }
305         if ( value[ 0 ] == '1' ) {
306                 ignoreLeaks = qtrue;
307         }
308         else{
309                 ignoreLeaks = qfalse;
310         }
311
312         /* begin worldspawn model */
313         BeginModel();
314         e = &entities[ 0 ];
315         e->firstDrawSurf = 0;
316
317         /* ydnar: gs mods */
318         ClearMetaTriangles();
319
320         /* check for patches with adjacent edges that need to lod together */
321         PatchMapDrawSurfs( e );
322
323         /* build an initial bsp tree using all of the sides of all of the structural brushes */
324         faces = MakeStructuralBSPFaceList( entities[ 0 ].brushes );
325         tree = FaceBSP( faces );
326         MakeTreePortals( tree );
327         FilterStructuralBrushesIntoTree( e, tree );
328
329         /* see if the bsp is completely enclosed */
330         leakStatus = FloodEntities( tree );
331         if ( ignoreLeaks ) {
332                 if ( leakStatus == FLOODENTITIES_LEAKED ) {
333                         leakStatus = FLOODENTITIES_GOOD;
334                 }
335         }
336
337         if ( leakStatus == FLOODENTITIES_GOOD ) {
338                 leaked = qfalse;
339         }
340         else
341         {
342                 leaked = qtrue;
343
344                 Sys_FPrintf( SYS_NOXML, "**********************\n" );
345                 Sys_FPrintf( SYS_NOXML, "******* leaked *******\n" );
346                 Sys_FPrintf( SYS_NOXML, "**********************\n" );
347                 polyline = LeakFile( tree, lineFilePath );
348                 leaknode = xmlNewNode( NULL, (xmlChar*)"message" );
349                 xmlNodeAddContent( leaknode, (xmlChar*)"MAP LEAKED\n" );
350                 xmlAddChild( leaknode, polyline );
351                 level[0] = (int) '0' + SYS_ERR;
352                 level[1] = 0;
353                 xmlSetProp( leaknode, (xmlChar*)"level", (xmlChar*) &level );
354                 xml_SendNode( leaknode );
355                 if ( leaktest ) {
356                         Sys_Printf( "--- MAP LEAKED, ABORTING LEAKTEST ---\n" );
357                         exit( 0 );
358                 }
359         }
360
361         if ( leakStatus != FLOODENTITIES_EMPTY ) { /* if no entities exist, this would accidentally the whole map, and that IS bad */
362                 /* rebuild a better bsp tree using only the sides that are visible from the inside */
363                 FillOutside( tree->headnode );
364
365                 /* chop the sides to the convex hull of their visible fragments, giving us the smallest polygons */
366                 ClipSidesIntoTree( e, tree );
367
368                 /* build a visible face tree (same thing as the initial bsp tree but after reducing the faces) */
369                 faces = MakeVisibleBSPFaceList( entities[ 0 ].brushes );
370                 FreeTree( tree );
371                 tree = FaceBSP( faces );
372                 MakeTreePortals( tree );
373                 FilterStructuralBrushesIntoTree( e, tree );
374
375                 /* ydnar: flood again for skybox */
376                 if ( skyboxPresent ) {
377                         FloodEntities( tree );
378                 }
379         }
380
381         /* save out information for visibility processing */
382         NumberClusters( tree );
383         if ( !leaked ) {
384                 WritePortalFile( tree, portalFilePath );
385         }
386
387         /* flood from entities */
388         FloodAreas( tree );
389
390         /* create drawsurfs for triangle models */
391         AddTriangleModels( e );
392
393         /* create drawsurfs for surface models */
394         AddEntitySurfaceModels( e );
395
396         /* generate bsp brushes from map brushes */
397         EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes );
398
399         /* add references to the detail brushes */
400         FilterDetailBrushesIntoTree( e, tree );
401
402         /* drawsurfs that cross fog boundaries will need to be split along the fog boundary */
403         if ( !nofog ) {
404                 FogDrawSurfaces( e );
405         }
406
407         /* subdivide each drawsurf as required by shader tesselation */
408         if ( !nosubdivide ) {
409                 SubdivideFaceSurfaces( e, tree );
410         }
411
412         /* add in any vertexes required to fix t-junctions */
413         if ( !notjunc ) {
414                 FixTJunctions( e );
415         }
416
417         /* ydnar: classify the surfaces */
418         ClassifyEntitySurfaces( e );
419
420         /* ydnar: project decals */
421         MakeEntityDecals( e );
422
423         /* ydnar: meta surfaces */
424         MakeEntityMetaTriangles( e );
425         SmoothMetaTriangles();
426         FixMetaTJunctions();
427         MergeMetaTriangles();
428
429         /* ydnar: debug portals */
430         if ( debugPortals ) {
431                 MakeDebugPortalSurfs( tree );
432         }
433
434         /* ydnar: fog hull */
435         value = ValueForKey( &entities[ 0 ], "_foghull" );
436         if ( value[ 0 ] != '\0' ) {
437                 sprintf( shader, "textures/%s", value );
438                 MakeFogHullSurfs( e, tree, shader );
439         }
440
441         /* ydnar: bug 645: do flares for lights */
442         for ( i = 0; i < numEntities && emitFlares; i++ )
443         {
444                 entity_t    *light, *target;
445                 const char  *value, *flareShader;
446                 vec3_t origin, targetOrigin, normal, color;
447                 int lightStyle;
448
449
450                 /* get light */
451                 light = &entities[ i ];
452                 value = ValueForKey( light, "classname" );
453                 if ( !strcmp( value, "light" ) ) {
454                         /* get flare shader */
455                         flareShader = ValueForKey( light, "_flareshader" );
456                         value = ValueForKey( light, "_flare" );
457                         if ( flareShader[ 0 ] != '\0' || value[ 0 ] != '\0' ) {
458                                 /* get specifics */
459                                 GetVectorForKey( light, "origin", origin );
460                                 GetVectorForKey( light, "_color", color );
461                                 lightStyle = IntForKey( light, "_style" );
462                                 if ( lightStyle == 0 ) {
463                                         lightStyle = IntForKey( light, "style" );
464                                 }
465
466                                 /* handle directional spotlights */
467                                 value = ValueForKey( light, "target" );
468                                 if ( value[ 0 ] != '\0' ) {
469                                         /* get target light */
470                                         target = FindTargetEntity( value );
471                                         if ( target != NULL ) {
472                                                 GetVectorForKey( target, "origin", targetOrigin );
473                                                 VectorSubtract( targetOrigin, origin, normal );
474                                                 VectorNormalize( normal, normal );
475                                         }
476                                 }
477                                 else{
478                                         //%     VectorClear( normal );
479                                         VectorSet( normal, 0, 0, -1 );
480                                 }
481
482                                 if ( colorsRGB ) {
483                                         color[0] = Image_LinearFloatFromsRGBFloat( color[0] );
484                                         color[1] = Image_LinearFloatFromsRGBFloat( color[1] );
485                                         color[2] = Image_LinearFloatFromsRGBFloat( color[2] );
486                                 }
487
488                                 /* create the flare surface (note shader defaults automatically) */
489                                 DrawSurfaceForFlare( mapEntityNum, origin, normal, color, flareShader, lightStyle );
490                         }
491                 }
492         }
493
494         /* add references to the final drawsurfs in the apropriate clusters */
495         FilterDrawsurfsIntoTree( e, tree );
496
497         /* match drawsurfaces back to original brushsides (sof2) */
498         FixBrushSides( e );
499
500         /* finish */
501         EndModel( e, tree->headnode );
502         FreeTree( tree );
503 }
504
505
506
507 /*
508    ProcessSubModel()
509    creates bsp + surfaces for other brush models
510  */
511
512 void ProcessSubModel( void ){
513         entity_t    *e;
514         tree_t      *tree;
515         brush_t     *b, *bc;
516         node_t      *node;
517
518
519         /* start a brush model */
520         BeginModel();
521         e = &entities[ mapEntityNum ];
522         e->firstDrawSurf = numMapDrawSurfs;
523
524         /* ydnar: gs mods */
525         ClearMetaTriangles();
526
527         /* check for patches with adjacent edges that need to lod together */
528         PatchMapDrawSurfs( e );
529
530         /* allocate a tree */
531         node = AllocNode();
532         node->planenum = PLANENUM_LEAF;
533         tree = AllocTree();
534         tree->headnode = node;
535
536         /* add the sides to the tree */
537         ClipSidesIntoTree( e, tree );
538
539         /* ydnar: create drawsurfs for triangle models */
540         AddTriangleModels( e );
541
542         /* create drawsurfs for surface models */
543         AddEntitySurfaceModels( e );
544
545         /* generate bsp brushes from map brushes */
546         EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes );
547
548         /* just put all the brushes in headnode */
549         for ( b = e->brushes; b; b = b->next )
550         {
551                 bc = CopyBrush( b );
552                 bc->next = node->brushlist;
553                 node->brushlist = bc;
554         }
555
556         /* subdivide each drawsurf as required by shader tesselation */
557         if ( !nosubdivide ) {
558                 SubdivideFaceSurfaces( e, tree );
559         }
560
561         /* add in any vertexes required to fix t-junctions */
562         if ( !notjunc ) {
563                 FixTJunctions( e );
564         }
565
566         /* ydnar: classify the surfaces and project lightmaps */
567         ClassifyEntitySurfaces( e );
568
569         /* ydnar: project decals */
570         MakeEntityDecals( e );
571
572         /* ydnar: meta surfaces */
573         MakeEntityMetaTriangles( e );
574         SmoothMetaTriangles();
575         FixMetaTJunctions();
576         MergeMetaTriangles();
577
578         /* add references to the final drawsurfs in the apropriate clusters */
579         FilterDrawsurfsIntoTree( e, tree );
580
581         /* match drawsurfaces back to original brushsides (sof2) */
582         FixBrushSides( e );
583
584         /* finish */
585         EndModel( e, node );
586         FreeTree( tree );
587 }
588
589
590
591 /*
592    ProcessModels()
593    process world + other models into the bsp
594  */
595
596 void ProcessModels( const char *portalFilePath, const char *lineFilePath ){
597         qboolean oldVerbose;
598         entity_t    *entity;
599
600
601         /* preserve -v setting */
602         oldVerbose = verbose;
603
604         /* start a new bsp */
605         BeginBSPFile();
606
607         /* create map fogs */
608         CreateMapFogs();
609
610         /* walk entity list */
611         for ( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ )
612         {
613                 /* get entity */
614                 entity = &entities[ mapEntityNum ];
615                 if ( entity->brushes == NULL && entity->patches == NULL ) {
616                         continue;
617                 }
618
619                 /* process the model */
620                 Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels );
621                 if ( mapEntityNum == 0 ) {
622                         ProcessWorldModel(portalFilePath, lineFilePath);
623                 }
624                 else{
625                         ProcessSubModel();
626                 }
627
628                 /* potentially turn off the deluge of text */
629                 verbose = verboseEntities;
630         }
631
632         /* restore -v setting */
633         verbose = oldVerbose;
634
635         /* write fogs */
636         EmitFogs();
637
638         /* vortex: emit meta stats */
639         EmitMetaStats();
640 }
641
642
643
644 /*
645    OnlyEnts()
646    this is probably broken unless teamed with a radiant version that preserves entity order
647  */
648
649 void OnlyEnts( const char *BSPFilePath ){
650         char save_cmdline[1024], save_version[1024], save_gridsize[1024];
651         const char *p;
652
653         /* note it */
654         Sys_Printf( "--- OnlyEnts ---\n" );
655
656         LoadBSPFile( BSPFilePath );
657
658         ParseEntities();
659         p = ValueForKey( &entities[0], "_q3map2_cmdline" );
660         strncpy( save_cmdline, p, sizeof( save_cmdline ) );
661         save_cmdline[sizeof( save_cmdline ) - 1] = 0;
662         p = ValueForKey( &entities[0], "_q3map2_version" );
663         strncpy( save_version, p, sizeof( save_version ) );
664         save_version[sizeof( save_version ) - 1] = 0;
665         p = ValueForKey( &entities[0], "gridsize" );
666         strncpy( save_gridsize, p, sizeof( save_gridsize ) );
667         save_gridsize[sizeof( save_gridsize ) - 1] = 0;
668
669         numEntities = 0;
670
671         LoadShaderInfo();
672         LoadMapFile( name, qfalse, qfalse );
673         SetModelNumbers();
674         SetLightStyles();
675
676         if ( *save_cmdline ) {
677                 SetKeyValue( &entities[0], "_q3map2_cmdline", save_cmdline );
678         }
679         if ( *save_version ) {
680                 SetKeyValue( &entities[0], "_q3map2_version", save_version );
681         }
682         if ( *save_gridsize ) {
683                 SetKeyValue( &entities[0], "gridsize", save_gridsize );
684         }
685
686         numBSPEntities = numEntities;
687         UnparseEntities();
688
689         WriteBSPFile( BSPFilePath );
690 }
691
692
693
694 /*
695    BSPMain() - ydnar
696    handles creation of a bsp from a map file
697  */
698
699 int BSPMain( int argc, char **argv ){
700         int i;
701         char path[ 1024 ], tempSource[ 1024 ];
702         qboolean onlyents = qfalse;
703         char BSPFilePath [ 1024 ];
704         char lineFilePath [ 1024 ];
705         char portalFilePath [ 1024 ];
706         char surfaceFilePath [ 1024 ];
707         BSPFilePath[0] = 0;
708         lineFilePath[0] = 0;
709         portalFilePath[0] = 0;
710         surfaceFilePath[0] = 0;
711
712         if ( argc >= 2 && !strcmp( argv[ 1 ], "-bsp" ) ) {
713                 Sys_Printf( "-bsp argument unnecessary\n" );
714                 argv++;
715                 argc--;
716         }
717
718         /* note it */
719         Sys_Printf( "--- BSP ---\n" );
720
721         SetDrawSurfacesBuffer();
722         mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
723         memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
724         numMapDrawSurfs = 0;
725
726         tempSource[ 0 ] = '\0';
727         globalCelShader[0] = 0;
728
729         /* set standard game flags */
730         maxSurfaceVerts = game->maxSurfaceVerts;
731         maxSurfaceIndexes = game->maxSurfaceIndexes;
732         emitFlares = game->emitFlares;
733         texturesRGB = game->texturesRGB;
734         colorsRGB = game->colorsRGB;
735
736         /* process arguments */
737         for ( i = 1; i < ( argc - 1 ); i++ )
738         {
739                 if ( !strcmp( argv[ i ], "-onlyents" ) ) {
740                         Sys_Printf( "Running entity-only compile\n" );
741                         onlyents = qtrue;
742                 }
743                 else if ( !strcmp( argv[ i ], "-tempname" ) ) {
744                         strcpy( tempSource, argv[ ++i ] );
745                 }
746                 else if ( !strcmp( argv[ i ], "-tmpout" ) ) {
747                         strcpy( outbase, "/tmp" );
748                 }
749                 else if ( !strcmp( argv[ i ],  "-nowater" ) ) {
750                         Sys_Printf( "Disabling water\n" );
751                         nowater = qtrue;
752                 }
753                 else if ( !strcmp( argv[ i ], "-keeplights" ) ) {
754                         keepLights = qtrue;
755                         Sys_Printf( "Leaving light entities on map after compile\n" );
756                 }
757                 else if ( !strcmp( argv[ i ],  "-nodetail" ) ) {
758                         Sys_Printf( "Ignoring detail brushes\n" ) ;
759                         nodetail = qtrue;
760                 }
761                 else if ( !strcmp( argv[ i ],  "-fulldetail" ) ) {
762                         Sys_Printf( "Turning detail brushes into structural brushes\n" );
763                         fulldetail = qtrue;
764                 }
765                 else if ( !strcmp( argv[ i ],  "-nofog" ) ) {
766                         Sys_Printf( "Fog volumes disabled\n" );
767                         nofog = qtrue;
768                 }
769                 else if ( !strcmp( argv[ i ],  "-nosubdivide" ) ) {
770                         Sys_Printf( "Disabling brush face subdivision\n" );
771                         nosubdivide = qtrue;
772                 }
773                 else if ( !strcmp( argv[ i ],  "-leaktest" ) ) {
774                         Sys_Printf( "Leaktest enabled\n" );
775                         leaktest = qtrue;
776                 }
777                 else if ( !strcmp( argv[ i ],  "-verboseentities" ) ) {
778                         Sys_Printf( "Verbose entities enabled\n" );
779                         verboseEntities = qtrue;
780                 }
781                 else if ( !strcmp( argv[ i ], "-nocurves" ) ) {
782                         Sys_Printf( "Ignoring curved surfaces (patches)\n" );
783                         noCurveBrushes = qtrue;
784                 }
785                 else if ( !strcmp( argv[ i ], "-notjunc" ) ) {
786                         Sys_Printf( "T-junction fixing disabled\n" );
787                         notjunc = qtrue;
788                 }
789                 else if ( !strcmp( argv[ i ], "-fakemap" ) ) {
790                         Sys_Printf( "Generating fakemap.map\n" );
791                         fakemap = qtrue;
792                 }
793                 else if ( !strcmp( argv[ i ],  "-samplesize" ) ) {
794                         sampleSize = atoi( argv[ i + 1 ] );
795                         if ( sampleSize < 1 ) {
796                                 sampleSize = 1;
797                         }
798                         i++;
799                         Sys_Printf( "Lightmap sample size set to %dx%d units\n", sampleSize, sampleSize );
800                 }
801                 else if ( !strcmp( argv[ i ], "-minsamplesize" ) ) {
802                         minSampleSize = atoi( argv[ i + 1 ] );
803                         if ( minSampleSize < 1 ) {
804                                 minSampleSize = 1;
805                         }
806                         i++;
807                         Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize );
808                 }
809                 else if ( !strcmp( argv[ i ],  "-custinfoparms" ) ) {
810                         Sys_Printf( "Custom info parms enabled\n" );
811                         useCustomInfoParms = qtrue;
812                 }
813
814                 /* sof2 args */
815                 else if ( !strcmp( argv[ i ], "-rename" ) ) {
816                         Sys_Printf( "Appending _bsp suffix to misc_model shaders (SOF2)\n" );
817                         renameModelShaders = qtrue;
818                 }
819
820                 /* ydnar args */
821                 else if ( !strcmp( argv[ i ],  "-ne" ) ) {
822                         normalEpsilon = atof( argv[ i + 1 ] );
823                         i++;
824                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
825                 }
826                 else if ( !strcmp( argv[ i ],  "-de" ) ) {
827                         distanceEpsilon = atof( argv[ i + 1 ] );
828                         i++;
829                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
830                 }
831                 else if ( !strcmp( argv[ i ],  "-mv" ) ) {
832                         maxLMSurfaceVerts = atoi( argv[ i + 1 ] );
833                         if ( maxLMSurfaceVerts < 3 ) {
834                                 maxLMSurfaceVerts = 3;
835                         }
836                         if ( maxLMSurfaceVerts > maxSurfaceVerts ) {
837                                 maxSurfaceVerts = maxLMSurfaceVerts;
838                         }
839                         i++;
840                         Sys_Printf( "Maximum lightmapped surface vertex count set to %d\n", maxLMSurfaceVerts );
841                 }
842                 else if ( !strcmp( argv[ i ],  "-mi" ) ) {
843                         maxSurfaceIndexes = atoi( argv[ i + 1 ] );
844                         if ( maxSurfaceIndexes < 3 ) {
845                                 maxSurfaceIndexes = 3;
846                         }
847                         i++;
848                         Sys_Printf( "Maximum per-surface index count set to %d\n", maxSurfaceIndexes );
849                 }
850                 else if ( !strcmp( argv[ i ], "-np" ) ) {
851                         npDegrees = atof( argv[ i + 1 ] );
852                         if ( npDegrees < 0.0f ) {
853                                 npDegrees = 0.0f;
854                         }
855                         else if ( npDegrees > 0.0f ) {
856                                 Sys_Printf( "Forcing nonplanar surfaces with a breaking angle of %f degrees\n", npDegrees );
857                         }
858                         i++;
859                 }
860                 else if ( !strcmp( argv[ i ],  "-snap" ) ) {
861                         bevelSnap = atoi( argv[ i + 1 ] );
862                         if ( bevelSnap < 0 ) {
863                                 bevelSnap = 0;
864                         }
865                         i++;
866                         if ( bevelSnap > 0 ) {
867                                 Sys_Printf( "Snapping brush bevel planes to %d units\n", bevelSnap );
868                         }
869                 }
870                 else if ( !strcmp( argv[ i ],  "-texrange" ) ) {
871                         texRange = atoi( argv[ i + 1 ] );
872                         if ( texRange < 0 ) {
873                                 texRange = 0;
874                         }
875                         i++;
876                         Sys_Printf( "Limiting per-surface texture range to %d texels\n", texRange );
877                 }
878                 else if ( !strcmp( argv[ i ], "-nohint" ) ) {
879                         Sys_Printf( "Hint brushes disabled\n" );
880                         noHint = qtrue;
881                 }
882                 else if ( !strcmp( argv[ i ], "-flat" ) ) {
883                         Sys_Printf( "Flatshading enabled\n" );
884                         flat = qtrue;
885                 }
886                 else if ( !strcmp( argv[ i ], "-celshader" ) ) {
887                         ++i;
888                         if ( argv[i][0] ) {
889                                 sprintf( globalCelShader, "textures/%s", argv[ i ] );
890                         }
891                         else{
892                                 *globalCelShader = 0;
893                         }
894                         Sys_Printf( "Global cel shader set to \"%s\"\n", globalCelShader );
895                 }
896                 else if ( !strcmp( argv[ i ], "-meta" ) ) {
897                         Sys_Printf( "Creating meta surfaces from brush faces\n" );
898                         meta = qtrue;
899                 }
900                 else if ( !strcmp( argv[ i ], "-metaadequatescore" ) ) {
901                         metaAdequateScore = atoi( argv[ i + 1 ] );
902                         if ( metaAdequateScore < 0 ) {
903                                 metaAdequateScore = -1;
904                         }
905                         i++;
906                         if ( metaAdequateScore >= 0 ) {
907                                 Sys_Printf( "Setting ADEQUATE meta score to %d (see surface_meta.c)\n", metaAdequateScore );
908                         }
909                 }
910                 else if ( !strcmp( argv[ i ], "-metagoodscore" ) ) {
911                         metaGoodScore = atoi( argv[ i + 1 ] );
912                         if ( metaGoodScore < 0 ) {
913                                 metaGoodScore = -1;
914                         }
915                         i++;
916                         if ( metaGoodScore >= 0 ) {
917                                 Sys_Printf( "Setting GOOD meta score to %d (see surface_meta.c)\n", metaGoodScore );
918                         }
919                 }
920                 else if ( !strcmp( argv[ i ], "-metamaxbboxdistance" ) ) {
921                         metaMaxBBoxDistance = atof( argv[ i + 1 ] );
922                         if ( metaMaxBBoxDistance < 0 ) {
923                                 metaMaxBBoxDistance = -1;
924                         }
925                         i++;
926                         if ( metaMaxBBoxDistance >= 0 ) {
927                                 Sys_Printf( "Setting meta maximum bounding box distance to %f\n", metaMaxBBoxDistance );
928                         }
929                 }
930                 else if ( !strcmp( argv[ i ], "-patchmeta" ) ) {
931                         Sys_Printf( "Creating meta surfaces from patches\n" );
932                         patchMeta = qtrue;
933                 }
934                 else if ( !strcmp( argv[ i ], "-flares" ) ) {
935                         Sys_Printf( "Flare surfaces enabled\n" );
936                         emitFlares = qtrue;
937                 }
938                 else if ( !strcmp( argv[ i ], "-noflares" ) ) {
939                         Sys_Printf( "Flare surfaces disabled\n" );
940                         emitFlares = qfalse;
941                 }
942                 else if ( !strcmp( argv[ i ], "-skyfix" ) ) {
943                         Sys_Printf( "GL_CLAMP sky fix/hack/workaround enabled\n" );
944                         skyFixHack = qtrue;
945                 }
946                 else if ( !strcmp( argv[ i ], "-debugsurfaces" ) ) {
947                         Sys_Printf( "emitting debug surfaces\n" );
948                         debugSurfaces = qtrue;
949                 }
950                 else if ( !strcmp( argv[ i ], "-debuginset" ) ) {
951                         Sys_Printf( "Debug surface triangle insetting enabled\n" );
952                         debugInset = qtrue;
953                 }
954                 else if ( !strcmp( argv[ i ], "-debugportals" ) ) {
955                         Sys_Printf( "Debug portal surfaces enabled\n" );
956                         debugPortals = qtrue;
957                 }
958                 else if ( !strcmp( argv[ i ], "-sRGBtex" ) ) {
959                         texturesRGB = qtrue;
960                         Sys_Printf( "Textures are in sRGB\n" );
961                 }
962                 else if ( !strcmp( argv[ i ], "-nosRGBtex" ) ) {
963                         texturesRGB = qfalse;
964                         Sys_Printf( "Textures are linear\n" );
965                 }
966                 else if ( !strcmp( argv[ i ], "-sRGBcolor" ) ) {
967                         colorsRGB = qtrue;
968                         Sys_Printf( "Colors are in sRGB\n" );
969                 }
970                 else if ( !strcmp( argv[ i ], "-nosRGBcolor" ) ) {
971                         colorsRGB = qfalse;
972                         Sys_Printf( "Colors are linear\n" );
973                 }
974                 else if ( !strcmp( argv[ i ], "-nosRGB" ) ) {
975                         texturesRGB = qfalse;
976                         Sys_Printf( "Textures are linear\n" );
977                         colorsRGB = qfalse;
978                         Sys_Printf( "Colors are linear\n" );
979                 }
980                 else if ( !strcmp( argv[ i ], "-altsplit" ) )
981                 {
982                         Sys_Printf( "Alternate BSP splitting (by 27) enabled\n" );
983                         bspAlternateSplitWeights = qtrue;
984                 }
985                 else if ( !strcmp( argv[ i ], "-deep" ) )
986                 {
987                         Sys_Printf( "Deep BSP tree generation enabled\n" );
988                         deepBSP = qtrue;
989                 }
990                 else if ( !strcmp( argv[ i ], "-maxarea" ) ) {
991                         Sys_Printf( "Max Area face surface generation enabled\n" );
992                         maxAreaFaceSurface = qtrue;
993                 }
994                 else if ( !strcmp( argv[ i ], "-bspfile" ) )
995                 {
996                         strcpy( BSPFilePath, argv[i + 1] );
997                         i++;
998                         Sys_Printf( "Use %s as bsp file\n", BSPFilePath );
999                 }
1000                 else if ( !strcmp( argv[ i ], "-linfile" ) )
1001                 {
1002                         strcpy( lineFilePath, argv[i + 1] );
1003                         i++;
1004                         Sys_Printf( "Use %s as line file\n", lineFilePath );
1005                 }
1006                 else if ( !strcmp( argv[ i ], "-prtfile" ) )
1007                 {
1008                         strcpy( portalFilePath, argv[i + 1] );
1009                         i++;
1010                         Sys_Printf( "Use %s as portal file\n", portalFilePath );
1011                 }
1012                 else if ( !strcmp( argv[ i ], "-srffile" ) )
1013                 {
1014                         strcpy( surfaceFilePath, argv[i + 1] );
1015                         i++;
1016                         Sys_Printf( "Use %s as surface file\n", surfaceFilePath );
1017                 }
1018                 else{
1019                         Sys_FPrintf( SYS_WRN, "WARNING: Unknown option \"%s\"\n", argv[ i ] );
1020                 }
1021         }
1022
1023         /* fixme: print more useful usage here */
1024         if ( i != ( argc - 1 ) ) {
1025                 Error( "usage: q3map [options] mapfile" );
1026         }
1027
1028         /* copy source name */
1029         strcpy( source, ExpandArg( argv[ i ] ) );
1030         StripExtension( source );
1031
1032         /* ydnar: set default sample size */
1033         SetDefaultSampleSize( sampleSize );
1034
1035         if (!BSPFilePath[0]) {
1036                 sprintf( BSPFilePath, "%s.bsp", source );
1037         }
1038         if (!lineFilePath[0]) {
1039                 sprintf( lineFilePath, "%s.lin", source );
1040         }
1041         if (!portalFilePath[0]) {
1042                 sprintf( portalFilePath, "%s.prt", source );
1043         }
1044         if (!surfaceFilePath[0]) {
1045                 sprintf( surfaceFilePath, "%s.srf", source );
1046         }
1047
1048         /* delete portal, line and surface files */
1049         remove( portalFilePath );
1050         remove( lineFilePath );
1051         //%     remove( surfaceFilePath )       /* ydnar */
1052
1053         /* expand mapname */
1054         strcpy( name, ExpandArg( argv[ i ] ) );
1055         if ( strcmp( name + strlen( name ) - 4, ".reg" ) ) {
1056                 /* if we are doing a full map, delete the last saved region map */
1057                 sprintf( path, "%s.reg", source );
1058                 remove( path );
1059                 DefaultExtension( name, ".map" );   /* might be .reg */
1060         }
1061
1062         /* if onlyents, just grab the entites and resave */
1063         if ( onlyents ) {
1064                 OnlyEnts( BSPFilePath );
1065                 return 0;
1066         }
1067
1068         /* load shaders */
1069         LoadShaderInfo();
1070
1071         /* load original file from temp spot in case it was renamed by the editor on the way in */
1072         if ( strlen( tempSource ) > 0 ) {
1073                 LoadMapFile( tempSource, qfalse, qfalse );
1074         }
1075         else{
1076                 LoadMapFile( name, qfalse, qfalse );
1077         }
1078
1079         /* div0: inject command line parameters */
1080         InjectCommandLine( argv, 1, argc - 1 );
1081
1082         /* ydnar: decal setup */
1083         ProcessDecals();
1084
1085         /* ydnar: cloned brush model entities */
1086         SetCloneModelNumbers();
1087
1088         /* process world and submodels */
1089         ProcessModels( portalFilePath, lineFilePath );
1090
1091         /* set light styles from targetted light entities */
1092         SetLightStyles();
1093
1094         /* process in game advertisements */
1095         ProcessAdvertisements();
1096
1097         /* finish and write bsp */
1098         EndBSPFile( qtrue, BSPFilePath, surfaceFilePath );
1099
1100         /* remove temp map source file if appropriate */
1101         if ( strlen( tempSource ) > 0 ) {
1102                 remove( tempSource );
1103         }
1104
1105         /* return to sender */
1106         return 0;
1107 }