]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/surface_meta.c
bsp: new option -maxarea, selects more GPU friendly face surface splitting algorithm
[divverent/netradiant.git] / tools / quake3 / q3map2 / surface_meta.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 SURFACE_META_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 #define LIGHTMAP_EXCEEDED       -1
42 #define S_EXCEEDED                      -2
43 #define T_EXCEEDED                      -3
44 #define ST_EXCEEDED                     -4
45 #define UNSUITABLE_TRIANGLE     -10
46 #define VERTS_EXCEEDED          -1000
47 #define INDEXES_EXCEEDED        -2000
48
49 #define GROW_META_VERTS         1024
50 #define GROW_META_TRIANGLES     1024
51
52 static int                                      numMetaSurfaces, numPatchMetaSurfaces;
53
54 static int                                      maxMetaVerts = 0;
55 static int                                      numMetaVerts = 0;
56 static int                                      firstSearchMetaVert = 0;
57 static bspDrawVert_t            *metaVerts = NULL;
58
59 static int                                      maxMetaTriangles = 0;
60 static int                                      numMetaTriangles = 0;
61 static metaTriangle_t           *metaTriangles = NULL;
62
63
64
65 /*
66 ClearMetaVertexes()
67 called before staring a new entity to clear out the triangle list
68 */
69
70 void ClearMetaTriangles( void )
71 {
72         numMetaVerts = 0;
73         numMetaTriangles = 0;
74 }
75
76
77
78 /*
79 FindMetaVertex()
80 finds a matching metavertex in the global list, returning its index
81 */
82
83 static int FindMetaVertex( bspDrawVert_t *src )
84 {
85         int                     i;
86         bspDrawVert_t   *v, *temp;
87
88         
89         /* try to find an existing drawvert */
90         for( i = firstSearchMetaVert, v = &metaVerts[ i ]; i < numMetaVerts; i++, v++ )
91         {
92                 if( memcmp( src, v, sizeof( bspDrawVert_t ) ) == 0 )
93                         return i;
94         }
95         
96         /* enough space? */
97         if( numMetaVerts >= maxMetaVerts )
98         {
99                 /* reallocate more room */
100                 maxMetaVerts += GROW_META_VERTS;
101                 temp = safe_malloc( maxMetaVerts * sizeof( bspDrawVert_t ) );
102                 if( metaVerts != NULL )
103                 {
104                         memcpy( temp, metaVerts, numMetaVerts * sizeof( bspDrawVert_t ) );
105                         free( metaVerts );
106                 }
107                 metaVerts = temp;
108         }
109         
110         /* add the triangle */
111         memcpy( &metaVerts[ numMetaVerts ], src, sizeof( bspDrawVert_t ) );
112         numMetaVerts++;
113         
114         /* return the count */
115         return (numMetaVerts - 1);
116 }
117
118
119
120 /*
121 AddMetaTriangle()
122 adds a new meta triangle, allocating more memory if necessary
123 */
124
125 static int AddMetaTriangle( void )
126 {
127         metaTriangle_t  *temp;
128         
129         
130         /* enough space? */
131         if( numMetaTriangles >= maxMetaTriangles )
132         {
133                 /* reallocate more room */
134                 maxMetaTriangles += GROW_META_TRIANGLES;
135                 temp = safe_malloc( maxMetaTriangles * sizeof( metaTriangle_t ) );
136                 if( metaTriangles != NULL )
137                 {
138                         memcpy( temp, metaTriangles, numMetaTriangles * sizeof( metaTriangle_t ) );
139                         free( metaTriangles );
140                 }
141                 metaTriangles = temp;
142         }
143         
144         /* increment and return */
145         numMetaTriangles++;
146         return numMetaTriangles - 1;
147 }
148
149
150
151 /*
152 FindMetaTriangle()
153 finds a matching metatriangle in the global list,
154 otherwise adds it and returns the index to the metatriangle
155 */
156
157 int FindMetaTriangle( metaTriangle_t *src, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c, int planeNum )
158 {
159         int                             triIndex;
160         vec3_t                  dir;
161
162         
163         
164         /* detect degenerate triangles fixme: do something proper here */
165         VectorSubtract( a->xyz, b->xyz, dir );
166         if( VectorLength( dir ) < 0.125f )
167                 return -1;
168         VectorSubtract( b->xyz, c->xyz, dir );
169         if( VectorLength( dir ) < 0.125f )
170                 return -1;
171         VectorSubtract( c->xyz, a->xyz, dir );
172         if( VectorLength( dir ) < 0.125f )
173                 return -1;
174         
175         /* find plane */
176         if( planeNum >= 0 )
177         {
178                 /* because of precision issues with small triangles, try to use the specified plane */
179                 src->planeNum = planeNum;
180                 VectorCopy( mapplanes[ planeNum ].normal, src->plane );
181                 src->plane[ 3 ] = mapplanes[ planeNum ].dist;
182         }
183         else
184         {
185                 /* calculate a plane from the triangle's points (and bail if a plane can't be constructed) */
186                 src->planeNum = -1;
187                 if( PlaneFromPoints( src->plane, a->xyz, b->xyz, c->xyz ) == qfalse )
188                         return -1;
189         }
190         
191         /* ydnar 2002-10-03: repair any bogus normals (busted ase import kludge) */
192         if( VectorLength( a->normal ) <= 0.0f )
193                 VectorCopy( src->plane, a->normal );
194         if( VectorLength( b->normal ) <= 0.0f )
195                 VectorCopy( src->plane, b->normal );
196         if( VectorLength( c->normal ) <= 0.0f )
197                 VectorCopy( src->plane, c->normal );
198         
199         /* ydnar 2002-10-04: set lightmap axis if not already set */
200         if( !(src->si->compileFlags & C_VERTEXLIT) &&
201                 src->lightmapAxis[ 0 ] == 0.0f && src->lightmapAxis[ 1 ] == 0.0f && src->lightmapAxis[ 2 ] == 0.0f )
202         {
203                 /* the shader can specify an explicit lightmap axis */
204                 if( src->si->lightmapAxis[ 0 ] || src->si->lightmapAxis[ 1 ] || src->si->lightmapAxis[ 2 ] )
205                         VectorCopy( src->si->lightmapAxis, src->lightmapAxis );
206                 
207                 /* new axis-finding code */
208                 else
209                         CalcLightmapAxis( src->plane, src->lightmapAxis );
210         }
211         
212         /* fill out the src triangle */
213         src->indexes[ 0 ] = FindMetaVertex( a );
214         src->indexes[ 1 ] = FindMetaVertex( b );
215         src->indexes[ 2 ] = FindMetaVertex( c );
216         
217         /* try to find an existing triangle */
218         #ifdef USE_EXHAUSTIVE_SEARCH
219         {
220                 int                             i;
221                 metaTriangle_t  *tri;
222                 
223                 
224                 for( i = 0, tri = metaTriangles; i < numMetaTriangles; i++, tri++ )
225                 {
226                         if( memcmp( src, tri, sizeof( metaTriangle_t ) ) == 0 )
227                                 return i;
228                 }
229         }
230         #endif
231         
232         /* get a new triangle */
233         triIndex = AddMetaTriangle();
234         
235         /* add the triangle */
236         memcpy( &metaTriangles[ triIndex ], src, sizeof( metaTriangle_t ) );
237         
238         /* return the triangle index */
239         return triIndex;
240 }
241
242
243
244 /*
245 SurfaceToMetaTriangles()
246 converts a classified surface to metatriangles
247 */
248
249 static void SurfaceToMetaTriangles( mapDrawSurface_t *ds )
250 {
251         int                             i;
252         metaTriangle_t  src;
253         bspDrawVert_t   a, b, c;
254         
255         
256         /* only handle certain types of surfaces */
257         if( ds->type != SURFACE_FACE &&
258                 ds->type != SURFACE_META &&
259                 ds->type != SURFACE_FORCED_META &&
260                 ds->type != SURFACE_DECAL )
261                 return;
262         
263         /* speed at the expense of memory */
264         firstSearchMetaVert = numMetaVerts;
265         
266         /* only handle valid surfaces */
267         if( ds->type != SURFACE_BAD && ds->numVerts >= 3 && ds->numIndexes >= 3 )
268         {
269                 /* walk the indexes and create triangles */
270                 for( i = 0; i < ds->numIndexes; i += 3 )
271                 {
272                         /* sanity check the indexes */
273                         if( ds->indexes[ i ] == ds->indexes[ i + 1 ] ||
274                                 ds->indexes[ i ] == ds->indexes[ i + 2 ] ||
275                                 ds->indexes[ i + 1 ] == ds->indexes[ i + 2 ] )
276                         {
277                                 //%     Sys_Printf( "%d! ", ds->numVerts );
278                                 continue;
279                         }
280                         
281                         /* build a metatriangle */
282                         src.si = ds->shaderInfo;
283                         src.side = (ds->sideRef != NULL ? ds->sideRef->side : NULL);
284                         src.entityNum = ds->entityNum;
285                         src.surfaceNum = ds->surfaceNum;
286                         src.planeNum = ds->planeNum;
287                         src.castShadows = ds->castShadows;
288                         src.recvShadows = ds->recvShadows;
289                         src.fogNum = ds->fogNum;
290                         src.sampleSize = ds->sampleSize;
291                         src.shadeAngleDegrees = ds->shadeAngleDegrees;
292                         VectorCopy( ds->lightmapAxis, src.lightmapAxis );
293                         
294                         /* copy drawverts */
295                         memcpy( &a, &ds->verts[ ds->indexes[ i ] ], sizeof( a ) );
296                         memcpy( &b, &ds->verts[ ds->indexes[ i + 1 ] ], sizeof( b ) );
297                         memcpy( &c, &ds->verts[ ds->indexes[ i + 2 ] ], sizeof( c ) );
298                         FindMetaTriangle( &src, &a, &b, &c, ds->planeNum );
299                 }
300                 
301                 /* add to count */
302                 numMetaSurfaces++;
303         }
304         
305         /* clear the surface (free verts and indexes, sets it to SURFACE_BAD) */
306         ClearSurface( ds );
307 }
308
309
310
311 /*
312 TriangulatePatchSurface()
313 creates triangles from a patch
314 */
315
316 void TriangulatePatchSurface( entity_t *e , mapDrawSurface_t *ds )
317 {
318         int                                     iterations, x, y, pw[ 5 ], r;
319         mapDrawSurface_t        *dsNew;
320         mesh_t                          src, *subdivided, *mesh;
321         int                                     forcePatchMeta;
322         int                                     patchQuality;
323         int                                     patchSubdivision;
324
325         /* vortex: _patchMeta, _patchQuality, _patchSubdivide support */
326         forcePatchMeta = IntForKey(e, "_patchMeta" );
327         if (!forcePatchMeta)
328                 forcePatchMeta = IntForKey(e, "patchMeta" );
329         patchQuality = IntForKey(e, "_patchQuality" );
330         if (!patchQuality)
331                 patchQuality = IntForKey(e, "patchQuality" );
332         if (!patchQuality)
333                 patchQuality = 1.0;
334         patchSubdivision = IntForKey(e, "_patchSubdivide" );
335         if (!patchSubdivision)
336                 patchSubdivision = IntForKey(e, "patchSubdivide" );
337
338         /* try to early out */
339         if(ds->numVerts == 0 || ds->type != SURFACE_PATCH || ( patchMeta == qfalse && !forcePatchMeta) )
340                 return;
341         /* make a mesh from the drawsurf */ 
342         src.width = ds->patchWidth;
343         src.height = ds->patchHeight;
344         src.verts = ds->verts;
345         //%     subdivided = SubdivideMesh( src, 8, 999 );
346         if (patchSubdivision)
347                 iterations = IterationsForCurve( ds->longestCurve, patchSubdivision );
348         else
349                 iterations = IterationsForCurve( ds->longestCurve, patchSubdivisions / patchQuality );
350
351         subdivided = SubdivideMesh2( src, iterations ); //%     ds->maxIterations
352         
353         /* fit it to the curve and remove colinear verts on rows/columns */
354         PutMeshOnCurve( *subdivided );
355         mesh = RemoveLinearMeshColumnsRows( subdivided );
356         FreeMesh( subdivided );
357         //% MakeMeshNormals( mesh );
358         
359         /* make a copy of the drawsurface */
360         dsNew = AllocDrawSurface( SURFACE_META );
361         memcpy( dsNew, ds, sizeof( *ds ) );
362         
363         /* if the patch is nonsolid, then discard it */
364         if( !(ds->shaderInfo->compileFlags & C_SOLID) )
365                 ClearSurface( ds );
366         
367         /* set new pointer */
368         ds = dsNew;
369         
370         /* basic transmogrification */
371         ds->type = SURFACE_META;
372         ds->numIndexes = 0;
373         ds->indexes = safe_malloc( mesh->width * mesh->height * 6 * sizeof( int ) );
374         
375         /* copy the verts in */
376         ds->numVerts = (mesh->width * mesh->height);
377         ds->verts = mesh->verts;
378         
379         /* iterate through the mesh quads */
380         for( y = 0; y < (mesh->height - 1); y++ )
381         {
382                 for( x = 0; x < (mesh->width - 1); x++ )
383                 {
384                         /* set indexes */
385                         pw[ 0 ] = x + (y * mesh->width);
386                         pw[ 1 ] = x + ((y + 1) * mesh->width);
387                         pw[ 2 ] = x + 1 + ((y + 1) * mesh->width);
388                         pw[ 3 ] = x + 1 + (y * mesh->width);
389                         pw[ 4 ] = x + (y * mesh->width);        /* same as pw[ 0 ] */
390                         
391                         /* set radix */
392                         r = (x + y) & 1;
393                         
394                         /* make first triangle */
395                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
396                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 1 ];
397                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
398                         
399                         /* make second triangle */
400                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
401                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
402                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 3 ];
403                 }
404         }
405         
406         /* free the mesh, but not the verts */
407         free( mesh );
408         
409         /* add to count */
410         numPatchMetaSurfaces++;
411         
412         /* classify it */
413         ClassifySurfaces( 1, ds );
414 }
415
416 #define TINY_AREA 1.0f
417 int MaxAreaIndexes(bspDrawVert_t *vert, int cnt, int *indexes)
418 {
419         int r, s, t, bestR = 0, bestS = 1, bestT = 2;
420         int i, j, k;
421         double A, bestA = -1;
422         vec3_t ab, ac, cross;
423         bspDrawVert_t *buf;
424
425         if(cnt < 3)
426                 return 0;
427
428         /* find the triangle with highest area */
429         for(r = 0; r+2 < cnt; ++r)
430         for(s = r+1; s+1 < cnt; ++s)
431         for(t = s+1; t < cnt; ++t)
432         {
433                 VectorSubtract(vert[s].xyz, vert[r].xyz, ab);
434                 VectorSubtract(vert[t].xyz, vert[r].xyz, ac);
435                 CrossProduct(ab, ac, cross);
436                 A = VectorLength(cross);
437                 if(A > bestA)
438                 {
439                         bestA = A;
440                         bestR = r;
441                         bestS = s;
442                         bestT = t;
443                 }
444         }
445
446         if(bestA < TINY_AREA)
447                 /* the biggest triangle is degenerate - then every other is too, and the other algorithms wouldn't generate anything useful either */
448                 return 0;
449
450         i = 0;
451         indexes[i++] = bestR;
452         indexes[i++] = bestS;
453         indexes[i++] = bestT;
454                 /* uses 3 */
455
456         /* identify the other fragments */
457
458         /* full polygon without triangle (bestR,bestS,bestT) = three new polygons:
459          * 1. bestR..bestS
460          * 2. bestS..bestT
461          * 3. bestT..bestR
462          */
463
464         j = i + MaxAreaIndexes(vert + bestR, bestS - bestR + 1, indexes + i);
465         for(; i < j; ++i)
466                 indexes[i] += bestR;
467                 /* uses 3*(bestS-bestR+1)-6 */
468         j = i + MaxAreaIndexes(vert + bestS, bestT - bestS + 1, indexes + i);
469         for(; i < j; ++i)
470                 indexes[i] += bestS;
471                 /* uses 3*(bestT-bestS+1)-6 */
472
473         /* can'bestT recurse this one directly... therefore, buffering */
474         if(cnt + bestR - bestT + 1 >= 3)
475         {
476                 buf = safe_malloc(sizeof(*vert) * (cnt + bestR - bestT + 1));
477                 memcpy(buf, vert + bestT, sizeof(*vert) * (cnt - bestT));
478                 memcpy(buf + (cnt - bestT), vert, sizeof(*vert) * (bestR + 1));
479                 j = i + MaxAreaIndexes(buf, cnt + bestR - bestT + 1, indexes + i);
480                 for(; i < j; ++i)
481                         indexes[i] = (indexes[i] + bestT) % cnt;
482                         /* uses 3*(cnt+bestR-bestT+1)-6 */
483                 free(buf);
484         }
485
486         /* together 3 + 3*(cnt+3) - 18 = 3*cnt-6 q.e.d. */
487
488         return i;
489 }
490
491 /*
492 MaxAreaFaceSurface() - divVerent
493 creates a triangle list using max area indexes
494 */
495
496 void MaxAreaFaceSurface(mapDrawSurface_t *ds)
497 {
498         /* try to early out  */
499         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
500                 return;
501
502         /* is this a simple triangle? */
503         if( ds->numVerts == 3 )
504         {
505                 ds->numIndexes = 3;
506                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
507                 VectorSet( ds->indexes, 0, 1, 2 );
508                 numMaxAreaSurfaces++;
509                 return;
510         }
511
512         /* do it! */
513         ds->numIndexes = 3 * ds->numVerts - 6;
514         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
515         ds->numIndexes = MaxAreaIndexes(ds->verts, ds->numVerts, ds->indexes);
516
517         /* add to count */
518         numMaxAreaSurfaces++;
519
520         /* classify it */
521         ClassifySurfaces( 1, ds );
522 }
523
524
525 /*
526 FanFaceSurface() - ydnar
527 creates a tri-fan from a brush face winding
528 loosely based on SurfaceAsTriFan()
529 */
530
531 void FanFaceSurface( mapDrawSurface_t *ds )
532 {
533         int                             i, j, k, a, b, c, color[ MAX_LIGHTMAPS ][ 4 ];
534         bspDrawVert_t   *verts, *centroid, *dv;
535         double                  iv;
536         
537         
538         /* try to early out */
539         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
540                 return;
541         
542         /* add a new vertex at the beginning of the surface */
543         verts = safe_malloc( (ds->numVerts + 1) * sizeof( bspDrawVert_t ) );
544         memset( verts, 0, sizeof( bspDrawVert_t ) );
545         memcpy( &verts[ 1 ], ds->verts, ds->numVerts * sizeof( bspDrawVert_t ) );
546         free( ds->verts );
547         ds->verts = verts;
548         
549         /* add up the drawverts to create a centroid */
550         centroid = &verts[ 0 ];
551         memset( color, 0,  4 * MAX_LIGHTMAPS * sizeof( int ) );
552         for( i = 1, dv = &verts[ 1 ]; i < (ds->numVerts + 1); i++, dv++ )
553         {
554                 VectorAdd( centroid->xyz, dv->xyz, centroid->xyz );
555                 VectorAdd( centroid->normal, dv->normal, centroid->normal );
556                 for( j = 0; j < 4; j++ )
557                 {
558                         for( k = 0; k < MAX_LIGHTMAPS; k++ )
559                                 color[ k ][ j ] += dv->color[ k ][ j ];
560                         if( j < 2 )
561                         {
562                                 centroid->st[ j ] += dv->st[ j ];
563                                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
564                                         centroid->lightmap[ k ][ j ] += dv->lightmap[ k ][ j ];
565                         }
566                 }
567         }
568         
569         /* average the centroid */
570         iv = 1.0f / ds->numVerts;
571         VectorScale( centroid->xyz, iv, centroid->xyz );
572         if( VectorNormalize( centroid->normal, centroid->normal ) <= 0 )
573                 VectorCopy( verts[ 1 ].normal, centroid->normal );
574         for( j = 0; j < 4; j++ )
575         {
576                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
577                 {
578                         color[ k ][ j ] /= ds->numVerts;
579                         centroid->color[ k ][ j ] = (color[ k ][ j ] < 255.0f ? color[ k ][ j ] : 255);
580                 }
581                 if( j < 2 )
582                 {
583                         centroid->st[ j ] *= iv;
584                         for( k = 0; k < MAX_LIGHTMAPS; k++ )
585                                 centroid->lightmap[ k ][ j ] *= iv;
586                 }
587         }
588         
589         /* add to vert count */
590         ds->numVerts++;
591         
592         /* fill indexes in triangle fan order */
593         ds->numIndexes = 0;
594         ds->indexes = safe_malloc( ds->numVerts * 3 * sizeof( int ) );
595         for( i = 1; i < ds->numVerts; i++ )
596         {
597                 a = 0;
598                 b = i;
599                 c = (i + 1) % ds->numVerts;
600                 c = c ? c : 1;
601                 ds->indexes[ ds->numIndexes++ ] = a;
602                 ds->indexes[ ds->numIndexes++ ] = b;
603                 ds->indexes[ ds->numIndexes++ ] = c;
604         }
605         
606         /* add to count */
607         numFanSurfaces++;
608
609         /* classify it */
610         ClassifySurfaces( 1, ds );
611 }
612
613
614
615 /*
616 StripFaceSurface() - ydnar
617 attempts to create a valid tri-strip w/o degenerate triangles from a brush face winding
618 based on SurfaceAsTriStrip()
619 */
620
621 #define MAX_INDEXES             1024
622
623 void StripFaceSurface( mapDrawSurface_t *ds ) 
624 {
625         int                     i, r, least, rotate, numIndexes, ni, a, b, c, indexes[ MAX_INDEXES ];
626         vec_t           *v1, *v2;
627         
628         
629         /* try to early out  */
630         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
631                 return;
632         
633         /* is this a simple triangle? */
634         if( ds->numVerts == 3 )
635         {
636                 numIndexes = 3;
637                 VectorSet( indexes, 0, 1, 2 );
638         }
639         else
640         {
641                 /* ydnar: find smallest coordinate */
642                 least = 0;
643                 if( ds->shaderInfo != NULL && ds->shaderInfo->autosprite == qfalse )
644                 {
645                         for( i = 0; i < ds->numVerts; i++ )
646                         {
647                                 /* get points */
648                                 v1 = ds->verts[ i ].xyz;
649                                 v2 = ds->verts[ least ].xyz;
650                                 
651                                 /* compare */
652                                 if( v1[ 0 ] < v2[ 0 ] ||
653                                         (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] < v2[ 1 ]) ||
654                                         (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] == v2[ 1 ] && v1[ 2 ] < v2[ 2 ]) )
655                                         least = i;
656                         }
657                 }
658                 
659                 /* determine the triangle strip order */
660                 numIndexes = (ds->numVerts - 2) * 3;
661                 if( numIndexes > MAX_INDEXES )
662                         Error( "MAX_INDEXES exceeded for surface (%d > %d) (%d verts)", numIndexes, MAX_INDEXES, ds->numVerts );
663                 
664                 /* try all possible orderings of the points looking for a non-degenerate strip order */
665                 for( r = 0; r < ds->numVerts; r++ )
666                 {
667                         /* set rotation */
668                         rotate = (r + least) % ds->numVerts;
669                         
670                         /* walk the winding in both directions */
671                         for( ni = 0, i = 0; i < ds->numVerts - 2 - i; i++ )
672                         {
673                                 /* make indexes */
674                                 a = (ds->numVerts - 1 - i + rotate) % ds->numVerts;
675                                 b = (i + rotate ) % ds->numVerts;
676                                 c = (ds->numVerts - 2 - i + rotate) % ds->numVerts;
677                                 
678                                 /* test this triangle */
679                                 if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
680                                         break;
681                                 indexes[ ni++ ] = a;
682                                 indexes[ ni++ ] = b;
683                                 indexes[ ni++ ] = c;
684                                 
685                                 /* handle end case */
686                                 if( i + 1 != ds->numVerts - 1 - i )
687                                 {
688                                         /* make indexes */
689                                         a = (ds->numVerts - 2 - i + rotate ) % ds->numVerts;
690                                         b = (i + rotate ) % ds->numVerts;
691                                         c = (i + 1 + rotate ) % ds->numVerts;
692                                         
693                                         /* test triangle */
694                                         if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
695                                                 break;
696                                         indexes[ ni++ ] = a;
697                                         indexes[ ni++ ] = b;
698                                         indexes[ ni++ ] = c;
699                                 }
700                         }
701                         
702                         /* valid strip? */
703                         if( ni == numIndexes )
704                                 break;
705                 }
706                 
707                 /* if any triangle in the strip is degenerate, render from a centered fan point instead */
708                 if( ni < numIndexes )
709                 {
710                         FanFaceSurface( ds );
711                         return;
712                 }
713         }
714         
715         /* copy strip triangle indexes */
716         ds->numIndexes = numIndexes;
717         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
718         memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
719         
720         /* add to count */
721         numStripSurfaces++;
722         
723         /* classify it */
724         ClassifySurfaces( 1, ds );
725 }
726  
727  
728 /*
729 EmitMetaStatictics
730 vortex: prints meta statistics in general output
731 */
732
733 void EmitMetaStats()
734 {
735         Sys_Printf( "--- EmitMetaStats ---\n" );
736         Sys_Printf( "%9d total meta surfaces\n", numMetaSurfaces );
737         Sys_Printf( "%9d stripped surfaces\n", numStripSurfaces );
738         Sys_Printf( "%9d fanned surfaces\n", numFanSurfaces );
739         Sys_Printf( "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
740         Sys_Printf( "%9d patch meta surfaces\n", numPatchMetaSurfaces );
741         Sys_Printf( "%9d meta verts\n", numMetaVerts );
742         Sys_Printf( "%9d meta triangles\n", numMetaTriangles );
743 }
744
745 /*
746 MakeEntityMetaTriangles()
747 builds meta triangles from brush faces (tristrips and fans)
748 */
749
750 void MakeEntityMetaTriangles( entity_t *e )
751 {
752         int                                     i, f, fOld, start;
753         mapDrawSurface_t        *ds;
754         
755         
756         /* note it */
757         Sys_FPrintf( SYS_VRB, "--- MakeEntityMetaTriangles ---\n" );
758         
759         /* init pacifier */
760         fOld = -1;
761         start = I_FloatTime();
762         
763         /* walk the list of surfaces in the entity */
764         for( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ )
765         {
766                 /* print pacifier */
767                 f = 10 * (i - e->firstDrawSurf) / (numMapDrawSurfs - e->firstDrawSurf);
768                 if( f != fOld )
769                 {
770                         fOld = f;
771                         Sys_FPrintf( SYS_VRB, "%d...", f );
772                 }
773                 
774                 /* get surface */
775                 ds = &mapDrawSurfs[ i ];
776                 if( ds->numVerts <= 0 )
777                         continue;
778                 
779                 /* ignore autosprite surfaces */
780                 if( ds->shaderInfo->autosprite )
781                         continue;
782                 
783                 /* meta this surface? */
784                 if( meta == qfalse && ds->shaderInfo->forceMeta == qfalse )
785                         continue;
786                 
787                 /* switch on type */
788                 switch( ds->type )
789                 {
790                         case SURFACE_FACE:
791                         case SURFACE_DECAL:
792                                 if(maxAreaFaceSurface)
793                                         MaxAreaFaceSurface( ds );
794                                 else
795                                         StripFaceSurface( ds );
796                                 SurfaceToMetaTriangles( ds );
797                                 break;
798                         
799                         case SURFACE_PATCH:
800                                 TriangulatePatchSurface(e, ds );
801                                 break;
802                         
803                         case SURFACE_TRIANGLES:
804                                 break;
805                 
806                         case SURFACE_FORCED_META:
807                         case SURFACE_META:
808                                 SurfaceToMetaTriangles( ds );
809                                 break;
810                         
811                         default:
812                                 break;
813                 }
814         }
815         
816         /* print time */
817         if( (numMapDrawSurfs - e->firstDrawSurf) )
818                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
819         
820         /* emit some stats */
821         Sys_FPrintf( SYS_VRB, "%9d total meta surfaces\n", numMetaSurfaces );
822         Sys_FPrintf( SYS_VRB, "%9d stripped surfaces\n", numStripSurfaces );
823         Sys_FPrintf( SYS_VRB, "%9d fanned surfaces\n", numFanSurfaces );
824         Sys_FPrintf( SYS_VRB, "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
825         Sys_FPrintf( SYS_VRB, "%9d patch meta surfaces\n", numPatchMetaSurfaces );
826         Sys_FPrintf( SYS_VRB, "%9d meta verts\n", numMetaVerts );
827         Sys_FPrintf( SYS_VRB, "%9d meta triangles\n", numMetaTriangles );
828         
829         /* tidy things up */
830         TidyEntitySurfaces( e );
831 }
832
833
834
835 /*
836 PointTriangleIntersect()
837 assuming that all points lie in plane, determine if pt
838 is inside the triangle abc
839 code originally (c) 2001 softSurfer (www.softsurfer.com)
840 */
841
842 #define MIN_OUTSIDE_EPSILON             -0.01f
843 #define MAX_OUTSIDE_EPSILON             1.01f
844
845 static qboolean PointTriangleIntersect( vec3_t pt, vec4_t plane, vec3_t a, vec3_t b, vec3_t c, vec3_t bary )
846 {
847         vec3_t  u, v, w;
848         float   uu, uv, vv, wu, wv, d;
849         
850         
851         /* make vectors */
852         VectorSubtract( b, a, u );
853         VectorSubtract( c, a, v );
854         VectorSubtract( pt, a, w );
855         
856         /* more setup */
857         uu = DotProduct( u, u );
858         uv = DotProduct( u, v );
859         vv = DotProduct( v, v );
860         wu = DotProduct( w, u );
861         wv = DotProduct( w, v );
862         d = uv * uv - uu * vv;
863         
864         /* calculate barycentric coordinates */
865         bary[ 1 ] = (uv * wv - vv * wu) / d;
866         if( bary[ 1 ] < MIN_OUTSIDE_EPSILON || bary[ 1 ] > MAX_OUTSIDE_EPSILON )
867                 return qfalse;
868         bary[ 2 ] = (uv * wv - uu * wv) / d;
869         if( bary[ 2 ] < MIN_OUTSIDE_EPSILON || bary[ 2 ] > MAX_OUTSIDE_EPSILON )
870                 return qfalse;
871         bary[ 0 ] = 1.0f - (bary[ 1 ] + bary[ 2 ]);
872         
873         /* point is in triangle */
874         return qtrue;
875 }
876
877
878
879 /*
880 CreateEdge()
881 sets up an edge structure from a plane and 2 points that the edge ab falls lies in
882 */
883
884 typedef struct edge_s
885 {
886         vec3_t  origin, edge;
887         vec_t   length, kingpinLength;
888         int             kingpin;
889         vec4_t  plane;
890 }
891 edge_t;
892
893 void CreateEdge( vec4_t plane, vec3_t a, vec3_t b, edge_t *edge )
894 {
895         /* copy edge origin */
896         VectorCopy( a, edge->origin );
897         
898         /* create vector aligned with winding direction of edge */
899         VectorSubtract( b, a, edge->edge );
900         
901         if( fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 1 ] ) && fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 2 ] ) )
902                 edge->kingpin = 0;
903         else if( fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 0 ] ) && fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 2 ] ) )
904                 edge->kingpin = 1;
905         else
906                 edge->kingpin = 2;
907         edge->kingpinLength = edge->edge[ edge->kingpin ];
908         
909         VectorNormalize( edge->edge, edge->edge );
910         edge->edge[ 3 ] = DotProduct( a, edge->edge );
911         edge->length = DotProduct( b, edge->edge ) - edge->edge[ 3 ];
912         
913         /* create perpendicular plane that edge lies in */
914         CrossProduct( plane, edge->edge, edge->plane );
915         edge->plane[ 3 ] = DotProduct( a, edge->plane );
916 }
917
918
919
920 /*
921 FixMetaTJunctions()
922 fixes t-junctions on meta triangles
923 */
924
925 #define TJ_PLANE_EPSILON        (1.0f / 8.0f)
926 #define TJ_EDGE_EPSILON         (1.0f / 8.0f)
927 #define TJ_POINT_EPSILON        (1.0f / 8.0f)
928
929 void FixMetaTJunctions( void )
930 {
931         int                             i, j, k, f, fOld, start, vertIndex, triIndex, numTJuncs;
932         metaTriangle_t  *tri, *newTri;
933         shaderInfo_t    *si;
934         bspDrawVert_t   *a, *b, *c, junc;
935         float                   dist, amount;
936         vec3_t                  pt;
937         vec4_t                  plane;
938         edge_t                  edges[ 3 ];
939         
940         
941         /* this code is crap; revisit later */
942         return;
943         
944         /* note it */
945         Sys_FPrintf( SYS_VRB, "--- FixMetaTJunctions ---\n" );
946         
947         /* init pacifier */
948         fOld = -1;
949         start = I_FloatTime();
950         
951         /* walk triangle list */
952         numTJuncs = 0;
953         for( i = 0; i < numMetaTriangles; i++ )
954         {
955                 /* get triangle */
956                 tri = &metaTriangles[ i ];
957                 
958                 /* print pacifier */
959                 f = 10 * i / numMetaTriangles;
960                 if( f != fOld )
961                 {
962                         fOld = f;
963                         Sys_FPrintf( SYS_VRB, "%d...", f );
964                 }
965                 
966                 /* attempt to early out */
967                 si = tri->si;
968                 if( (si->compileFlags & C_NODRAW) || si->autosprite || si->notjunc )
969                         continue;
970                 
971                 /* calculate planes */
972                 VectorCopy( tri->plane, plane );
973                 plane[ 3 ] = tri->plane[ 3 ];
974                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
975                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
976                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
977                 
978                 /* walk meta vert list */
979                 for( j = 0; j < numMetaVerts; j++ )
980                 {
981                         /* get vert */
982                         VectorCopy( metaVerts[ j ].xyz, pt );
983
984                         /* debug code: darken verts */
985                         if( i == 0 )
986                                 VectorSet( metaVerts[ j ].color[ 0 ], 8, 8, 8 );
987                         
988                         /* determine if point lies in the triangle's plane */
989                         dist = DotProduct( pt, plane ) - plane[ 3 ];
990                         if( fabs( dist ) > TJ_PLANE_EPSILON )
991                                 continue;
992                         
993                         /* skip this point if it already exists in the triangle */
994                         for( k = 0; k < 3; k++ )
995                         {
996                                 if( fabs( pt[ 0 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 0 ] ) <= TJ_POINT_EPSILON &&
997                                         fabs( pt[ 1 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 1 ] ) <= TJ_POINT_EPSILON &&
998                                         fabs( pt[ 2 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 2 ] ) <= TJ_POINT_EPSILON )
999                                         break;
1000                         }
1001                         if( k < 3 )
1002                                 continue;
1003                         
1004                         /* walk edges */
1005                         for( k = 0; k < 3; k++ )
1006                         {
1007                                 /* ignore bogus edges */
1008                                 if( fabs( edges[ k ].kingpinLength ) < TJ_EDGE_EPSILON )
1009                                         continue;
1010                                 
1011                                 /* determine if point lies on the edge */
1012                                 dist = DotProduct( pt, edges[ k ].plane ) - edges[ k ].plane[ 3 ];
1013                                 if( fabs( dist ) > TJ_EDGE_EPSILON )
1014                                         continue;
1015                                 
1016                                 /* determine how far along the edge the point lies */
1017                                 amount = (pt[ edges[ k ].kingpin ] - edges[ k ].origin[ edges[ k ].kingpin ]) / edges[ k ].kingpinLength;
1018                                 if( amount <= 0.0f || amount >= 1.0f )
1019                                         continue;
1020                                 
1021                                 #if 0
1022                                 dist = DotProduct( pt, edges[ k ].edge ) - edges[ k ].edge[ 3 ];
1023                                 if( dist <= -0.0f || dist >= edges[ k ].length )
1024                                         continue;
1025                                 amount = dist / edges[ k ].length;
1026                                 #endif
1027                                 
1028                                 /* debug code: brighten this point */
1029                                 //%     metaVerts[ j ].color[ 0 ][ 0 ] += 5;
1030                                 //%     metaVerts[ j ].color[ 0 ][ 1 ] += 4;
1031                                 VectorSet( metaVerts[ tri->indexes[ k ] ].color[ 0 ], 255, 204, 0 );
1032                                 VectorSet( metaVerts[ tri->indexes[ (k + 1) % 3 ] ].color[ 0 ], 255, 204, 0 );
1033                                 
1034
1035                                 /* the edge opposite the zero-weighted vertex was hit, so use that as an amount */
1036                                 a = &metaVerts[ tri->indexes[ k % 3 ] ];
1037                                 b = &metaVerts[ tri->indexes[ (k + 1) % 3 ] ];
1038                                 c = &metaVerts[ tri->indexes[ (k + 2) % 3 ] ];
1039                                 
1040                                 /* make new vert */
1041                                 LerpDrawVertAmount( a, b, amount, &junc );
1042                                 VectorCopy( pt, junc.xyz );
1043                                 
1044                                 /* compare against existing verts */
1045                                 if( VectorCompare( junc.xyz, a->xyz ) || VectorCompare( junc.xyz, b->xyz ) || VectorCompare( junc.xyz, c->xyz ) )
1046                                         continue;
1047                                 
1048                                 /* see if we can just re-use the existing vert */
1049                                 if( !memcmp( &metaVerts[ j ], &junc, sizeof( junc ) ) )
1050                                         vertIndex = j;
1051                                 else
1052                                 {
1053                                         /* find new vertex (note: a and b are invalid pointers after this) */
1054                                         firstSearchMetaVert = numMetaVerts;
1055                                         vertIndex = FindMetaVertex( &junc );
1056                                         if( vertIndex < 0 )
1057                                                 continue;
1058                                 }
1059                                                 
1060                                 /* make new triangle */
1061                                 triIndex = AddMetaTriangle();
1062                                 if( triIndex < 0 )
1063                                         continue;
1064                                 
1065                                 /* get triangles */
1066                                 tri = &metaTriangles[ i ];
1067                                 newTri = &metaTriangles[ triIndex ];
1068                                 
1069                                 /* copy the triangle */
1070                                 memcpy( newTri, tri, sizeof( *tri ) );
1071                                 
1072                                 /* fix verts */
1073                                 tri->indexes[ (k + 1) % 3 ] = vertIndex;
1074                                 newTri->indexes[ k ] = vertIndex;
1075                                 
1076                                 /* recalculate edges */
1077                                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1078                                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1079                                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1080                                 
1081                                 /* debug code */
1082                                 metaVerts[ vertIndex ].color[ 0 ][ 0 ] = 255;
1083                                 metaVerts[ vertIndex ].color[ 0 ][ 1 ] = 204;
1084                                 metaVerts[ vertIndex ].color[ 0 ][ 2 ] = 0;
1085                                 
1086                                 /* add to counter and end processing of this vert */
1087                                 numTJuncs++;
1088                                 break;
1089                         }
1090                 }
1091         }
1092         
1093         /* print time */
1094         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1095         
1096         /* emit some stats */
1097         Sys_FPrintf( SYS_VRB, "%9d T-junctions added\n", numTJuncs );
1098 }
1099
1100
1101
1102 /*
1103 SmoothMetaTriangles()
1104 averages coincident vertex normals in the meta triangles
1105 */
1106
1107 #define MAX_SAMPLES                             256
1108 #define THETA_EPSILON                   0.000001
1109 #define EQUAL_NORMAL_EPSILON    0.01
1110
1111 void SmoothMetaTriangles( void )
1112 {
1113         int                             i, j, k, f, fOld, start, cs, numVerts, numVotes, numSmoothed;
1114         float                   shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle;
1115         metaTriangle_t  *tri;
1116         float                   *shadeAngles;
1117         byte                    *smoothed;
1118         vec3_t                  average, diff;
1119         int                             indexes[ MAX_SAMPLES ];
1120         vec3_t                  votes[ MAX_SAMPLES ];
1121         
1122         /* note it */
1123         Sys_FPrintf( SYS_VRB, "--- SmoothMetaTriangles ---\n" );
1124         
1125         /* allocate shade angle table */
1126         shadeAngles = safe_malloc( numMetaVerts * sizeof( float ) );
1127         memset( shadeAngles, 0, numMetaVerts * sizeof( float ) );
1128         
1129         /* allocate smoothed table */
1130         cs = (numMetaVerts / 8) + 1;
1131         smoothed = safe_malloc( cs );
1132         memset( smoothed, 0, cs );
1133         
1134         /* set default shade angle */
1135         defaultShadeAngle = DEG2RAD( npDegrees );
1136         maxShadeAngle = 0.0f;
1137         
1138         /* run through every surface and flag verts belonging to non-lightmapped surfaces
1139            and set per-vertex smoothing angle */
1140         for( i = 0, tri = &metaTriangles[ i ]; i < numMetaTriangles; i++, tri++ )
1141         {
1142                 shadeAngle = defaultShadeAngle;
1143
1144                 /* get shade angle from shader */
1145                 if( tri->si->shadeAngleDegrees > 0.0f )
1146                         shadeAngle = DEG2RAD( tri->si->shadeAngleDegrees );
1147                 /* get shade angle from entity */
1148                 else if( tri->shadeAngleDegrees > 0.0f )
1149                         shadeAngle = DEG2RAD( tri->shadeAngleDegrees );
1150                 
1151                 if( shadeAngle <= 0.0f ) 
1152                         shadeAngle = defaultShadeAngle;
1153
1154                 if( shadeAngle > maxShadeAngle )
1155                         maxShadeAngle = shadeAngle;
1156                 
1157                 /* flag its verts */
1158                 for( j = 0; j < 3; j++ )
1159                 {
1160                         shadeAngles[ tri->indexes[ j ] ] = shadeAngle;
1161                         if( shadeAngle <= 0 )
1162                                 smoothed[ tri->indexes[ j ] >> 3 ] |= (1 << (tri->indexes[ j ] & 7));
1163                 }
1164         }
1165         
1166         /* bail if no surfaces have a shade angle */
1167         if( maxShadeAngle <= 0 )
1168         {
1169                 Sys_FPrintf( SYS_VRB, "No smoothing angles specified, aborting\n" );
1170                 free( shadeAngles );
1171                 free( smoothed );
1172                 return;
1173         }
1174         
1175         /* init pacifier */
1176         fOld = -1;
1177         start = I_FloatTime();
1178         
1179         /* go through the list of vertexes */
1180         numSmoothed = 0;
1181         for( i = 0; i < numMetaVerts; i++ )
1182         {
1183                 /* print pacifier */
1184                 f = 10 * i / numMetaVerts;
1185                 if( f != fOld )
1186                 {
1187                         fOld = f;
1188                         Sys_FPrintf( SYS_VRB, "%d...", f );
1189                 }
1190                 
1191                 /* already smoothed? */
1192                 if( smoothed[ i >> 3 ] & (1 << (i & 7)) )
1193                         continue;
1194                 
1195                 /* clear */
1196                 VectorClear( average );
1197                 numVerts = 0;
1198                 numVotes = 0;
1199                 
1200                 /* build a table of coincident vertexes */
1201                 for( j = i; j < numMetaVerts && numVerts < MAX_SAMPLES; j++ )
1202                 {
1203                         /* already smoothed? */
1204                         if( smoothed[ j >> 3 ] & (1 << (j & 7)) )
1205                                 continue;
1206                         
1207                         /* test vertexes */
1208                         if( VectorCompare( metaVerts[ i ].xyz, metaVerts[ j ].xyz ) == qfalse )
1209                                 continue;
1210                         
1211                         /* use smallest shade angle */
1212                         shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]);
1213                         
1214                         /* check shade angle */
1215                         dot = DotProduct( metaVerts[ i ].normal, metaVerts[ j ].normal );
1216                         if( dot > 1.0 )
1217                                 dot = 1.0;
1218                         else if( dot < -1.0 )
1219                                 dot = -1.0;
1220                         testAngle = acos( dot ) + THETA_EPSILON;
1221                         if( testAngle >= shadeAngle )
1222                                 continue;
1223                         
1224                         /* add to the list */
1225                         indexes[ numVerts++ ] = j;
1226                         
1227                         /* flag vertex */
1228                         smoothed[ j >> 3 ] |= (1 << (j & 7));
1229                         
1230                         /* see if this normal has already been voted */
1231                         for( k = 0; k < numVotes; k++ )
1232                         {
1233                                 VectorSubtract( metaVerts[ j ].normal, votes[ k ], diff );
1234                                 if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON &&
1235                                         fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON &&
1236                                         fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON )
1237                                         break;
1238                         }
1239                         
1240                         /* add a new vote? */
1241                         if( k == numVotes && numVotes < MAX_SAMPLES )
1242                         {
1243                                 VectorAdd( average, metaVerts[ j ].normal, average );
1244                                 VectorCopy( metaVerts[ j ].normal, votes[ numVotes ] );
1245                                 numVotes++;
1246                         }
1247                 }
1248                 
1249                 /* don't average for less than 2 verts */
1250                 if( numVerts < 2 )
1251                         continue;
1252                 
1253                 /* average normal */
1254                 if( VectorNormalize( average, average ) > 0 )
1255                 {
1256                         /* smooth */
1257                         for( j = 0; j < numVerts; j++ )
1258                                 VectorCopy( average, metaVerts[ indexes[ j ] ].normal );
1259                         numSmoothed++;
1260                 }
1261         }
1262         
1263         /* free the tables */
1264         free( shadeAngles );
1265         free( smoothed );
1266         
1267         /* print time */
1268         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1269
1270         /* emit some stats */
1271         Sys_FPrintf( SYS_VRB, "%9d smoothed vertexes\n", numSmoothed );
1272 }
1273
1274
1275
1276 /*
1277 AddMetaVertToSurface()
1278 adds a drawvert to a surface unless an existing vert matching already exists
1279 returns the index of that vert (or < 0 on failure)
1280 */
1281
1282 int AddMetaVertToSurface( mapDrawSurface_t *ds, bspDrawVert_t *dv1, int *coincident )
1283 {
1284         int                             i;
1285         bspDrawVert_t   *dv2;
1286         
1287         
1288         /* go through the verts and find a suitable candidate */
1289         for( i = 0; i < ds->numVerts; i++ )
1290         {
1291                 /* get test vert */
1292                 dv2 = &ds->verts[ i ];
1293                 
1294                 /* compare xyz and normal */
1295                 if( VectorCompare( dv1->xyz, dv2->xyz ) == qfalse )
1296                         continue;
1297                 if( VectorCompare( dv1->normal, dv2->normal ) == qfalse )
1298                         continue;
1299                 
1300                 /* good enough at this point */
1301                 (*coincident)++;
1302                 
1303                 /* compare texture coordinates and color */
1304                 if( dv1->st[ 0 ] != dv2->st[ 0 ] || dv1->st[ 1 ] != dv2->st[ 1 ] )
1305                         continue;
1306                 if( dv1->color[ 0 ][ 3 ] != dv2->color[ 0 ][ 3 ] )
1307                         continue;
1308                 
1309                 /* found a winner */
1310                 numMergedVerts++;
1311                 return i;
1312         }
1313
1314         /* overflow check */
1315         if( ds->numVerts >= ((ds->shaderInfo->compileFlags & C_VERTEXLIT) ? maxSurfaceVerts : maxLMSurfaceVerts) )
1316                 return VERTS_EXCEEDED;
1317         
1318         /* made it this far, add the vert and return */
1319         dv2 = &ds->verts[ ds->numVerts++ ];
1320         *dv2 = *dv1;
1321         return (ds->numVerts - 1);
1322 }
1323
1324
1325
1326
1327 /*
1328 AddMetaTriangleToSurface()
1329 attempts to add a metatriangle to a surface
1330 returns the score of the triangle added
1331 */
1332
1333 #define AXIS_SCORE                      100000
1334 #define AXIS_MIN                        100000
1335 #define VERT_SCORE                      10000
1336 #define SURFACE_SCORE           1000
1337 #define ST_SCORE                        50
1338 #define ST_SCORE2                       (2 * (ST_SCORE))
1339
1340 #define ADEQUATE_SCORE          ((AXIS_MIN) + 1 * (VERT_SCORE))
1341 #define GOOD_SCORE                      ((AXIS_MIN) + 2 * (VERT_SCORE)                   + 4 * (ST_SCORE))
1342 #define PERFECT_SCORE           ((AXIS_MIN) + 3 * (VERT_SCORE) + (SURFACE_SCORE) + 4 * (ST_SCORE))
1343 //#define MAX_BBOX_DISTANCE   16
1344
1345 static int AddMetaTriangleToSurface( mapDrawSurface_t *ds, metaTriangle_t *tri, qboolean testAdd )
1346 {
1347         int                                     i, score, coincident, ai, bi, ci, oldTexRange[ 2 ];
1348         float                           lmMax;
1349         vec3_t                          mins, maxs, p;
1350         qboolean                        inTexRange, es, et;
1351         mapDrawSurface_t        old;
1352         
1353         
1354         /* overflow check */
1355         if( ds->numIndexes >= maxSurfaceIndexes )
1356                 return 0;
1357         
1358         /* test the triangle */
1359         if( ds->entityNum != tri->entityNum )   /* ydnar: added 2002-07-06 */
1360                 return 0;
1361         if( ds->castShadows != tri->castShadows || ds->recvShadows != tri->recvShadows )
1362                 return 0;
1363         if( ds->shaderInfo != tri->si || ds->fogNum != tri->fogNum || ds->sampleSize != tri->sampleSize )
1364                 return 0;
1365         #if 0
1366                 if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1367                         //% VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) == qfalse )
1368                         DotProduct( ds->lightmapAxis, tri->plane ) < 0.25f )
1369                         return 0;
1370         #endif
1371         
1372         /* planar surfaces will only merge with triangles in the same plane */
1373         if( npDegrees == 0.0f && ds->shaderInfo->nonplanar == qfalse && ds->planeNum >= 0 )
1374         {
1375                 if( VectorCompare( mapplanes[ ds->planeNum ].normal, tri->plane ) == qfalse || mapplanes[ ds->planeNum ].dist != tri->plane[ 3 ] )
1376                         return 0;
1377                 if( tri->planeNum >= 0 && tri->planeNum != ds->planeNum )
1378                         return 0;
1379         }
1380
1381 #if MAX_BBOX_DISTANCE > 0
1382         VectorCopy( ds->mins, mins );
1383         VectorCopy( ds->maxs, maxs );
1384         mins[0] -= MAX_BBOX_DISTANCE;
1385         mins[1] -= MAX_BBOX_DISTANCE;
1386         mins[2] -= MAX_BBOX_DISTANCE;
1387         maxs[0] += MAX_BBOX_DISTANCE;
1388         maxs[1] += MAX_BBOX_DISTANCE;
1389         maxs[2] += MAX_BBOX_DISTANCE;
1390 #define CHECK_1D(mins, v, maxs) ((mins) <= (v) && (v) <= (maxs))
1391 #define CHECK_3D(mins, v, maxs) (CHECK_1D((mins)[0], (v)[0], (maxs)[0]) && CHECK_1D((mins)[1], (v)[1], (maxs)[1]) && CHECK_1D((mins)[2], (v)[2], (maxs)[2]))
1392         VectorCopy(metaVerts[ tri->indexes[ 0 ] ].xyz, p);
1393         if(!CHECK_3D(mins, p, maxs))
1394         {
1395                 VectorCopy(metaVerts[ tri->indexes[ 1 ] ].xyz, p);
1396                 if(!CHECK_3D(mins, p, maxs))
1397                 {
1398                         VectorCopy(metaVerts[ tri->indexes[ 2 ] ].xyz, p);
1399                         if(!CHECK_3D(mins, p, maxs))
1400                                 return 0;
1401                 }
1402         }
1403 #undef CHECK_3D
1404 #undef CHECK_1D
1405 #endif
1406         
1407         /* set initial score */
1408         score = tri->surfaceNum == ds->surfaceNum ? SURFACE_SCORE : 0;
1409         
1410         /* score the the dot product of lightmap axis to plane */
1411         if( (ds->shaderInfo->compileFlags & C_VERTEXLIT) || VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) )
1412                 score += AXIS_SCORE;
1413         else
1414                 score += AXIS_SCORE * DotProduct( ds->lightmapAxis, tri->plane );
1415         
1416         /* preserve old drawsurface if this fails */
1417         memcpy( &old, ds, sizeof( *ds ) );
1418         
1419         /* attempt to add the verts */
1420         coincident = 0;
1421         ai = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 0 ] ], &coincident );
1422         bi = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 1 ] ], &coincident );
1423         ci = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 2 ] ], &coincident );
1424         
1425         /* check vertex underflow */
1426         if( ai < 0 || bi < 0 || ci < 0 )
1427         {
1428                 memcpy( ds, &old, sizeof( *ds ) );
1429                 return 0;
1430         }
1431         
1432         /* score coincident vertex count (2003-02-14: changed so this only matters on planar surfaces) */
1433         score += (coincident * VERT_SCORE);
1434         
1435         /* add new vertex bounds to mins/maxs */
1436         VectorCopy( ds->mins, mins );
1437         VectorCopy( ds->maxs, maxs );
1438         AddPointToBounds( metaVerts[ tri->indexes[ 0 ] ].xyz, mins, maxs );
1439         AddPointToBounds( metaVerts[ tri->indexes[ 1 ] ].xyz, mins, maxs );
1440         AddPointToBounds( metaVerts[ tri->indexes[ 2 ] ].xyz, mins, maxs );
1441         
1442         /* check lightmap bounds overflow (after at least 1 triangle has been added) */
1443         if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1444                 ds->numIndexes > 0 && VectorLength( ds->lightmapAxis ) > 0.0f &&
1445                 (VectorCompare( ds->mins, mins ) == qfalse || VectorCompare( ds->maxs, maxs ) == qfalse) )
1446         {
1447                 /* set maximum size before lightmap scaling (normally 2032 units) */
1448                 /* 2004-02-24: scale lightmap test size by 2 to catch larger brush faces */
1449                 /* 2004-04-11: reverting to actual lightmap size */
1450                 lmMax = (ds->sampleSize * (ds->shaderInfo->lmCustomWidth - 1));
1451                 for( i = 0; i < 3; i++ )
1452                 {
1453                         if( (maxs[ i ] - mins[ i ]) > lmMax )
1454                         {
1455                                 memcpy( ds, &old, sizeof( *ds ) );
1456                                 return 0;
1457                         }
1458                 }
1459         }
1460         
1461         /* check texture range overflow */
1462         oldTexRange[ 0 ] = ds->texRange[ 0 ];
1463         oldTexRange[ 1 ] = ds->texRange[ 1 ];
1464         inTexRange = CalcSurfaceTextureRange( ds );
1465         
1466         es = (ds->texRange[ 0 ] > oldTexRange[ 0 ]) ? qtrue : qfalse;
1467         et = (ds->texRange[ 1 ] > oldTexRange[ 1 ]) ? qtrue : qfalse;
1468         
1469         if( inTexRange == qfalse && ds->numIndexes > 0 )
1470         {
1471                 memcpy( ds, &old, sizeof( *ds ) );
1472                 return UNSUITABLE_TRIANGLE;
1473         }
1474         
1475         /* score texture range */
1476         if( ds->texRange[ 0 ] <= oldTexRange[ 0 ] )
1477                 score += ST_SCORE2;
1478         else if( ds->texRange[ 0 ] > oldTexRange[ 0 ] && oldTexRange[ 1 ] > oldTexRange[ 0 ] )
1479                 score += ST_SCORE;
1480         
1481         if( ds->texRange[ 1 ] <= oldTexRange[ 1 ] )
1482                 score += ST_SCORE2;
1483         else if( ds->texRange[ 1 ] > oldTexRange[ 1 ] && oldTexRange[ 0 ] > oldTexRange[ 1 ] )
1484                 score += ST_SCORE;
1485         
1486         
1487         /* go through the indexes and try to find an existing triangle that matches abc */
1488         for( i = 0; i < ds->numIndexes; i += 3 )
1489         {
1490                 /* 2002-03-11 (birthday!): rotate the triangle 3x to find an existing triangle */
1491                 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 1 ] && ci == ds->indexes[ i + 2 ]) ||
1492                         (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 1 ] && ai == ds->indexes[ i + 2 ]) ||
1493                         (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 1 ] && bi == ds->indexes[ i + 2 ]) )
1494                 {
1495                         /* triangle already present */
1496                         memcpy( ds, &old, sizeof( *ds ) );
1497                         tri->si = NULL;
1498                         return 0;
1499                 }
1500                 
1501                 /* rotate the triangle 3x to find an inverse triangle (error case) */
1502                 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 2 ] && ci == ds->indexes[ i + 1 ]) ||
1503                         (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 2 ] && ai == ds->indexes[ i + 1 ]) ||
1504                         (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 2 ] && bi == ds->indexes[ i + 1 ]) )
1505                 {
1506                         /* warn about it */
1507                         Sys_Printf( "WARNING: Flipped triangle: (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f)\n",
1508                                 ds->verts[ ai ].xyz[ 0 ], ds->verts[ ai ].xyz[ 1 ], ds->verts[ ai ].xyz[ 2 ],
1509                                 ds->verts[ bi ].xyz[ 0 ], ds->verts[ bi ].xyz[ 1 ], ds->verts[ bi ].xyz[ 2 ],
1510                                 ds->verts[ ci ].xyz[ 0 ], ds->verts[ ci ].xyz[ 1 ], ds->verts[ ci ].xyz[ 2 ] );
1511                         
1512                         /* reverse triangle already present */
1513                         memcpy( ds, &old, sizeof( *ds ) );
1514                         tri->si = NULL;
1515                         return 0;
1516                 }
1517         }
1518         
1519         /* add the triangle indexes */
1520         if( ds->numIndexes < maxSurfaceIndexes )
1521                 ds->indexes[ ds->numIndexes++ ] = ai;
1522         if( ds->numIndexes < maxSurfaceIndexes )
1523                 ds->indexes[ ds->numIndexes++ ] = bi;
1524         if( ds->numIndexes < maxSurfaceIndexes )
1525                 ds->indexes[ ds->numIndexes++ ] = ci;
1526         
1527         /* check index overflow */
1528         if( ds->numIndexes >= maxSurfaceIndexes  )
1529         {
1530                 memcpy( ds, &old, sizeof( *ds ) );
1531                 return 0;
1532         }
1533         
1534         /* sanity check the indexes */
1535         if( ds->numIndexes >= 3 &&
1536                 (ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 2 ] ||
1537                 ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 1 ] ||
1538                 ds->indexes[ ds->numIndexes - 2 ] == ds->indexes[ ds->numIndexes - 1 ]) )
1539                 Sys_Printf( "DEG:%d! ", ds->numVerts );
1540         
1541         /* testing only? */
1542         if( testAdd )
1543                 memcpy( ds, &old, sizeof( *ds ) );
1544         else
1545         {
1546                 /* copy bounds back to surface */
1547                 VectorCopy( mins, ds->mins );
1548                 VectorCopy( maxs, ds->maxs );
1549                 
1550                 /* mark triangle as used */
1551                 tri->si = NULL;
1552         }
1553         
1554         /* add a side reference */
1555         ds->sideRef = AllocSideRef( tri->side, ds->sideRef );
1556         
1557         /* return to sender */
1558         return score;
1559 }
1560
1561
1562
1563 /*
1564 MetaTrianglesToSurface()
1565 creates map drawsurface(s) from the list of possibles
1566 */
1567
1568 static void MetaTrianglesToSurface( int numPossibles, metaTriangle_t *possibles, int *fOld, int *numAdded )
1569 {
1570         int                                     i, j, f, best, score, bestScore;
1571         metaTriangle_t          *seed, *test;
1572         mapDrawSurface_t        *ds;
1573         bspDrawVert_t           *verts;
1574         int                                     *indexes;
1575         qboolean                        added;
1576         
1577         
1578         /* allocate arrays */
1579         verts = safe_malloc( sizeof( *verts ) * maxSurfaceVerts );
1580         indexes = safe_malloc( sizeof( *indexes ) * maxSurfaceIndexes );
1581         
1582         /* walk the list of triangles */
1583         for( i = 0, seed = possibles; i < numPossibles; i++, seed++ )
1584         {
1585                 /* skip this triangle if it has already been merged */
1586                 if( seed->si == NULL )
1587                         continue;
1588                 
1589                 /* -----------------------------------------------------------------
1590                    initial drawsurf construction
1591                    ----------------------------------------------------------------- */
1592                 
1593                 /* start a new drawsurface */
1594                 ds = AllocDrawSurface( SURFACE_META );
1595                 ds->entityNum = seed->entityNum;
1596                 ds->surfaceNum = seed->surfaceNum;
1597                 ds->castShadows = seed->castShadows;
1598                 ds->recvShadows = seed->recvShadows;
1599                 
1600                 ds->shaderInfo = seed->si;
1601                 ds->planeNum = seed->planeNum;
1602                 ds->fogNum = seed->fogNum;
1603                 ds->sampleSize = seed->sampleSize;
1604                 ds->shadeAngleDegrees = seed->shadeAngleDegrees;
1605                 ds->verts = verts;
1606                 ds->indexes = indexes;
1607                 VectorCopy( seed->lightmapAxis, ds->lightmapAxis );
1608                 ds->sideRef = AllocSideRef( seed->side, NULL );
1609                 
1610                 ClearBounds( ds->mins, ds->maxs );
1611                 
1612                 /* clear verts/indexes */
1613                 memset( verts, 0, sizeof( verts ) );
1614                 memset( indexes, 0, sizeof( indexes ) );
1615                 
1616                 /* add the first triangle */
1617                 if( AddMetaTriangleToSurface( ds, seed, qfalse ) )
1618                         (*numAdded)++;
1619                 
1620                 /* -----------------------------------------------------------------
1621                    add triangles
1622                    ----------------------------------------------------------------- */
1623                 
1624                 /* progressively walk the list until no more triangles can be added */
1625                 added = qtrue;
1626                 while( added )
1627                 {
1628                         /* print pacifier */
1629                         f = 10 * *numAdded / numMetaTriangles;
1630                         if( f > *fOld )
1631                         {
1632                                 *fOld = f;
1633                                 Sys_FPrintf( SYS_VRB, "%d...", f );
1634                         }
1635                         
1636                         /* reset best score */
1637                         best = -1;
1638                         bestScore = 0;
1639                         added = qfalse;
1640                         
1641                         /* walk the list of possible candidates for merging */
1642                         for( j = i + 1, test = &possibles[ j ]; j < numPossibles; j++, test++ )
1643                         {
1644                                 /* skip this triangle if it has already been merged */
1645                                 if( test->si == NULL )
1646                                         continue;
1647                                 
1648                                 /* score this triangle */
1649                                 score = AddMetaTriangleToSurface( ds, test, qtrue );
1650                                 if( score > bestScore )
1651                                 {
1652                                         best = j;
1653                                         bestScore = score;
1654                                         
1655                                         /* if we have a score over a certain threshold, just use it */
1656                                         if( bestScore >= GOOD_SCORE )
1657                                         {
1658                                                 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1659                                                         (*numAdded)++;
1660                                                 
1661                                                 /* reset */
1662                                                 best = -1;
1663                                                 bestScore = 0;
1664                                                 added = qtrue;
1665                                         }
1666                                 }
1667                         }
1668                         
1669                         /* add best candidate */
1670                         if( best >= 0 && bestScore > ADEQUATE_SCORE )
1671                         {
1672                                 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1673                                         (*numAdded)++;
1674                                 
1675                                 /* reset */
1676                                 added = qtrue;
1677                         }
1678                 }
1679                 
1680                 /* copy the verts and indexes to the new surface */
1681                 ds->verts = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
1682                 memcpy( ds->verts, verts, ds->numVerts * sizeof( bspDrawVert_t ) );
1683                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
1684                 memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
1685                 
1686                 /* classify the surface */
1687                 ClassifySurfaces( 1, ds );
1688                 
1689                 /* add to count */
1690                 numMergedSurfaces++;
1691         }
1692         
1693         /* free arrays */
1694         free( verts );
1695         free( indexes );
1696 }
1697
1698
1699
1700 /*
1701 CompareMetaTriangles()
1702 compare function for qsort()
1703 */
1704
1705 static int CompareMetaTriangles( const void *a, const void *b )
1706 {
1707         int             i, j, av, bv;
1708         vec3_t  aMins, bMins;
1709         
1710         
1711         /* shader first */
1712         if( ((metaTriangle_t*) a)->si < ((metaTriangle_t*) b)->si )
1713                 return 1;
1714         else if( ((metaTriangle_t*) a)->si > ((metaTriangle_t*) b)->si )
1715                 return -1;
1716         
1717         /* then fog */
1718         else if( ((metaTriangle_t*) a)->fogNum < ((metaTriangle_t*) b)->fogNum )
1719                 return 1;
1720         else if( ((metaTriangle_t*) a)->fogNum > ((metaTriangle_t*) b)->fogNum )
1721                 return -1;
1722         
1723         /* then plane */
1724         #if 0
1725                 else if( npDegrees == 0.0f && ((metaTriangle_t*) a)->si->nonplanar == qfalse &&
1726                         ((metaTriangle_t*) a)->planeNum >= 0 && ((metaTriangle_t*) a)->planeNum >= 0 )
1727                 {
1728                         if( ((metaTriangle_t*) a)->plane[ 3 ] < ((metaTriangle_t*) b)->plane[ 3 ] )
1729                                 return 1;
1730                         else if( ((metaTriangle_t*) a)->plane[ 3 ] > ((metaTriangle_t*) b)->plane[ 3 ] )
1731                                 return -1;
1732                         else if( ((metaTriangle_t*) a)->plane[ 0 ] < ((metaTriangle_t*) b)->plane[ 0 ] )
1733                                 return 1;
1734                         else if( ((metaTriangle_t*) a)->plane[ 0 ] > ((metaTriangle_t*) b)->plane[ 0 ] )
1735                                 return -1;
1736                         else if( ((metaTriangle_t*) a)->plane[ 1 ] < ((metaTriangle_t*) b)->plane[ 1 ] )
1737                                 return 1;
1738                         else if( ((metaTriangle_t*) a)->plane[ 1 ] > ((metaTriangle_t*) b)->plane[ 1 ] )
1739                                 return -1;
1740                         else if( ((metaTriangle_t*) a)->plane[ 2 ] < ((metaTriangle_t*) b)->plane[ 2 ] )
1741                                 return 1;
1742                         else if( ((metaTriangle_t*) a)->plane[ 2 ] > ((metaTriangle_t*) b)->plane[ 2 ] )
1743                                 return -1;
1744                 }
1745         #endif
1746         
1747         /* then position in world */
1748         
1749         /* find mins */
1750         VectorSet( aMins, 999999, 999999, 999999 );
1751         VectorSet( bMins, 999999, 999999, 999999 );
1752         for( i = 0; i < 3; i++ )
1753         {
1754                 av = ((metaTriangle_t*) a)->indexes[ i ];
1755                 bv = ((metaTriangle_t*) b)->indexes[ i ];
1756                 for( j = 0; j < 3; j++ )
1757                 {
1758                         if( metaVerts[ av ].xyz[ j ] < aMins[ j ] )
1759                                 aMins[ j ] = metaVerts[ av ].xyz[ j ];
1760                         if( metaVerts[ bv ].xyz[ j ] < bMins[ j ] )
1761                                 bMins[ j ] = metaVerts[ bv ].xyz[ j ];
1762                 }
1763         }
1764         
1765         /* test it */
1766         for( i = 0; i < 3; i++ )
1767         {
1768                 if( aMins[ i ] < bMins[ i ] )
1769                         return 1;
1770                 else if( aMins[ i ] > bMins[ i ] )
1771                         return -1;
1772         }
1773         
1774         /* functionally equivalent */
1775         return 0;
1776 }
1777
1778
1779
1780 /*
1781 MergeMetaTriangles()
1782 merges meta triangles into drawsurfaces
1783 */
1784
1785 void MergeMetaTriangles( void )
1786 {
1787         int                                     i, j, fOld, start, numAdded;
1788         metaTriangle_t          *head, *end;
1789         
1790         
1791         /* only do this if there are meta triangles */
1792         if( numMetaTriangles <= 0 )
1793                 return;
1794         
1795         /* note it */
1796         Sys_FPrintf( SYS_VRB, "--- MergeMetaTriangles ---\n" );
1797         
1798         /* sort the triangles by shader major, fognum minor */
1799         qsort( metaTriangles, numMetaTriangles, sizeof( metaTriangle_t ), CompareMetaTriangles );
1800
1801         /* init pacifier */
1802         fOld = -1;
1803         start = I_FloatTime();
1804         numAdded = 0;
1805         
1806         /* merge */
1807         for( i = 0, j = 0; i < numMetaTriangles; i = j )
1808         {
1809                 /* get head of list */
1810                 head = &metaTriangles[ i ];
1811                 
1812                 /* skip this triangle if it has already been merged */
1813                 if( head->si == NULL )
1814                         continue;
1815                 
1816                 /* find end */
1817                 if( j <= i )
1818                 {
1819                         for( j = i + 1; j < numMetaTriangles; j++ )
1820                         {
1821                                 /* get end of list */
1822                                 end = &metaTriangles[ j ];
1823                                 if( head->si != end->si || head->fogNum != end->fogNum )
1824                                         break;
1825                         }
1826                 }
1827                 
1828                 /* try to merge this list of possible merge candidates */
1829                 MetaTrianglesToSurface( (j - i), head, &fOld, &numAdded );
1830         }
1831         
1832         /* clear meta triangle list */
1833         ClearMetaTriangles();
1834         
1835         /* print time */
1836         if( i )
1837                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1838         
1839         /* emit some stats */
1840         Sys_FPrintf( SYS_VRB, "%9d surfaces merged\n", numMergedSurfaces );
1841         Sys_FPrintf( SYS_VRB, "%9d vertexes merged\n", numMergedVerts );
1842 }