]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/main.c
Merge branch 'master' into divVerent/farplanedist-sky-fix
[xonotic/netradiant.git] / tools / quake3 / q3map2 / main.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 MAIN_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /*
42    Random()
43    returns a pseudorandom number between 0 and 1
44  */
45
46 vec_t Random( void ){
47         return (vec_t) rand() / RAND_MAX;
48 }
49
50
51 char *Q_strncpyz( char *dst, const char *src, size_t len ) {
52         if ( len == 0 ) {
53                 abort();
54         }
55
56         strncpy( dst, src, len );
57         dst[ len - 1 ] = '\0';
58         return dst;
59 }
60
61
62 char *Q_strcat( char *dst, size_t dlen, const char *src ) {
63         size_t n = strlen( dst  );
64
65         if ( n > dlen ) {
66                 abort(); /* buffer overflow */
67         }
68
69         return Q_strncpyz( dst + n, src, dlen - n );
70 }
71
72
73 char *Q_strncat( char *dst, size_t dlen, const char *src, size_t slen ) {
74         size_t n = strlen( dst );
75
76         if ( n > dlen ) {
77                 abort(); /* buffer overflow */
78         }
79
80         return Q_strncpyz( dst + n, src, MIN( slen, dlen - n ) );
81 }
82
83
84 /*
85    ExitQ3Map()
86    cleanup routine
87  */
88
89 static void ExitQ3Map( void ){
90         BSPFilesCleanup();
91         if ( mapDrawSurfs != NULL ) {
92                 free( mapDrawSurfs );
93         }
94 }
95
96
97
98 /* minimap stuff */
99
100 typedef struct minimap_s
101 {
102         bspModel_t *model;
103         int width;
104         int height;
105         int samples;
106         float *sample_offsets;
107         float sharpen_boxmult;
108         float sharpen_centermult;
109         float boost, brightness, contrast;
110         float *data1f;
111         float *sharpendata1f;
112         vec3_t mins, size;
113 }
114 minimap_t;
115 static minimap_t minimap;
116
117 qboolean BrushIntersectionWithLine( bspBrush_t *brush, vec3_t start, vec3_t dir, float *t_in, float *t_out ){
118         int i;
119         qboolean in = qfalse, out = qfalse;
120         bspBrushSide_t *sides = &bspBrushSides[brush->firstSide];
121
122         for ( i = 0; i < brush->numSides; ++i )
123         {
124                 bspPlane_t *p = &bspPlanes[sides[i].planeNum];
125                 float sn = DotProduct( start, p->normal );
126                 float dn = DotProduct( dir, p->normal );
127                 if ( dn == 0 ) {
128                         if ( sn > p->dist ) {
129                                 return qfalse; // outside!
130                         }
131                 }
132                 else
133                 {
134                         float t = ( p->dist - sn ) / dn;
135                         if ( dn < 0 ) {
136                                 if ( !in || t > *t_in ) {
137                                         *t_in = t;
138                                         in = qtrue;
139                                         // as t_in can only increase, and t_out can only decrease, early out
140                                         if ( out && *t_in >= *t_out ) {
141                                                 return qfalse;
142                                         }
143                                 }
144                         }
145                         else
146                         {
147                                 if ( !out || t < *t_out ) {
148                                         *t_out = t;
149                                         out = qtrue;
150                                         // as t_in can only increase, and t_out can only decrease, early out
151                                         if ( in && *t_in >= *t_out ) {
152                                                 return qfalse;
153                                         }
154                                 }
155                         }
156                 }
157         }
158         return in && out;
159 }
160
161 static float MiniMapSample( float x, float y ){
162         vec3_t org, dir;
163         int i, bi;
164         float t0, t1;
165         float samp;
166         bspBrush_t *b;
167         bspBrushSide_t *s;
168         int cnt;
169
170         org[0] = x;
171         org[1] = y;
172         org[2] = 0;
173         dir[0] = 0;
174         dir[1] = 0;
175         dir[2] = 1;
176
177         cnt = 0;
178         samp = 0;
179         for ( i = 0; i < minimap.model->numBSPBrushes; ++i )
180         {
181                 bi = minimap.model->firstBSPBrush + i;
182                 if ( opaqueBrushes[bi >> 3] & ( 1 << ( bi & 7 ) ) ) {
183                         b = &bspBrushes[bi];
184
185                         // sort out mins/maxs of the brush
186                         s = &bspBrushSides[b->firstSide];
187                         if ( x < -bspPlanes[s[0].planeNum].dist ) {
188                                 continue;
189                         }
190                         if ( x > +bspPlanes[s[1].planeNum].dist ) {
191                                 continue;
192                         }
193                         if ( y < -bspPlanes[s[2].planeNum].dist ) {
194                                 continue;
195                         }
196                         if ( y > +bspPlanes[s[3].planeNum].dist ) {
197                                 continue;
198                         }
199
200                         if ( BrushIntersectionWithLine( b, org, dir, &t0, &t1 ) ) {
201                                 samp += t1 - t0;
202                                 ++cnt;
203                         }
204                 }
205         }
206
207         return samp;
208 }
209
210 void RandomVector2f( float v[2] ){
211         do
212         {
213                 v[0] = 2 * Random() - 1;
214                 v[1] = 2 * Random() - 1;
215         }
216         while ( v[0] * v[0] + v[1] * v[1] > 1 );
217 }
218
219 static void MiniMapRandomlySupersampled( int y ){
220         int x, i;
221         float *p = &minimap.data1f[y * minimap.width];
222         float ymin = minimap.mins[1] + minimap.size[1] * ( y / (float) minimap.height );
223         float dx   =                   minimap.size[0]      / (float) minimap.width;
224         float dy   =                   minimap.size[1]      / (float) minimap.height;
225         float uv[2];
226         float thisval;
227
228         for ( x = 0; x < minimap.width; ++x )
229         {
230                 float xmin = minimap.mins[0] + minimap.size[0] * ( x / (float) minimap.width );
231                 float val = 0;
232
233                 for ( i = 0; i < minimap.samples; ++i )
234                 {
235                         RandomVector2f( uv );
236                         thisval = MiniMapSample(
237                                 xmin + ( uv[0] + 0.5 ) * dx, /* exaggerated random pattern for better results */
238                                 ymin + ( uv[1] + 0.5 ) * dy  /* exaggerated random pattern for better results */
239                                 );
240                         val += thisval;
241                 }
242                 val /= minimap.samples * minimap.size[2];
243                 *p++ = val;
244         }
245 }
246
247 static void MiniMapSupersampled( int y ){
248         int x, i;
249         float *p = &minimap.data1f[y * minimap.width];
250         float ymin = minimap.mins[1] + minimap.size[1] * ( y / (float) minimap.height );
251         float dx   =                   minimap.size[0]      / (float) minimap.width;
252         float dy   =                   minimap.size[1]      / (float) minimap.height;
253
254         for ( x = 0; x < minimap.width; ++x )
255         {
256                 float xmin = minimap.mins[0] + minimap.size[0] * ( x / (float) minimap.width );
257                 float val = 0;
258
259                 for ( i = 0; i < minimap.samples; ++i )
260                 {
261                         float thisval = MiniMapSample(
262                                 xmin + minimap.sample_offsets[2 * i + 0] * dx,
263                                 ymin + minimap.sample_offsets[2 * i + 1] * dy
264                                 );
265                         val += thisval;
266                 }
267                 val /= minimap.samples * minimap.size[2];
268                 *p++ = val;
269         }
270 }
271
272 static void MiniMapNoSupersampling( int y ){
273         int x;
274         float *p = &minimap.data1f[y * minimap.width];
275         float ymin = minimap.mins[1] + minimap.size[1] * ( ( y + 0.5 ) / (float) minimap.height );
276
277         for ( x = 0; x < minimap.width; ++x )
278         {
279                 float xmin = minimap.mins[0] + minimap.size[0] * ( ( x + 0.5 ) / (float) minimap.width );
280                 *p++ = MiniMapSample( xmin, ymin ) / minimap.size[2];
281         }
282 }
283
284 static void MiniMapSharpen( int y ){
285         int x;
286         qboolean up = ( y > 0 );
287         qboolean down = ( y < minimap.height - 1 );
288         float *p = &minimap.data1f[y * minimap.width];
289         float *q = &minimap.sharpendata1f[y * minimap.width];
290
291         for ( x = 0; x < minimap.width; ++x )
292         {
293                 qboolean left = ( x > 0 );
294                 qboolean right = ( x < minimap.width - 1 );
295                 float val = p[0] * minimap.sharpen_centermult;
296
297                 if ( left && up ) {
298                         val += p[-1 - minimap.width] * minimap.sharpen_boxmult;
299                 }
300                 if ( left && down ) {
301                         val += p[-1 + minimap.width] * minimap.sharpen_boxmult;
302                 }
303                 if ( right && up ) {
304                         val += p[+1 - minimap.width] * minimap.sharpen_boxmult;
305                 }
306                 if ( right && down ) {
307                         val += p[+1 + minimap.width] * minimap.sharpen_boxmult;
308                 }
309
310                 if ( left ) {
311                         val += p[-1] * minimap.sharpen_boxmult;
312                 }
313                 if ( right ) {
314                         val += p[+1] * minimap.sharpen_boxmult;
315                 }
316                 if ( up ) {
317                         val += p[-minimap.width] * minimap.sharpen_boxmult;
318                 }
319                 if ( down ) {
320                         val += p[+minimap.width] * minimap.sharpen_boxmult;
321                 }
322
323                 ++p;
324                 *q++ = val;
325         }
326 }
327
328 static void MiniMapContrastBoost( int y ){
329         int x;
330         float *q = &minimap.data1f[y * minimap.width];
331         for ( x = 0; x < minimap.width; ++x )
332         {
333                 *q = *q * minimap.boost / ( ( minimap.boost - 1 ) * *q + 1 );
334                 ++q;
335         }
336 }
337
338 static void MiniMapBrightnessContrast( int y ){
339         int x;
340         float *q = &minimap.data1f[y * minimap.width];
341         for ( x = 0; x < minimap.width; ++x )
342         {
343                 *q = *q * minimap.contrast + minimap.brightness;
344                 ++q;
345         }
346 }
347
348 void MiniMapMakeMinsMaxs( vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect ){
349         vec3_t mins, maxs, extend;
350         VectorCopy( mins_in, mins );
351         VectorCopy( maxs_in, maxs );
352
353         // line compatible to nexuiz mapinfo
354         Sys_Printf( "size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2] );
355
356         if ( keepaspect ) {
357                 VectorSubtract( maxs, mins, extend );
358                 if ( extend[1] > extend[0] ) {
359                         mins[0] -= ( extend[1] - extend[0] ) * 0.5;
360                         maxs[0] += ( extend[1] - extend[0] ) * 0.5;
361                 }
362                 else
363                 {
364                         mins[1] -= ( extend[0] - extend[1] ) * 0.5;
365                         maxs[1] += ( extend[0] - extend[1] ) * 0.5;
366                 }
367         }
368
369         /* border: amount of black area around the image */
370         /* input: border, 1-2*border, border but we need border/(1-2*border) */
371
372         VectorSubtract( maxs, mins, extend );
373         VectorScale( extend, border / ( 1 - 2 * border ), extend );
374
375         VectorSubtract( mins, extend, mins );
376         VectorAdd( maxs, extend, maxs );
377
378         VectorCopy( mins, minimap.mins );
379         VectorSubtract( maxs, mins, minimap.size );
380
381         // line compatible to nexuiz mapinfo
382         Sys_Printf( "size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2] );
383 }
384
385 /*
386    MiniMapSetupBrushes()
387    determines solid non-sky brushes in the world
388  */
389
390 void MiniMapSetupBrushes( void ){
391         SetupBrushesFlags( C_SOLID | C_SKY, C_SOLID, 0, 0 );
392         // at least one must be solid
393         // none may be sky
394         // not all may be nodraw
395 }
396
397 qboolean MiniMapEvaluateSampleOffsets( int *bestj, int *bestk, float *bestval ){
398         float val, dx, dy;
399         int j, k;
400
401         *bestj = *bestk = -1;
402         *bestval = 3; /* max possible val is 2 */
403
404         for ( j = 0; j < minimap.samples; ++j )
405                 for ( k = j + 1; k < minimap.samples; ++k )
406                 {
407                         dx = minimap.sample_offsets[2 * j + 0] - minimap.sample_offsets[2 * k + 0];
408                         dy = minimap.sample_offsets[2 * j + 1] - minimap.sample_offsets[2 * k + 1];
409                         if ( dx > +0.5 ) {
410                                 dx -= 1;
411                         }
412                         if ( dx < -0.5 ) {
413                                 dx += 1;
414                         }
415                         if ( dy > +0.5 ) {
416                                 dy -= 1;
417                         }
418                         if ( dy < -0.5 ) {
419                                 dy += 1;
420                         }
421                         val = dx * dx + dy * dy;
422                         if ( val < *bestval ) {
423                                 *bestj = j;
424                                 *bestk = k;
425                                 *bestval = val;
426                         }
427                 }
428
429         return *bestval < 3;
430 }
431
432 void MiniMapMakeSampleOffsets(){
433         int i, j, k, jj, kk;
434         float val, valj, valk, sx, sy, rx, ry;
435
436         Sys_Printf( "Generating good sample offsets (this may take a while)...\n" );
437
438         /* start with entirely random samples */
439         for ( i = 0; i < minimap.samples; ++i )
440         {
441                 minimap.sample_offsets[2 * i + 0] = Random();
442                 minimap.sample_offsets[2 * i + 1] = Random();
443         }
444
445         for ( i = 0; i < 1000; ++i )
446         {
447                 if ( MiniMapEvaluateSampleOffsets( &j, &k, &val ) ) {
448                         sx = minimap.sample_offsets[2 * j + 0];
449                         sy = minimap.sample_offsets[2 * j + 1];
450                         minimap.sample_offsets[2 * j + 0] = rx = Random();
451                         minimap.sample_offsets[2 * j + 1] = ry = Random();
452                         if ( !MiniMapEvaluateSampleOffsets( &jj, &kk, &valj ) ) {
453                                 valj = -1;
454                         }
455                         minimap.sample_offsets[2 * j + 0] = sx;
456                         minimap.sample_offsets[2 * j + 1] = sy;
457
458                         sx = minimap.sample_offsets[2 * k + 0];
459                         sy = minimap.sample_offsets[2 * k + 1];
460                         minimap.sample_offsets[2 * k + 0] = rx;
461                         minimap.sample_offsets[2 * k + 1] = ry;
462                         if ( !MiniMapEvaluateSampleOffsets( &jj, &kk, &valk ) ) {
463                                 valk = -1;
464                         }
465                         minimap.sample_offsets[2 * k + 0] = sx;
466                         minimap.sample_offsets[2 * k + 1] = sy;
467
468                         if ( valj > valk ) {
469                                 if ( valj > val ) {
470                                         /* valj is the greatest */
471                                         minimap.sample_offsets[2 * j + 0] = rx;
472                                         minimap.sample_offsets[2 * j + 1] = ry;
473                                         i = -1;
474                                 }
475                                 else
476                                 {
477                                         /* valj is the greater and it is useless - forget it */
478                                 }
479                         }
480                         else
481                         {
482                                 if ( valk > val ) {
483                                         /* valk is the greatest */
484                                         minimap.sample_offsets[2 * k + 0] = rx;
485                                         minimap.sample_offsets[2 * k + 1] = ry;
486                                         i = -1;
487                                 }
488                                 else
489                                 {
490                                         /* valk is the greater and it is useless - forget it */
491                                 }
492                         }
493                 }
494                 else{
495                         break;
496                 }
497         }
498 }
499
500 void MergeRelativePath( char *out, const char *absolute, const char *relative ){
501         const char *endpos = absolute + strlen( absolute );
502         while ( endpos != absolute && ( endpos[-1] == '/' || endpos[-1] == '\\' ) )
503                 --endpos;
504         while ( relative[0] == '.' && relative[1] == '.' && ( relative[2] == '/' || relative[2] == '\\' ) )
505         {
506                 relative += 3;
507                 while ( endpos != absolute )
508                 {
509                         --endpos;
510                         if ( *endpos == '/' || *endpos == '\\' ) {
511                                 break;
512                         }
513                 }
514                 while ( endpos != absolute && ( endpos[-1] == '/' || endpos[-1] == '\\' ) )
515                         --endpos;
516         }
517         memcpy( out, absolute, endpos - absolute );
518         out[endpos - absolute] = '/';
519         strcpy( out + ( endpos - absolute + 1 ), relative );
520 }
521
522 int MiniMapBSPMain( int argc, char **argv ){
523         char minimapFilename[1024];
524         char basename[1024];
525         char path[1024];
526         char relativeMinimapFilename[1024];
527         qboolean autolevel;
528         float minimapSharpen;
529         float border;
530         byte *data4b, *p;
531         float *q;
532         int x, y;
533         int i;
534         miniMapMode_t mode;
535         vec3_t mins, maxs;
536         qboolean keepaspect;
537
538         /* arg checking */
539         if ( argc < 2 ) {
540                 Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen f] [-samples n | -random n] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] <mapname>\n" );
541                 return 0;
542         }
543
544         /* load the BSP first */
545         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
546         StripExtension( source );
547         DefaultExtension( source, ".bsp" );
548         Sys_Printf( "Loading %s\n", source );
549         BeginMapShaderFile( source );
550         LoadShaderInfo();
551         LoadBSPFile( source );
552
553         minimap.model = &bspModels[0];
554         VectorCopy( minimap.model->mins, mins );
555         VectorCopy( minimap.model->maxs, maxs );
556
557         *minimapFilename = 0;
558         minimapSharpen = game->miniMapSharpen;
559         minimap.width = minimap.height = game->miniMapSize;
560         border = game->miniMapBorder;
561         keepaspect = game->miniMapKeepAspect;
562         mode = game->miniMapMode;
563
564         autolevel = qfalse;
565         minimap.samples = 1;
566         minimap.sample_offsets = NULL;
567         minimap.boost = 1.0;
568         minimap.brightness = 0.0;
569         minimap.contrast = 1.0;
570
571         /* process arguments */
572         for ( i = 1; i < ( argc - 1 ); i++ )
573         {
574                 if ( !strcmp( argv[ i ],  "-size" ) ) {
575                         minimap.width = minimap.height = atoi( argv[i + 1] );
576                         i++;
577                         Sys_Printf( "Image size set to %i\n", minimap.width );
578                 }
579                 else if ( !strcmp( argv[ i ],  "-sharpen" ) ) {
580                         minimapSharpen = atof( argv[i + 1] );
581                         i++;
582                         Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen );
583                 }
584                 else if ( !strcmp( argv[ i ],  "-samples" ) ) {
585                         minimap.samples = atoi( argv[i + 1] );
586                         i++;
587                         Sys_Printf( "Samples set to %i\n", minimap.samples );
588                         if ( minimap.sample_offsets ) {
589                                 free( minimap.sample_offsets );
590                         }
591                         minimap.sample_offsets = malloc( 2 * sizeof( *minimap.sample_offsets ) * minimap.samples );
592                         MiniMapMakeSampleOffsets();
593                 }
594                 else if ( !strcmp( argv[ i ],  "-random" ) ) {
595                         minimap.samples = atoi( argv[i + 1] );
596                         i++;
597                         Sys_Printf( "Random samples set to %i\n", minimap.samples );
598                         if ( minimap.sample_offsets ) {
599                                 free( minimap.sample_offsets );
600                         }
601                         minimap.sample_offsets = NULL;
602                 }
603                 else if ( !strcmp( argv[ i ],  "-border" ) ) {
604                         border = atof( argv[i + 1] );
605                         i++;
606                         Sys_Printf( "Border set to %f\n", border );
607                 }
608                 else if ( !strcmp( argv[ i ],  "-keepaspect" ) ) {
609                         keepaspect = qtrue;
610                         Sys_Printf( "Keeping aspect ratio by letterboxing\n", border );
611                 }
612                 else if ( !strcmp( argv[ i ],  "-nokeepaspect" ) ) {
613                         keepaspect = qfalse;
614                         Sys_Printf( "Not keeping aspect ratio\n", border );
615                 }
616                 else if ( !strcmp( argv[ i ],  "-o" ) ) {
617                         strcpy( minimapFilename, argv[i + 1] );
618                         i++;
619                         Sys_Printf( "Output file name set to %s\n", minimapFilename );
620                 }
621                 else if ( !strcmp( argv[ i ],  "-minmax" ) && i < ( argc - 7 ) ) {
622                         mins[0] = atof( argv[i + 1] );
623                         mins[1] = atof( argv[i + 2] );
624                         mins[2] = atof( argv[i + 3] );
625                         maxs[0] = atof( argv[i + 4] );
626                         maxs[1] = atof( argv[i + 5] );
627                         maxs[2] = atof( argv[i + 6] );
628                         i += 6;
629                         Sys_Printf( "Map mins/maxs overridden\n" );
630                 }
631                 else if ( !strcmp( argv[ i ],  "-gray" ) ) {
632                         mode = MINIMAP_MODE_GRAY;
633                         Sys_Printf( "Writing as white-on-black image\n" );
634                 }
635                 else if ( !strcmp( argv[ i ],  "-black" ) ) {
636                         mode = MINIMAP_MODE_BLACK;
637                         Sys_Printf( "Writing as black alpha image\n" );
638                 }
639                 else if ( !strcmp( argv[ i ],  "-white" ) ) {
640                         mode = MINIMAP_MODE_WHITE;
641                         Sys_Printf( "Writing as white alpha image\n" );
642                 }
643                 else if ( !strcmp( argv[ i ],  "-boost" ) && i < ( argc - 2 ) ) {
644                         minimap.boost = atof( argv[i + 1] );
645                         i++;
646                         Sys_Printf( "Contrast boost set to %f\n", minimap.boost );
647                 }
648                 else if ( !strcmp( argv[ i ],  "-brightness" ) && i < ( argc - 2 ) ) {
649                         minimap.brightness = atof( argv[i + 1] );
650                         i++;
651                         Sys_Printf( "Brightness set to %f\n", minimap.brightness );
652                 }
653                 else if ( !strcmp( argv[ i ],  "-contrast" ) && i < ( argc - 2 ) ) {
654                         minimap.contrast = atof( argv[i + 1] );
655                         i++;
656                         Sys_Printf( "Contrast set to %f\n", minimap.contrast );
657                 }
658                 else if ( !strcmp( argv[ i ],  "-autolevel" ) ) {
659                         autolevel = qtrue;
660                         Sys_Printf( "Auto level enabled\n", border );
661                 }
662                 else if ( !strcmp( argv[ i ],  "-noautolevel" ) ) {
663                         autolevel = qfalse;
664                         Sys_Printf( "Auto level disabled\n", border );
665                 }
666         }
667
668         MiniMapMakeMinsMaxs( mins, maxs, border, keepaspect );
669
670         if ( !*minimapFilename ) {
671                 ExtractFileBase( source, basename );
672                 ExtractFilePath( source, path );
673                 sprintf( relativeMinimapFilename, game->miniMapNameFormat, basename );
674                 MergeRelativePath( minimapFilename, path, relativeMinimapFilename );
675                 Sys_Printf( "Output file name automatically set to %s\n", minimapFilename );
676         }
677         ExtractFilePath( minimapFilename, path );
678         Q_mkdir( path );
679
680         if ( minimapSharpen >= 0 ) {
681                 minimap.sharpen_centermult = 8 * minimapSharpen + 1;
682                 minimap.sharpen_boxmult    =    -minimapSharpen;
683         }
684
685         minimap.data1f = safe_malloc( minimap.width * minimap.height * sizeof( *minimap.data1f ) );
686         data4b = safe_malloc( minimap.width * minimap.height * 4 );
687         if ( minimapSharpen >= 0 ) {
688                 minimap.sharpendata1f = safe_malloc( minimap.width * minimap.height * sizeof( *minimap.data1f ) );
689         }
690
691         MiniMapSetupBrushes();
692
693         if ( minimap.samples <= 1 ) {
694                 Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height );
695                 RunThreadsOnIndividual( minimap.height, qtrue, MiniMapNoSupersampling );
696         }
697         else
698         {
699                 if ( minimap.sample_offsets ) {
700                         Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height );
701                         RunThreadsOnIndividual( minimap.height, qtrue, MiniMapSupersampled );
702                 }
703                 else
704                 {
705                         Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height );
706                         RunThreadsOnIndividual( minimap.height, qtrue, MiniMapRandomlySupersampled );
707                 }
708         }
709
710         if ( minimap.boost != 1.0 ) {
711                 Sys_Printf( "\n--- MiniMapContrastBoost (%d) ---\n", minimap.height );
712                 RunThreadsOnIndividual( minimap.height, qtrue, MiniMapContrastBoost );
713         }
714
715         if ( autolevel ) {
716                 Sys_Printf( "\n--- MiniMapAutoLevel (%d) ---\n", minimap.height );
717                 float mi = 1, ma = 0;
718                 float s, o;
719
720                 // TODO threads!
721                 q = minimap.data1f;
722                 for ( y = 0; y < minimap.height; ++y )
723                         for ( x = 0; x < minimap.width; ++x )
724                         {
725                                 float v = *q++;
726                                 if ( v < mi ) {
727                                         mi = v;
728                                 }
729                                 if ( v > ma ) {
730                                         ma = v;
731                                 }
732                         }
733                 if ( ma > mi ) {
734                         s = 1 / ( ma - mi );
735                         o = mi / ( ma - mi );
736
737                         // equations:
738                         //   brightness + contrast * v
739                         // after autolevel:
740                         //   brightness + contrast * (v * s - o)
741                         // =
742                         //   (brightness - contrast * o) + (contrast * s) * v
743                         minimap.brightness = minimap.brightness - minimap.contrast * o;
744                         minimap.contrast *= s;
745
746                         Sys_Printf( "Auto level: Brightness changed to %f\n", minimap.brightness );
747                         Sys_Printf( "Auto level: Contrast changed to %f\n", minimap.contrast );
748                 }
749                 else{
750                         Sys_Printf( "Auto level: failed because all pixels are the same value\n" );
751                 }
752         }
753
754         if ( minimap.brightness != 0 || minimap.contrast != 1 ) {
755                 Sys_Printf( "\n--- MiniMapBrightnessContrast (%d) ---\n", minimap.height );
756                 RunThreadsOnIndividual( minimap.height, qtrue, MiniMapBrightnessContrast );
757         }
758
759         if ( minimap.sharpendata1f ) {
760                 Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height );
761                 RunThreadsOnIndividual( minimap.height, qtrue, MiniMapSharpen );
762                 q = minimap.sharpendata1f;
763         }
764         else
765         {
766                 q = minimap.data1f;
767         }
768
769         Sys_Printf( "\nConverting..." );
770
771         switch ( mode )
772         {
773         case MINIMAP_MODE_GRAY:
774                 p = data4b;
775                 for ( y = 0; y < minimap.height; ++y )
776                         for ( x = 0; x < minimap.width; ++x )
777                         {
778                                 byte b;
779                                 float v = *q++;
780                                 if ( v < 0 ) {
781                                         v = 0;
782                                 }
783                                 if ( v > 255.0 / 256.0 ) {
784                                         v = 255.0 / 256.0;
785                                 }
786                                 b = v * 256;
787                                 *p++ = b;
788                         }
789                 Sys_Printf( " writing to %s...", minimapFilename );
790                 WriteTGAGray( minimapFilename, data4b, minimap.width, minimap.height );
791                 break;
792         case MINIMAP_MODE_BLACK:
793                 p = data4b;
794                 for ( y = 0; y < minimap.height; ++y )
795                         for ( x = 0; x < minimap.width; ++x )
796                         {
797                                 byte b;
798                                 float v = *q++;
799                                 if ( v < 0 ) {
800                                         v = 0;
801                                 }
802                                 if ( v > 255.0 / 256.0 ) {
803                                         v = 255.0 / 256.0;
804                                 }
805                                 b = v * 256;
806                                 *p++ = 0;
807                                 *p++ = 0;
808                                 *p++ = 0;
809                                 *p++ = b;
810                         }
811                 Sys_Printf( " writing to %s...", minimapFilename );
812                 WriteTGA( minimapFilename, data4b, minimap.width, minimap.height );
813                 break;
814         case MINIMAP_MODE_WHITE:
815                 p = data4b;
816                 for ( y = 0; y < minimap.height; ++y )
817                         for ( x = 0; x < minimap.width; ++x )
818                         {
819                                 byte b;
820                                 float v = *q++;
821                                 if ( v < 0 ) {
822                                         v = 0;
823                                 }
824                                 if ( v > 255.0 / 256.0 ) {
825                                         v = 255.0 / 256.0;
826                                 }
827                                 b = v * 256;
828                                 *p++ = 255;
829                                 *p++ = 255;
830                                 *p++ = 255;
831                                 *p++ = b;
832                         }
833                 Sys_Printf( " writing to %s...", minimapFilename );
834                 WriteTGA( minimapFilename, data4b, minimap.width, minimap.height );
835                 break;
836         }
837
838         Sys_Printf( " done.\n" );
839
840         /* return to sender */
841         return 0;
842 }
843
844
845
846
847
848 /*
849    MD4BlockChecksum()
850    calculates an md4 checksum for a block of data
851  */
852
853 static int MD4BlockChecksum( void *buffer, int length ){
854         return Com_BlockChecksum( buffer, length );
855 }
856
857 /*
858    FixAAS()
859    resets an aas checksum to match the given BSP
860  */
861
862 int FixAAS( int argc, char **argv ){
863         int length, checksum;
864         void        *buffer;
865         FILE        *file;
866         char aas[ 1024 ], **ext;
867         char        *exts[] =
868         {
869                 ".aas",
870                 "_b0.aas",
871                 "_b1.aas",
872                 NULL
873         };
874
875
876         /* arg checking */
877         if ( argc < 2 ) {
878                 Sys_Printf( "Usage: q3map -fixaas [-v] <mapname>\n" );
879                 return 0;
880         }
881
882         /* do some path mangling */
883         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
884         StripExtension( source );
885         DefaultExtension( source, ".bsp" );
886
887         /* note it */
888         Sys_Printf( "--- FixAAS ---\n" );
889
890         /* load the bsp */
891         Sys_Printf( "Loading %s\n", source );
892         length = LoadFile( source, &buffer );
893
894         /* create bsp checksum */
895         Sys_Printf( "Creating checksum...\n" );
896         checksum = LittleLong( MD4BlockChecksum( buffer, length ) );
897
898         /* write checksum to aas */
899         ext = exts;
900         while ( *ext )
901         {
902                 /* mangle name */
903                 strcpy( aas, source );
904                 StripExtension( aas );
905                 strcat( aas, *ext );
906                 Sys_Printf( "Trying %s\n", aas );
907                 ext++;
908
909                 /* fix it */
910                 file = fopen( aas, "r+b" );
911                 if ( !file ) {
912                         continue;
913                 }
914                 if ( fwrite( &checksum, 4, 1, file ) != 1 ) {
915                         Error( "Error writing checksum to %s", aas );
916                 }
917                 fclose( file );
918         }
919
920         /* return to sender */
921         return 0;
922 }
923
924
925
926 /*
927    AnalyzeBSP() - ydnar
928    analyzes a Quake engine BSP file
929  */
930
931 typedef struct abspHeader_s
932 {
933         char ident[ 4 ];
934         int version;
935
936         bspLump_t lumps[ 1 ];       /* unknown size */
937 }
938 abspHeader_t;
939
940 typedef struct abspLumpTest_s
941 {
942         int radix, minCount;
943         char            *name;
944 }
945 abspLumpTest_t;
946
947 int AnalyzeBSP( int argc, char **argv ){
948         abspHeader_t            *header;
949         int size, i, version, offset, length, lumpInt, count;
950         char ident[ 5 ];
951         void                    *lump;
952         float lumpFloat;
953         char lumpString[ 1024 ], source[ 1024 ];
954         qboolean lumpSwap = qfalse;
955         abspLumpTest_t          *lumpTest;
956         static abspLumpTest_t lumpTests[] =
957         {
958                 { sizeof( bspPlane_t ),         6,      "IBSP LUMP_PLANES" },
959                 { sizeof( bspBrush_t ),         1,      "IBSP LUMP_BRUSHES" },
960                 { 8,                            6,      "IBSP LUMP_BRUSHSIDES" },
961                 { sizeof( bspBrushSide_t ),     6,      "RBSP LUMP_BRUSHSIDES" },
962                 { sizeof( bspModel_t ),         1,      "IBSP LUMP_MODELS" },
963                 { sizeof( bspNode_t ),          2,      "IBSP LUMP_NODES" },
964                 { sizeof( bspLeaf_t ),          1,      "IBSP LUMP_LEAFS" },
965                 { 104,                          3,      "IBSP LUMP_DRAWSURFS" },
966                 { 44,                           3,      "IBSP LUMP_DRAWVERTS" },
967                 { 4,                            6,      "IBSP LUMP_DRAWINDEXES" },
968                 { 128 * 128 * 3,                1,      "IBSP LUMP_LIGHTMAPS" },
969                 { 256 * 256 * 3,                1,      "IBSP LUMP_LIGHTMAPS (256 x 256)" },
970                 { 512 * 512 * 3,                1,      "IBSP LUMP_LIGHTMAPS (512 x 512)" },
971                 { 0, 0, NULL }
972         };
973
974
975         /* arg checking */
976         if ( argc < 1 ) {
977                 Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] <mapname>\n" );
978                 return 0;
979         }
980
981         /* process arguments */
982         for ( i = 1; i < ( argc - 1 ); i++ )
983         {
984                 /* -format map|ase|... */
985                 if ( !strcmp( argv[ i ],  "-lumpswap" ) ) {
986                         Sys_Printf( "Swapped lump structs enabled\n" );
987                         lumpSwap = qtrue;
988                 }
989         }
990
991         /* clean up map name */
992         strcpy( source, ExpandArg( argv[ i ] ) );
993         Sys_Printf( "Loading %s\n", source );
994
995         /* load the file */
996         size = LoadFile( source, (void**) &header );
997         if ( size == 0 || header == NULL ) {
998                 Sys_Printf( "Unable to load %s.\n", source );
999                 return -1;
1000         }
1001
1002         /* analyze ident/version */
1003         memcpy( ident, header->ident, 4 );
1004         ident[ 4 ] = '\0';
1005         version = LittleLong( header->version );
1006
1007         Sys_Printf( "Identity:      %s\n", ident );
1008         Sys_Printf( "Version:       %d\n", version );
1009         Sys_Printf( "---------------------------------------\n" );
1010
1011         /* analyze each lump */
1012         for ( i = 0; i < 100; i++ )
1013         {
1014                 /* call of duty swapped lump pairs */
1015                 if ( lumpSwap ) {
1016                         offset = LittleLong( header->lumps[ i ].length );
1017                         length = LittleLong( header->lumps[ i ].offset );
1018                 }
1019
1020                 /* standard lump pairs */
1021                 else
1022                 {
1023                         offset = LittleLong( header->lumps[ i ].offset );
1024                         length = LittleLong( header->lumps[ i ].length );
1025                 }
1026
1027                 /* extract data */
1028                 lump = (byte*) header + offset;
1029                 lumpInt = LittleLong( (int) *( (int*) lump ) );
1030                 lumpFloat = LittleFloat( (float) *( (float*) lump ) );
1031                 memcpy( lumpString, (char*) lump, ( (size_t)length < sizeof( lumpString ) ? (size_t)length : sizeof( lumpString ) - 1 ) );
1032                 lumpString[ sizeof( lumpString ) - 1 ] = '\0';
1033
1034                 /* print basic lump info */
1035                 Sys_Printf( "Lump:          %d\n", i );
1036                 Sys_Printf( "Offset:        %d bytes\n", offset );
1037                 Sys_Printf( "Length:        %d bytes\n", length );
1038
1039                 /* only operate on valid lumps */
1040                 if ( length > 0 ) {
1041                         /* print data in 4 formats */
1042                         Sys_Printf( "As hex:        %08X\n", lumpInt );
1043                         Sys_Printf( "As int:        %d\n", lumpInt );
1044                         Sys_Printf( "As float:      %f\n", lumpFloat );
1045                         Sys_Printf( "As string:     %s\n", lumpString );
1046
1047                         /* guess lump type */
1048                         if ( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' ) {
1049                                 Sys_Printf( "Type guess:    IBSP LUMP_ENTITIES\n" );
1050                         }
1051                         else if ( strstr( lumpString, "textures/" ) ) {
1052                                 Sys_Printf( "Type guess:    IBSP LUMP_SHADERS\n" );
1053                         }
1054                         else
1055                         {
1056                                 /* guess based on size/count */
1057                                 for ( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ )
1058                                 {
1059                                         if ( ( length % lumpTest->radix ) != 0 ) {
1060                                                 continue;
1061                                         }
1062                                         count = length / lumpTest->radix;
1063                                         if ( count < lumpTest->minCount ) {
1064                                                 continue;
1065                                         }
1066                                         Sys_Printf( "Type guess:    %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix );
1067                                 }
1068                         }
1069                 }
1070
1071                 Sys_Printf( "---------------------------------------\n" );
1072
1073                 /* end of file */
1074                 if ( offset + length >= size ) {
1075                         break;
1076                 }
1077         }
1078
1079         /* last stats */
1080         Sys_Printf( "Lump count:    %d\n", i + 1 );
1081         Sys_Printf( "File size:     %d bytes\n", size );
1082
1083         /* return to caller */
1084         return 0;
1085 }
1086
1087
1088
1089 /*
1090    BSPInfo()
1091    emits statistics about the bsp file
1092  */
1093
1094 int BSPInfo( int count, char **fileNames ){
1095         int i;
1096         char source[ 1024 ], ext[ 64 ];
1097         int size;
1098         FILE        *f;
1099
1100
1101         /* dummy check */
1102         if ( count < 1 ) {
1103                 Sys_Printf( "No files to dump info for.\n" );
1104                 return -1;
1105         }
1106
1107         /* enable info mode */
1108         infoMode = qtrue;
1109
1110         /* walk file list */
1111         for ( i = 0; i < count; i++ )
1112         {
1113                 Sys_Printf( "---------------------------------\n" );
1114
1115                 /* mangle filename and get size */
1116                 strcpy( source, fileNames[ i ] );
1117                 ExtractFileExtension( source, ext );
1118                 if ( !Q_stricmp( ext, "map" ) ) {
1119                         StripExtension( source );
1120                 }
1121                 DefaultExtension( source, ".bsp" );
1122                 f = fopen( source, "rb" );
1123                 if ( f ) {
1124                         size = Q_filelength( f );
1125                         fclose( f );
1126                 }
1127                 else{
1128                         size = 0;
1129                 }
1130
1131                 /* load the bsp file and print lump sizes */
1132                 Sys_Printf( "%s\n", source );
1133                 LoadBSPFile( source );
1134                 PrintBSPFileSizes();
1135
1136                 /* print sizes */
1137                 Sys_Printf( "\n" );
1138                 Sys_Printf( "          total         %9d\n", size );
1139                 Sys_Printf( "                        %9d KB\n", size / 1024 );
1140                 Sys_Printf( "                        %9d MB\n", size / ( 1024 * 1024 ) );
1141
1142                 Sys_Printf( "---------------------------------\n" );
1143         }
1144
1145         /* return count */
1146         return i;
1147 }
1148
1149
1150 static void ExtrapolateTexcoords( const float *axyz, const float *ast, const float *bxyz, const float *bst, const float *cxyz, const float *cst, const float *axyz_new, float *ast_out, const float *bxyz_new, float *bst_out, const float *cxyz_new, float *cst_out ){
1151         vec4_t scoeffs, tcoeffs;
1152         float md;
1153         m4x4_t solvematrix;
1154
1155         vec3_t norm;
1156         vec3_t dab, dac;
1157         VectorSubtract( bxyz, axyz, dab );
1158         VectorSubtract( cxyz, axyz, dac );
1159         CrossProduct( dab, dac, norm );
1160
1161         // assume:
1162         //   s = f(x, y, z)
1163         //   s(v + norm) = s(v) when n ortho xyz
1164
1165         // s(v) = DotProduct(v, scoeffs) + scoeffs[3]
1166
1167         // solve:
1168         //   scoeffs * (axyz, 1) == ast[0]
1169         //   scoeffs * (bxyz, 1) == bst[0]
1170         //   scoeffs * (cxyz, 1) == cst[0]
1171         //   scoeffs * (norm, 0) == 0
1172         // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0]
1173         solvematrix[0] = axyz[0];
1174         solvematrix[4] = axyz[1];
1175         solvematrix[8] = axyz[2];
1176         solvematrix[12] = 1;
1177         solvematrix[1] = bxyz[0];
1178         solvematrix[5] = bxyz[1];
1179         solvematrix[9] = bxyz[2];
1180         solvematrix[13] = 1;
1181         solvematrix[2] = cxyz[0];
1182         solvematrix[6] = cxyz[1];
1183         solvematrix[10] = cxyz[2];
1184         solvematrix[14] = 1;
1185         solvematrix[3] = norm[0];
1186         solvematrix[7] = norm[1];
1187         solvematrix[11] = norm[2];
1188         solvematrix[15] = 0;
1189
1190         md = m4_det( solvematrix );
1191         if ( md * md < 1e-10 ) {
1192                 Sys_Printf( "Cannot invert some matrix, some texcoords aren't extrapolated!" );
1193                 return;
1194         }
1195
1196         m4x4_invert( solvematrix );
1197
1198         scoeffs[0] = ast[0];
1199         scoeffs[1] = bst[0];
1200         scoeffs[2] = cst[0];
1201         scoeffs[3] = 0;
1202         m4x4_transform_vec4( solvematrix, scoeffs );
1203         tcoeffs[0] = ast[1];
1204         tcoeffs[1] = bst[1];
1205         tcoeffs[2] = cst[1];
1206         tcoeffs[3] = 0;
1207         m4x4_transform_vec4( solvematrix, tcoeffs );
1208
1209         ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3];
1210         ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3];
1211         bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3];
1212         bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3];
1213         cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3];
1214         cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3];
1215 }
1216
1217 /*
1218    ScaleBSPMain()
1219    amaze and confuse your enemies with wierd scaled maps!
1220  */
1221
1222 int ScaleBSPMain( int argc, char **argv ){
1223         int i, j;
1224         float f, a;
1225         vec3_t scale;
1226         vec3_t vec;
1227         char str[ 1024 ];
1228         int uniform, axis;
1229         qboolean texscale;
1230         float *old_xyzst = NULL;
1231         float spawn_ref = 0;
1232
1233
1234         /* arg checking */
1235         if ( argc < 3 ) {
1236                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
1237                 return 0;
1238         }
1239
1240         texscale = qfalse;
1241         for ( i = 1; i < argc - 2; ++i )
1242         {
1243                 if ( !strcmp( argv[i], "-tex" ) ) {
1244                         texscale = qtrue;
1245                 }
1246                 else if ( !strcmp( argv[i], "-spawn_ref" ) ) {
1247                         spawn_ref = atof( argv[i + 1] );
1248                         ++i;
1249                 }
1250                 else{
1251                         break;
1252                 }
1253         }
1254
1255         /* get scale */
1256         // if(argc-2 >= i) // always true
1257         scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] );
1258         if ( argc - 3 >= i ) {
1259                 scale[1] = scale[0] = atof( argv[ argc - 3 ] );
1260         }
1261         if ( argc - 4 >= i ) {
1262                 scale[0] = atof( argv[ argc - 4 ] );
1263         }
1264
1265         uniform = ( ( scale[0] == scale[1] ) && ( scale[1] == scale[2] ) );
1266
1267         if ( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f ) {
1268                 Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref <value>] <value> <mapname>\n" );
1269                 Sys_Printf( "Non-zero scale value required.\n" );
1270                 return 0;
1271         }
1272
1273         /* do some path mangling */
1274         strcpy( source, ExpandArg( argv[ argc - 1 ] ) );
1275         StripExtension( source );
1276         DefaultExtension( source, ".bsp" );
1277
1278         /* load the bsp */
1279         Sys_Printf( "Loading %s\n", source );
1280         LoadBSPFile( source );
1281         ParseEntities();
1282
1283         /* note it */
1284         Sys_Printf( "--- ScaleBSP ---\n" );
1285         Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities );
1286
1287         /* scale entity keys */
1288         for ( i = 0; i < numBSPEntities && i < numEntities; i++ )
1289         {
1290                 /* scale origin */
1291                 GetVectorForKey( &entities[ i ], "origin", vec );
1292                 if ( ( vec[ 0 ] || vec[ 1 ] || vec[ 2 ] ) ) {
1293                         if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
1294                                 vec[2] += spawn_ref;
1295                         }
1296                         vec[0] *= scale[0];
1297                         vec[1] *= scale[1];
1298                         vec[2] *= scale[2];
1299                         if ( !strncmp( ValueForKey( &entities[i], "classname" ), "info_player_", 12 ) ) {
1300                                 vec[2] -= spawn_ref;
1301                         }
1302                         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1303                         SetKeyValue( &entities[ i ], "origin", str );
1304                 }
1305
1306                 a = FloatForKey( &entities[ i ], "angle" );
1307                 if ( a == -1 || a == -2 ) { // z scale
1308                         axis = 2;
1309                 }
1310                 else if ( fabs( sin( DEG2RAD( a ) ) ) < 0.707 ) {
1311                         axis = 0;
1312                 }
1313                 else{
1314                         axis = 1;
1315                 }
1316
1317                 /* scale door lip */
1318                 f = FloatForKey( &entities[ i ], "lip" );
1319                 if ( f ) {
1320                         f *= scale[axis];
1321                         sprintf( str, "%f", f );
1322                         SetKeyValue( &entities[ i ], "lip", str );
1323                 }
1324
1325                 /* scale plat height */
1326                 f = FloatForKey( &entities[ i ], "height" );
1327                 if ( f ) {
1328                         f *= scale[2];
1329                         sprintf( str, "%f", f );
1330                         SetKeyValue( &entities[ i ], "height", str );
1331                 }
1332
1333                 // TODO maybe allow a definition file for entities to specify which values are scaled how?
1334         }
1335
1336         /* scale models */
1337         for ( i = 0; i < numBSPModels; i++ )
1338         {
1339                 bspModels[ i ].mins[0] *= scale[0];
1340                 bspModels[ i ].mins[1] *= scale[1];
1341                 bspModels[ i ].mins[2] *= scale[2];
1342                 bspModels[ i ].maxs[0] *= scale[0];
1343                 bspModels[ i ].maxs[1] *= scale[1];
1344                 bspModels[ i ].maxs[2] *= scale[2];
1345         }
1346
1347         /* scale nodes */
1348         for ( i = 0; i < numBSPNodes; i++ )
1349         {
1350                 bspNodes[ i ].mins[0] *= scale[0];
1351                 bspNodes[ i ].mins[1] *= scale[1];
1352                 bspNodes[ i ].mins[2] *= scale[2];
1353                 bspNodes[ i ].maxs[0] *= scale[0];
1354                 bspNodes[ i ].maxs[1] *= scale[1];
1355                 bspNodes[ i ].maxs[2] *= scale[2];
1356         }
1357
1358         /* scale leafs */
1359         for ( i = 0; i < numBSPLeafs; i++ )
1360         {
1361                 bspLeafs[ i ].mins[0] *= scale[0];
1362                 bspLeafs[ i ].mins[1] *= scale[1];
1363                 bspLeafs[ i ].mins[2] *= scale[2];
1364                 bspLeafs[ i ].maxs[0] *= scale[0];
1365                 bspLeafs[ i ].maxs[1] *= scale[1];
1366                 bspLeafs[ i ].maxs[2] *= scale[2];
1367         }
1368
1369         if ( texscale ) {
1370                 Sys_Printf( "Using texture unlocking (and probably breaking texture alignment a lot)\n" );
1371                 old_xyzst = safe_malloc( sizeof( *old_xyzst ) * numBSPDrawVerts * 5 );
1372                 for ( i = 0; i < numBSPDrawVerts; i++ )
1373                 {
1374                         old_xyzst[5 * i + 0] = bspDrawVerts[i].xyz[0];
1375                         old_xyzst[5 * i + 1] = bspDrawVerts[i].xyz[1];
1376                         old_xyzst[5 * i + 2] = bspDrawVerts[i].xyz[2];
1377                         old_xyzst[5 * i + 3] = bspDrawVerts[i].st[0];
1378                         old_xyzst[5 * i + 4] = bspDrawVerts[i].st[1];
1379                 }
1380         }
1381
1382         /* scale drawverts */
1383         for ( i = 0; i < numBSPDrawVerts; i++ )
1384         {
1385                 bspDrawVerts[i].xyz[0] *= scale[0];
1386                 bspDrawVerts[i].xyz[1] *= scale[1];
1387                 bspDrawVerts[i].xyz[2] *= scale[2];
1388                 bspDrawVerts[i].normal[0] /= scale[0];
1389                 bspDrawVerts[i].normal[1] /= scale[1];
1390                 bspDrawVerts[i].normal[2] /= scale[2];
1391                 VectorNormalize( bspDrawVerts[i].normal, bspDrawVerts[i].normal );
1392         }
1393
1394         if ( texscale ) {
1395                 for ( i = 0; i < numBSPDrawSurfaces; i++ )
1396                 {
1397                         switch ( bspDrawSurfaces[i].surfaceType )
1398                         {
1399                         case SURFACE_FACE:
1400                         case SURFACE_META:
1401                                 if ( bspDrawSurfaces[i].numIndexes % 3 ) {
1402                                         Error( "Not a triangulation!" );
1403                                 }
1404                                 for ( j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3 )
1405                                 {
1406                                         int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j + 1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j + 2] + bspDrawSurfaces[i].firstVert;
1407                                         bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic];
1408                                         float *oa = &old_xyzst[ia * 5], *ob = &old_xyzst[ib * 5], *oc = &old_xyzst[ic * 5];
1409                                         // extrapolate:
1410                                         //   a->xyz -> oa
1411                                         //   b->xyz -> ob
1412                                         //   c->xyz -> oc
1413                                         ExtrapolateTexcoords(
1414                                                 &oa[0], &oa[3],
1415                                                 &ob[0], &ob[3],
1416                                                 &oc[0], &oc[3],
1417                                                 a->xyz, a->st,
1418                                                 b->xyz, b->st,
1419                                                 c->xyz, c->st );
1420                                 }
1421                                 break;
1422                         }
1423                 }
1424         }
1425
1426         /* scale planes */
1427         if ( uniform ) {
1428                 for ( i = 0; i < numBSPPlanes; i++ )
1429                 {
1430                         bspPlanes[ i ].dist *= scale[0];
1431                 }
1432         }
1433         else
1434         {
1435                 for ( i = 0; i < numBSPPlanes; i++ )
1436                 {
1437                         bspPlanes[ i ].normal[0] /= scale[0];
1438                         bspPlanes[ i ].normal[1] /= scale[1];
1439                         bspPlanes[ i ].normal[2] /= scale[2];
1440                         f = 1 / VectorLength( bspPlanes[i].normal );
1441                         VectorScale( bspPlanes[i].normal, f, bspPlanes[i].normal );
1442                         bspPlanes[ i ].dist *= f;
1443                 }
1444         }
1445
1446         /* scale gridsize */
1447         GetVectorForKey( &entities[ 0 ], "gridsize", vec );
1448         if ( ( vec[ 0 ] + vec[ 1 ] + vec[ 2 ] ) == 0.0f ) {
1449                 VectorCopy( gridSize, vec );
1450         }
1451         vec[0] *= scale[0];
1452         vec[1] *= scale[1];
1453         vec[2] *= scale[2];
1454         sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] );
1455         SetKeyValue( &entities[ 0 ], "gridsize", str );
1456
1457         /* inject command line parameters */
1458         InjectCommandLine( argv, 0, argc - 1 );
1459
1460         /* write the bsp */
1461         UnparseEntities();
1462         StripExtension( source );
1463         DefaultExtension( source, "_s.bsp" );
1464         Sys_Printf( "Writing %s\n", source );
1465         WriteBSPFile( source );
1466
1467         /* return to sender */
1468         return 0;
1469 }
1470
1471
1472 /*
1473    PseudoCompileBSP()
1474    a stripped down ProcessModels
1475  */
1476 void PseudoCompileBSP( qboolean need_tree ){
1477         int models;
1478         char modelValue[10];
1479         entity_t *entity;
1480         face_t *faces;
1481         tree_t *tree;
1482         node_t *node;
1483         brush_t *brush;
1484         side_t *side;
1485         int i;
1486
1487         SetDrawSurfacesBuffer();
1488         mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
1489         memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS );
1490         numMapDrawSurfs = 0;
1491
1492         BeginBSPFile();
1493         models = 1;
1494         for ( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ )
1495         {
1496                 /* get entity */
1497                 entity = &entities[ mapEntityNum ];
1498                 if ( entity->brushes == NULL && entity->patches == NULL ) {
1499                         continue;
1500                 }
1501
1502                 if ( mapEntityNum != 0 ) {
1503                         sprintf( modelValue, "*%d", models++ );
1504                         SetKeyValue( entity, "model", modelValue );
1505                 }
1506
1507                 /* process the model */
1508                 Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels );
1509                 BeginModel();
1510
1511                 entity->firstDrawSurf = numMapDrawSurfs;
1512
1513                 ClearMetaTriangles();
1514                 PatchMapDrawSurfs( entity );
1515
1516                 if ( mapEntityNum == 0 && need_tree ) {
1517                         faces = MakeStructuralBSPFaceList( entities[0].brushes );
1518                         tree = FaceBSP( faces );
1519                         node = tree->headnode;
1520                 }
1521                 else
1522                 {
1523                         node = AllocNode();
1524                         node->planenum = PLANENUM_LEAF;
1525                         tree = AllocTree();
1526                         tree->headnode = node;
1527                 }
1528
1529                 /* a minimized ClipSidesIntoTree */
1530                 for ( brush = entity->brushes; brush; brush = brush->next )
1531                 {
1532                         /* walk the brush sides */
1533                         for ( i = 0; i < brush->numsides; i++ )
1534                         {
1535                                 /* get side */
1536                                 side = &brush->sides[ i ];
1537                                 if ( side->winding == NULL ) {
1538                                         continue;
1539                                 }
1540                                 /* shader? */
1541                                 if ( side->shaderInfo == NULL ) {
1542                                         continue;
1543                                 }
1544                                 /* save this winding as a visible surface */
1545                                 DrawSurfaceForSide( entity, brush, side, side->winding );
1546                         }
1547                 }
1548
1549                 if ( meta ) {
1550                         ClassifyEntitySurfaces( entity );
1551                         MakeEntityDecals( entity );
1552                         MakeEntityMetaTriangles( entity );
1553                         SmoothMetaTriangles();
1554                         MergeMetaTriangles();
1555                 }
1556                 FilterDrawsurfsIntoTree( entity, tree );
1557
1558                 FilterStructuralBrushesIntoTree( entity, tree );
1559                 FilterDetailBrushesIntoTree( entity, tree );
1560
1561                 EmitBrushes( entity->brushes, &entity->firstBrush, &entity->numBrushes );
1562                 EndModel( entity, node );
1563         }
1564         EndBSPFile( qfalse );
1565 }
1566
1567 /*
1568    ConvertBSPMain()
1569    main argument processing function for bsp conversion
1570  */
1571
1572 int ConvertBSPMain( int argc, char **argv ){
1573         int i;
1574         int ( *convertFunc )( char * );
1575         game_t  *convertGame;
1576         char ext[1024];
1577         qboolean map_allowed, force_bsp, force_map;
1578
1579
1580         /* set default */
1581         convertFunc = ConvertBSPToASE;
1582         convertGame = NULL;
1583         map_allowed = qfalse;
1584         force_bsp = qfalse;
1585         force_map = qfalse;
1586
1587         /* arg checking */
1588         if ( argc < 1 ) {
1589                 Sys_Printf( "Usage: q3map -convert [-format <ase|obj|map_bp|map>] [-shadersasbitmap|-lightmapsastexcoord|-deluxemapsastexcoord] [-readbsp|-readmap [-meta|-patchmeta]] [-v] <mapname>\n" );
1590                 return 0;
1591         }
1592
1593         /* process arguments */
1594         for ( i = 1; i < ( argc - 1 ); i++ )
1595         {
1596                 /* -format map|ase|... */
1597                 if ( !strcmp( argv[ i ],  "-format" ) ) {
1598                         i++;
1599                         if ( !Q_stricmp( argv[ i ], "ase" ) ) {
1600                                 convertFunc = ConvertBSPToASE;
1601                                 map_allowed = qfalse;
1602                         }
1603                         else if ( !Q_stricmp( argv[ i ], "obj" ) ) {
1604                                 convertFunc = ConvertBSPToOBJ;
1605                                 map_allowed = qfalse;
1606                         }
1607                         else if ( !Q_stricmp( argv[ i ], "map_bp" ) ) {
1608                                 convertFunc = ConvertBSPToMap_BP;
1609                                 map_allowed = qtrue;
1610                         }
1611                         else if ( !Q_stricmp( argv[ i ], "map" ) ) {
1612                                 convertFunc = ConvertBSPToMap;
1613                                 map_allowed = qtrue;
1614                         }
1615                         else
1616                         {
1617                                 convertGame = GetGame( argv[ i ] );
1618                                 map_allowed = qfalse;
1619                                 if ( convertGame == NULL ) {
1620                                         Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] );
1621                                 }
1622                         }
1623                 }
1624                 else if ( !strcmp( argv[ i ],  "-ne" ) ) {
1625                         normalEpsilon = atof( argv[ i + 1 ] );
1626                         i++;
1627                         Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon );
1628                 }
1629                 else if ( !strcmp( argv[ i ],  "-de" ) ) {
1630                         distanceEpsilon = atof( argv[ i + 1 ] );
1631                         i++;
1632                         Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon );
1633                 }
1634                 else if ( !strcmp( argv[ i ],  "-shaderasbitmap" ) || !strcmp( argv[ i ],  "-shadersasbitmap" ) ) {
1635                         shadersAsBitmap = qtrue;
1636                 }
1637                 else if ( !strcmp( argv[ i ],  "-lightmapastexcoord" ) || !strcmp( argv[ i ],  "-lightmapsastexcoord" ) ) {
1638                         lightmapsAsTexcoord = qtrue;
1639                 }
1640                 else if ( !strcmp( argv[ i ],  "-deluxemapastexcoord" ) || !strcmp( argv[ i ],  "-deluxemapsastexcoord" ) ) {
1641                         lightmapsAsTexcoord = qtrue;
1642                         deluxemap = qtrue;
1643                 }
1644                 else if ( !strcmp( argv[ i ],  "-readbsp" ) ) {
1645                         force_bsp = qtrue;
1646                 }
1647                 else if ( !strcmp( argv[ i ],  "-readmap" ) ) {
1648                         force_map = qtrue;
1649                 }
1650                 else if ( !strcmp( argv[ i ],  "-meta" ) ) {
1651                         meta = qtrue;
1652                 }
1653                 else if ( !strcmp( argv[ i ],  "-patchmeta" ) ) {
1654                         meta = qtrue;
1655                         patchMeta = qtrue;
1656                 }
1657         }
1658
1659         LoadShaderInfo();
1660
1661         /* clean up map name */
1662         strcpy( source, ExpandArg( argv[i] ) );
1663         ExtractFileExtension( source, ext );
1664
1665         if ( !map_allowed && !force_map ) {
1666                 force_bsp = qtrue;
1667         }
1668
1669         if ( force_map || ( !force_bsp && !Q_stricmp( ext, "map" ) && map_allowed ) ) {
1670                 if ( !map_allowed ) {
1671                         Sys_Printf( "WARNING: the requested conversion should not be done from .map files. Compile a .bsp first.\n" );
1672                 }
1673                 StripExtension( source );
1674                 DefaultExtension( source, ".map" );
1675                 Sys_Printf( "Loading %s\n", source );
1676                 LoadMapFile( source, qfalse, convertGame == NULL );
1677                 PseudoCompileBSP( convertGame != NULL );
1678         }
1679         else
1680         {
1681                 StripExtension( source );
1682                 DefaultExtension( source, ".bsp" );
1683                 Sys_Printf( "Loading %s\n", source );
1684                 LoadBSPFile( source );
1685                 ParseEntities();
1686         }
1687
1688         /* bsp format convert? */
1689         if ( convertGame != NULL ) {
1690                 /* set global game */
1691                 game = convertGame;
1692
1693                 /* write bsp */
1694                 StripExtension( source );
1695                 DefaultExtension( source, "_c.bsp" );
1696                 Sys_Printf( "Writing %s\n", source );
1697                 WriteBSPFile( source );
1698
1699                 /* return to sender */
1700                 return 0;
1701         }
1702
1703         /* normal convert */
1704         return convertFunc( source );
1705 }
1706
1707
1708
1709 /*
1710    main()
1711    q3map mojo...
1712  */
1713
1714 int main( int argc, char **argv ){
1715         int i, r;
1716         double start, end;
1717
1718
1719         /* we want consistent 'randomness' */
1720         srand( 0 );
1721
1722         /* start timer */
1723         start = I_FloatTime();
1724
1725         /* this was changed to emit version number over the network */
1726         printf( Q3MAP_VERSION "\n" );
1727
1728         /* set exit call */
1729         atexit( ExitQ3Map );
1730
1731         /* read general options first */
1732         for ( i = 1; i < argc; i++ )
1733         {
1734                 /* -connect */
1735                 if ( !strcmp( argv[ i ], "-connect" ) ) {
1736                         argv[ i ] = NULL;
1737                         i++;
1738                         Broadcast_Setup( argv[ i ] );
1739                         argv[ i ] = NULL;
1740                 }
1741
1742                 /* verbose */
1743                 else if ( !strcmp( argv[ i ], "-v" ) ) {
1744                         if ( !verbose ) {
1745                                 verbose = qtrue;
1746                                 argv[ i ] = NULL;
1747                         }
1748                 }
1749
1750                 /* force */
1751                 else if ( !strcmp( argv[ i ], "-force" ) ) {
1752                         force = qtrue;
1753                         argv[ i ] = NULL;
1754                 }
1755
1756                 /* patch subdivisions */
1757                 else if ( !strcmp( argv[ i ], "-subdivisions" ) ) {
1758                         argv[ i ] = NULL;
1759                         i++;
1760                         patchSubdivisions = atoi( argv[ i ] );
1761                         argv[ i ] = NULL;
1762                         if ( patchSubdivisions <= 0 ) {
1763                                 patchSubdivisions = 1;
1764                         }
1765                 }
1766
1767                 /* threads */
1768                 else if ( !strcmp( argv[ i ], "-threads" ) ) {
1769                         argv[ i ] = NULL;
1770                         i++;
1771                         numthreads = atoi( argv[ i ] );
1772                         argv[ i ] = NULL;
1773                 }
1774         }
1775
1776         /* init model library */
1777         PicoInit();
1778         PicoSetMallocFunc( safe_malloc );
1779         PicoSetFreeFunc( free );
1780         PicoSetPrintFunc( PicoPrintFunc );
1781         PicoSetLoadFileFunc( PicoLoadFileFunc );
1782         PicoSetFreeFileFunc( free );
1783
1784         /* set number of threads */
1785         ThreadSetDefault();
1786
1787         /* generate sinusoid jitter table */
1788         for ( i = 0; i < MAX_JITTERS; i++ )
1789         {
1790                 jitters[ i ] = sin( i * 139.54152147 );
1791                 //%     Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] );
1792         }
1793
1794         /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant)
1795            and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */
1796
1797         Sys_Printf( "Q3Map         - v1.0r (c) 1999 Id Software Inc.\n" );
1798         Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" );
1799         Sys_Printf( "NetRadiant    - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" );
1800         Sys_Printf( "%s\n", Q3MAP_MOTD );
1801
1802         /* ydnar: new path initialization */
1803         InitPaths( &argc, argv );
1804
1805         /* set game options */
1806         if ( !patchSubdivisions ) {
1807                 patchSubdivisions = game->patchSubdivisions;
1808         }
1809
1810         /* check if we have enough options left to attempt something */
1811         if ( argc < 2 ) {
1812                 Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] );
1813         }
1814
1815         /* fixaas */
1816         if ( !strcmp( argv[ 1 ], "-fixaas" ) ) {
1817                 r = FixAAS( argc - 1, argv + 1 );
1818         }
1819
1820         /* analyze */
1821         else if ( !strcmp( argv[ 1 ], "-analyze" ) ) {
1822                 r = AnalyzeBSP( argc - 1, argv + 1 );
1823         }
1824
1825         /* info */
1826         else if ( !strcmp( argv[ 1 ], "-info" ) ) {
1827                 r = BSPInfo( argc - 2, argv + 2 );
1828         }
1829
1830         /* vis */
1831         else if ( !strcmp( argv[ 1 ], "-vis" ) ) {
1832                 r = VisMain( argc - 1, argv + 1 );
1833         }
1834
1835         /* light */
1836         else if ( !strcmp( argv[ 1 ], "-light" ) ) {
1837                 r = LightMain( argc - 1, argv + 1 );
1838         }
1839
1840         /* vlight */
1841         else if ( !strcmp( argv[ 1 ], "-vlight" ) ) {
1842                 Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" );
1843                 argv[ 1 ] = "-fast";    /* eek a hack */
1844                 r = LightMain( argc, argv );
1845         }
1846
1847         /* ydnar: lightmap export */
1848         else if ( !strcmp( argv[ 1 ], "-export" ) ) {
1849                 r = ExportLightmapsMain( argc - 1, argv + 1 );
1850         }
1851
1852         /* ydnar: lightmap import */
1853         else if ( !strcmp( argv[ 1 ], "-import" ) ) {
1854                 r = ImportLightmapsMain( argc - 1, argv + 1 );
1855         }
1856
1857         /* ydnar: bsp scaling */
1858         else if ( !strcmp( argv[ 1 ], "-scale" ) ) {
1859                 r = ScaleBSPMain( argc - 1, argv + 1 );
1860         }
1861
1862         /* ydnar: bsp conversion */
1863         else if ( !strcmp( argv[ 1 ], "-convert" ) ) {
1864                 r = ConvertBSPMain( argc - 1, argv + 1 );
1865         }
1866
1867         /* div0: minimap */
1868         else if ( !strcmp( argv[ 1 ], "-minimap" ) ) {
1869                 r = MiniMapBSPMain( argc - 1, argv + 1 );
1870         }
1871
1872         /* ydnar: otherwise create a bsp */
1873         else{
1874                 r = BSPMain( argc, argv );
1875         }
1876
1877         /* emit time */
1878         end = I_FloatTime();
1879         Sys_Printf( "%9.0f seconds elapsed\n", end - start );
1880
1881         /* shut down connection */
1882         Broadcast_Shutdown();
1883
1884         /* return any error code */
1885         return r;
1886 }