summaryrefslogtreecommitdiff
path: root/utils/studiomdl/UnifyLODs.cpp
blob: 19bf9d7eeccd7d72c6b58282f647b20b74861113 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 
//
// $NoKeywords: $
//
//=============================================================================//
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <math.h>
#include <float.h>

#include "cmdlib.h"
#include "scriplib.h"
#include "mathlib/mathlib.h"
#include "studio.h"
#include "studiomdl.h"
#include "bone_setup.h"
#include "tier1/strtools.h"
#include "mathlib/vmatrix.h"
#include "optimize.h"

// debugging only - enabling turns off remapping to create all lod vertexes as unique
// to ensure remapping logic does not introduce collapse anomalies
//#define UNIQUE_VERTEXES_FOR_LOD



//-----------------------------------------------------------------------------
// Forward declarations local to this file
//-----------------------------------------------------------------------------
class CVertexDictionary;
struct VertexInfo_t;
static void BuildBoneLODMapping( CUtlVector<int> &boneMap, int lodID );


//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
static int g_NumBonesInLOD[MAX_NUM_LODS];


//-----------------------------------------------------------------------------
// Makes sure all boneweights in a s_boneweight_t are valid
//-----------------------------------------------------------------------------
static void ValidateBoneWeight( const s_boneweight_t &boneWeight )
{
#ifdef _DEBUG
	int i;
	if( boneWeight.weight[0] == 1.0f )
	{
		Assert( boneWeight.numbones == 1 );
	}
	for( i = 0; i < boneWeight.numbones; i++ )
	{
		Assert( boneWeight.bone[i] >= 0 && boneWeight.bone[i] < g_numbones );
	}

	float weight = 0.0f;
	for( i = 0; i < boneWeight.numbones; i++ )
	{
		weight += boneWeight.weight[i] ;
	}
	Assert( fabs( weight - 1.0f ) < 1e-3 );
#endif
}


//-----------------------------------------------------------------------------
// Swap bones
//-----------------------------------------------------------------------------
static inline void SwapBones( s_boneweight_t &boneWeight, int nBone1, int nBone2 )
{
	// swap
	int nTmpBone = boneWeight.bone[nBone1];
	float flTmpWeight = boneWeight.weight[nBone1];
	boneWeight.bone[nBone1] = boneWeight.bone[nBone2];
	boneWeight.weight[nBone1] = boneWeight.weight[nBone2];
	boneWeight.bone[nBone2] = nTmpBone;
	boneWeight.weight[nBone2] = flTmpWeight;
}


//-----------------------------------------------------------------------------
// Sort the bone weight structure to be sorted by bone weight
//-----------------------------------------------------------------------------
static void SortBoneWeightByWeight( s_boneweight_t &boneWeight )
{
	// bubble sort the bones by weight. . .put the largest weight first.
	for( int j = boneWeight.numbones; j > 1; j-- )
	{
		for( int k = 0; k < j - 1; k++ )
		{
			if( boneWeight.weight[k] >= boneWeight.weight[k+1] )
				continue;

			SwapBones( boneWeight, k, k+1 );
		}
	}
}


//-----------------------------------------------------------------------------
// Sort the bone weight structure to be sorted by bone index
//-----------------------------------------------------------------------------
static void SortBoneWeightByIndex( s_boneweight_t &boneWeight )
{
	// bubble sort the bones by index. . .put the smallest index first.
	for ( int j = boneWeight.numbones; j > 1; j-- )
	{
		for( int k = 0; k < j - 1; k++ )
		{
			if( boneWeight.bone[k] <= boneWeight.bone[k+1] )
				continue;

			SwapBones( boneWeight, k, k+1 );
		}
	}
}


//-----------------------------------------------------------------------------
// A vertex format
//-----------------------------------------------------------------------------
struct VertexInfo_t
{
	Vector			m_Position;
	Vector			m_Normal;
	Vector2D		m_TexCoord;
	Vector4D		m_TangentS;
	s_boneweight_t	m_BoneWeight;
	int				m_nLodFlag;
};


//-----------------------------------------------------------------------------
// Stores all vertices in the vertex dictionary
//-----------------------------------------------------------------------------
class CVertexDictionary
{
public:
	CVertexDictionary();

	// Adds a vertex to the dictionary
	int AddVertex( const VertexInfo_t &srcVertex );
	int AddVertexFromSource( const s_source_t *pSrc, int nVertexIndex, int nLod );

	// Iteration
	int VertexCount() const;
	VertexInfo_t &Vertex( int i );
	const VertexInfo_t &Vertex( int i ) const;

	int RootLODVertexStart() const;
	int RootLODVertexEnd() const;

	// Gets the vertex count for the previous LOD
	int PrevLODVertexCount() const;

	// Marks the dictionary as starting defining vertices for a new LOD
	void StartNewLOD();

	void SetRootVertexRange( int start, int end );

private:
	CUtlVector<VertexInfo_t>	m_Verts;
	int							m_nPrevLODCount;
	int							m_nRootLODStart;
	int							m_nRootLODEnd;
};


//-----------------------------------------------------------------------------
// Copies in a particular vertex from the s_source_t
//-----------------------------------------------------------------------------
CVertexDictionary::CVertexDictionary()
{
	m_nPrevLODCount = 0;
}


//-----------------------------------------------------------------------------
// Accessor
//-----------------------------------------------------------------------------
inline VertexInfo_t &CVertexDictionary::Vertex( int i )
{
	return m_Verts[i];
}

inline const VertexInfo_t &CVertexDictionary::Vertex( int i ) const
{
	return m_Verts[i];
}

	
//-----------------------------------------------------------------------------
// Gets the vertex count for the previous LOD
//-----------------------------------------------------------------------------
inline int CVertexDictionary::PrevLODVertexCount() const
{
	return m_nPrevLODCount;
}


inline int CVertexDictionary::RootLODVertexStart() const
{
	return m_nRootLODStart;
}


inline int CVertexDictionary::RootLODVertexEnd() const
{
	return m_nRootLODEnd;
}

	
//-----------------------------------------------------------------------------
// Marks the dictionary as starting defining vertices for a new LOD
//-----------------------------------------------------------------------------
void CVertexDictionary::StartNewLOD()
{
	m_nPrevLODCount = VertexCount();
}


void CVertexDictionary::SetRootVertexRange( int start, int end )
{
	m_nRootLODStart = start;
	m_nRootLODEnd   = end;
}

	
//-----------------------------------------------------------------------------
// Adds a vertex to the dictionary
//-----------------------------------------------------------------------------
int CVertexDictionary::AddVertex( const VertexInfo_t &srcVertex )
{
	int nDstVertID = m_Verts.AddToTail( srcVertex );
	VertexInfo_t &vertex = m_Verts[ nDstVertID ];
	ValidateBoneWeight( vertex.m_BoneWeight );
	SortBoneWeightByIndex( vertex.m_BoneWeight );
	ValidateBoneWeight( vertex.m_BoneWeight );

	return nDstVertID;
}


//-----------------------------------------------------------------------------
// Copies in a particular vertex from the s_source_t
//-----------------------------------------------------------------------------
int CVertexDictionary::AddVertexFromSource( const s_source_t *pSrc, int nVertexIndex, int nLod )
{
	int nDstVertID = m_Verts.AddToTail( );
	VertexInfo_t &vertex = m_Verts[ nDstVertID ];

	const s_vertexinfo_t &srcVertex = pSrc->m_GlobalVertices[nVertexIndex];
	vertex.m_Position   = srcVertex.position;
	vertex.m_Normal     = srcVertex.normal;
	vertex.m_TexCoord   = srcVertex.texcoord;
	vertex.m_TangentS   = srcVertex.tangentS;
	vertex.m_BoneWeight = srcVertex.boneweight;
	vertex.m_nLodFlag	= 1 << nLod;

	ValidateBoneWeight( vertex.m_BoneWeight );
	SortBoneWeightByIndex( vertex.m_BoneWeight );
	ValidateBoneWeight( vertex.m_BoneWeight );

	return nDstVertID;
}


//-----------------------------------------------------------------------------
// How many vertices in the dictionary?
//-----------------------------------------------------------------------------
int CVertexDictionary::VertexCount() const
{
	return m_Verts.Count();
}


s_source_t* GetModelLODSource( const char *pModelName, 
								const LodScriptData_t& scriptLOD, bool* pFound )
{
	// When doing LOD replacement, ignore all path + extension information
	char* pTempBuf = (char*)_alloca( Q_strlen(pModelName) + 1 );

	// Strip off extensions for the source...
	strcpy( pTempBuf, pModelName ); 
	char* pDot = strrchr( pTempBuf, '.' );
	if (pDot)
	{
		*pDot = 0;
	}

	for( int i = 0; i < scriptLOD.modelReplacements.Count(); i++ )
	{
		// FIXME: Should we strip off path information?
//		char* pSlash = strrchr( pTempBuf1, '\\' );
//		char* pSlash2 = strrchr( pTempBuf1, '/' );
//		if (pSlash2 > pSlash)
//			pSlash = pSlash2;
//		if (!pSlash)
//			pSlash = pTempBuf1;

		if( !Q_stricmp( pTempBuf, scriptLOD.modelReplacements[i].GetSrcName() ) )
		{
			*pFound = true;
			return scriptLOD.modelReplacements[i].m_pSource;
		}
	}

	*pFound = false;
	return 0;
}


//-----------------------------------------------------------------------------
// Tolerances for all fields of the vertex
//-----------------------------------------------------------------------------
#define POSITION_EPSILON	0.01f	// Was 0.05f
#define TEXCOORD_EPSILON	0.01f
#define NORMAL_EPSILON		10.0f	// in degrees
#define TANGENT_EPSILON		10.0f	// in degrees
#define BONEWEIGHT_EPSILON	0.05f

#define UNMATCHED_BONE_WEIGHT 1.0f

//-----------------------------------------------------------------------------
// Computes error between two positions; returns false if the error is too great
//-----------------------------------------------------------------------------
bool ComparePositionFuzzy( const Vector &p1, const Vector &p2, float &flError )
{
	Vector vecDelta;
	VectorSubtract( p1, p2, vecDelta );
	flError = DotProduct( vecDelta, vecDelta );
	return ( flError <= (POSITION_EPSILON * POSITION_EPSILON) );
}


//-----------------------------------------------------------------------------
// Computes error between two normals; returns false if the error is too great
//-----------------------------------------------------------------------------
bool CompareNormalFuzzy( const Vector &n1, const Vector &n2, float &flError )
{ 
	static float flEpsilon = cos( DEG2RAD( NORMAL_EPSILON ) );

	Vector v1, v2;
	v1 = n1;
	v2 = n2;
	VectorNormalize( v1 );
	VectorNormalize( v2 );
	float flDot = DotProduct( v1, v2 );
	flError = 1.0F - flDot;
	return ( flDot >= flEpsilon );
}

//-----------------------------------------------------------------------------
// Computes error between two tangentS vectors; returns false if the error is too great
//-----------------------------------------------------------------------------
bool CompareTangentSFuzzy( const Vector4D &n1, const Vector4D &n2, float &flError )
{ 
	static float flEpsilon = cos( DEG2RAD( TANGENT_EPSILON ) );

	Vector4D v1, v2;
	v1 = n1;
	v2 = n2;

	if (v1.w != v2.w)
	{
		// must match as -1 or 1
		flError = 2;
		return false;
	}

	VectorNormalize( v1.AsVector3D() );
	VectorNormalize( v2.AsVector3D() );
	float flDot = DotProduct( v1.AsVector3D(), v2.AsVector3D() );

	// error ranges from [0..2]
	flError = 1.0F - flDot;

	return ( flDot >= flEpsilon );
}

//-----------------------------------------------------------------------------
// Computes error between two texcoords; returns false if the error is too great
//-----------------------------------------------------------------------------
bool CompareTexCoordsFuzzy( const Vector2D &t1, const Vector2D &t2, float &flError )
{
	Vector2D vecError;
	vecError[0] = fabs( t2[0] - t1[0] );
	vecError[1] = fabs( t2[1] - t1[1] );
	flError = vecError.LengthSqr();
	return ( flError <= (TEXCOORD_EPSILON * TEXCOORD_EPSILON) );
}


//-----------------------------------------------------------------------------
// Computes the error between two bone weights, returns false if they are too far
//-----------------------------------------------------------------------------
bool CompareBoneWeightsFuzzy( const s_boneweight_t &b1, const s_boneweight_t &b2, float &flError )
{
	// This is a list of which bones that exist in b1 also exist in b2.
	// Use the index to figure out where in the array for b2 that the corresponding bone in b1 is.
	int nMatchingBones = 0;
	int pBoneIndexMap1[MAX_NUM_BONES_PER_VERT]; 
	int pBoneIndexMap2[MAX_NUM_BONES_PER_VERT]; 

	int i;
	for ( i = 0; i < b2.numbones; ++i )
	{
		pBoneIndexMap2[i] = -1;
	}

	for ( i = 0; i < b1.numbones; ++i )
	{
		pBoneIndexMap1[i] = -1;
		for ( int j = 0; j < b2.numbones; ++j )
		{
			if ( b2.bone[j] == b1.bone[i] )
			{
				pBoneIndexMap1[i] = j;
				pBoneIndexMap2[j] = i;
				++nMatchingBones;
				break;
			}
		}
	}

	// If no bones match, we're done
	if ( !nMatchingBones )
	{
		flError = FLT_MAX;
		return false;
	}

	// At least one bone matches, so we're going to consider this vertex as a potential match
	// This loop will take care of figuring out the error for all bones that exist in
	// b1 alone, and all bones that exist in b1 and b2
	flError = 0;
	for ( i = 0; i < b1.numbones; ++i )
	{
		// If we didn't find a match for this bone, compute a more expensive weight
		if ( pBoneIndexMap1[i] == -1 )
		{
			flError += b1.weight[i] * b1.weight[i] * UNMATCHED_BONE_WEIGHT;
			continue;
		}

		float flDeltaWeight = fabs( b1.weight[i] - b2.weight[ pBoneIndexMap1[i] ] );
		flError += flDeltaWeight * flDeltaWeight;
	}

	// This loop will take care of figuring out the error for all bones that exist in b2 alone
	for ( i = 0; i < b2.numbones; ++i )
	{
		// If we didn't find a match for this bone, compute a more expensive weight
		if ( pBoneIndexMap2[i] == -1 )
		{
			flError += b2.weight[i] * b2.weight[i] * UNMATCHED_BONE_WEIGHT;
		}
	}

	// This renormalizes the error. The error will become greater with the total
	// number of bones in the two vertices.
	flError /= sqrt( (float) (b1.numbones + b2.numbones));
	return ( flError <= BONEWEIGHT_EPSILON );
}


//-----------------------------------------------------------------------------
// Searches for a material in the texture list
//-----------------------------------------------------------------------------
int FindMaterialByName( const char *pMaterialName )
{
	int i;
	int allocLen = strlen( pMaterialName ) + 1;
	char *pBaseName = ( char * )_alloca( allocLen );
	Q_FileBase( ( char * )pMaterialName, pBaseName, allocLen );

	for( i = 0; i < g_numtextures; i++ )
	{
		if( stricmp( pBaseName, g_texture[i].name ) == 0 )
		{
			return i;
		}
	}
	return -1;
}

static s_mesh_t *FindMeshByMaterial( s_source_t *pSrc, int nMaterialID )
{
	for ( int m = 0; m < pSrc->nummeshes; m++ )
	{
		if ( pSrc->meshindex[m] == nMaterialID )
			return &pSrc->mesh[ pSrc->meshindex[m] ];
	}
	
	// this mesh/material doesn't exist at this lod.
	return NULL;
}


static s_mesh_t *FindOrCullMesh( int nLodID, s_source_t *pSrc, int nMaterialID )
{
	char	baseMeshName[MAX_PATH];
	char	baseRemovalName[MAX_PATH];

	// possibly marked for removal via $removemesh
	// determine mesh name
	int nTextureID = MaterialToTexture( nMaterialID );
	if (nTextureID == -1)
	{
		MdlError( "Unknown Texture for Material %d\n", nMaterialID );
	}

	Q_FileBase(g_texture[nTextureID].name, baseMeshName, sizeof(baseMeshName)-1);
	for ( int i = 0; i < g_ScriptLODs[nLodID].meshRemovals.Count(); i++ )
	{
		const char *pMeshRemovalName = g_ScriptLODs[nLodID].meshRemovals[i].GetSrcName();
		Q_FileBase( pMeshRemovalName, baseRemovalName, sizeof(baseRemovalName)-1);

		if (!stricmp( baseRemovalName, baseMeshName ))
		{
			// mesh has been marked for removal
			return NULL;
		}
	}

	s_mesh_t *pMesh = FindMeshByMaterial( pSrc, nMaterialID );
	return pMesh;
}


static void CopyVerts( int nLodID, const s_source_t *pSrc, const s_mesh_t *pSrcMesh, CVertexDictionary &vertexDict, s_mesh_t *pDstMesh, int *pMeshVertIndexMap )
{
	// populate the dictionary with the verts
	for( int srcVertID = 0; srcVertID < pSrcMesh->numvertices; srcVertID++ )
	{
		int nVertexIndex = pSrcMesh->vertexoffset + srcVertID;
		pMeshVertIndexMap[ nVertexIndex ] = vertexDict.AddVertexFromSource( pSrc, nVertexIndex, nLodID ) - pDstMesh->vertexoffset;
	}

	pDstMesh->numvertices = pSrcMesh->numvertices;
}

static void CopyFaces( const s_source_t *pSrc, const s_mesh_t *pSrcMesh, CUtlVector<s_face_t> &faces, s_mesh_t *pDstMesh )
{
	int srcFaceID;
	for( srcFaceID = 0; srcFaceID < pSrcMesh->numfaces; srcFaceID++ )
	{
		int srcID = srcFaceID + pSrcMesh->faceoffset;
		s_face_t *pSrcFace = &pSrc->face[srcID];
		s_face_t *pDstFace = &faces[faces.AddToTail()];
		pDstFace->a = pSrcFace->a;
		pDstFace->b = pSrcFace->b;
		pDstFace->c = pSrcFace->c;
		pDstMesh->numfaces++;
	}
}

#define IGNORE_POSITION		0x01
#define IGNORE_TEXCOORD		0x02
#define IGNORE_BONEWEIGHT	0x04
#define IGNORE_NORMAL		0x08
#define IGNORE_TANGENTS		0x10

//-----------------------------------------------------------------------------
// return -1 if there is no match. The index returned is used to index into vertexDict.
//-----------------------------------------------------------------------------
static int FindVertexWithinVertexDictionary( const VertexInfo_t &find, 
	const CVertexDictionary &vertexDict, int nStartVert, int nEndVert, int fIgnore )
{
	int		nBestIndex = -1;
	float	flPositionError = 0.0f;
	float	flNormalError = 0.0f;
	float	flTangentSError = 0.0f;
	float	flTexcoordError = 0.0f;
	float	flBoneWeightError = 0.0f;
	float	flMinPositionError = FLT_MAX;
	float	flMinNormalError = FLT_MAX;
	float	flMinTangentSError = FLT_MAX;
	float	flMinTexcoordError = FLT_MAX;
	float	flMinBoneWeightError = FLT_MAX;
	bool	bFound;

	if (fIgnore & IGNORE_POSITION)
	{
		flMinPositionError = 0;
		flPositionError    = 0;
	}

	if (fIgnore & IGNORE_TEXCOORD)
	{
		flMinTexcoordError = 0;
		flTexcoordError    = 0;
	}

	if (fIgnore & IGNORE_BONEWEIGHT)
	{
		flMinBoneWeightError = 0;
		flBoneWeightError    = 0;
	}

	if (fIgnore & IGNORE_NORMAL)
	{
		flMinNormalError = 0;
		flNormalError    = 0;
	}

	if (fIgnore & IGNORE_TANGENTS)
	{
		flMinTangentSError = 0;
		flTangentSError    = 0;
	}

	for ( int nVertexIndex = nStartVert; nVertexIndex < nEndVert; ++nVertexIndex )
	{
		// see if the position is reasonable
		if ( !(fIgnore & IGNORE_POSITION) && !ComparePositionFuzzy( find.m_Position, vertexDict.Vertex(nVertexIndex).m_Position, flPositionError ) )
			continue;

		if ( !(fIgnore & IGNORE_TEXCOORD) && !CompareTexCoordsFuzzy( find.m_TexCoord, vertexDict.Vertex(nVertexIndex).m_TexCoord, flTexcoordError ) )
			continue;

		if ( !(fIgnore & IGNORE_BONEWEIGHT) && !CompareBoneWeightsFuzzy( find.m_BoneWeight, vertexDict.Vertex(nVertexIndex).m_BoneWeight, flBoneWeightError ) )
			continue;

		if ( !(fIgnore & IGNORE_NORMAL) && !CompareNormalFuzzy( find.m_Normal, vertexDict.Vertex(nVertexIndex).m_Normal, flNormalError ) )
			continue;

		if ( !(fIgnore & IGNORE_TANGENTS) && !CompareTangentSFuzzy( find.m_TangentS, vertexDict.Vertex(nVertexIndex).m_TangentS, flTangentSError ) )
			continue;

		// the vert with minimum error is the best or exact candidate
		bFound = false;
		if (flMinPositionError > flPositionError)
		{
			bFound = true;
		}
		else if (flMinPositionError == flPositionError)
		{
			if (flMinTexcoordError > flTexcoordError)
			{
				bFound = true;
			}
			else if (flMinTexcoordError == flTexcoordError)
			{
				if (flMinBoneWeightError > flBoneWeightError)
				{
					bFound = true;
				}
				else if (flMinBoneWeightError == flBoneWeightError)
				{
					if (flMinNormalError > flNormalError)
					{
						bFound = true;
					}
					else if (flMinNormalError == flNormalError)
					{
						if (flMinTangentSError >= flTangentSError)
						{
							bFound = true;	
						}
					}
				}
			}
		}

		if (!bFound)
			continue;

		flMinPositionError	 = flPositionError;
		flMinTexcoordError	 = flTexcoordError;
		flMinBoneWeightError = flBoneWeightError;
		flMinNormalError	 = flNormalError;
		flMinTangentSError	 = flTangentSError;
		nBestIndex			 = nVertexIndex;
	}

	return nBestIndex;
}


//-----------------------------------------------------------------------------
// Use position, normal, and texcoord checks across the entire model to find a boneweight
//-----------------------------------------------------------------------------
static void FindBoneWeightWithinModel( const VertexInfo_t &searchVertex, const s_source_t *pSrc, s_boneweight_t &boneWeight, int fIgnore )
{
	int		nBestIndex = -1;
	float	flPositionError = 0.0f;
	float	flNormalError = 0.0f;
	float	flTangentSError = 0.0f;
	float	flTexcoordError = 0.0f;
	float	flMinPositionError = FLT_MAX;
	float	flMinNormalError = FLT_MAX;
	float	flMinTangentSError = FLT_MAX;
	float	flMinTexcoordError = FLT_MAX;
	bool	bFound;

	if (fIgnore & IGNORE_NORMAL)
	{
		flMinNormalError = 0;
		flNormalError    = 0;
	}

	if (fIgnore & IGNORE_TEXCOORD)
	{
		flMinTexcoordError = 0;
		flTexcoordError    = 0;
	}

	if (fIgnore & IGNORE_TANGENTS)
	{
		flMinTangentSError = 0;
		flTangentSError    = 0;
	}

	int nVertexCount = pSrc->m_GlobalVertices.Count();
	for ( int i = 0; i < nVertexCount; i++ )
	{
		const s_vertexinfo_t &srcVertex = pSrc->m_GlobalVertices[i];

		// Compute error metrics
		ComparePositionFuzzy( searchVertex.m_Position, srcVertex.position, flPositionError );

		if (!(fIgnore & IGNORE_NORMAL))
		{
			CompareNormalFuzzy( searchVertex.m_Normal, srcVertex.normal, flNormalError );
		}

		if (!(fIgnore & IGNORE_TEXCOORD))
		{
			CompareTexCoordsFuzzy( searchVertex.m_TexCoord, srcVertex.texcoord, flTexcoordError );
		}

		if (!(fIgnore & IGNORE_TANGENTS))
		{
			CompareTangentSFuzzy( searchVertex.m_TangentS, srcVertex.tangentS, flTangentSError );
		}

		// the vert with minimum error is the best or exact candidate
		bFound = false;
		if (flMinPositionError > flPositionError)
		{
			bFound = true;
		}
		else if (flMinPositionError == flPositionError)
		{
			if (flMinTexcoordError > flTexcoordError)
			{
				bFound = true;
			}
			else if (flMinTexcoordError == flTexcoordError)
			{
				if (flMinNormalError > flNormalError)
				{
					bFound = true;
				}
				else if (flMinNormalError == flNormalError)
				{
					if (flMinTangentSError >= flTangentSError)
					{
						bFound = true;
					}
				}
			}
		}

		if (bFound)
		{
			flMinPositionError  = flPositionError;
			flMinTexcoordError  = flTexcoordError;
			flMinNormalError    = flNormalError;
			flMinTangentSError  = flTangentSError;
			nBestIndex          = i;
		}
	}
	
	if ( nBestIndex == -1 )
	{
		MdlError( "Encountered a mesh with no vertices!\n" );
	}

	memcpy( &boneWeight, &pSrc->m_GlobalVertices[ nBestIndex ].boneweight, sizeof(s_boneweight_t) );
}


//-----------------------------------------------------------------------------
// Modify the bone weights in all of the vertices....
//-----------------------------------------------------------------------------
static void RemapBoneWeights( const CUtlVector<int> &boneMap, s_boneweight_t &boneWeight )
{
	for( int i = 0; i < boneWeight.numbones; i++ )
	{
		Assert( boneWeight.bone[i] >= 0 && boneWeight.bone[i] < boneMap.Count() );
		boneWeight.bone[i] = boneMap[ boneWeight.bone[i] ];
	}
}


//-----------------------------------------------------------------------------
// After the remapping, we may get multiple instances of the same bone
// which we want to collapse into a single bone
//-----------------------------------------------------------------------------
static void CollapseBoneWeights( s_boneweight_t &boneWeight )
{
	// We need the bones to be sorted by bone index for the loop right below
	SortBoneWeightByIndex( boneWeight );

	for( int i = 0; i < boneWeight.numbones-1; i++ )
	{
		if( boneWeight.bone[i] != boneWeight.bone[i+1] )
			continue;

		// add i+1's weight to i since they have the same bone index
		boneWeight.weight[i] += boneWeight.weight[i+1];

		// remove i+1
		for( int j = i+1; j < boneWeight.numbones-1; j++ )
		{
			boneWeight.bone[j] = boneWeight.bone[j+1];
			boneWeight.weight[j] = boneWeight.weight[j+1];
		}
		--boneWeight.numbones;

		// Gotta step back one, may have many bones collapsing into one
		--i;
	}

	ValidateBoneWeight( boneWeight );
}


//-----------------------------------------------------------------------------
// Find a matching vertex within the root lod 
//-----------------------------------------------------------------------------
static void CalculateBoneWeightFromRootLod( const VertexInfo_t &searchVertex, CVertexDictionary &vertexDict, 
	const s_source_t *pRootLODSrc, VertexInfo_t &idealVertex )
{
	idealVertex = searchVertex;

	// Look through the part of the vertex dictionary associated with the root LODs for a match
	// bone weights are not defined properly in SMDs for lower LODs, so don't consider
	// we can only accept the boneweight from the root LOD
	int nVertexDictID = FindVertexWithinVertexDictionary( searchVertex, vertexDict, 
		vertexDict.RootLODVertexStart(), vertexDict.RootLODVertexEnd(), IGNORE_BONEWEIGHT|IGNORE_TANGENTS ); 
	if ( nVertexDictID != -1 )
	{
		Assert( nVertexDictID >= vertexDict.RootLODVertexStart() && nVertexDictID < vertexDict.RootLODVertexEnd() );
		Assert( nVertexDictID >= 0 && nVertexDictID < vertexDict.VertexCount() );

		// found vertex in dictionary
#ifdef UNIQUE_VERTEXES_FOR_LOD
		// keep entry vertex and fill in the missing bone weight attribute
		idealVertex.m_BoneWeight = vertexDict.Vertex( nVertexDictID ).m_BoneWeight;
#else
		// discard entry vertex in favor of best match
		// this ensures all the attributes, including bone weight are correct for that vertex
		// the worst case is that the vertex is not an *exact* match for entry attributes just a "close" match
		idealVertex = vertexDict.Vertex( nVertexDictID );
#endif
		return;
	}

	// In this case, we didn't find anything within the tolerance, so we need to
	// do a *positional check only* to give us a bone weight to assign to this vertex.
	FindBoneWeightWithinModel( searchVertex, pRootLODSrc, idealVertex.m_BoneWeight, IGNORE_BONEWEIGHT|IGNORE_TANGENTS );
}

//-----------------------------------------------------------------------------
// Find a matching vertex
//-----------------------------------------------------------------------------
static void CalculateIdealVert( const VertexInfo_t &searchVertex, CVertexDictionary &vertexDict, 
	const s_mesh_t *pVertexDictMesh, const s_source_t *pRootLODSrc, VertexInfo_t &idealVertex )
{
#ifndef UNIQUE_VERTEXES_FOR_LOD
	// Only look through the part of the vertex dictionary associated with all *higher* LODs for a match
	int nVertexDictID = FindVertexWithinVertexDictionary( searchVertex, vertexDict, 
		pVertexDictMesh->vertexoffset, vertexDict.PrevLODVertexCount(), 0 ); 
	if ( nVertexDictID != -1 )
	{
		Assert( nVertexDictID >= pVertexDictMesh->vertexoffset && nVertexDictID < vertexDict.PrevLODVertexCount() );
		Assert( nVertexDictID >= 0 && nVertexDictID < vertexDict.VertexCount() );

		// found vertex in dictionary
		idealVertex = vertexDict.Vertex( nVertexDictID );
		return;
	}
#endif

	// could not find a tolerant match
	// the search vertex is unique
	idealVertex = searchVertex;
}


static bool FuzzyFloatCompare( float f1, float f2, float epsilon )
{
	if( fabs( f1 - f2 ) < epsilon )
	{
		return true;
	}
	else
	{
		return false;
	}
}
								

//-----------------------------------------------------------------------------
// Is this bone weight structure sorted by bone?
//-----------------------------------------------------------------------------
static bool IsBoneWeightSortedByBone( const s_boneweight_t &src )
{
	for ( int i = 1; i < src.numbones; ++i )
	{
		Assert( src.bone[i] != -1 );
		if ( src.bone[ i-1 ] > src.bone[ i ] )
			return false;
	}

	return true;
}

	
//-----------------------------------------------------------------------------
// Are two bone-weight structures equal?
//-----------------------------------------------------------------------------
static bool AreBoneWeightsEqual( const s_boneweight_t &b1, const s_boneweight_t &b2 )
{
	// Have to have the same number of bones
	if ( b1.numbones != b2.numbones )
		return false;

	// This is a list of which bones that exist in b1 also exist in b2.
	// Use the index to figure out where in the array for b2 that the corresponding bone in b1 is.
	int nMatchingBones = 0;
	int pBoneIndexMap[MAX_NUM_BONES_PER_VERT]; 

	int i;
	for ( i = 0; i < b1.numbones; ++i )
	{
		pBoneIndexMap[i] = -1;
		for ( int j = 0; j < b2.numbones; ++j )
		{
			if ( b2.bone[j] == b1.bone[i] )
			{
				pBoneIndexMap[i] = j;
				++nMatchingBones;
				break;
			}
		}
	}

	// If we aren't using the same bone indices, we're done
	if ( nMatchingBones != b1.numbones )
		return false;

	// Check to see if the weights are the same
	for ( i = 0; i < b1.numbones; ++i )
	{
		Assert( pBoneIndexMap[i] != -1 );
		if ( b1.weight[i] != b2.weight[ pBoneIndexMap[i] ] )
			return false;
	}

	return true;
}



//-----------------------------------------------------------------------------
// Finds an *exact* requested vertex in the dictionary
//-----------------------------------------------------------------------------
static int FindVertexInDictionaryExact( CVertexDictionary &vertexDict, int nStartVert, int nEndVert, const VertexInfo_t &vertex )
{
	for ( int nVertID = nStartVert; nVertID < nEndVert; ++nVertID )
	{
		if ( vertexDict.Vertex( nVertID ).m_Position != vertex.m_Position )
			continue;

		if ( !AreBoneWeightsEqual( vertexDict.Vertex( nVertID ).m_BoneWeight, vertex.m_BoneWeight ) )
			continue;

		if ( vertexDict.Vertex( nVertID ).m_TexCoord != vertex.m_TexCoord )
			continue;

		if ( vertexDict.Vertex( nVertID ).m_Normal != vertex.m_Normal )
			continue;

		if ( vertexDict.Vertex( nVertID ).m_TangentS != vertex.m_TangentS )
			continue;

		return nVertID;
	}

	return -1;
}


//-----------------------------------------------------------------------------
// Finds the *exact* requested vertex in the dictionary or creates it
//-----------------------------------------------------------------------------
static int FindOrCreateExactVertexInDictionary( CVertexDictionary &vertexDict, 
	const VertexInfo_t &vertex, s_mesh_t *pDstMesh )
{
	int nMeshVertID = FindVertexInDictionaryExact( vertexDict, pDstMesh->vertexoffset, pDstMesh->vertexoffset+pDstMesh->numvertices, vertex );
	if ( nMeshVertID != -1 )
	{
		// flag vertex for what LoD's are using it
		vertexDict.Vertex( nMeshVertID ).m_nLodFlag |= vertex.m_nLodFlag;
		return nMeshVertID - pDstMesh->vertexoffset;
	}

	nMeshVertID = vertexDict.AddVertex( vertex );
	++pDstMesh->numvertices;
	return nMeshVertID - pDstMesh->vertexoffset;
}

static void PrintBonesUsedInLOD( s_source_t *pSrc )
{
	printf( "PrintBonesUsedInLOD\n" );

	int nVertexCount = pSrc->m_GlobalVertices.Count();
	for( int i = 0; i <nVertexCount; i++ )
	{
		Vector &pos = pSrc->m_GlobalVertices[i].position;
		Vector &norm = pSrc->m_GlobalVertices[i].normal;
		Vector2D &texcoord = pSrc->m_GlobalVertices[i].texcoord;
		printf( "pos: %f %f %f norm: %f %f %f texcoord: %f %f\n",
			pos[0], pos[1], pos[2], norm[0], norm[1], norm[2], texcoord[0], texcoord[1] );
		s_boneweight_t *pBoneWeight = &pSrc->m_GlobalVertices[i].boneweight;
		int j;
		for( j = 0; j < pBoneWeight->numbones; j++ )
		{
			int globalBoneID = pBoneWeight->bone[j];
			const char *pBoneName = g_bonetable[globalBoneID].name;
			printf( "vert: %d bone: %d boneid: %d weight: %f name: \"%s\"\n", i, ( int )j, ( int )pBoneWeight->bone[j], 
				( float )pBoneWeight->weight[j], pBoneName );
		}
		printf( "\n" );
		fflush( stdout );
	}
}


//-----------------------------------------------------------------------------
// Indicates a particular set of bones is used by a particular LOD
//-----------------------------------------------------------------------------
static void	MarkBonesUsedByLod( const s_boneweight_t &boneWeight, int nLodID )
{
	for( int j = 0; j < boneWeight.numbones; ++j )
	{
		int nGlobalBoneID = boneWeight.bone[j];
		s_bonetable_t *pBone = &g_bonetable[nGlobalBoneID];
		pBone->flags |= ( BONE_USED_BY_VERTEX_LOD0 << nLodID );
	}
}


static void PrintSBoneWeight( s_boneweight_t *pBoneWeight, const s_source_t *pSrc )
{
	int j;
	for( j = 0; j < pBoneWeight->numbones; j++ )
	{
		int globalBoneID;
		globalBoneID = pBoneWeight->bone[j];
		const char *pBoneName = g_bonetable[globalBoneID].name;
		printf( "bone: %d boneid: %d weight: %f name: \"%s\"\n", ( int )j, ( int )pBoneWeight->bone[j], 
			( float )pBoneWeight->weight[j], pBoneName );
	}
}



//-----------------------------------------------------------------------------
// In the non-top LOD, look for vertices that would be appropriate from the
// vertex dictionary, and use them if you find them, or add new vertices to the 
// vertex dictionary if not and use those new vertices.
//-----------------------------------------------------------------------------
static void CreateLODVertsInDictionary( int nLodID, const s_source_t *pRootLODSrc, s_source_t *pCurrentLODSrc, 
	const s_mesh_t *pCurrLODMesh, s_mesh_t *pVertexDictMesh, CVertexDictionary &vertexDict, int *pMeshVertIndexMap )
{
	// this function is specific to lods and not the root
	Assert( nLodID );

	int nNumCurrentVerts = vertexDict.VertexCount();

	// Used to control where we look for vertices + merging rules
	vertexDict.StartNewLOD();

	CUtlVector<int> boneMap;
	BuildBoneLODMapping( boneMap, nLodID );

	for( int nSrcVertID = 0; nSrcVertID < pCurrLODMesh->numvertices; ++nSrcVertID )
	{
		int nSrcID = nSrcVertID + pCurrLODMesh->vertexoffset;

		// candidate vertex
		// vertices at lower LODs have bogus boneweights assigned
		// must get the boneweight from the nearest or exact vertex at root lod
		const s_vertexinfo_t& srcVertex = pCurrentLODSrc->m_GlobalVertices[nSrcID];
		VertexInfo_t vertex;
		vertex.m_Position   = srcVertex.position; 
		vertex.m_Normal     = srcVertex.normal;
		vertex.m_TexCoord   = srcVertex.texcoord;
		vertex.m_TangentS   = srcVertex.tangentS;

#ifdef _DEBUG
		memset( &vertex.m_BoneWeight, 0xDD, sizeof( s_boneweight_t ) );
#endif
		// determine the best bone weight for the desired vertex within the root lod only
		// the root lod contains no bone remappings
		// this ensures we get a vertex with its matched proper boneweight assignment
		VertexInfo_t idealVertex;
		CalculateBoneWeightFromRootLod( vertex, vertexDict, pRootLODSrc, idealVertex );

		// try again to match the candidate vertex
		// determine the ideal vertex with desired remapped boneweight
		vertex = idealVertex;
		CalculateIdealVert( vertex, vertexDict, pVertexDictMesh, pRootLODSrc, idealVertex);

		// remap bone
		RemapBoneWeights( boneMap, idealVertex.m_BoneWeight );
		CollapseBoneWeights( idealVertex.m_BoneWeight );
		SortBoneWeightByWeight( idealVertex.m_BoneWeight );

		// FIXME: this is marking bones based on the slammed vertex data
		MarkBonesUsedByLod( idealVertex.m_BoneWeight, nLodID );

		// tag ideal vertex as being part of the current lod
		idealVertex.m_nLodFlag		= 1 << nLodID;

		// Find the exact vertex or create it in the dictionary
		int nMeshVertID = FindOrCreateExactVertexInDictionary( vertexDict, idealVertex, pVertexDictMesh );

		// Indicate where in the higher LODs the vertex we selected resides
		pMeshVertIndexMap[nSrcID] = nMeshVertID;
	}

	int nNewVertsCreated = vertexDict.VertexCount() - nNumCurrentVerts;
	if (!g_quiet && nNewVertsCreated)
	{
		printf( "Lod %d: vertexes: %d (%d new)\n", nLodID, vertexDict.VertexCount(), nNewVertsCreated);
	}
}

static void PrintSourceVerts( s_source_t *pSrc )
{
	int nVertexCount = pSrc->m_GlobalVertices.Count();
	for( int i = 0; i < nVertexCount; i++ )
	{
		const s_vertexinfo_t &srcVertex = pSrc->m_GlobalVertices[i];
		printf( "v %d ", i );
		printf( "pos: %f %f %f ", srcVertex.position[0], srcVertex.position[1], srcVertex.position[2] );
		printf( "norm: %f %f %f ", srcVertex.normal[0], srcVertex.normal[1], srcVertex.normal[2] );
		printf( "texcoord: %f %f\n", srcVertex.texcoord[0], srcVertex.texcoord[1] );
		int j;
		for( j = 0; j < srcVertex.boneweight.numbones; j++ )
		{
			printf( "\t%d: %d %f\n", j, ( int )srcVertex.boneweight.bone[j], 
				srcVertex.boneweight.weight[j] );
		}
		fflush( stdout );
	}
}


//-----------------------------------------------------------------------------
// Copy the vertex dictionary to the finalized processed data
// Leaves the source data intact, necessary for later processes.
// Routines can then choose which data they operate on
//-----------------------------------------------------------------------------
static void SetProcessedWithDictionary( s_model_t* pSrcModel, CVertexDictionary &vertexDict,
	CUtlVector<s_face_t> &faces, CUtlVector<s_mesh_t> &meshes, int *pMeshVertIndexMaps[MAX_NUM_LODS] )
{
	int	i;

	s_loddata_t *pLodData = new s_loddata_t;
	memset( pLodData, 0, sizeof(s_loddata_t) );
	
	pSrcModel->m_pLodData = pLodData;

	int nVertexCount = vertexDict.VertexCount();

	pLodData->vertex = (s_lodvertexinfo_t *)kalloc( nVertexCount, sizeof( s_lodvertexinfo_t ) );
	pLodData->numvertices = nVertexCount;
	pLodData->face = (s_face_t *)kalloc( faces.Count(), sizeof( s_face_t ));
	pLodData->numfaces = faces.Count();
	
	for ( i = 0; i < nVertexCount; ++i )
	{
		const VertexInfo_t &srcVertex = vertexDict.Vertex( i );
		s_lodvertexinfo_t &dstVertex = pLodData->vertex[i];

		dstVertex.boneweight = srcVertex.m_BoneWeight;
		Assert( dstVertex.boneweight.numbones <= 4 );
		dstVertex.position	= srcVertex.m_Position;
		dstVertex.normal	= srcVertex.m_Normal;
		dstVertex.texcoord	= srcVertex.m_TexCoord;
		dstVertex.tangentS	= srcVertex.m_TangentS;
		dstVertex.lodFlag	= srcVertex.m_nLodFlag;
	}

	memcpy( pLodData->face, faces.Base(), faces.Count() * sizeof( s_face_t ) );
	memcpy( pLodData->mesh, meshes.Base(), meshes.Count() * sizeof( s_mesh_t ) );

	for (i=0; i<MAX_NUM_LODS; i++)
	{
		pLodData->pMeshVertIndexMaps[i] = pMeshVertIndexMaps[i];
	}
}


//-----------------------------------------------------------------------------
// This fills out boneMap, which is a mapping from src bone to src bone replacement (or to itself
// if there is no bone replacement.
//-----------------------------------------------------------------------------
static void BuildBoneLODMapping( CUtlVector<int> &boneMap, int lodID )
{
	boneMap.AddMultipleToTail( g_numbones );

	Assert( lodID < g_ScriptLODs.Size() );
	LodScriptData_t& scriptLOD = g_ScriptLODs[lodID];

	// First, create a direct mapping where no bones are collapsed
	int i;
	for( i = 0; i < g_numbones; i++ )
	{
		boneMap[i] = i;
	}

	for( i = 0; i < scriptLOD.boneReplacements.Size(); i++ )
	{
		const char *src, *dst;
		src = scriptLOD.boneReplacements[i].GetSrcName();
		dst = scriptLOD.boneReplacements[i].GetDstName();
		int j = findGlobalBone( src );
		int k = findGlobalBone( dst );

		if ( j != -1 && k != -1)
		{
			boneMap[j] = k;
		}
		else if ( j == -1)
		{
			// FIXME: is this really an error?  It could just be  replacement command for bone that doesnt' exist anymore.
			if (g_verbose)
			{
				MdlWarning( "Couldn't replace unknown bone \"%s\" with \"%s\"\n", src, dst );
			}
		}
		else
		{
			// FIXME: is this really an error?  It could just be  replacement command for bone that doesnt' exist anymore.
			if (g_verbose)
			{
				MdlWarning( "Couldn't replace bone \"%s\" with unknown \"%s\"\n", src, dst );
			}
		}
	}
}

static void MarkRootLODBones( CVertexDictionary &vertexDictionary )
{
	// should result in an identity mapping
	// because their are no bone remaps at the root lod
	CUtlVector<int> boneMap;
	BuildBoneLODMapping( boneMap, 0 );

	// iterate and mark bones
	for (int nVertDictID=vertexDictionary.RootLODVertexStart(); nVertDictID<vertexDictionary.RootLODVertexEnd(); nVertDictID++)
	{
		s_boneweight_t &boneWeight = vertexDictionary.Vertex( nVertDictID ).m_BoneWeight;

		RemapBoneWeights( boneMap, boneWeight );
		CollapseBoneWeights( boneWeight );
		SortBoneWeightByWeight( boneWeight );

		MarkBonesUsedByLod( boneWeight, 0 );
	}
}


//-----------------------------------------------------------------------------
// Computes LOD vertices for a model piece.
//-----------------------------------------------------------------------------
static void UnifyModelLODs( s_model_t *pSrcModel )
{
	if ( !Q_stricmp( pSrcModel->name, "blank" ) )
		return;

	// each lod has a unique vertex mapping table
	int nNumLODs = pSrcModel->m_LodSources.Count();
	int nLodID;
	int *pMeshVertIndexMaps[MAX_NUM_LODS];
	for ( nLodID = 0; nLodID < MAX_NUM_LODS; nLodID++ )
	{
		if ( nLodID < nNumLODs && pSrcModel->m_LodSources[nLodID] )
		{
			int nVertexCount = pSrcModel->m_LodSources[nLodID]->m_GlobalVertices.Count();
			pMeshVertIndexMaps[nLodID] = new int[ nVertexCount ];
#ifdef _DEBUG
			memset( pMeshVertIndexMaps[nLodID], 0xDD, nVertexCount * sizeof(int) );
#endif
		}
		else
		{
			pMeshVertIndexMaps[nLodID] = NULL;
		}
	}

	// These hold the aggregate data for the model that grows as lods are processed
	CVertexDictionary vertexDictionary;
	CUtlVector<s_face_t> faces;
	CUtlVector<s_mesh_t> meshes;
	
	meshes.AddMultipleToTail( MAXSTUDIOSKINS );
	Assert( meshes.Count() == MAXSTUDIOSKINS );
	memset( meshes.Base(), 0, meshes.Count() * sizeof( s_mesh_t ) );

	int nMeshID;
	for( nMeshID = 0; nMeshID < pSrcModel->source->nummeshes; nMeshID++ )
	{
		s_mesh_t *pVertexDictMesh = &meshes[pSrcModel->source->meshindex[nMeshID]];
		
		pVertexDictMesh->numvertices = 0;
		pVertexDictMesh->vertexoffset = vertexDictionary.VertexCount();
		pVertexDictMesh->numfaces = 0;
		pVertexDictMesh->faceoffset = faces.Count();
		
		// First build up information for LOD 0
		if ( !pSrcModel->m_LodSources[0] )
			continue;

		s_source_t *pLOD0Source = pSrcModel->m_LodSources[0];

		// lookup the material used by this mesh
		int nMaterialID = pLOD0Source->meshindex[nMeshID];
		s_mesh_t *pLOD0Mesh = FindMeshByMaterial( pLOD0Source, nMaterialID );
		if ( !pLOD0Mesh )
			continue;

		// populate with all vertices from LOD 0
		int nStart = vertexDictionary.VertexCount();
		CopyVerts( 0, pLOD0Source, pLOD0Mesh, vertexDictionary, pVertexDictMesh, pMeshVertIndexMaps[0] );
		vertexDictionary.SetRootVertexRange( nStart, vertexDictionary.VertexCount() );
	
		MarkRootLODBones( vertexDictionary );

		// only fix up the faces for the highest lod since the lowest ones are going
		// to be reprocessed later.
		CopyFaces( pLOD0Source, pLOD0Mesh, faces, pVertexDictMesh );

		// Now, for each LOD, try to build meshes using the vertices in LOD 0.
		// Ideally, vertices used in an LOD would be in LOD 0 for the benefit of shared vertices.
		// If we don't find vertices in LOD 0, this code will add vertices into LOD 0's list
		// of vertices for the next LOD to find
		for ( nLodID = 1; nLodID < nNumLODs; ++nLodID )
		{
			s_source_t *pCurrLOD = pSrcModel->m_LodSources[nLodID];
			if ( !pCurrLOD )
				continue;

			// Find the mesh that matches the material
			// mesh may not be present or could be culled due to $removemesh commands
			s_mesh_t *pCurrLODMesh = FindOrCullMesh( nLodID, pCurrLOD, nMaterialID );
			if ( !pCurrLODMesh )
				continue;

			CreateLODVertsInDictionary( nLodID, pLOD0Source, pCurrLOD, pCurrLODMesh, pVertexDictMesh, vertexDictionary, pMeshVertIndexMaps[nLodID]);
		}
	}

#ifdef _DEBUG
	Msg( "Total vertex count: %d\n", vertexDictionary.VertexCount() );
#endif

	// save the data we just built into the processed data section
	// The processed data has all of the verts that are needed for all LODs.
	SetProcessedWithDictionary( pSrcModel, vertexDictionary, faces, meshes, pMeshVertIndexMaps );
//	PrintSourceVerts( pSrcModel->m_LodModels[0] );
}


//-----------------------------------------------------------------------------
// Force the vertex array for a model to have all of the vertices that are needed
// for all of the LODs of the model.
//-----------------------------------------------------------------------------
void UnifyLODs( void )
{
	// todo: need to fixup the firstref/lastref stuff . . do we really need it anymore?
	for( int modelID = 0; modelID < g_nummodelsbeforeLOD; modelID++ )
	{
		UnifyModelLODs( g_model[modelID] );
	}
}


static void PrintSpaces( int numSpaces )
{
	int i;
	for( i = 0; i < numSpaces; i++ )
	{
		printf( " " );
	}
}

static void SpewBoneInfo( int globalBoneID, int depth )
{
	s_bonetable_t *pBone = &g_bonetable[globalBoneID];
	if( g_bPrintBones )
	{
		PrintSpaces( depth * 2 );
		printf( "%d \"%s\" ", depth, pBone->name );
	}
	int i;
	for( i = 0; i < 8; i++ )
	{
		if( pBone->flags & ( BONE_USED_BY_VERTEX_LOD0 << i ) )
		{
			if( g_bPrintBones )
			{
				printf( "lod%d ", i );
			}
			g_NumBonesInLOD[i]++;
		}
	}
	if( g_bPrintBones )
	{
		printf( "\n" );	
	}
	
	int j;
	for( j = 0; j < g_numbones; j++ )
	{
		s_bonetable_t *pBone = &g_bonetable[j];
		if( pBone->parent == globalBoneID )
		{
			SpewBoneInfo( j, depth + 1 );
		}
	}
}

void SpewBoneUsageStats( void )
{
	memset( g_NumBonesInLOD, 0, sizeof( int ) * MAX_NUM_LODS );
	if( g_numbones == 0 )
	{
		return;
	}
	SpewBoneInfo( 0, 0 );
	if( g_bPrintBones )
	{
		int i;
		for( i = 0; i < g_ScriptLODs.Count(); i++ )
		{
			printf( "\t%d bones used in lod %d\n", g_NumBonesInLOD[i], i );
		}
	}
}

void MarkParentBoneLODs( void )
{
	int i;
	for( i = 0; i < g_numbones; i++ )
	{
		int flags = g_bonetable[i].flags;
		flags &= BONE_USED_BY_VERTEX_MASK;
		int globalBoneID = g_bonetable[i].parent;
		while( globalBoneID != -1 )
		{
			g_bonetable[globalBoneID].flags |= flags;
			globalBoneID = g_bonetable[globalBoneID].parent;
		}
	}
}


//-----------------------------------------------------------------------------
// Returns the sources associated with the various LODs based on the script commands
//-----------------------------------------------------------------------------
static void GetLODSources( CUtlVector< s_source_t * > &lods, const s_model_t *pSrcModel )
{
	int nNumLODs = g_ScriptLODs.Count();
	lods.EnsureCount( nNumLODs );
	for( int lodID = 0; lodID < nNumLODs; lodID++ )
	{
		LodScriptData_t& scriptLOD = g_ScriptLODs[lodID];

		bool bFound;
		s_source_t* pSource = GetModelLODSource( pSrcModel->filename, scriptLOD, &bFound );
		if ( !pSource && !bFound )
		{
			pSource = pSrcModel->source;
		}

		lods[lodID] = pSource;
	}
}


//-----------------------------------------------------------------------------
// Creates models to store converted data for the various LODs
//-----------------------------------------------------------------------------
void LoadLODSources( void )
{
	g_nummodelsbeforeLOD = g_nummodels;
	for( int modelID = 0; modelID < g_nummodelsbeforeLOD; modelID++ )
	{
		if ( !Q_stricmp( g_model[modelID]->name, "blank" ) )
		{
			int nNumLODs = g_ScriptLODs.Count();
			g_model[modelID]->m_LodSources.SetCount( nNumLODs );
			for ( int i = 0; i < nNumLODs; ++i )
			{
				g_model[modelID]->m_LodSources[i] = NULL;
			}
			continue;
		}

		GetLODSources( g_model[modelID]->m_LodSources, g_model[modelID] );
	}
}

static void ReplaceBonesRecursive( int globalBoneID, bool replaceThis, 
								   CUtlVector<CLodScriptReplacement_t> &boneReplacements, 
								   const char *replacementName )
{
	if( replaceThis )
	{
		CLodScriptReplacement_t &boneReplacement = boneReplacements[boneReplacements.AddToTail()];
		boneReplacement.SetSrcName( g_bonetable[globalBoneID].name );
		boneReplacement.SetDstName( replacementName );
	}

	// find children and recurse.
	int i;
	for( i = 0; i < g_numbones; i++ )
	{
		if( g_bonetable[i].parent == globalBoneID )
		{
			ReplaceBonesRecursive( i, true, boneReplacements, replacementName );
		}
	}
}

static void ConvertSingleBoneTreeCollapseToReplaceBones( CLodScriptReplacement_t &boneTreeCollapse, 
														 CUtlVector<CLodScriptReplacement_t> &boneReplacements )
{
	// find the bone that we are starting with.
	int i = findGlobalBone( boneTreeCollapse.GetSrcName() );
	if (i != -1)
	{
		ReplaceBonesRecursive( i, false, boneReplacements, g_bonetable[i].name );
		return;
	}
	MdlWarning( "Couldn't find bone %s for bonetreecollapse, skipping\n", boneTreeCollapse.GetSrcName() );
}

void ConvertBoneTreeCollapsesToReplaceBones( void )
{
	int i;
	for( i = 0; i < g_ScriptLODs.Size(); i++ )
	{
		LodScriptData_t& lod = g_ScriptLODs[i];
		int j;
		for( j = 0; j < lod.boneTreeCollapses.Size(); j++ )
		{
			ConvertSingleBoneTreeCollapseToReplaceBones( lod.boneTreeCollapses[j], 
				lod.boneReplacements );
		}
	}
}

/*
static void PrintReplacedBones( LodScriptData_t &lod )
{
	int i;
	for( i = 0; i < lod.boneReplacements.Count(); i++ )
	{
		printf( "%s -> %s\n", 
			lod.boneReplacements[i].GetSrcName(), 
			lod.boneReplacements[i].GetDstName() );
	}
}
*/

void FixupReplacedBonesForLOD( LodScriptData_t &lod )
{
/*
	printf( "before:\n" );
	PrintReplacedBones( lod );
*/
	bool changed;
	int i;
	int j;
	do
	{
		changed = false;
		for( i = 0; i < lod.boneReplacements.Count(); i++ )
		{
			for( j = 0; j < lod.boneReplacements.Count(); j++ )
			{
				if( i == j )
				{
					continue;
				}
				if( Q_stricmp( lod.boneReplacements[i].GetSrcName(), lod.boneReplacements[j].GetDstName() ) == 0 )
				{
					lod.boneReplacements[j].SetDstName( lod.boneReplacements[i].GetDstName() );
					changed = true;
				}
			}
		}
	} while( changed );
/*
	printf( "after:\n" );
	PrintReplacedBones( lod );
*/
}

void FixupReplacedBones( void )
{
	int i;
	for( i = 0; i < g_ScriptLODs.Size(); i++ )
	{
		FixupReplacedBonesForLOD( g_ScriptLODs[i] );
	}
}