1 /* -------------------------------------------------------------------------------
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
6 This file is part of GtkRadiant.
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.
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.
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
22 ----------------------------------------------------------------------------------
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."
27 ------------------------------------------------------------------------------- */
41 /* -------------------------------------------------------------------------------
45 ------------------------------------------------------------------------------- */
48 AllocSideRef() - ydnar
49 allocates and assigns a brush side reference
52 sideRef_t *AllocSideRef( side_t *side, sideRef_t *next )
61 /* allocate and return */
62 sideRef = safe_malloc( sizeof( *sideRef ) );
72 counts the number of brushes in a brush linked list
75 int CountBrushList( brush_t *brushes )
81 for( ; brushes != NULL; brushes = brushes->next )
93 brush_t *AllocBrush( int numSides )
99 /* allocate and clear */
101 Error( "AllocBrush called with numsides = %d", numSides );
102 c = (size_t)&(((brush_t*) 0)->sides[ numSides ]);
103 bb = safe_malloc( c );
105 if( numthreads == 1 )
116 frees a single brush and all sides/windings
119 void FreeBrush( brush_t *b )
125 if( *((unsigned int*) b) == 0xFEFEFEFE )
127 Sys_FPrintf( SYS_VRB, "WARNING: Attempt to free an already freed brush!\n" );
131 /* free brush sides */
132 for( i = 0; i < b->numsides; i++ )
133 if( b->sides[i].winding != NULL )
134 FreeWinding( b->sides[ i ].winding );
136 /* ydnar: overwrite it */
137 memset( b, 0xFE, (size_t)&(((brush_t*) 0)->sides[ b->numsides ]) );
138 *((unsigned int*) b) = 0xFEFEFEFE;
142 if( numthreads == 1 )
150 frees a linked list of brushes
153 void FreeBrushList( brush_t *brushes )
158 /* walk brush list */
159 for( ; brushes != NULL; brushes = next )
161 next = brushes->next;
162 FreeBrush( brushes );
170 duplicates the brush, sides, and windings
173 brush_t *CopyBrush( brush_t *brush )
181 size = (size_t)&(((brush_t*) 0)->sides[ brush->numsides ]);
182 newBrush = AllocBrush( brush->numsides );
183 memcpy( newBrush, brush, size );
185 /* ydnar: nuke linked list */
186 newBrush->next = NULL;
189 for( i = 0; i < brush->numsides; i++ )
191 if( brush->sides[ i ].winding != NULL )
192 newBrush->sides[ i ].winding = CopyWinding( brush->sides[ i ].winding );
204 sets the mins/maxs based on the windings
205 returns false if the brush doesn't enclose a valid volume
208 qboolean BoundBrush( brush_t *brush )
214 ClearBounds( brush->mins, brush->maxs );
215 for( i = 0; i < brush->numsides; i++ )
217 w = brush->sides[ i ].winding;
220 for( j = 0; j < w->numpoints; j++ )
221 AddPointToBounds( w->p[ j ], brush->mins, brush->maxs );
224 for( i = 0; i < 3; i++ )
226 if( brush->mins[ i ] < MIN_WORLD_COORD || brush->maxs[ i ] > MAX_WORLD_COORD || brush->mins[i] >= brush->maxs[ i ] )
237 SnapWeldVector() - ydnar
238 welds two vec3_t's into a third, taking into account nearest-to-integer
242 #define SNAP_EPSILON 0.01
244 void SnapWeldVector( vec3_t a, vec3_t b, vec3_t out )
251 if( a == NULL || b == NULL || out == NULL )
254 /* do each element */
255 for( i = 0; i < 3; i++ )
257 /* round to integer */
258 ai = Q_rint( a[ i ] );
259 bi = Q_rint( a[ i ] );
261 /* prefer exact integer */
264 else if( bi == b[ i ] )
268 else if( fabs( ai - a[ i ] ) < fabs( bi < b[ i ] ) )
274 outi = Q_rint( out[ i ] );
275 if( fabs( outi - out[ i ] ) <= SNAP_EPSILON )
284 Welds two vectors into a third, taking into account nearest-to-integer
285 instead of averaging.
288 void SnapWeldVectorAccu(vec3_accu_t a, vec3_accu_t b, vec3_accu_t out)
290 // I'm just preserving what I think was the intended logic of the original
291 // SnapWeldVector(). I'm not actually sure where this function should even
292 // be used. I'd like to know which kinds of problems this function addresses.
294 // TODO: I thought we're snapping all coordinates to nearest 1/8 unit?
295 // So what is natural about snapping to the nearest integer? Maybe we should
296 // be snapping to the nearest 1/8 unit instead?
299 vec_accu_t ai, bi, ad, bd;
301 if (a == NULL || b == NULL || out == NULL)
302 Error("SnapWeldVectorAccu: NULL argument");
304 for (i = 0; i < 3; i++)
306 ai = Q_rintAccu(a[i]);
307 bi = Q_rintAccu(b[i]);
308 ad = fabs(ai - a[i]);
309 bd = fabs(bi - b[i]);
313 if (ad < SNAP_EPSILON) out[i] = ai;
318 if (bd < SNAP_EPSILON) out[i] = bi;
328 removes degenerate edges from a winding
329 returns qtrue if the winding is valid
332 #define DEGENERATE_EPSILON 0.1
334 qboolean FixWinding( winding_t *w )
336 qboolean valid = qtrue;
346 /* check all verts */
347 for( i = 0; i < w->numpoints; i++ )
349 /* don't remove points if winding is a triangle */
350 if( w->numpoints == 3 )
353 /* get second point index */
354 j = (i + 1) % w->numpoints;
356 /* degenerate edge? */
357 VectorSubtract( w->p[ i ], w->p[ j ], vec );
358 dist = VectorLength( vec );
359 if( dist < DEGENERATE_EPSILON )
362 //Sys_FPrintf( SYS_VRB, "WARNING: Degenerate winding edge found, fixing...\n" );
364 /* create an average point (ydnar 2002-01-26: using nearest-integer weld preference) */
365 SnapWeldVector( w->p[ i ], w->p[ j ], vec );
366 VectorCopy( vec, w->p[ i ] );
367 //VectorAdd( w->p[ i ], w->p[ j ], vec );
368 //VectorScale( vec, 0.5, w->p[ i ] );
370 /* move the remaining verts */
371 for( k = i + 2; k < w->numpoints; k++ )
373 VectorCopy( w->p[ k ], w->p[ k - 1 ] );
379 /* one last check and return */
380 if( w->numpoints < 3 )
389 Removes degenerate edges (edges that are too short) from a winding.
390 Returns qtrue if the winding has been altered by this function.
391 Returns qfalse if the winding is untouched by this function.
393 It's advised that you check the winding after this function exits to make
394 sure it still has at least 3 points. If that is not the case, the winding
395 cannot be considered valid. The winding may degenerate to one or two points
396 if the some of the winding's points are close together.
399 qboolean FixWindingAccu(winding_accu_t *w)
404 qboolean done, altered;
406 if (w == NULL) Error("FixWindingAccu: NULL argument");
412 if (w->numpoints < 2) break; // Don't remove the only remaining point.
414 for (i = 0; i < w->numpoints; i++)
416 j = (((i + 1) == w->numpoints) ? 0 : (i + 1));
418 VectorSubtractAccu(w->p[i], w->p[j], vec);
419 dist = VectorLengthAccu(vec);
420 if (dist < DEGENERATE_EPSILON)
422 // TODO: I think the "snap weld vector" was written before
423 // some of the math precision fixes, and its purpose was
424 // probably to address math accuracy issues. We can think
425 // about changing the logic here. Maybe once plane distance
426 // gets 64 bits, we can look at it then.
427 SnapWeldVectorAccu(w->p[i], w->p[j], vec);
428 VectorCopyAccu(vec, w->p[i]);
429 for (k = j + 1; k < w->numpoints; k++)
431 VectorCopyAccu(w->p[k], w->p[k - 1]);
435 // The only way to finish off fixing the winding consistently and
436 // accurately is by fixing the winding all over again. For example,
437 // the point at index i and the point at index i-1 could now be
438 // less than the epsilon distance apart. There are too many special
439 // case problems we'd need to handle if we didn't start from the
442 break; // This will cause us to return to the "while" loop.
453 CreateBrushWindings()
454 makes basewindigs for sides and mins/maxs for the brush
455 returns false if the brush doesn't enclose a valid volume
458 qboolean CreateBrushWindings( brush_t *brush )
461 #if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES
470 /* walk the list of brush sides */
471 for( i = 0; i < brush->numsides; i++ )
473 /* get side and plane */
474 side = &brush->sides[ i ];
475 plane = &mapplanes[ side->planenum ];
477 /* make huge winding */
478 #if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES
479 w = BaseWindingForPlaneAccu(plane->normal, plane->dist);
481 w = BaseWindingForPlane( plane->normal, plane->dist );
484 /* walk the list of brush sides */
485 for( j = 0; j < brush->numsides && w != NULL; j++ )
489 if( brush->sides[ j ].planenum == (brush->sides[ i ].planenum ^ 1) )
490 continue; /* back side clipaway */
491 if( brush->sides[ j ].bevel )
493 plane = &mapplanes[ brush->sides[ j ].planenum ^ 1 ];
494 #if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES
495 ChopWindingInPlaceAccu(&w, plane->normal, plane->dist, 0);
497 ChopWindingInPlace( &w, plane->normal, plane->dist, 0 ); // CLIP_EPSILON );
500 /* ydnar: fix broken windings that would generate trifans */
501 #if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES
502 // I think it's better to FixWindingAccu() once after we chop with all planes
503 // so that error isn't multiplied. There is nothing natural about welding
504 // the points unless they are the final endpoints. ChopWindingInPlaceAccu()
505 // is able to handle all kinds of degenerate windings.
511 /* set side winding */
512 #if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES
516 if (w->numpoints < 3)
522 side->winding = (w ? CopyWindingAccuToRegular(w) : NULL);
523 if (w) FreeWindingAccu(w);
529 /* find brush bounds */
530 return BoundBrush( brush );
540 Creates a new axial brush
543 brush_t *BrushFromBounds (vec3_t mins, vec3_t maxs)
552 for (i=0 ; i<3 ; i++)
554 VectorClear (normal);
557 b->sides[i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &maxs );
561 b->sides[3+i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &mins );
564 CreateBrushWindings (b);
575 vec_t BrushVolume (brush_t *brush)
580 vec_t d, area, volume;
586 // grab the first valid point as the corner
589 for (i=0 ; i<brush->numsides ; i++)
591 w = brush->sides[i].winding;
597 VectorCopy (w->p[0], corner);
599 // make tetrahedrons to all other faces
602 for ( ; i<brush->numsides ; i++)
604 w = brush->sides[i].winding;
607 plane = &mapplanes[brush->sides[i].planenum];
608 d = -(DotProduct (corner, plane->normal) - plane->dist);
609 area = WindingArea (w);
621 writes a map with the split bsp brushes
624 void WriteBSPBrushMap( char *name, brush_t *list )
633 Sys_Printf( "Writing %s\n", name );
635 /* open the map file */
636 f = fopen( name, "wb" );
638 Error( "Can't write %s\b", name );
640 fprintf (f, "{\n\"classname\" \"worldspawn\"\n");
642 for ( ; list ; list=list->next )
645 for (i=0,s=list->sides ; i<list->numsides ; i++,s++)
647 // TODO: See if we can use a smaller winding to prevent resolution loss.
648 // Is WriteBSPBrushMap() used only to decompile maps?
649 w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist);
651 fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]);
652 fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]);
653 fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]);
655 fprintf (f, "notexture 0 0 0 1 1\n" );
669 FilterBrushIntoTree_r()
670 adds brush reference to any intersecting bsp leafnode
673 int FilterBrushIntoTree_r( brush_t *b, node_t *node )
675 brush_t *front, *back;
683 /* add it to the leaf list */
684 if( node->planenum == PLANENUM_LEAF )
686 /* something somewhere is hammering brushlist */
687 b->next = node->brushlist;
690 /* classify the leaf by the structural brush */
695 node->opaque = qtrue;
696 node->areaportal = qfalse;
698 else if( b->compileFlags & C_AREAPORTAL )
701 node->areaportal = qtrue;
708 /* split it by the node plane */
710 SplitBrush( b, node->planenum, &front, &back );
714 c += FilterBrushIntoTree_r( front, node->children[ 0 ] );
715 c += FilterBrushIntoTree_r( back, node->children[ 1 ] );
723 FilterDetailBrushesIntoTree
724 fragment all the detail brushes into the structural leafs
727 void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree )
731 int c_unique, c_clusters;
736 Sys_FPrintf( SYS_VRB, "--- FilterDetailBrushesIntoTree ---\n" );
738 /* walk the list of brushes */
741 for( b = e->brushes; b; b = b->next )
746 newb = CopyBrush( b );
747 r = FilterBrushIntoTree_r( newb, tree->headnode );
750 /* mark all sides as visible so drawsurfs are created */
753 for( i = 0; i < b->numsides; i++ )
755 if( b->sides[ i ].winding )
756 b->sides[ i ].visible = qtrue;
761 /* emit some statistics */
762 Sys_FPrintf( SYS_VRB, "%9d detail brushes\n", c_unique );
763 Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters );
767 =====================
768 FilterStructuralBrushesIntoTree
770 Mark the leafs as opaque and areaportals
771 =====================
773 void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ) {
776 int c_unique, c_clusters;
779 Sys_FPrintf (SYS_VRB, "--- FilterStructuralBrushesIntoTree ---\n");
783 for ( b = e->brushes ; b ; b = b->next ) {
788 newb = CopyBrush( b );
789 r = FilterBrushIntoTree_r( newb, tree->headnode );
792 // mark all sides as visible so drawsurfs are created
794 for ( i = 0 ; i < b->numsides ; i++ ) {
795 if ( b->sides[i].winding ) {
796 b->sides[i].visible = qtrue;
802 /* emit some statistics */
803 Sys_FPrintf( SYS_VRB, "%9d structural brushes\n", c_unique );
804 Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters );
814 tree_t *AllocTree (void)
818 tree = safe_malloc(sizeof(*tree));
819 memset (tree, 0, sizeof(*tree));
820 ClearBounds (tree->mins, tree->maxs);
830 node_t *AllocNode (void)
834 node = safe_malloc(sizeof(*node));
835 memset (node, 0, sizeof(*node));
845 Returns true if the winding would be crunched out of
846 existance by the vertex snapping.
849 #define EDGE_LENGTH 0.2
850 qboolean WindingIsTiny (winding_t *w)
853 if (WindingArea (w) < 1)
863 for (i=0 ; i<w->numpoints ; i++)
865 j = i == w->numpoints - 1 ? 0 : i+1;
866 VectorSubtract (w->p[j], w->p[i], delta);
867 len = VectorLength (delta);
868 if (len > EDGE_LENGTH)
881 Returns true if the winding still has one of the points
882 from basewinding for plane
885 qboolean WindingIsHuge (winding_t *w)
889 for (i=0 ; i<w->numpoints ; i++)
891 for (j=0 ; j<3 ; j++)
892 if (w->p[i][j] <= MIN_WORLD_COORD || w->p[i][j] >= MAX_WORLD_COORD)
898 //============================================================
906 int BrushMostlyOnSide (brush_t *brush, plane_t *plane)
915 for (i=0 ; i<brush->numsides ; i++)
917 w = brush->sides[i].winding;
920 for (j=0 ; j<w->numpoints ; j++)
922 d = DotProduct (w->p[j], plane->normal) - plane->dist;
942 generates two new brushes, leaving the original unchanged
945 void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back )
949 winding_t *w, *cw[2], *midwinding;
950 plane_t *plane, *plane2;
952 float d, d_front, d_back;
957 plane = &mapplanes[planenum];
960 d_front = d_back = 0;
961 for (i=0 ; i<brush->numsides ; i++)
963 w = brush->sides[i].winding;
966 for (j=0 ; j<w->numpoints ; j++)
968 d = DotProduct (w->p[j], plane->normal) - plane->dist;
969 if (d > 0 && d > d_front)
971 if (d < 0 && d < d_back)
976 if (d_front < 0.1) // PLANESIDE_EPSILON)
978 *back = CopyBrush( brush );
982 if (d_back > -0.1) // PLANESIDE_EPSILON)
984 *front = CopyBrush( brush );
988 // create a new winding from the split plane
989 w = BaseWindingForPlane (plane->normal, plane->dist);
990 for (i=0 ; i<brush->numsides && w ; i++)
992 plane2 = &mapplanes[brush->sides[i].planenum ^ 1];
993 ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON);
996 if (!w || WindingIsTiny (w) )
997 { // the brush isn't really split
1000 side = BrushMostlyOnSide (brush, plane);
1001 if (side == PSIDE_FRONT)
1002 *front = CopyBrush (brush);
1003 if (side == PSIDE_BACK)
1004 *back = CopyBrush (brush);
1008 if( WindingIsHuge( w ) )
1009 Sys_FPrintf( SYS_VRB,"WARNING: huge winding\n" );
1013 // split it for real
1015 for (i=0 ; i<2 ; i++)
1017 b[i] = AllocBrush (brush->numsides+1);
1018 memcpy( b[i], brush, sizeof( brush_t ) - sizeof( brush->sides ) );
1021 b[i]->original = brush->original;
1024 // split all the current windings
1026 for (i=0 ; i<brush->numsides ; i++)
1028 s = &brush->sides[i];
1032 ClipWindingEpsilon (w, plane->normal, plane->dist,
1033 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]);
1034 for (j=0 ; j<2 ; j++)
1038 cs = &b[j]->sides[b[j]->numsides];
1041 cs->winding = cw[j];
1046 // see if we have valid polygons on both sides
1047 for (i=0 ; i<2 ; i++)
1049 if (b[i]->numsides < 3 || !BoundBrush (b[i]))
1051 if (b[i]->numsides >= 3)
1052 Sys_FPrintf (SYS_VRB,"bogus brush after clip\n");
1058 if ( !(b[0] && b[1]) )
1061 Sys_FPrintf (SYS_VRB,"split removed brush\n");
1063 Sys_FPrintf (SYS_VRB,"split not on both sides\n");
1067 *front = CopyBrush (brush);
1072 *back = CopyBrush (brush);
1077 // add the midwinding to both sides
1078 for (i=0 ; i<2 ; i++)
1080 cs = &b[i]->sides[b[i]->numsides];
1083 cs->planenum = planenum^i^1;
1084 cs->shaderInfo = NULL;
1086 cs->winding = CopyWinding (midwinding);
1088 cs->winding = midwinding;
1096 for (i=0 ; i<2 ; i++)
1098 v1 = BrushVolume (b[i]);
1103 // Sys_FPrintf (SYS_VRB,"tiny volume after clip\n");