]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/surface_meta.c
another debug print
[xonotic/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;
421         double A, bestA = -1, V, bestV = -1;
422         vec3_t ab, ac, bc, cross;
423         bspDrawVert_t *buf;
424         double shiftWidth;
425
426         if(cnt < 3)
427                 return 0;
428
429         /* calculate total area */
430         A = 0;
431         for(i = 1; i+1 < cnt; ++i)
432         {
433                 VectorSubtract(vert[i].xyz, vert[0].xyz, ab);
434                 VectorSubtract(vert[i+1].xyz, vert[0].xyz, ac);
435                 CrossProduct(ab, ac, cross);
436                 A += VectorLength(cross);
437         }
438         V = 0;
439         for(i = 0; i < cnt; ++i)
440         {
441                 VectorSubtract(vert[(i+1)%cnt].xyz, vert[i].xyz, ab);
442                 V += VectorLength(ab);
443         }
444
445         /* calculate shift width from the area sensibly, assuming the polygon
446          * fits about 25% of the screen in both dimensions
447          * we assume 1280x1024
448          * 1 pixel is then about sqrt(A) / (0.25 * screenwidth)
449          * 8 pixels are then about sqrt(A) /  (0.25 * 1280) * 8
450          * 8 pixels are then about sqrt(A) * 0.025
451          * */
452         shiftWidth = sqrt(A) * 0.0125;
453         /*     3->1 6->2 12->3 ... */
454         if(A - ceil(log(cnt/1.5) / log(2)) * V * shiftWidth * 2 < 0)
455         {
456                 /* printf("Small triangle detected (area %f, circumference %f), adjusting shiftWidth from %f to ", A, V, shiftWidth); */
457                 shiftWidth = A / (ceil(log(cnt/1.5) / log(2)) * V * 2);
458                 /* printf("%f\n", shiftWidth); */
459         }
460
461         /* find the triangle with highest area */
462         for(r = 0; r+2 < cnt; ++r)
463         for(s = r+1; s+1 < cnt; ++s)
464         for(t = s+1; t < cnt; ++t)
465         {
466                 VectorSubtract(vert[s].xyz, vert[r].xyz, ab);
467                 VectorSubtract(vert[t].xyz, vert[r].xyz, ac);
468                 VectorSubtract(vert[t].xyz, vert[s].xyz, bc);
469                 CrossProduct(ab, ac, cross);
470                 A = VectorLength(cross);
471
472                 V = A - (VectorLength(ab) - VectorLength(ac) - VectorLength(bc)) * shiftWidth;
473                 /* value = A - circumference * shiftWidth, i.e. we back out by shiftWidth units from each side, to prevent too acute triangles */
474                 /* this kind of simulates "number of shiftWidth*shiftWidth fragments in the triangle not touched by an edge" */
475
476                 if(bestA < 0 || V > bestV)
477                 {
478                         bestA = A;
479                         bestV = V;
480                         bestR = r;
481                         bestS = s;
482                         bestT = t;
483                 }
484         }
485
486         /*
487         if(bestV < 0)
488                 printf("value was REALLY bad\n");
489         */
490
491         if(bestA < TINY_AREA)
492                 /* the biggest triangle is degenerate - then every other is too, and the other algorithms wouldn't generate anything useful either */
493                 return 0;
494
495         i = 0;
496         indexes[i++] = bestR;
497         indexes[i++] = bestS;
498         indexes[i++] = bestT;
499                 /* uses 3 */
500
501         /* identify the other fragments */
502
503         /* full polygon without triangle (bestR,bestS,bestT) = three new polygons:
504          * 1. bestR..bestS
505          * 2. bestS..bestT
506          * 3. bestT..bestR
507          */
508
509         j = i + MaxAreaIndexes(vert + bestR, bestS - bestR + 1, indexes + i);
510         for(; i < j; ++i)
511                 indexes[i] += bestR;
512                 /* uses 3*(bestS-bestR+1)-6 */
513         j = i + MaxAreaIndexes(vert + bestS, bestT - bestS + 1, indexes + i);
514         for(; i < j; ++i)
515                 indexes[i] += bestS;
516                 /* uses 3*(bestT-bestS+1)-6 */
517
518         /* can'bestT recurse this one directly... therefore, buffering */
519         if(cnt + bestR - bestT + 1 >= 3)
520         {
521                 buf = safe_malloc(sizeof(*vert) * (cnt + bestR - bestT + 1));
522                 memcpy(buf, vert + bestT, sizeof(*vert) * (cnt - bestT));
523                 memcpy(buf + (cnt - bestT), vert, sizeof(*vert) * (bestR + 1));
524                 j = i + MaxAreaIndexes(buf, cnt + bestR - bestT + 1, indexes + i);
525                 for(; i < j; ++i)
526                         indexes[i] = (indexes[i] + bestT) % cnt;
527                         /* uses 3*(cnt+bestR-bestT+1)-6 */
528                 free(buf);
529         }
530
531         /* together 3 + 3*(cnt+3) - 18 = 3*cnt-6 q.e.d. */
532
533         return i;
534 }
535
536 /*
537 MaxAreaFaceSurface() - divVerent
538 creates a triangle list using max area indexes
539 */
540
541 void MaxAreaFaceSurface(mapDrawSurface_t *ds)
542 {
543         /* try to early out  */
544         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
545                 return;
546
547         /* is this a simple triangle? */
548         if( ds->numVerts == 3 )
549         {
550                 ds->numIndexes = 3;
551                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
552                 VectorSet( ds->indexes, 0, 1, 2 );
553                 numMaxAreaSurfaces++;
554                 return;
555         }
556
557         /* do it! */
558         ds->numIndexes = 3 * ds->numVerts - 6;
559         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
560         ds->numIndexes = MaxAreaIndexes(ds->verts, ds->numVerts, ds->indexes);
561
562         /* add to count */
563         numMaxAreaSurfaces++;
564
565         /* classify it */
566         ClassifySurfaces( 1, ds );
567 }
568
569
570 /*
571 FanFaceSurface() - ydnar
572 creates a tri-fan from a brush face winding
573 loosely based on SurfaceAsTriFan()
574 */
575
576 void FanFaceSurface( mapDrawSurface_t *ds )
577 {
578         int                             i, j, k, a, b, c, color[ MAX_LIGHTMAPS ][ 4 ];
579         bspDrawVert_t   *verts, *centroid, *dv;
580         double                  iv;
581         
582         
583         /* try to early out */
584         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
585                 return;
586         
587         /* add a new vertex at the beginning of the surface */
588         verts = safe_malloc( (ds->numVerts + 1) * sizeof( bspDrawVert_t ) );
589         memset( verts, 0, sizeof( bspDrawVert_t ) );
590         memcpy( &verts[ 1 ], ds->verts, ds->numVerts * sizeof( bspDrawVert_t ) );
591         free( ds->verts );
592         ds->verts = verts;
593         
594         /* add up the drawverts to create a centroid */
595         centroid = &verts[ 0 ];
596         memset( color, 0,  4 * MAX_LIGHTMAPS * sizeof( int ) );
597         for( i = 1, dv = &verts[ 1 ]; i < (ds->numVerts + 1); i++, dv++ )
598         {
599                 VectorAdd( centroid->xyz, dv->xyz, centroid->xyz );
600                 VectorAdd( centroid->normal, dv->normal, centroid->normal );
601                 for( j = 0; j < 4; j++ )
602                 {
603                         for( k = 0; k < MAX_LIGHTMAPS; k++ )
604                                 color[ k ][ j ] += dv->color[ k ][ j ];
605                         if( j < 2 )
606                         {
607                                 centroid->st[ j ] += dv->st[ j ];
608                                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
609                                         centroid->lightmap[ k ][ j ] += dv->lightmap[ k ][ j ];
610                         }
611                 }
612         }
613         
614         /* average the centroid */
615         iv = 1.0f / ds->numVerts;
616         VectorScale( centroid->xyz, iv, centroid->xyz );
617         if( VectorNormalize( centroid->normal, centroid->normal ) <= 0 )
618                 VectorCopy( verts[ 1 ].normal, centroid->normal );
619         for( j = 0; j < 4; j++ )
620         {
621                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
622                 {
623                         color[ k ][ j ] /= ds->numVerts;
624                         centroid->color[ k ][ j ] = (color[ k ][ j ] < 255.0f ? color[ k ][ j ] : 255);
625                 }
626                 if( j < 2 )
627                 {
628                         centroid->st[ j ] *= iv;
629                         for( k = 0; k < MAX_LIGHTMAPS; k++ )
630                                 centroid->lightmap[ k ][ j ] *= iv;
631                 }
632         }
633         
634         /* add to vert count */
635         ds->numVerts++;
636         
637         /* fill indexes in triangle fan order */
638         ds->numIndexes = 0;
639         ds->indexes = safe_malloc( ds->numVerts * 3 * sizeof( int ) );
640         for( i = 1; i < ds->numVerts; i++ )
641         {
642                 a = 0;
643                 b = i;
644                 c = (i + 1) % ds->numVerts;
645                 c = c ? c : 1;
646                 ds->indexes[ ds->numIndexes++ ] = a;
647                 ds->indexes[ ds->numIndexes++ ] = b;
648                 ds->indexes[ ds->numIndexes++ ] = c;
649         }
650         
651         /* add to count */
652         numFanSurfaces++;
653
654         /* classify it */
655         ClassifySurfaces( 1, ds );
656 }
657
658
659
660 /*
661 StripFaceSurface() - ydnar
662 attempts to create a valid tri-strip w/o degenerate triangles from a brush face winding
663 based on SurfaceAsTriStrip()
664 */
665
666 #define MAX_INDEXES             1024
667
668 void StripFaceSurface( mapDrawSurface_t *ds ) 
669 {
670         int                     i, r, least, rotate, numIndexes, ni, a, b, c, indexes[ MAX_INDEXES ];
671         vec_t           *v1, *v2;
672         
673         
674         /* try to early out  */
675         if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
676                 return;
677         
678         /* is this a simple triangle? */
679         if( ds->numVerts == 3 )
680         {
681                 numIndexes = 3;
682                 VectorSet( indexes, 0, 1, 2 );
683         }
684         else
685         {
686                 /* ydnar: find smallest coordinate */
687                 least = 0;
688                 if( ds->shaderInfo != NULL && ds->shaderInfo->autosprite == qfalse )
689                 {
690                         for( i = 0; i < ds->numVerts; i++ )
691                         {
692                                 /* get points */
693                                 v1 = ds->verts[ i ].xyz;
694                                 v2 = ds->verts[ least ].xyz;
695                                 
696                                 /* compare */
697                                 if( v1[ 0 ] < v2[ 0 ] ||
698                                         (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] < v2[ 1 ]) ||
699                                         (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] == v2[ 1 ] && v1[ 2 ] < v2[ 2 ]) )
700                                         least = i;
701                         }
702                 }
703                 
704                 /* determine the triangle strip order */
705                 numIndexes = (ds->numVerts - 2) * 3;
706                 if( numIndexes > MAX_INDEXES )
707                         Error( "MAX_INDEXES exceeded for surface (%d > %d) (%d verts)", numIndexes, MAX_INDEXES, ds->numVerts );
708                 
709                 /* try all possible orderings of the points looking for a non-degenerate strip order */
710                 for( r = 0; r < ds->numVerts; r++ )
711                 {
712                         /* set rotation */
713                         rotate = (r + least) % ds->numVerts;
714                         
715                         /* walk the winding in both directions */
716                         for( ni = 0, i = 0; i < ds->numVerts - 2 - i; i++ )
717                         {
718                                 /* make indexes */
719                                 a = (ds->numVerts - 1 - i + rotate) % ds->numVerts;
720                                 b = (i + rotate ) % ds->numVerts;
721                                 c = (ds->numVerts - 2 - i + rotate) % ds->numVerts;
722                                 
723                                 /* test this triangle */
724                                 if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
725                                         break;
726                                 indexes[ ni++ ] = a;
727                                 indexes[ ni++ ] = b;
728                                 indexes[ ni++ ] = c;
729                                 
730                                 /* handle end case */
731                                 if( i + 1 != ds->numVerts - 1 - i )
732                                 {
733                                         /* make indexes */
734                                         a = (ds->numVerts - 2 - i + rotate ) % ds->numVerts;
735                                         b = (i + rotate ) % ds->numVerts;
736                                         c = (i + 1 + rotate ) % ds->numVerts;
737                                         
738                                         /* test triangle */
739                                         if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
740                                                 break;
741                                         indexes[ ni++ ] = a;
742                                         indexes[ ni++ ] = b;
743                                         indexes[ ni++ ] = c;
744                                 }
745                         }
746                         
747                         /* valid strip? */
748                         if( ni == numIndexes )
749                                 break;
750                 }
751                 
752                 /* if any triangle in the strip is degenerate, render from a centered fan point instead */
753                 if( ni < numIndexes )
754                 {
755                         FanFaceSurface( ds );
756                         return;
757                 }
758         }
759         
760         /* copy strip triangle indexes */
761         ds->numIndexes = numIndexes;
762         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
763         memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
764         
765         /* add to count */
766         numStripSurfaces++;
767         
768         /* classify it */
769         ClassifySurfaces( 1, ds );
770 }
771  
772  
773 /*
774 EmitMetaStatictics
775 vortex: prints meta statistics in general output
776 */
777
778 void EmitMetaStats()
779 {
780         Sys_Printf( "--- EmitMetaStats ---\n" );
781         Sys_Printf( "%9d total meta surfaces\n", numMetaSurfaces );
782         Sys_Printf( "%9d stripped surfaces\n", numStripSurfaces );
783         Sys_Printf( "%9d fanned surfaces\n", numFanSurfaces );
784         Sys_Printf( "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
785         Sys_Printf( "%9d patch meta surfaces\n", numPatchMetaSurfaces );
786         Sys_Printf( "%9d meta verts\n", numMetaVerts );
787         Sys_Printf( "%9d meta triangles\n", numMetaTriangles );
788 }
789
790 /*
791 MakeEntityMetaTriangles()
792 builds meta triangles from brush faces (tristrips and fans)
793 */
794
795 void MakeEntityMetaTriangles( entity_t *e )
796 {
797         int                                     i, f, fOld, start;
798         mapDrawSurface_t        *ds;
799         
800         
801         /* note it */
802         Sys_FPrintf( SYS_VRB, "--- MakeEntityMetaTriangles ---\n" );
803         
804         /* init pacifier */
805         fOld = -1;
806         start = I_FloatTime();
807         
808         /* walk the list of surfaces in the entity */
809         for( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ )
810         {
811                 /* print pacifier */
812                 f = 10 * (i - e->firstDrawSurf) / (numMapDrawSurfs - e->firstDrawSurf);
813                 if( f != fOld )
814                 {
815                         fOld = f;
816                         Sys_FPrintf( SYS_VRB, "%d...", f );
817                 }
818                 
819                 /* get surface */
820                 ds = &mapDrawSurfs[ i ];
821                 if( ds->numVerts <= 0 )
822                         continue;
823                 
824                 /* ignore autosprite surfaces */
825                 if( ds->shaderInfo->autosprite )
826                         continue;
827                 
828                 /* meta this surface? */
829                 if( meta == qfalse && ds->shaderInfo->forceMeta == qfalse )
830                         continue;
831                 
832                 /* switch on type */
833                 switch( ds->type )
834                 {
835                         case SURFACE_FACE:
836                         case SURFACE_DECAL:
837                                 if(maxAreaFaceSurface)
838                                         MaxAreaFaceSurface( ds );
839                                 else
840                                         StripFaceSurface( ds );
841                                 SurfaceToMetaTriangles( ds );
842                                 break;
843                         
844                         case SURFACE_PATCH:
845                                 TriangulatePatchSurface(e, ds );
846                                 break;
847                         
848                         case SURFACE_TRIANGLES:
849                                 break;
850                 
851                         case SURFACE_FORCED_META:
852                         case SURFACE_META:
853                                 SurfaceToMetaTriangles( ds );
854                                 break;
855                         
856                         default:
857                                 break;
858                 }
859         }
860         
861         /* print time */
862         if( (numMapDrawSurfs - e->firstDrawSurf) )
863                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
864         
865         /* emit some stats */
866         Sys_FPrintf( SYS_VRB, "%9d total meta surfaces\n", numMetaSurfaces );
867         Sys_FPrintf( SYS_VRB, "%9d stripped surfaces\n", numStripSurfaces );
868         Sys_FPrintf( SYS_VRB, "%9d fanned surfaces\n", numFanSurfaces );
869         Sys_FPrintf( SYS_VRB, "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
870         Sys_FPrintf( SYS_VRB, "%9d patch meta surfaces\n", numPatchMetaSurfaces );
871         Sys_FPrintf( SYS_VRB, "%9d meta verts\n", numMetaVerts );
872         Sys_FPrintf( SYS_VRB, "%9d meta triangles\n", numMetaTriangles );
873         
874         /* tidy things up */
875         TidyEntitySurfaces( e );
876 }
877
878
879
880 /*
881 PointTriangleIntersect()
882 assuming that all points lie in plane, determine if pt
883 is inside the triangle abc
884 code originally (c) 2001 softSurfer (www.softsurfer.com)
885 */
886
887 #define MIN_OUTSIDE_EPSILON             -0.01f
888 #define MAX_OUTSIDE_EPSILON             1.01f
889
890 static qboolean PointTriangleIntersect( vec3_t pt, vec4_t plane, vec3_t a, vec3_t b, vec3_t c, vec3_t bary )
891 {
892         vec3_t  u, v, w;
893         float   uu, uv, vv, wu, wv, d;
894         
895         
896         /* make vectors */
897         VectorSubtract( b, a, u );
898         VectorSubtract( c, a, v );
899         VectorSubtract( pt, a, w );
900         
901         /* more setup */
902         uu = DotProduct( u, u );
903         uv = DotProduct( u, v );
904         vv = DotProduct( v, v );
905         wu = DotProduct( w, u );
906         wv = DotProduct( w, v );
907         d = uv * uv - uu * vv;
908         
909         /* calculate barycentric coordinates */
910         bary[ 1 ] = (uv * wv - vv * wu) / d;
911         if( bary[ 1 ] < MIN_OUTSIDE_EPSILON || bary[ 1 ] > MAX_OUTSIDE_EPSILON )
912                 return qfalse;
913         bary[ 2 ] = (uv * wv - uu * wv) / d;
914         if( bary[ 2 ] < MIN_OUTSIDE_EPSILON || bary[ 2 ] > MAX_OUTSIDE_EPSILON )
915                 return qfalse;
916         bary[ 0 ] = 1.0f - (bary[ 1 ] + bary[ 2 ]);
917         
918         /* point is in triangle */
919         return qtrue;
920 }
921
922
923
924 /*
925 CreateEdge()
926 sets up an edge structure from a plane and 2 points that the edge ab falls lies in
927 */
928
929 typedef struct edge_s
930 {
931         vec3_t  origin, edge;
932         vec_t   length, kingpinLength;
933         int             kingpin;
934         vec4_t  plane;
935 }
936 edge_t;
937
938 void CreateEdge( vec4_t plane, vec3_t a, vec3_t b, edge_t *edge )
939 {
940         /* copy edge origin */
941         VectorCopy( a, edge->origin );
942         
943         /* create vector aligned with winding direction of edge */
944         VectorSubtract( b, a, edge->edge );
945         
946         if( fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 1 ] ) && fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 2 ] ) )
947                 edge->kingpin = 0;
948         else if( fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 0 ] ) && fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 2 ] ) )
949                 edge->kingpin = 1;
950         else
951                 edge->kingpin = 2;
952         edge->kingpinLength = edge->edge[ edge->kingpin ];
953         
954         VectorNormalize( edge->edge, edge->edge );
955         edge->edge[ 3 ] = DotProduct( a, edge->edge );
956         edge->length = DotProduct( b, edge->edge ) - edge->edge[ 3 ];
957         
958         /* create perpendicular plane that edge lies in */
959         CrossProduct( plane, edge->edge, edge->plane );
960         edge->plane[ 3 ] = DotProduct( a, edge->plane );
961 }
962
963
964
965 /*
966 FixMetaTJunctions()
967 fixes t-junctions on meta triangles
968 */
969
970 #define TJ_PLANE_EPSILON        (1.0f / 8.0f)
971 #define TJ_EDGE_EPSILON         (1.0f / 8.0f)
972 #define TJ_POINT_EPSILON        (1.0f / 8.0f)
973
974 void FixMetaTJunctions( void )
975 {
976         int                             i, j, k, f, fOld, start, vertIndex, triIndex, numTJuncs;
977         metaTriangle_t  *tri, *newTri;
978         shaderInfo_t    *si;
979         bspDrawVert_t   *a, *b, *c, junc;
980         float                   dist, amount;
981         vec3_t                  pt;
982         vec4_t                  plane;
983         edge_t                  edges[ 3 ];
984         
985         
986         /* this code is crap; revisit later */
987         return;
988         
989         /* note it */
990         Sys_FPrintf( SYS_VRB, "--- FixMetaTJunctions ---\n" );
991         
992         /* init pacifier */
993         fOld = -1;
994         start = I_FloatTime();
995         
996         /* walk triangle list */
997         numTJuncs = 0;
998         for( i = 0; i < numMetaTriangles; i++ )
999         {
1000                 /* get triangle */
1001                 tri = &metaTriangles[ i ];
1002                 
1003                 /* print pacifier */
1004                 f = 10 * i / numMetaTriangles;
1005                 if( f != fOld )
1006                 {
1007                         fOld = f;
1008                         Sys_FPrintf( SYS_VRB, "%d...", f );
1009                 }
1010                 
1011                 /* attempt to early out */
1012                 si = tri->si;
1013                 if( (si->compileFlags & C_NODRAW) || si->autosprite || si->notjunc )
1014                         continue;
1015                 
1016                 /* calculate planes */
1017                 VectorCopy( tri->plane, plane );
1018                 plane[ 3 ] = tri->plane[ 3 ];
1019                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1020                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1021                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1022                 
1023                 /* walk meta vert list */
1024                 for( j = 0; j < numMetaVerts; j++ )
1025                 {
1026                         /* get vert */
1027                         VectorCopy( metaVerts[ j ].xyz, pt );
1028
1029                         /* debug code: darken verts */
1030                         if( i == 0 )
1031                                 VectorSet( metaVerts[ j ].color[ 0 ], 8, 8, 8 );
1032                         
1033                         /* determine if point lies in the triangle's plane */
1034                         dist = DotProduct( pt, plane ) - plane[ 3 ];
1035                         if( fabs( dist ) > TJ_PLANE_EPSILON )
1036                                 continue;
1037                         
1038                         /* skip this point if it already exists in the triangle */
1039                         for( k = 0; k < 3; k++ )
1040                         {
1041                                 if( fabs( pt[ 0 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 0 ] ) <= TJ_POINT_EPSILON &&
1042                                         fabs( pt[ 1 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 1 ] ) <= TJ_POINT_EPSILON &&
1043                                         fabs( pt[ 2 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 2 ] ) <= TJ_POINT_EPSILON )
1044                                         break;
1045                         }
1046                         if( k < 3 )
1047                                 continue;
1048                         
1049                         /* walk edges */
1050                         for( k = 0; k < 3; k++ )
1051                         {
1052                                 /* ignore bogus edges */
1053                                 if( fabs( edges[ k ].kingpinLength ) < TJ_EDGE_EPSILON )
1054                                         continue;
1055                                 
1056                                 /* determine if point lies on the edge */
1057                                 dist = DotProduct( pt, edges[ k ].plane ) - edges[ k ].plane[ 3 ];
1058                                 if( fabs( dist ) > TJ_EDGE_EPSILON )
1059                                         continue;
1060                                 
1061                                 /* determine how far along the edge the point lies */
1062                                 amount = (pt[ edges[ k ].kingpin ] - edges[ k ].origin[ edges[ k ].kingpin ]) / edges[ k ].kingpinLength;
1063                                 if( amount <= 0.0f || amount >= 1.0f )
1064                                         continue;
1065                                 
1066                                 #if 0
1067                                 dist = DotProduct( pt, edges[ k ].edge ) - edges[ k ].edge[ 3 ];
1068                                 if( dist <= -0.0f || dist >= edges[ k ].length )
1069                                         continue;
1070                                 amount = dist / edges[ k ].length;
1071                                 #endif
1072                                 
1073                                 /* debug code: brighten this point */
1074                                 //%     metaVerts[ j ].color[ 0 ][ 0 ] += 5;
1075                                 //%     metaVerts[ j ].color[ 0 ][ 1 ] += 4;
1076                                 VectorSet( metaVerts[ tri->indexes[ k ] ].color[ 0 ], 255, 204, 0 );
1077                                 VectorSet( metaVerts[ tri->indexes[ (k + 1) % 3 ] ].color[ 0 ], 255, 204, 0 );
1078                                 
1079
1080                                 /* the edge opposite the zero-weighted vertex was hit, so use that as an amount */
1081                                 a = &metaVerts[ tri->indexes[ k % 3 ] ];
1082                                 b = &metaVerts[ tri->indexes[ (k + 1) % 3 ] ];
1083                                 c = &metaVerts[ tri->indexes[ (k + 2) % 3 ] ];
1084                                 
1085                                 /* make new vert */
1086                                 LerpDrawVertAmount( a, b, amount, &junc );
1087                                 VectorCopy( pt, junc.xyz );
1088                                 
1089                                 /* compare against existing verts */
1090                                 if( VectorCompare( junc.xyz, a->xyz ) || VectorCompare( junc.xyz, b->xyz ) || VectorCompare( junc.xyz, c->xyz ) )
1091                                         continue;
1092                                 
1093                                 /* see if we can just re-use the existing vert */
1094                                 if( !memcmp( &metaVerts[ j ], &junc, sizeof( junc ) ) )
1095                                         vertIndex = j;
1096                                 else
1097                                 {
1098                                         /* find new vertex (note: a and b are invalid pointers after this) */
1099                                         firstSearchMetaVert = numMetaVerts;
1100                                         vertIndex = FindMetaVertex( &junc );
1101                                         if( vertIndex < 0 )
1102                                                 continue;
1103                                 }
1104                                                 
1105                                 /* make new triangle */
1106                                 triIndex = AddMetaTriangle();
1107                                 if( triIndex < 0 )
1108                                         continue;
1109                                 
1110                                 /* get triangles */
1111                                 tri = &metaTriangles[ i ];
1112                                 newTri = &metaTriangles[ triIndex ];
1113                                 
1114                                 /* copy the triangle */
1115                                 memcpy( newTri, tri, sizeof( *tri ) );
1116                                 
1117                                 /* fix verts */
1118                                 tri->indexes[ (k + 1) % 3 ] = vertIndex;
1119                                 newTri->indexes[ k ] = vertIndex;
1120                                 
1121                                 /* recalculate edges */
1122                                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1123                                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1124                                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1125                                 
1126                                 /* debug code */
1127                                 metaVerts[ vertIndex ].color[ 0 ][ 0 ] = 255;
1128                                 metaVerts[ vertIndex ].color[ 0 ][ 1 ] = 204;
1129                                 metaVerts[ vertIndex ].color[ 0 ][ 2 ] = 0;
1130                                 
1131                                 /* add to counter and end processing of this vert */
1132                                 numTJuncs++;
1133                                 break;
1134                         }
1135                 }
1136         }
1137         
1138         /* print time */
1139         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1140         
1141         /* emit some stats */
1142         Sys_FPrintf( SYS_VRB, "%9d T-junctions added\n", numTJuncs );
1143 }
1144
1145
1146
1147 /*
1148 SmoothMetaTriangles()
1149 averages coincident vertex normals in the meta triangles
1150 */
1151
1152 #define MAX_SAMPLES                             256
1153 #define THETA_EPSILON                   0.000001
1154 #define EQUAL_NORMAL_EPSILON    0.01
1155
1156 void SmoothMetaTriangles( void )
1157 {
1158         int                             i, j, k, f, fOld, start, cs, numVerts, numVotes, numSmoothed;
1159         float                   shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle;
1160         metaTriangle_t  *tri;
1161         float                   *shadeAngles;
1162         byte                    *smoothed;
1163         vec3_t                  average, diff;
1164         int                             indexes[ MAX_SAMPLES ];
1165         vec3_t                  votes[ MAX_SAMPLES ];
1166         
1167         /* note it */
1168         Sys_FPrintf( SYS_VRB, "--- SmoothMetaTriangles ---\n" );
1169         
1170         /* allocate shade angle table */
1171         shadeAngles = safe_malloc( numMetaVerts * sizeof( float ) );
1172         memset( shadeAngles, 0, numMetaVerts * sizeof( float ) );
1173         
1174         /* allocate smoothed table */
1175         cs = (numMetaVerts / 8) + 1;
1176         smoothed = safe_malloc( cs );
1177         memset( smoothed, 0, cs );
1178         
1179         /* set default shade angle */
1180         defaultShadeAngle = DEG2RAD( npDegrees );
1181         maxShadeAngle = 0.0f;
1182         
1183         /* run through every surface and flag verts belonging to non-lightmapped surfaces
1184            and set per-vertex smoothing angle */
1185         for( i = 0, tri = &metaTriangles[ i ]; i < numMetaTriangles; i++, tri++ )
1186         {
1187                 shadeAngle = defaultShadeAngle;
1188
1189                 /* get shade angle from shader */
1190                 if( tri->si->shadeAngleDegrees > 0.0f )
1191                         shadeAngle = DEG2RAD( tri->si->shadeAngleDegrees );
1192                 /* get shade angle from entity */
1193                 else if( tri->shadeAngleDegrees > 0.0f )
1194                         shadeAngle = DEG2RAD( tri->shadeAngleDegrees );
1195                 
1196                 if( shadeAngle <= 0.0f ) 
1197                         shadeAngle = defaultShadeAngle;
1198
1199                 if( shadeAngle > maxShadeAngle )
1200                         maxShadeAngle = shadeAngle;
1201                 
1202                 /* flag its verts */
1203                 for( j = 0; j < 3; j++ )
1204                 {
1205                         shadeAngles[ tri->indexes[ j ] ] = shadeAngle;
1206                         if( shadeAngle <= 0 )
1207                                 smoothed[ tri->indexes[ j ] >> 3 ] |= (1 << (tri->indexes[ j ] & 7));
1208                 }
1209         }
1210         
1211         /* bail if no surfaces have a shade angle */
1212         if( maxShadeAngle <= 0 )
1213         {
1214                 Sys_FPrintf( SYS_VRB, "No smoothing angles specified, aborting\n" );
1215                 free( shadeAngles );
1216                 free( smoothed );
1217                 return;
1218         }
1219         
1220         /* init pacifier */
1221         fOld = -1;
1222         start = I_FloatTime();
1223         
1224         /* go through the list of vertexes */
1225         numSmoothed = 0;
1226         for( i = 0; i < numMetaVerts; i++ )
1227         {
1228                 /* print pacifier */
1229                 f = 10 * i / numMetaVerts;
1230                 if( f != fOld )
1231                 {
1232                         fOld = f;
1233                         Sys_FPrintf( SYS_VRB, "%d...", f );
1234                 }
1235                 
1236                 /* already smoothed? */
1237                 if( smoothed[ i >> 3 ] & (1 << (i & 7)) )
1238                         continue;
1239                 
1240                 /* clear */
1241                 VectorClear( average );
1242                 numVerts = 0;
1243                 numVotes = 0;
1244                 
1245                 /* build a table of coincident vertexes */
1246                 for( j = i; j < numMetaVerts && numVerts < MAX_SAMPLES; j++ )
1247                 {
1248                         /* already smoothed? */
1249                         if( smoothed[ j >> 3 ] & (1 << (j & 7)) )
1250                                 continue;
1251                         
1252                         /* test vertexes */
1253                         if( VectorCompare( metaVerts[ i ].xyz, metaVerts[ j ].xyz ) == qfalse )
1254                                 continue;
1255                         
1256                         /* use smallest shade angle */
1257                         shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]);
1258                         
1259                         /* check shade angle */
1260                         dot = DotProduct( metaVerts[ i ].normal, metaVerts[ j ].normal );
1261                         if( dot > 1.0 )
1262                                 dot = 1.0;
1263                         else if( dot < -1.0 )
1264                                 dot = -1.0;
1265                         testAngle = acos( dot ) + THETA_EPSILON;
1266                         if( testAngle >= shadeAngle )
1267                                 continue;
1268                         
1269                         /* add to the list */
1270                         indexes[ numVerts++ ] = j;
1271                         
1272                         /* flag vertex */
1273                         smoothed[ j >> 3 ] |= (1 << (j & 7));
1274                         
1275                         /* see if this normal has already been voted */
1276                         for( k = 0; k < numVotes; k++ )
1277                         {
1278                                 VectorSubtract( metaVerts[ j ].normal, votes[ k ], diff );
1279                                 if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON &&
1280                                         fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON &&
1281                                         fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON )
1282                                         break;
1283                         }
1284                         
1285                         /* add a new vote? */
1286                         if( k == numVotes && numVotes < MAX_SAMPLES )
1287                         {
1288                                 VectorAdd( average, metaVerts[ j ].normal, average );
1289                                 VectorCopy( metaVerts[ j ].normal, votes[ numVotes ] );
1290                                 numVotes++;
1291                         }
1292                 }
1293                 
1294                 /* don't average for less than 2 verts */
1295                 if( numVerts < 2 )
1296                         continue;
1297                 
1298                 /* average normal */
1299                 if( VectorNormalize( average, average ) > 0 )
1300                 {
1301                         /* smooth */
1302                         for( j = 0; j < numVerts; j++ )
1303                                 VectorCopy( average, metaVerts[ indexes[ j ] ].normal );
1304                         numSmoothed++;
1305                 }
1306         }
1307         
1308         /* free the tables */
1309         free( shadeAngles );
1310         free( smoothed );
1311         
1312         /* print time */
1313         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1314
1315         /* emit some stats */
1316         Sys_FPrintf( SYS_VRB, "%9d smoothed vertexes\n", numSmoothed );
1317 }
1318
1319
1320
1321 /*
1322 AddMetaVertToSurface()
1323 adds a drawvert to a surface unless an existing vert matching already exists
1324 returns the index of that vert (or < 0 on failure)
1325 */
1326
1327 int AddMetaVertToSurface( mapDrawSurface_t *ds, bspDrawVert_t *dv1, int *coincident )
1328 {
1329         int                             i;
1330         bspDrawVert_t   *dv2;
1331         
1332         
1333         /* go through the verts and find a suitable candidate */
1334         for( i = 0; i < ds->numVerts; i++ )
1335         {
1336                 /* get test vert */
1337                 dv2 = &ds->verts[ i ];
1338                 
1339                 /* compare xyz and normal */
1340                 if( VectorCompare( dv1->xyz, dv2->xyz ) == qfalse )
1341                         continue;
1342                 if( VectorCompare( dv1->normal, dv2->normal ) == qfalse )
1343                         continue;
1344                 
1345                 /* good enough at this point */
1346                 (*coincident)++;
1347                 
1348                 /* compare texture coordinates and color */
1349                 if( dv1->st[ 0 ] != dv2->st[ 0 ] || dv1->st[ 1 ] != dv2->st[ 1 ] )
1350                         continue;
1351                 if( dv1->color[ 0 ][ 3 ] != dv2->color[ 0 ][ 3 ] )
1352                         continue;
1353                 
1354                 /* found a winner */
1355                 numMergedVerts++;
1356                 return i;
1357         }
1358
1359         /* overflow check */
1360         if( ds->numVerts >= ((ds->shaderInfo->compileFlags & C_VERTEXLIT) ? maxSurfaceVerts : maxLMSurfaceVerts) )
1361                 return VERTS_EXCEEDED;
1362         
1363         /* made it this far, add the vert and return */
1364         dv2 = &ds->verts[ ds->numVerts++ ];
1365         *dv2 = *dv1;
1366         return (ds->numVerts - 1);
1367 }
1368
1369
1370
1371
1372 /*
1373 AddMetaTriangleToSurface()
1374 attempts to add a metatriangle to a surface
1375 returns the score of the triangle added
1376 */
1377
1378 #define AXIS_SCORE                      100000
1379 #define AXIS_MIN                        100000
1380 #define VERT_SCORE                      10000
1381 #define SURFACE_SCORE           1000
1382 #define ST_SCORE                        50
1383 #define ST_SCORE2                       (2 * (ST_SCORE))
1384
1385 #define ADEQUATE_SCORE          ((AXIS_MIN) + 1 * (VERT_SCORE))
1386 #define GOOD_SCORE                      ((AXIS_MIN) + 2 * (VERT_SCORE)                   + 4 * (ST_SCORE))
1387 #define PERFECT_SCORE           ((AXIS_MIN) + 3 * (VERT_SCORE) + (SURFACE_SCORE) + 4 * (ST_SCORE))
1388 //#define MAX_BBOX_DISTANCE   16
1389
1390 static int AddMetaTriangleToSurface( mapDrawSurface_t *ds, metaTriangle_t *tri, qboolean testAdd )
1391 {
1392         int                                     i, score, coincident, ai, bi, ci, oldTexRange[ 2 ];
1393         float                           lmMax;
1394         vec3_t                          mins, maxs, p;
1395         qboolean                        inTexRange, es, et;
1396         mapDrawSurface_t        old;
1397         
1398         
1399         /* overflow check */
1400         if( ds->numIndexes >= maxSurfaceIndexes )
1401                 return 0;
1402         
1403         /* test the triangle */
1404         if( ds->entityNum != tri->entityNum )   /* ydnar: added 2002-07-06 */
1405                 return 0;
1406         if( ds->castShadows != tri->castShadows || ds->recvShadows != tri->recvShadows )
1407                 return 0;
1408         if( ds->shaderInfo != tri->si || ds->fogNum != tri->fogNum || ds->sampleSize != tri->sampleSize )
1409                 return 0;
1410         #if 0
1411                 if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1412                         //% VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) == qfalse )
1413                         DotProduct( ds->lightmapAxis, tri->plane ) < 0.25f )
1414                         return 0;
1415         #endif
1416         
1417         /* planar surfaces will only merge with triangles in the same plane */
1418         if( npDegrees == 0.0f && ds->shaderInfo->nonplanar == qfalse && ds->planeNum >= 0 )
1419         {
1420                 if( VectorCompare( mapplanes[ ds->planeNum ].normal, tri->plane ) == qfalse || mapplanes[ ds->planeNum ].dist != tri->plane[ 3 ] )
1421                         return 0;
1422                 if( tri->planeNum >= 0 && tri->planeNum != ds->planeNum )
1423                         return 0;
1424         }
1425
1426 #if MAX_BBOX_DISTANCE > 0
1427         VectorCopy( ds->mins, mins );
1428         VectorCopy( ds->maxs, maxs );
1429         mins[0] -= MAX_BBOX_DISTANCE;
1430         mins[1] -= MAX_BBOX_DISTANCE;
1431         mins[2] -= MAX_BBOX_DISTANCE;
1432         maxs[0] += MAX_BBOX_DISTANCE;
1433         maxs[1] += MAX_BBOX_DISTANCE;
1434         maxs[2] += MAX_BBOX_DISTANCE;
1435 #define CHECK_1D(mins, v, maxs) ((mins) <= (v) && (v) <= (maxs))
1436 #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]))
1437         VectorCopy(metaVerts[ tri->indexes[ 0 ] ].xyz, p);
1438         if(!CHECK_3D(mins, p, maxs))
1439         {
1440                 VectorCopy(metaVerts[ tri->indexes[ 1 ] ].xyz, p);
1441                 if(!CHECK_3D(mins, p, maxs))
1442                 {
1443                         VectorCopy(metaVerts[ tri->indexes[ 2 ] ].xyz, p);
1444                         if(!CHECK_3D(mins, p, maxs))
1445                                 return 0;
1446                 }
1447         }
1448 #undef CHECK_3D
1449 #undef CHECK_1D
1450 #endif
1451         
1452         /* set initial score */
1453         score = tri->surfaceNum == ds->surfaceNum ? SURFACE_SCORE : 0;
1454         
1455         /* score the the dot product of lightmap axis to plane */
1456         if( (ds->shaderInfo->compileFlags & C_VERTEXLIT) || VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) )
1457                 score += AXIS_SCORE;
1458         else
1459                 score += AXIS_SCORE * DotProduct( ds->lightmapAxis, tri->plane );
1460         
1461         /* preserve old drawsurface if this fails */
1462         memcpy( &old, ds, sizeof( *ds ) );
1463         
1464         /* attempt to add the verts */
1465         coincident = 0;
1466         ai = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 0 ] ], &coincident );
1467         bi = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 1 ] ], &coincident );
1468         ci = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 2 ] ], &coincident );
1469         
1470         /* check vertex underflow */
1471         if( ai < 0 || bi < 0 || ci < 0 )
1472         {
1473                 memcpy( ds, &old, sizeof( *ds ) );
1474                 return 0;
1475         }
1476         
1477         /* score coincident vertex count (2003-02-14: changed so this only matters on planar surfaces) */
1478         score += (coincident * VERT_SCORE);
1479         
1480         /* add new vertex bounds to mins/maxs */
1481         VectorCopy( ds->mins, mins );
1482         VectorCopy( ds->maxs, maxs );
1483         AddPointToBounds( metaVerts[ tri->indexes[ 0 ] ].xyz, mins, maxs );
1484         AddPointToBounds( metaVerts[ tri->indexes[ 1 ] ].xyz, mins, maxs );
1485         AddPointToBounds( metaVerts[ tri->indexes[ 2 ] ].xyz, mins, maxs );
1486         
1487         /* check lightmap bounds overflow (after at least 1 triangle has been added) */
1488         if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1489                 ds->numIndexes > 0 && VectorLength( ds->lightmapAxis ) > 0.0f &&
1490                 (VectorCompare( ds->mins, mins ) == qfalse || VectorCompare( ds->maxs, maxs ) == qfalse) )
1491         {
1492                 /* set maximum size before lightmap scaling (normally 2032 units) */
1493                 /* 2004-02-24: scale lightmap test size by 2 to catch larger brush faces */
1494                 /* 2004-04-11: reverting to actual lightmap size */
1495                 lmMax = (ds->sampleSize * (ds->shaderInfo->lmCustomWidth - 1));
1496                 for( i = 0; i < 3; i++ )
1497                 {
1498                         if( (maxs[ i ] - mins[ i ]) > lmMax )
1499                         {
1500                                 memcpy( ds, &old, sizeof( *ds ) );
1501                                 return 0;
1502                         }
1503                 }
1504         }
1505         
1506         /* check texture range overflow */
1507         oldTexRange[ 0 ] = ds->texRange[ 0 ];
1508         oldTexRange[ 1 ] = ds->texRange[ 1 ];
1509         inTexRange = CalcSurfaceTextureRange( ds );
1510         
1511         es = (ds->texRange[ 0 ] > oldTexRange[ 0 ]) ? qtrue : qfalse;
1512         et = (ds->texRange[ 1 ] > oldTexRange[ 1 ]) ? qtrue : qfalse;
1513         
1514         if( inTexRange == qfalse && ds->numIndexes > 0 )
1515         {
1516                 memcpy( ds, &old, sizeof( *ds ) );
1517                 return UNSUITABLE_TRIANGLE;
1518         }
1519         
1520         /* score texture range */
1521         if( ds->texRange[ 0 ] <= oldTexRange[ 0 ] )
1522                 score += ST_SCORE2;
1523         else if( ds->texRange[ 0 ] > oldTexRange[ 0 ] && oldTexRange[ 1 ] > oldTexRange[ 0 ] )
1524                 score += ST_SCORE;
1525         
1526         if( ds->texRange[ 1 ] <= oldTexRange[ 1 ] )
1527                 score += ST_SCORE2;
1528         else if( ds->texRange[ 1 ] > oldTexRange[ 1 ] && oldTexRange[ 0 ] > oldTexRange[ 1 ] )
1529                 score += ST_SCORE;
1530         
1531         
1532         /* go through the indexes and try to find an existing triangle that matches abc */
1533         for( i = 0; i < ds->numIndexes; i += 3 )
1534         {
1535                 /* 2002-03-11 (birthday!): rotate the triangle 3x to find an existing triangle */
1536                 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 1 ] && ci == ds->indexes[ i + 2 ]) ||
1537                         (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 1 ] && ai == ds->indexes[ i + 2 ]) ||
1538                         (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 1 ] && bi == ds->indexes[ i + 2 ]) )
1539                 {
1540                         /* triangle already present */
1541                         memcpy( ds, &old, sizeof( *ds ) );
1542                         tri->si = NULL;
1543                         return 0;
1544                 }
1545                 
1546                 /* rotate the triangle 3x to find an inverse triangle (error case) */
1547                 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 2 ] && ci == ds->indexes[ i + 1 ]) ||
1548                         (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 2 ] && ai == ds->indexes[ i + 1 ]) ||
1549                         (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 2 ] && bi == ds->indexes[ i + 1 ]) )
1550                 {
1551                         /* warn about it */
1552                         Sys_Printf( "WARNING: Flipped triangle: (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f)\n",
1553                                 ds->verts[ ai ].xyz[ 0 ], ds->verts[ ai ].xyz[ 1 ], ds->verts[ ai ].xyz[ 2 ],
1554                                 ds->verts[ bi ].xyz[ 0 ], ds->verts[ bi ].xyz[ 1 ], ds->verts[ bi ].xyz[ 2 ],
1555                                 ds->verts[ ci ].xyz[ 0 ], ds->verts[ ci ].xyz[ 1 ], ds->verts[ ci ].xyz[ 2 ] );
1556                         
1557                         /* reverse triangle already present */
1558                         memcpy( ds, &old, sizeof( *ds ) );
1559                         tri->si = NULL;
1560                         return 0;
1561                 }
1562         }
1563         
1564         /* add the triangle indexes */
1565         if( ds->numIndexes < maxSurfaceIndexes )
1566                 ds->indexes[ ds->numIndexes++ ] = ai;
1567         if( ds->numIndexes < maxSurfaceIndexes )
1568                 ds->indexes[ ds->numIndexes++ ] = bi;
1569         if( ds->numIndexes < maxSurfaceIndexes )
1570                 ds->indexes[ ds->numIndexes++ ] = ci;
1571         
1572         /* check index overflow */
1573         if( ds->numIndexes >= maxSurfaceIndexes  )
1574         {
1575                 memcpy( ds, &old, sizeof( *ds ) );
1576                 return 0;
1577         }
1578         
1579         /* sanity check the indexes */
1580         if( ds->numIndexes >= 3 &&
1581                 (ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 2 ] ||
1582                 ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 1 ] ||
1583                 ds->indexes[ ds->numIndexes - 2 ] == ds->indexes[ ds->numIndexes - 1 ]) )
1584                 Sys_Printf( "DEG:%d! ", ds->numVerts );
1585         
1586         /* testing only? */
1587         if( testAdd )
1588                 memcpy( ds, &old, sizeof( *ds ) );
1589         else
1590         {
1591                 /* copy bounds back to surface */
1592                 VectorCopy( mins, ds->mins );
1593                 VectorCopy( maxs, ds->maxs );
1594                 
1595                 /* mark triangle as used */
1596                 tri->si = NULL;
1597         }
1598         
1599         /* add a side reference */
1600         ds->sideRef = AllocSideRef( tri->side, ds->sideRef );
1601         
1602         /* return to sender */
1603         return score;
1604 }
1605
1606
1607
1608 /*
1609 MetaTrianglesToSurface()
1610 creates map drawsurface(s) from the list of possibles
1611 */
1612
1613 static void MetaTrianglesToSurface( int numPossibles, metaTriangle_t *possibles, int *fOld, int *numAdded )
1614 {
1615         int                                     i, j, f, best, score, bestScore;
1616         metaTriangle_t          *seed, *test;
1617         mapDrawSurface_t        *ds;
1618         bspDrawVert_t           *verts;
1619         int                                     *indexes;
1620         qboolean                        added;
1621         
1622         
1623         /* allocate arrays */
1624         verts = safe_malloc( sizeof( *verts ) * maxSurfaceVerts );
1625         indexes = safe_malloc( sizeof( *indexes ) * maxSurfaceIndexes );
1626         
1627         /* walk the list of triangles */
1628         for( i = 0, seed = possibles; i < numPossibles; i++, seed++ )
1629         {
1630                 /* skip this triangle if it has already been merged */
1631                 if( seed->si == NULL )
1632                         continue;
1633                 
1634                 /* -----------------------------------------------------------------
1635                    initial drawsurf construction
1636                    ----------------------------------------------------------------- */
1637                 
1638                 /* start a new drawsurface */
1639                 ds = AllocDrawSurface( SURFACE_META );
1640                 ds->entityNum = seed->entityNum;
1641                 ds->surfaceNum = seed->surfaceNum;
1642                 ds->castShadows = seed->castShadows;
1643                 ds->recvShadows = seed->recvShadows;
1644                 
1645                 ds->shaderInfo = seed->si;
1646                 ds->planeNum = seed->planeNum;
1647                 ds->fogNum = seed->fogNum;
1648                 ds->sampleSize = seed->sampleSize;
1649                 ds->shadeAngleDegrees = seed->shadeAngleDegrees;
1650                 ds->verts = verts;
1651                 ds->indexes = indexes;
1652                 VectorCopy( seed->lightmapAxis, ds->lightmapAxis );
1653                 ds->sideRef = AllocSideRef( seed->side, NULL );
1654                 
1655                 ClearBounds( ds->mins, ds->maxs );
1656                 
1657                 /* clear verts/indexes */
1658                 memset( verts, 0, sizeof( verts ) );
1659                 memset( indexes, 0, sizeof( indexes ) );
1660                 
1661                 /* add the first triangle */
1662                 if( AddMetaTriangleToSurface( ds, seed, qfalse ) )
1663                         (*numAdded)++;
1664                 
1665                 /* -----------------------------------------------------------------
1666                    add triangles
1667                    ----------------------------------------------------------------- */
1668                 
1669                 /* progressively walk the list until no more triangles can be added */
1670                 added = qtrue;
1671                 while( added )
1672                 {
1673                         /* print pacifier */
1674                         f = 10 * *numAdded / numMetaTriangles;
1675                         if( f > *fOld )
1676                         {
1677                                 *fOld = f;
1678                                 Sys_FPrintf( SYS_VRB, "%d...", f );
1679                         }
1680                         
1681                         /* reset best score */
1682                         best = -1;
1683                         bestScore = 0;
1684                         added = qfalse;
1685                         
1686                         /* walk the list of possible candidates for merging */
1687                         for( j = i + 1, test = &possibles[ j ]; j < numPossibles; j++, test++ )
1688                         {
1689                                 /* skip this triangle if it has already been merged */
1690                                 if( test->si == NULL )
1691                                         continue;
1692                                 
1693                                 /* score this triangle */
1694                                 score = AddMetaTriangleToSurface( ds, test, qtrue );
1695                                 if( score > bestScore )
1696                                 {
1697                                         best = j;
1698                                         bestScore = score;
1699                                         
1700                                         /* if we have a score over a certain threshold, just use it */
1701                                         if( bestScore >= GOOD_SCORE )
1702                                         {
1703                                                 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1704                                                         (*numAdded)++;
1705                                                 
1706                                                 /* reset */
1707                                                 best = -1;
1708                                                 bestScore = 0;
1709                                                 added = qtrue;
1710                                         }
1711                                 }
1712                         }
1713                         
1714                         /* add best candidate */
1715                         if( best >= 0 && bestScore > ADEQUATE_SCORE )
1716                         {
1717                                 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1718                                         (*numAdded)++;
1719                                 
1720                                 /* reset */
1721                                 added = qtrue;
1722                         }
1723                 }
1724                 
1725                 /* copy the verts and indexes to the new surface */
1726                 ds->verts = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
1727                 memcpy( ds->verts, verts, ds->numVerts * sizeof( bspDrawVert_t ) );
1728                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
1729                 memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
1730                 
1731                 /* classify the surface */
1732                 ClassifySurfaces( 1, ds );
1733                 
1734                 /* add to count */
1735                 numMergedSurfaces++;
1736         }
1737         
1738         /* free arrays */
1739         free( verts );
1740         free( indexes );
1741 }
1742
1743
1744
1745 /*
1746 CompareMetaTriangles()
1747 compare function for qsort()
1748 */
1749
1750 static int CompareMetaTriangles( const void *a, const void *b )
1751 {
1752         int             i, j, av, bv;
1753         vec3_t  aMins, bMins;
1754         
1755         
1756         /* shader first */
1757         if( ((metaTriangle_t*) a)->si < ((metaTriangle_t*) b)->si )
1758                 return 1;
1759         else if( ((metaTriangle_t*) a)->si > ((metaTriangle_t*) b)->si )
1760                 return -1;
1761         
1762         /* then fog */
1763         else if( ((metaTriangle_t*) a)->fogNum < ((metaTriangle_t*) b)->fogNum )
1764                 return 1;
1765         else if( ((metaTriangle_t*) a)->fogNum > ((metaTriangle_t*) b)->fogNum )
1766                 return -1;
1767         
1768         /* then plane */
1769         #if 0
1770                 else if( npDegrees == 0.0f && ((metaTriangle_t*) a)->si->nonplanar == qfalse &&
1771                         ((metaTriangle_t*) a)->planeNum >= 0 && ((metaTriangle_t*) a)->planeNum >= 0 )
1772                 {
1773                         if( ((metaTriangle_t*) a)->plane[ 3 ] < ((metaTriangle_t*) b)->plane[ 3 ] )
1774                                 return 1;
1775                         else if( ((metaTriangle_t*) a)->plane[ 3 ] > ((metaTriangle_t*) b)->plane[ 3 ] )
1776                                 return -1;
1777                         else if( ((metaTriangle_t*) a)->plane[ 0 ] < ((metaTriangle_t*) b)->plane[ 0 ] )
1778                                 return 1;
1779                         else if( ((metaTriangle_t*) a)->plane[ 0 ] > ((metaTriangle_t*) b)->plane[ 0 ] )
1780                                 return -1;
1781                         else if( ((metaTriangle_t*) a)->plane[ 1 ] < ((metaTriangle_t*) b)->plane[ 1 ] )
1782                                 return 1;
1783                         else if( ((metaTriangle_t*) a)->plane[ 1 ] > ((metaTriangle_t*) b)->plane[ 1 ] )
1784                                 return -1;
1785                         else if( ((metaTriangle_t*) a)->plane[ 2 ] < ((metaTriangle_t*) b)->plane[ 2 ] )
1786                                 return 1;
1787                         else if( ((metaTriangle_t*) a)->plane[ 2 ] > ((metaTriangle_t*) b)->plane[ 2 ] )
1788                                 return -1;
1789                 }
1790         #endif
1791         
1792         /* then position in world */
1793         
1794         /* find mins */
1795         VectorSet( aMins, 999999, 999999, 999999 );
1796         VectorSet( bMins, 999999, 999999, 999999 );
1797         for( i = 0; i < 3; i++ )
1798         {
1799                 av = ((metaTriangle_t*) a)->indexes[ i ];
1800                 bv = ((metaTriangle_t*) b)->indexes[ i ];
1801                 for( j = 0; j < 3; j++ )
1802                 {
1803                         if( metaVerts[ av ].xyz[ j ] < aMins[ j ] )
1804                                 aMins[ j ] = metaVerts[ av ].xyz[ j ];
1805                         if( metaVerts[ bv ].xyz[ j ] < bMins[ j ] )
1806                                 bMins[ j ] = metaVerts[ bv ].xyz[ j ];
1807                 }
1808         }
1809         
1810         /* test it */
1811         for( i = 0; i < 3; i++ )
1812         {
1813                 if( aMins[ i ] < bMins[ i ] )
1814                         return 1;
1815                 else if( aMins[ i ] > bMins[ i ] )
1816                         return -1;
1817         }
1818         
1819         /* functionally equivalent */
1820         return 0;
1821 }
1822
1823
1824
1825 /*
1826 MergeMetaTriangles()
1827 merges meta triangles into drawsurfaces
1828 */
1829
1830 void MergeMetaTriangles( void )
1831 {
1832         int                                     i, j, fOld, start, numAdded;
1833         metaTriangle_t          *head, *end;
1834         
1835         
1836         /* only do this if there are meta triangles */
1837         if( numMetaTriangles <= 0 )
1838                 return;
1839         
1840         /* note it */
1841         Sys_FPrintf( SYS_VRB, "--- MergeMetaTriangles ---\n" );
1842         
1843         /* sort the triangles by shader major, fognum minor */
1844         qsort( metaTriangles, numMetaTriangles, sizeof( metaTriangle_t ), CompareMetaTriangles );
1845
1846         /* init pacifier */
1847         fOld = -1;
1848         start = I_FloatTime();
1849         numAdded = 0;
1850         
1851         /* merge */
1852         for( i = 0, j = 0; i < numMetaTriangles; i = j )
1853         {
1854                 /* get head of list */
1855                 head = &metaTriangles[ i ];
1856                 
1857                 /* skip this triangle if it has already been merged */
1858                 if( head->si == NULL )
1859                         continue;
1860                 
1861                 /* find end */
1862                 if( j <= i )
1863                 {
1864                         for( j = i + 1; j < numMetaTriangles; j++ )
1865                         {
1866                                 /* get end of list */
1867                                 end = &metaTriangles[ j ];
1868                                 if( head->si != end->si || head->fogNum != end->fogNum )
1869                                         break;
1870                         }
1871                 }
1872                 
1873                 /* try to merge this list of possible merge candidates */
1874                 MetaTrianglesToSurface( (j - i), head, &fOld, &numAdded );
1875         }
1876         
1877         /* clear meta triangle list */
1878         ClearMetaTriangles();
1879         
1880         /* print time */
1881         if( i )
1882                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1883         
1884         /* emit some stats */
1885         Sys_FPrintf( SYS_VRB, "%9d surfaces merged\n", numMergedSurfaces );
1886         Sys_FPrintf( SYS_VRB, "%9d vertexes merged\n", numMergedVerts );
1887 }