]> git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/vis.c
q3map2: do not leak user temporary paths
[xonotic/netradiant.git] / tools / quake3 / q3map2 / vis.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 VIS_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41
42 void PlaneFromWinding( fixedWinding_t *w, visPlane_t *plane ){
43         vec3_t v1, v2;
44
45 // calc plane
46         VectorSubtract( w->points[2], w->points[1], v1 );
47         VectorSubtract( w->points[0], w->points[1], v2 );
48         CrossProduct( v2, v1, plane->normal );
49         VectorNormalize( plane->normal, plane->normal );
50         plane->dist = DotProduct( w->points[0], plane->normal );
51 }
52
53
54 /*
55    NewFixedWinding()
56    returns a new fixed winding
57    ydnar: altered this a bit to reconcile multiply-defined winding_t
58  */
59
60 fixedWinding_t *NewFixedWinding( int points ){
61         fixedWinding_t  *w;
62         int size;
63
64         if ( points > MAX_POINTS_ON_WINDING ) {
65                 Error( "NewWinding: %i points", points );
66         }
67
68         size = (int)( (size_t)( (fixedWinding_t *)0 )->points[points] );
69         w = safe_malloc0( size );
70
71         return w;
72 }
73
74
75
76 void prl( leaf_t *l ){
77         int i;
78         vportal_t   *p;
79         visPlane_t pl;
80
81         for ( i = 0 ; i < l->numportals ; i++ )
82         {
83                 p = l->portals[i];
84                 pl = p->plane;
85                 Sys_Printf( "portal %4i to leaf %4i : %7.1f : (%4.1f, %4.1f, %4.1f)\n",(int)( p - portals ),p->leaf,pl.dist, pl.normal[0], pl.normal[1], pl.normal[2] );
86         }
87 }
88
89
90 //=============================================================================
91
92 /*
93    =============
94    SortPortals
95
96    Sorts the portals from the least complex, so the later ones can reuse
97    the earlier information.
98    =============
99  */
100 int PComp( const void *a, const void *b ){
101         if ( ( *(const vportal_t *const *)a )->nummightsee == ( *(const vportal_t *const *)b )->nummightsee ) {
102                 return 0;
103         }
104         if ( ( *(const vportal_t *const *)a )->nummightsee < ( *(const vportal_t *const *)b )->nummightsee ) {
105                 return -1;
106         }
107         return 1;
108 }
109 void SortPortals( void ){
110         int i;
111
112         for ( i = 0 ; i < numportals * 2 ; i++ )
113                 sorted_portals[i] = &portals[i];
114
115         if ( nosort ) {
116                 return;
117         }
118         qsort( sorted_portals, numportals * 2, sizeof( sorted_portals[0] ), PComp );
119 }
120
121
122 /*
123    ==============
124    LeafVectorFromPortalVector
125    ==============
126  */
127 int LeafVectorFromPortalVector( byte *portalbits, byte *leafbits ){
128         int i, j, leafnum;
129         vportal_t   *p;
130         int c_leafs;
131
132
133         for ( i = 0 ; i < numportals * 2 ; i++ )
134         {
135                 if ( portalbits[i >> 3] & ( 1 << ( i & 7 ) ) ) {
136                         p = portals + i;
137                         leafbits[p->leaf >> 3] |= ( 1 << ( p->leaf & 7 ) );
138                 }
139         }
140
141         for ( j = 0; j < portalclusters; j++ )
142         {
143                 leafnum = j;
144                 while ( leafs[leafnum].merged >= 0 )
145                         leafnum = leafs[leafnum].merged;
146                 //if the merged leaf is visible then the original leaf is visible
147                 if ( leafbits[leafnum >> 3] & ( 1 << ( leafnum & 7 ) ) ) {
148                         leafbits[j >> 3] |= ( 1 << ( j & 7 ) );
149                 }
150         }
151
152         c_leafs = CountBits( leafbits, portalclusters );
153
154         return c_leafs;
155 }
156
157
158 /*
159    ===============
160    ClusterMerge
161
162    Merges the portal visibility for a leaf
163    ===============
164  */
165
166 static int clustersizehistogram[MAX_MAP_LEAFS] = {0};
167
168 void ClusterMerge( int leafnum ){
169         leaf_t      *leaf;
170         byte portalvector[MAX_PORTALS / 8];
171         byte uncompressed[MAX_MAP_LEAFS / 8];
172         int i, j;
173         int numvis, mergedleafnum;
174         vportal_t   *p;
175         int pnum;
176
177         // OR together all the portalvis bits
178
179         mergedleafnum = leafnum;
180         while ( leafs[mergedleafnum].merged >= 0 )
181                 mergedleafnum = leafs[mergedleafnum].merged;
182
183         memset( portalvector, 0, portalbytes );
184         leaf = &leafs[mergedleafnum];
185         for ( i = 0; i < leaf->numportals; i++ )
186         {
187                 p = leaf->portals[i];
188                 if ( p->removed ) {
189                         continue;
190                 }
191
192                 if ( p->status != stat_done ) {
193                         Error( "portal not done" );
194                 }
195                 for ( j = 0 ; j < portallongs ; j++ )
196                         ( (long *)portalvector )[j] |= ( (long *)p->portalvis )[j];
197                 pnum = p - portals;
198                 portalvector[pnum >> 3] |= 1 << ( pnum & 7 );
199         }
200
201         memset( uncompressed, 0, leafbytes );
202
203         uncompressed[mergedleafnum >> 3] |= ( 1 << ( mergedleafnum & 7 ) );
204         // convert portal bits to leaf bits
205         numvis = LeafVectorFromPortalVector( portalvector, uncompressed );
206
207 //      if (uncompressed[leafnum>>3] & (1<<(leafnum&7)))
208 //              Sys_FPrintf (SYS_WRN, "WARNING: Leaf portals saw into leaf\n");
209
210 //      uncompressed[leafnum>>3] |= (1<<(leafnum&7));
211
212         numvis++;       // count the leaf itself
213
214         //Sys_FPrintf( SYS_VRB,"cluster %4i : %4i visible\n", leafnum, numvis );
215         ++clustersizehistogram[numvis];
216
217         memcpy( bspVisBytes + VIS_HEADER_SIZE + leafnum * leafbytes, uncompressed, leafbytes );
218 }
219
220 /*
221    ==================
222    CalcPortalVis
223    ==================
224  */
225 void CalcPortalVis( void ){
226 #ifdef MREDEBUG
227         Sys_Printf( "%6d portals out of %d", 0, numportals * 2 );
228         //get rid of the counter
229         RunThreadsOnIndividual( numportals * 2, qfalse, PortalFlow );
230 #else
231         RunThreadsOnIndividual( numportals * 2, qtrue, PortalFlow );
232 #endif
233
234 }
235
236 /*
237    ==================
238    CalcPassageVis
239    ==================
240  */
241 void CalcPassageVis( void ){
242         PassageMemory();
243
244 #ifdef MREDEBUG
245         _printf( "%6d portals out of %d", 0, numportals * 2 );
246         RunThreadsOnIndividual( numportals * 2, qfalse, CreatePassages );
247         _printf( "\n" );
248         _printf( "%6d portals out of %d", 0, numportals * 2 );
249         RunThreadsOnIndividual( numportals * 2, qfalse, PassageFlow );
250         _printf( "\n" );
251 #else
252         Sys_Printf( "\n--- CreatePassages (%d) ---\n", numportals * 2 );
253         RunThreadsOnIndividual( numportals * 2, qtrue, CreatePassages );
254
255         Sys_Printf( "\n--- PassageFlow (%d) ---\n", numportals * 2 );
256         RunThreadsOnIndividual( numportals * 2, qtrue, PassageFlow );
257 #endif
258 }
259
260 /*
261    ==================
262    CalcPassagePortalVis
263    ==================
264  */
265 void CalcPassagePortalVis( void ){
266         PassageMemory();
267
268 #ifdef MREDEBUG
269         Sys_Printf( "%6d portals out of %d", 0, numportals * 2 );
270         RunThreadsOnIndividual( numportals * 2, qfalse, CreatePassages );
271         Sys_Printf( "\n" );
272         Sys_Printf( "%6d portals out of %d", 0, numportals * 2 );
273         RunThreadsOnIndividual( numportals * 2, qfalse, PassagePortalFlow );
274         Sys_Printf( "\n" );
275 #else
276         Sys_Printf( "\n--- CreatePassages (%d) ---\n", numportals * 2 );
277         RunThreadsOnIndividual( numportals * 2, qtrue, CreatePassages );
278
279         Sys_Printf( "\n--- PassagePortalFlow (%d) ---\n", numportals * 2 );
280         RunThreadsOnIndividual( numportals * 2, qtrue, PassagePortalFlow );
281 #endif
282 }
283
284 /*
285    ==================
286    CalcFastVis
287    ==================
288  */
289 void CalcFastVis( void ){
290         int i;
291
292         // fastvis just uses mightsee for a very loose bound
293         for ( i = 0 ; i < numportals * 2 ; i++ )
294         {
295                 portals[i].portalvis = portals[i].portalflood;
296                 portals[i].status = stat_done;
297         }
298 }
299
300 /*
301    ==================
302    CalcVis
303    ==================
304  */
305 void CalcVis( void ){
306         int i, minvis, maxvis;
307         const char  *value;
308         double mu, sigma, totalvis, totalvis2;
309
310
311         /* ydnar: rr2do2's farplane code */
312         farPlaneDist = 0.0f;
313         value = ValueForKey( &entities[ 0 ], "_farplanedist" );     /* proper '_' prefixed key */
314         if ( value[ 0 ] == '\0' ) {
315                 value = ValueForKey( &entities[ 0 ], "fogclip" );       /* wolf compatibility */
316         }
317         if ( value[ 0 ] == '\0' ) {
318                 value = ValueForKey( &entities[ 0 ], "distancecull" );  /* sof2 compatibility */
319         }
320         if ( value[ 0 ] != '\0' ) {
321                 farPlaneDist = atof( value );
322                 if ( farPlaneDist > 0.0f ) {
323                         Sys_Printf( "farplane distance = %.1f\n", farPlaneDist );
324                 }
325                 else{
326                         farPlaneDist = 0.0f;
327                 }
328         }
329
330
331
332         Sys_Printf( "\n--- BasePortalVis (%d) ---\n", numportals * 2 );
333         RunThreadsOnIndividual( numportals * 2, qtrue, BasePortalVis );
334
335 //      RunThreadsOnIndividual (numportals*2, qtrue, BetterPortalVis);
336
337         SortPortals();
338
339         if ( fastvis ) {
340                 CalcFastVis();
341         }
342         else if ( noPassageVis ) {
343                 CalcPortalVis();
344         }
345         else if ( passageVisOnly ) {
346                 CalcPassageVis();
347         }
348         else {
349                 CalcPassagePortalVis();
350         }
351         //
352         // assemble the leaf vis lists by oring and compressing the portal lists
353         //
354         Sys_Printf( "creating leaf vis...\n" );
355         for ( i = 0 ; i < portalclusters ; i++ )
356                 ClusterMerge( i );
357
358         totalvis = 0;
359         totalvis2 = 0;
360         minvis = -1;
361         maxvis = -1;
362         for ( i = 0; i < MAX_MAP_LEAFS; ++i )
363                 if ( clustersizehistogram[i] ) {
364                         if ( debugCluster ) {
365                                 Sys_FPrintf( SYS_VRB, "%4i clusters have exactly %4i visible clusters\n", clustersizehistogram[i], i );
366                         }
367                         /* cast is to prevent integer overflow */
368                         totalvis  += ( (double) i )                * ( (double) clustersizehistogram[i] );
369                         totalvis2 += ( (double) i ) * ( (double) i ) * ( (double) clustersizehistogram[i] );
370
371                         if ( minvis < 0 ) {
372                                 minvis = i;
373                         }
374                         maxvis = i;
375                 }
376
377         mu = totalvis / portalclusters;
378         sigma = sqrt( totalvis2 / portalclusters - mu * mu );
379
380         Sys_Printf( "Total clusters: %i\n", portalclusters );
381         Sys_Printf( "Total visible clusters: %.0f\n", totalvis );
382         Sys_Printf( "Average clusters visible: %.2f (%.3f%%/total)\n", mu, mu / portalclusters * 100.0 );
383         Sys_Printf( "  Standard deviation: %.2f (%.3f%%/total, %.3f%%/avg)\n", sigma, sigma / portalclusters * 100.0, sigma / mu * 100.0 );
384         Sys_Printf( "  Minimum: %i (%.3f%%/total, %.3f%%/avg)\n", minvis, minvis / (double) portalclusters * 100.0, minvis / mu * 100.0 );
385         Sys_Printf( "  Maximum: %i (%.3f%%/total, %.3f%%/avg)\n", maxvis, maxvis / (double) portalclusters * 100.0, maxvis / mu * 100.0 );
386 }
387
388 /*
389    ==================
390    SetPortalSphere
391    ==================
392  */
393 void SetPortalSphere( vportal_t *p ){
394         int i;
395         vec3_t total, dist;
396         fixedWinding_t  *w;
397         float r, bestr;
398
399         w = p->winding;
400         VectorCopy( vec3_origin, total );
401         for ( i = 0 ; i < w->numpoints ; i++ )
402         {
403                 VectorAdd( total, w->points[i], total );
404         }
405
406         for ( i = 0 ; i < 3 ; i++ )
407                 total[i] /= w->numpoints;
408
409         bestr = 0;
410         for ( i = 0 ; i < w->numpoints ; i++ )
411         {
412                 VectorSubtract( w->points[i], total, dist );
413                 r = VectorLength( dist );
414                 if ( r > bestr ) {
415                         bestr = r;
416                 }
417         }
418         VectorCopy( total, p->origin );
419         p->radius = bestr;
420 }
421
422 /*
423    =============
424    Winding_PlanesConcave
425    =============
426  */
427 #define WCONVEX_EPSILON     0.2
428
429 int Winding_PlanesConcave( fixedWinding_t *w1, fixedWinding_t *w2,
430                                                    vec3_t normal1, vec3_t normal2,
431                                                    float dist1, float dist2 ){
432         int i;
433
434         if ( !w1 || !w2 ) {
435                 return qfalse;
436         }
437
438         // check if one of the points of winding 1 is at the front of the plane of winding 2
439         for ( i = 0; i < w1->numpoints; i++ )
440         {
441                 if ( DotProduct( normal2, w1->points[i] ) - dist2 > WCONVEX_EPSILON ) {
442                         return qtrue;
443                 }
444         }
445         // check if one of the points of winding 2 is at the front of the plane of winding 1
446         for ( i = 0; i < w2->numpoints; i++ )
447         {
448                 if ( DotProduct( normal1, w2->points[i] ) - dist1 > WCONVEX_EPSILON ) {
449                         return qtrue;
450                 }
451         }
452
453         return qfalse;
454 }
455
456 /*
457    ============
458    TryMergeLeaves
459    ============
460  */
461 int TryMergeLeaves( int l1num, int l2num ){
462         int i, j, k, n, numportals;
463         visPlane_t plane1, plane2;
464         leaf_t *l1, *l2;
465         vportal_t *p1, *p2;
466         vportal_t *portals[MAX_PORTALS_ON_LEAF];
467
468         for ( k = 0; k < 2; k++ )
469         {
470                 if ( k ) {
471                         l1 = &leafs[l1num];
472                 }
473                 else{l1 = &faceleafs[l1num]; }
474                 for ( i = 0; i < l1->numportals; i++ )
475                 {
476                         p1 = l1->portals[i];
477                         if ( p1->leaf == l2num ) {
478                                 continue;
479                         }
480                         for ( n = 0; n < 2; n++ )
481                         {
482                                 if ( n ) {
483                                         l2 = &leafs[l2num];
484                                 }
485                                 else{l2 = &faceleafs[l2num]; }
486                                 for ( j = 0; j < l2->numportals; j++ )
487                                 {
488                                         p2 = l2->portals[j];
489                                         if ( p2->leaf == l1num ) {
490                                                 continue;
491                                         }
492                                         //
493                                         plane1 = p1->plane;
494                                         plane2 = p2->plane;
495                                         if ( Winding_PlanesConcave( p1->winding, p2->winding, plane1.normal, plane2.normal, plane1.dist, plane2.dist ) ) {
496                                                 return qfalse;
497                                         }
498                                 }
499                         }
500                 }
501         }
502         for ( k = 0; k < 2; k++ )
503         {
504                 if ( k ) {
505                         l1 = &leafs[l1num];
506                         l2 = &leafs[l2num];
507                 }
508                 else
509                 {
510                         l1 = &faceleafs[l1num];
511                         l2 = &faceleafs[l2num];
512                 }
513                 numportals = 0;
514                 //the leaves can be merged now
515                 for ( i = 0; i < l1->numportals; i++ )
516                 {
517                         p1 = l1->portals[i];
518                         if ( p1->leaf == l2num ) {
519                                 p1->removed = qtrue;
520                                 continue;
521                         }
522                         portals[numportals++] = p1;
523                 }
524                 for ( j = 0; j < l2->numportals; j++ )
525                 {
526                         p2 = l2->portals[j];
527                         if ( p2->leaf == l1num ) {
528                                 p2->removed = qtrue;
529                                 continue;
530                         }
531                         portals[numportals++] = p2;
532                 }
533                 for ( i = 0; i < numportals; i++ )
534                 {
535                         l2->portals[i] = portals[i];
536                 }
537                 l2->numportals = numportals;
538                 l1->merged = l2num;
539         }
540         return qtrue;
541 }
542
543 /*
544    ============
545    UpdatePortals
546    ============
547  */
548 void UpdatePortals( void ){
549         int i;
550         vportal_t *p;
551
552         for ( i = 0; i < numportals * 2; i++ )
553         {
554                 p = &portals[i];
555                 if ( p->removed ) {
556                         continue;
557                 }
558                 while ( leafs[p->leaf].merged >= 0 )
559                         p->leaf = leafs[p->leaf].merged;
560         }
561 }
562
563 /*
564    ============
565    MergeLeaves
566
567    try to merge leaves but don't merge through hint splitters
568    ============
569  */
570 void MergeLeaves( void ){
571         int i, j, nummerges, totalnummerges;
572         leaf_t *leaf;
573         vportal_t *p;
574
575         totalnummerges = 0;
576         do
577         {
578                 nummerges = 0;
579                 for ( i = 0; i < portalclusters; i++ )
580                 {
581                         leaf = &leafs[i];
582                         //if this leaf is merged already
583
584                         /* ydnar: vmods: merge all non-hint portals */
585                         if ( leaf->merged >= 0 && hint == qfalse ) {
586                                 continue;
587                         }
588
589
590                         for ( j = 0; j < leaf->numportals; j++ )
591                         {
592                                 p = leaf->portals[j];
593                                 //
594                                 if ( p->removed ) {
595                                         continue;
596                                 }
597                                 //never merge through hint portals
598                                 if ( p->hint ) {
599                                         continue;
600                                 }
601                                 if ( TryMergeLeaves( i, p->leaf ) ) {
602                                         UpdatePortals();
603                                         nummerges++;
604                                         break;
605                                 }
606                         }
607                 }
608                 totalnummerges += nummerges;
609         } while ( nummerges );
610         Sys_Printf( "%6d leaves merged\n", totalnummerges );
611 }
612
613 /*
614    ============
615    TryMergeWinding
616    ============
617  */
618 #define CONTINUOUS_EPSILON  0.005
619
620 fixedWinding_t *TryMergeWinding( fixedWinding_t *f1, fixedWinding_t *f2, vec3_t planenormal ){
621         vec_t       *p1, *p2, *p3, *p4, *back;
622         fixedWinding_t  *newf;
623         int i, j, k, l;
624         vec3_t normal, delta;
625         vec_t dot;
626         qboolean keep1, keep2;
627
628
629         //
630         // find a common edge
631         //
632         p1 = p2 = NULL; // stop compiler warning
633         j = 0;          //
634
635         for ( i = 0; i < f1->numpoints; i++ )
636         {
637                 p1 = f1->points[i];
638                 p2 = f1->points[( i + 1 ) % f1->numpoints];
639                 for ( j = 0; j < f2->numpoints; j++ )
640                 {
641                         p3 = f2->points[j];
642                         p4 = f2->points[( j + 1 ) % f2->numpoints];
643                         for ( k = 0; k < 3; k++ )
644                         {
645                                 if ( fabs( p1[k] - p4[k] ) > 0.1 ) { //EQUAL_EPSILON) //ME
646                                         break;
647                                 }
648                                 if ( fabs( p2[k] - p3[k] ) > 0.1 ) { //EQUAL_EPSILON) //ME
649                                         break;
650                                 }
651                         } //end for
652                         if ( k == 3 ) {
653                                 break;
654                         }
655                 } //end for
656                 if ( j < f2->numpoints ) {
657                         break;
658                 }
659         } //end for
660
661         if ( i == f1->numpoints ) {
662                 return NULL;            // no matching edges
663
664         }
665         //
666         // check slope of connected lines
667         // if the slopes are colinear, the point can be removed
668         //
669         back = f1->points[( i + f1->numpoints - 1 ) % f1->numpoints];
670         VectorSubtract( p1, back, delta );
671         CrossProduct( planenormal, delta, normal );
672         VectorNormalize( normal, normal );
673
674         back = f2->points[( j + 2 ) % f2->numpoints];
675         VectorSubtract( back, p1, delta );
676         dot = DotProduct( delta, normal );
677         if ( dot > CONTINUOUS_EPSILON ) {
678                 return NULL;            // not a convex polygon
679         }
680         keep1 = (qboolean)( dot < -CONTINUOUS_EPSILON );
681
682         back = f1->points[( i + 2 ) % f1->numpoints];
683         VectorSubtract( back, p2, delta );
684         CrossProduct( planenormal, delta, normal );
685         VectorNormalize( normal, normal );
686
687         back = f2->points[( j + f2->numpoints - 1 ) % f2->numpoints];
688         VectorSubtract( back, p2, delta );
689         dot = DotProduct( delta, normal );
690         if ( dot > CONTINUOUS_EPSILON ) {
691                 return NULL;            // not a convex polygon
692         }
693         keep2 = (qboolean)( dot < -CONTINUOUS_EPSILON );
694
695         //
696         // build the new polygon
697         //
698         newf = NewFixedWinding( f1->numpoints + f2->numpoints );
699
700         // copy first polygon
701         for ( k = ( i + 1 ) % f1->numpoints ; k != i ; k = ( k + 1 ) % f1->numpoints )
702         {
703                 if ( k == ( i + 1 ) % f1->numpoints && !keep2 ) {
704                         continue;
705                 }
706
707                 VectorCopy( f1->points[k], newf->points[newf->numpoints] );
708                 newf->numpoints++;
709         }
710
711         // copy second polygon
712         for ( l = ( j + 1 ) % f2->numpoints ; l != j ; l = ( l + 1 ) % f2->numpoints )
713         {
714                 if ( l == ( j + 1 ) % f2->numpoints && !keep1 ) {
715                         continue;
716                 }
717                 VectorCopy( f2->points[l], newf->points[newf->numpoints] );
718                 newf->numpoints++;
719         }
720
721         return newf;
722 }
723
724 /*
725    ============
726    MergeLeafPortals
727    ============
728  */
729 void MergeLeafPortals( void ){
730         int i, j, k, nummerges, hintsmerged;
731         leaf_t *leaf;
732         vportal_t *p1, *p2;
733         fixedWinding_t *w;
734
735         nummerges = 0;
736         hintsmerged = 0;
737         for ( i = 0; i < portalclusters; i++ )
738         {
739                 leaf = &leafs[i];
740                 if ( leaf->merged >= 0 ) {
741                         continue;
742                 }
743                 for ( j = 0; j < leaf->numportals; j++ )
744                 {
745                         p1 = leaf->portals[j];
746                         if ( p1->removed ) {
747                                 continue;
748                         }
749                         for ( k = j + 1; k < leaf->numportals; k++ )
750                         {
751                                 p2 = leaf->portals[k];
752                                 if ( p2->removed ) {
753                                         continue;
754                                 }
755                                 if ( p1->leaf == p2->leaf ) {
756                                         w = TryMergeWinding( p1->winding, p2->winding, p1->plane.normal );
757                                         if ( w ) {
758                                                 free( p1->winding );    //% FreeWinding(p1->winding);
759                                                 p1->winding = w;
760                                                 if ( p1->hint && p2->hint ) {
761                                                         hintsmerged++;
762                                                 }
763                                                 p1->hint |= p2->hint;
764                                                 SetPortalSphere( p1 );
765                                                 p2->removed = qtrue;
766                                                 nummerges++;
767                                                 i--;
768                                                 break;
769                                         }
770                                 }
771                         }
772                         if ( k < leaf->numportals ) {
773                                 break;
774                         }
775                 }
776         }
777         Sys_Printf( "%6d portals merged\n", nummerges );
778         Sys_Printf( "%6d hint portals merged\n", hintsmerged );
779 }
780
781
782 /*
783    ============
784    WritePortals
785    ============
786  */
787 int CountActivePortals( void ){
788         int num, hints, j;
789         vportal_t *p;
790
791         num = 0;
792         hints = 0;
793         for ( j = 0; j < numportals * 2; j++ )
794         {
795                 p = portals + j;
796                 if ( p->removed ) {
797                         continue;
798                 }
799                 if ( p->hint ) {
800                         hints++;
801                 }
802                 num++;
803         }
804         Sys_Printf( "%6d active portals\n", num );
805         Sys_Printf( "%6d hint portals\n", hints );
806         return num;
807 }
808
809 /*
810    ============
811    WritePortals
812    ============
813  */
814 void WriteFloat( FILE *f, vec_t v );
815
816 void WritePortals( char *portalpathfile ){
817         int i, j, num;
818         FILE *pf;
819         vportal_t *p;
820         fixedWinding_t *w;
821
822         // write the file
823         pf = fopen( portalpathfile, "w" );
824         if ( !pf ) {
825                 Error( "Error opening %s", portalpathfile );
826         }
827
828         num = 0;
829         for ( j = 0; j < numportals * 2; j++ )
830         {
831                 p = portals + j;
832                 if ( p->removed ) {
833                         continue;
834                 }
835 //              if (!p->hint)
836 //                      continue;
837                 num++;
838         }
839
840         fprintf( pf, "%s\n", PORTALFILE );
841         fprintf( pf, "%i\n", 0 );
842         fprintf( pf, "%i\n", num ); // + numfaces);
843         fprintf( pf, "%i\n", 0 );
844
845         for ( j = 0; j < numportals * 2; j++ )
846         {
847                 p = portals + j;
848                 if ( p->removed ) {
849                         continue;
850                 }
851 //              if (!p->hint)
852 //                      continue;
853                 w = p->winding;
854                 fprintf( pf,"%i %i %i ",w->numpoints, 0, 0 );
855                 fprintf( pf, "%d ", p->hint );
856                 for ( i = 0 ; i < w->numpoints ; i++ )
857                 {
858                         fprintf( pf,"(" );
859                         WriteFloat( pf, w->points[i][0] );
860                         WriteFloat( pf, w->points[i][1] );
861                         WriteFloat( pf, w->points[i][2] );
862                         fprintf( pf,") " );
863                 }
864                 fprintf( pf,"\n" );
865         }
866
867         /*
868            for (j = 0; j < numfaces; j++)
869            {
870             p = faces + j;
871             w = p->winding;
872             fprintf (pf,"%i %i %i ",w->numpoints, 0, 0);
873             fprintf (pf, "0 ");
874             for (i=0 ; i<w->numpoints ; i++)
875             {
876                 fprintf (pf,"(");
877                 WriteFloat (pf, w->points[i][0]);
878                 WriteFloat (pf, w->points[i][1]);
879                 WriteFloat (pf, w->points[i][2]);
880                 fprintf (pf,") ");
881             }
882             fprintf (pf,"\n");
883            }*/
884
885         fclose( pf );
886 }
887
888 /*
889    ============
890    LoadPortals
891    ============
892  */
893 void LoadPortals( char *name ){
894         int i, j, flags;
895         vportal_t   *p;
896         leaf_t      *l;
897         char magic[80];
898         FILE        *f;
899         int numpoints;
900         fixedWinding_t  *w;
901         int leafnums[2];
902         visPlane_t plane;
903
904         if ( !strcmp( name,"-" ) ) {
905                 f = stdin;
906         }
907         else
908         {
909                 f = fopen( name, "r" );
910                 if ( !f ) {
911                         Error( "LoadPortals: couldn't read %s\n",name );
912                 }
913         }
914
915         if ( fscanf( f,"%79s\n%i\n%i\n%i\n",magic, &portalclusters, &numportals, &numfaces ) != 4 ) {
916                 Error( "LoadPortals: failed to read header" );
917         }
918         if ( strcmp( magic,PORTALFILE ) ) {
919                 Error( "LoadPortals: not a portal file" );
920         }
921
922         Sys_Printf( "%6i portalclusters\n", portalclusters );
923         Sys_Printf( "%6i numportals\n", numportals );
924         Sys_Printf( "%6i numfaces\n", numfaces );
925
926         if ( numportals > MAX_PORTALS ) {
927                 Error( "MAX_PORTALS" );
928         }
929
930         // these counts should take advantage of 64 bit systems automatically
931         leafbytes = ( ( portalclusters + 63 ) & ~63 ) >> 3;
932         leaflongs = leafbytes / sizeof( long );
933
934         portalbytes = ( ( numportals * 2 + 63 ) & ~63 ) >> 3;
935         portallongs = portalbytes / sizeof( long );
936
937         // each file portal is split into two memory portals
938         portals = safe_malloc0( 2 * numportals * sizeof( vportal_t ) );
939
940         leafs = safe_malloc0( portalclusters * sizeof( leaf_t ) );
941
942         for ( i = 0; i < portalclusters; i++ )
943                 leafs[i].merged = -1;
944
945         numBSPVisBytes = VIS_HEADER_SIZE + portalclusters * leafbytes;
946
947         if ( numBSPVisBytes > MAX_MAP_VISIBILITY ) {
948                 Error( "MAX_MAP_VISIBILITY exceeded" );
949         }
950
951         ( (int *)bspVisBytes )[0] = portalclusters;
952         ( (int *)bspVisBytes )[1] = leafbytes;
953
954         for ( i = 0, p = portals ; i < numportals ; i++ )
955         {
956                 if ( fscanf( f, "%i %i %i ", &numpoints, &leafnums[0], &leafnums[1] ) != 3 ) {
957                         Error( "LoadPortals: reading portal %i", i );
958                 }
959                 if ( numpoints > MAX_POINTS_ON_WINDING ) {
960                         Error( "LoadPortals: portal %i has too many points", i );
961                 }
962                 if ( leafnums[0] > portalclusters
963                          || leafnums[1] > portalclusters ) {
964                         Error( "LoadPortals: reading portal %i", i );
965                 }
966                 if ( fscanf( f, "%i ", &flags ) != 1 ) {
967                         Error( "LoadPortals: reading flags" );
968                 }
969
970                 w = p->winding = NewFixedWinding( numpoints );
971                 w->numpoints = numpoints;
972
973                 for ( j = 0 ; j < numpoints ; j++ )
974                 {
975                         double v[3];
976                         int k;
977
978                         // scanf into double, then assign to vec_t
979                         // so we don't care what size vec_t is
980                         if ( fscanf( f, "(%lf %lf %lf ) "
981                                                  , &v[0], &v[1], &v[2] ) != 3 ) {
982                                 Error( "LoadPortals: reading portal %i", i );
983                         }
984                         for ( k = 0 ; k < 3 ; k++ )
985                                 w->points[j][k] = v[k];
986                 }
987                 if ( fscanf( f, "\n" ) != 0 ) {
988                         // silence gcc warning
989                 }
990
991                 // calc plane
992                 PlaneFromWinding( w, &plane );
993
994                 // create forward portal
995                 l = &leafs[leafnums[0]];
996                 if ( l->numportals == MAX_PORTALS_ON_LEAF ) {
997                         Error( "Leaf with too many portals" );
998                 }
999                 l->portals[l->numportals] = p;
1000                 l->numportals++;
1001
1002                 p->num = i + 1;
1003                 p->hint = ((flags & 1) != 0);
1004                 p->sky = ((flags & 2) != 0);
1005                 p->winding = w;
1006                 VectorSubtract( vec3_origin, plane.normal, p->plane.normal );
1007                 p->plane.dist = -plane.dist;
1008                 p->leaf = leafnums[1];
1009                 SetPortalSphere( p );
1010                 p++;
1011
1012                 // create backwards portal
1013                 l = &leafs[leafnums[1]];
1014                 if ( l->numportals == MAX_PORTALS_ON_LEAF ) {
1015                         Error( "Leaf with too many portals" );
1016                 }
1017                 l->portals[l->numportals] = p;
1018                 l->numportals++;
1019
1020                 p->num = i + 1;
1021                 p->hint = hint;
1022                 p->winding = NewFixedWinding( w->numpoints );
1023                 p->winding->numpoints = w->numpoints;
1024                 for ( j = 0 ; j < w->numpoints ; j++ )
1025                 {
1026                         VectorCopy( w->points[w->numpoints - 1 - j], p->winding->points[j] );
1027                 }
1028
1029                 p->plane = plane;
1030                 p->leaf = leafnums[0];
1031                 SetPortalSphere( p );
1032                 p++;
1033
1034         }
1035
1036         faces = safe_malloc0( 2 * numfaces * sizeof( vportal_t ) );
1037
1038         faceleafs = safe_malloc0( portalclusters * sizeof( leaf_t ) );
1039
1040         for ( i = 0, p = faces; i < numfaces; i++ )
1041         {
1042                 if ( fscanf( f, "%i %i ", &numpoints, &leafnums[0] ) != 2 ) {
1043                         Error( "LoadPortals: reading portal %i", i );
1044                 }
1045
1046                 w = p->winding = NewFixedWinding( numpoints );
1047                 w->numpoints = numpoints;
1048
1049                 for ( j = 0 ; j < numpoints ; j++ )
1050                 {
1051                         double v[3];
1052                         int k;
1053
1054                         // scanf into double, then assign to vec_t
1055                         // so we don't care what size vec_t is
1056                         if ( fscanf( f, "(%lf %lf %lf ) "
1057                                                  , &v[0], &v[1], &v[2] ) != 3 ) {
1058                                 Error( "LoadPortals: reading portal %i", i );
1059                         }
1060                         for ( k = 0 ; k < 3 ; k++ )
1061                                 w->points[j][k] = v[k];
1062                 }
1063                 if ( fscanf( f, "\n" ) != 0 ) {
1064                         // silence gcc warning
1065                 }
1066
1067                 // calc plane
1068                 PlaneFromWinding( w, &plane );
1069
1070                 l = &faceleafs[leafnums[0]];
1071                 l->merged = -1;
1072                 if ( l->numportals == MAX_PORTALS_ON_LEAF ) {
1073                         Error( "Leaf with too many faces" );
1074                 }
1075                 l->portals[l->numportals] = p;
1076                 l->numportals++;
1077
1078                 p->num = i + 1;
1079                 p->winding = w;
1080                 // normal pointing out of the leaf
1081                 VectorSubtract( vec3_origin, plane.normal, p->plane.normal );
1082                 p->plane.dist = -plane.dist;
1083                 p->leaf = -1;
1084                 SetPortalSphere( p );
1085                 p++;
1086         }
1087
1088         fclose( f );
1089 }
1090
1091
1092
1093 /*
1094    ===========
1095    VisMain
1096    ===========
1097  */
1098 int VisMain( int argc, char **argv ){
1099         int i;
1100         char portalFilePath[ 1024 ];
1101         portalFilePath[0] = 0;
1102
1103
1104         /* note it */
1105         Sys_Printf( "--- Vis ---\n" );
1106
1107         /* process arguments */
1108         for ( i = 1 ; i < ( argc - 1 ) ; i++ )
1109         {
1110                 if ( !strcmp( argv[i], "-fast" ) ) {
1111                         Sys_Printf( "fastvis = true\n" );
1112                         fastvis = qtrue;
1113                 }
1114                 else if ( !strcmp( argv[i], "-merge" ) ) {
1115                         Sys_Printf( "merge = true\n" );
1116                         mergevis = qtrue;
1117                 }
1118                 else if ( !strcmp( argv[i], "-mergeportals" ) ) {
1119                         Sys_Printf( "mergeportals = true\n" );
1120                         mergevisportals = qtrue;
1121                 }
1122                 else if ( !strcmp( argv[i], "-nopassage" ) ) {
1123                         Sys_Printf( "nopassage = true\n" );
1124                         noPassageVis = qtrue;
1125                 }
1126                 else if ( !strcmp( argv[i], "-passageOnly" ) ) {
1127                         Sys_Printf( "passageOnly = true\n" );
1128                         passageVisOnly = qtrue;
1129                 }
1130                 else if ( !strcmp( argv[i],"-nosort" ) ) {
1131                         Sys_Printf( "nosort = true\n" );
1132                         nosort = qtrue;
1133                 }
1134                 else if ( !strcmp( argv[i],"-saveprt" ) ) {
1135                         Sys_Printf( "saveprt = true\n" );
1136                         saveprt = qtrue;
1137                 }
1138                 else if ( !strcmp( argv[ i ], "-v" ) ) {
1139                         debugCluster = qtrue;
1140                         Sys_Printf( "Extra verbose mode enabled\n" );
1141                 }
1142                 else if ( !strcmp( argv[i],"-tmpin" ) ) {
1143                         strcpy( inbase, "/tmp" );
1144                 }
1145                 else if ( !strcmp( argv[i],"-tmpout" ) ) {
1146                         strcpy( outbase, "/tmp" );
1147                 }
1148
1149                 /* ydnar: -hint to merge all but hint portals */
1150                 else if ( !strcmp( argv[ i ], "-hint" ) ) {
1151                         Sys_Printf( "hint = true\n" );
1152                         hint = qtrue;
1153                         mergevis = qtrue;
1154                 }
1155                 else if ( !strcmp( argv[ i ], "-prtfile" ) )
1156                 {
1157                         strcpy( portalFilePath, argv[i + 1] );
1158                         argv[ i ] = NULL;
1159                         i++;
1160                         argv[ i ] = NULL;
1161                         Sys_Printf( "Use %s as portal file\n", portalFilePath );
1162                 }
1163
1164                 else{
1165                         Sys_FPrintf( SYS_WRN, "WARNING: Unknown option \"%s\"\n", argv[ i ] );
1166                 }
1167         }
1168
1169         if ( i != argc - 1 ) {
1170                 Error( "usage: vis [-threads #] [-fast] [-v] BSPFilePath" );
1171         }
1172
1173
1174         /* load the bsp */
1175         sprintf( source, "%s%s", inbase, ExpandArg( argv[ i ] ) );
1176         StripExtension( source );
1177         strcat( source, ".bsp" );
1178         Sys_Printf( "Loading %s\n", source );
1179         LoadBSPFile( source );
1180
1181         if ( game->texFile )
1182         {
1183                 // smokinguns-like tex file
1184                 StripExtension( source );
1185                 strcat( source, ".tex" );
1186                 LoadSurfaceFlags( source );
1187                 StripExtension( source );
1188                 strcat( source, ".bsp" );
1189         }
1190
1191         /* load the portal file */
1192         if (!portalFilePath[0]) {
1193                 sprintf( portalFilePath, "%s%s", inbase, ExpandArg( argv[ i ] ) );
1194                 StripExtension( portalFilePath );
1195                 strcat( portalFilePath, ".prt" );
1196         }
1197         Sys_Printf( "Loading %s\n", portalFilePath );
1198         LoadPortals( portalFilePath );
1199
1200         /* ydnar: exit if no portals, hence no vis */
1201         if ( numportals == 0 ) {
1202                 Sys_Printf( "No portals means no vis, exiting.\n" );
1203                 return 0;
1204         }
1205
1206         /* ydnar: for getting far plane */
1207         ParseEntities();
1208
1209         /* inject command line parameters */
1210         InjectCommandLine( argv, 0, argc - 1 );
1211         UnparseEntities();
1212
1213         if ( mergevis ) {
1214                 MergeLeaves();
1215         }
1216
1217         if ( mergevis || mergevisportals ) {
1218                 MergeLeafPortals();
1219         }
1220
1221         CountActivePortals();
1222         /* WritePortals( "maps/hints.prs" );*/
1223
1224         Sys_Printf( "visdatasize:%i\n", numBSPVisBytes );
1225
1226         CalcVis();
1227
1228         /* delete the prt file */
1229         if ( !saveprt ) {
1230                 remove( portalFilePath );
1231         }
1232
1233         if ( game->texFile )
1234         {
1235                 // smokinguns-like tex file
1236                 StripExtension( source );
1237                 WriteTexFile( source );
1238                 DefaultExtension( source, ".bsp" );
1239         }
1240
1241         /* write the bsp file */
1242         Sys_Printf( "Writing %s\n", source );
1243         WriteBSPFile( source );
1244
1245         return 0;
1246 }