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