File: gltfpack.cpp

package info (click to toggle)
meshoptimizer 0.22%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,408 kB
  • sloc: cpp: 14,548; ansic: 7,650; javascript: 291; makefile: 187; python: 100
file content (1666 lines) | stat: -rw-r--r-- 50,483 bytes parent folder | download
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
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
// This file is part of gltfpack; see gltfpack.h for version/license details
#include "gltfpack.h"

#include <algorithm>
#include <unordered_map>

#include <locale.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef __wasi__
#include <unistd.h>
#endif

#include "../src/meshoptimizer.h"

std::string getVersion()
{
	char result[32];
	snprintf(result, sizeof(result), "%d.%d", MESHOPTIMIZER_VERSION / 1000, (MESHOPTIMIZER_VERSION % 1000) / 10);
	return result;
}

static void finalizeBufferViews(std::string& json, std::vector<BufferView>& views, std::string& bin, std::string* fallback, size_t& fallback_size)
{
	for (size_t i = 0; i < views.size(); ++i)
	{
		BufferView& view = views[i];

		size_t bin_offset = bin.size();
		size_t fallback_offset = fallback_size;

		size_t count = view.data.size() / view.stride;

		if (view.compression == BufferView::Compression_None)
		{
			bin += view.data;
		}
		else
		{
			switch (view.compression)
			{
			case BufferView::Compression_Attribute:
				compressVertexStream(bin, view.data, count, view.stride);
				break;
			case BufferView::Compression_Index:
				compressIndexStream(bin, view.data, count, view.stride);
				break;
			case BufferView::Compression_IndexSequence:
				compressIndexSequence(bin, view.data, count, view.stride);
				break;
			default:
				assert(!"Unknown compression type");
			}

			if (fallback)
				*fallback += view.data;
			fallback_size += view.data.size();
		}

		size_t raw_offset = (view.compression != BufferView::Compression_None) ? fallback_offset : bin_offset;

		comma(json);
		writeBufferView(json, view.kind, view.filter, count, view.stride, raw_offset, view.data.size(), view.compression, bin_offset, bin.size() - bin_offset);

		// record written bytes for statistics
		view.bytes = bin.size() - bin_offset;

		// align each bufferView by 4 bytes
		bin.resize((bin.size() + 3) & ~3);
		if (fallback)
			fallback->resize((fallback->size() + 3) & ~3);
		fallback_size = (fallback_size + 3) & ~3;
	}
}

static void printMeshStats(const std::vector<Mesh>& meshes, const char* name)
{
	size_t mesh_triangles = 0;
	size_t mesh_vertices = 0;
	size_t total_triangles = 0;
	size_t total_instances = 0;
	size_t total_draws = 0;

	for (size_t i = 0; i < meshes.size(); ++i)
	{
		const Mesh& mesh = meshes[i];

		size_t triangles = mesh.type == cgltf_primitive_type_triangles ? mesh.indices.size() / 3 : 0;

		mesh_triangles += triangles;
		mesh_vertices += mesh.streams.empty() ? 0 : mesh.streams[0].data.size();

		size_t instances = std::max(size_t(1), mesh.nodes.size() + mesh.instances.size());

		total_triangles += triangles * instances;
		total_instances += instances;
		total_draws += std::max(size_t(1), mesh.nodes.size());
	}

	printf("%s: %d mesh primitives (%d triangles, %d vertices); %d draw calls (%d instances, %lld triangles)\n", name,
	    int(meshes.size()), int(mesh_triangles), int(mesh_vertices),
	    int(total_draws), int(total_instances), (long long)total_triangles);
}

static void printSceneStats(const std::vector<BufferView>& views, const std::vector<Mesh>& meshes, size_t node_offset, size_t mesh_offset, size_t material_offset, size_t json_size, size_t bin_size)
{
	size_t bytes[BufferView::Kind_Count] = {};

	for (size_t i = 0; i < views.size(); ++i)
	{
		const BufferView& view = views[i];
		bytes[view.kind] += view.bytes;
	}

	printf("output: %d nodes, %d meshes (%d primitives), %d materials\n", int(node_offset), int(mesh_offset), int(meshes.size()), int(material_offset));
	printf("output: JSON %d bytes, buffers %d bytes\n", int(json_size), int(bin_size));
	printf("output: buffers: vertex %d bytes, index %d bytes, skin %d bytes, time %d bytes, keyframe %d bytes, instance %d bytes, image %d bytes\n",
	    int(bytes[BufferView::Kind_Vertex]), int(bytes[BufferView::Kind_Index]), int(bytes[BufferView::Kind_Skin]),
	    int(bytes[BufferView::Kind_Time]), int(bytes[BufferView::Kind_Keyframe]), int(bytes[BufferView::Kind_Instance]),
	    int(bytes[BufferView::Kind_Image]));
}

static void printAttributeStats(const std::vector<BufferView>& views, BufferView::Kind kind, const char* name)
{
	for (size_t i = 0; i < views.size(); ++i)
	{
		const BufferView& view = views[i];

		if (view.kind != kind)
			continue;

		const char* variant = "unknown";

		switch (kind)
		{
		case BufferView::Kind_Vertex:
			variant = attributeType(cgltf_attribute_type(view.variant));
			break;

		case BufferView::Kind_Index:
			variant = "index";
			break;

		case BufferView::Kind_Keyframe:
		case BufferView::Kind_Instance:
			variant = animationPath(cgltf_animation_path_type(view.variant));
			break;

		default:;
		}

		size_t count = view.data.size() / view.stride;

		printf("stats: %s %s: compressed %d bytes (%.1f bits), raw %d bytes (%d bits)\n",
		    name, variant,
		    int(view.bytes), double(view.bytes) / double(count) * 8,
		    int(view.data.size()), int(view.stride * 8));
	}
}

static void printImageStats(const std::vector<BufferView>& views, TextureKind kind, const char* name)
{
	size_t bytes = 0;
	size_t count = 0;

	for (size_t i = 0; i < views.size(); ++i)
	{
		const BufferView& view = views[i];

		if (view.kind != BufferView::Kind_Image)
			continue;

		if (view.variant != -1 - kind)
			continue;

		count += 1;
		bytes += view.data.size();
	}

	if (count)
		printf("stats: image %s: %d bytes in %d images\n", name, int(bytes), int(count));
}

static bool printReport(const char* path, const std::vector<BufferView>& views, const std::vector<Mesh>& meshes, size_t node_count, size_t mesh_count, size_t texture_count, size_t material_count, size_t animation_count, size_t json_size, size_t bin_size)
{
	size_t bytes[BufferView::Kind_Count] = {};

	for (size_t i = 0; i < views.size(); ++i)
	{
		const BufferView& view = views[i];
		bytes[view.kind] += view.bytes;
	}

	size_t total_triangles = 0;
	size_t total_instances = 0;
	size_t total_draws = 0;

	for (size_t i = 0; i < meshes.size(); ++i)
	{
		const Mesh& mesh = meshes[i];

		size_t triangles = mesh.type == cgltf_primitive_type_triangles ? mesh.indices.size() / 3 : 0;
		size_t instances = std::max(size_t(1), mesh.nodes.size() + mesh.instances.size());

		total_triangles += triangles * instances;
		total_instances += instances;
		total_draws += std::max(size_t(1), mesh.nodes.size());
	}

	FILE* out = fopen(path, "wb");
	if (!out)
		return false;

	fprintf(out, "{\n");
	fprintf(out, "\t\"generator\": \"gltfpack %s\",\n", getVersion().c_str());
	fprintf(out, "\t\"scene\": {\n");
	fprintf(out, "\t\t\"nodeCount\": %d,\n", int(node_count));
	fprintf(out, "\t\t\"meshCount\": %d,\n", int(mesh_count));
	fprintf(out, "\t\t\"materialCount\": %d,\n", int(material_count));
	fprintf(out, "\t\t\"textureCount\": %d,\n", int(texture_count));
	fprintf(out, "\t\t\"animationCount\": %d\n", int(animation_count));
	fprintf(out, "\t},\n");
	fprintf(out, "\t\"render\": {\n");
	fprintf(out, "\t\t\"drawCount\": %d,\n", int(total_draws));
	fprintf(out, "\t\t\"instanceCount\": %d,\n", int(total_instances));
	fprintf(out, "\t\t\"triangleCount\": %lld\n", (long long)total_triangles);
	fprintf(out, "\t},\n");
	fprintf(out, "\t\"data\": {\n");
	fprintf(out, "\t\t\"json\": %d,\n", int(json_size));
	fprintf(out, "\t\t\"binary\": %d,\n", int(bin_size));
	fprintf(out, "\t\t\"buffers\": {\n");
	fprintf(out, "\t\t\t\"vertex\": %d,\n", int(bytes[BufferView::Kind_Vertex]));
	fprintf(out, "\t\t\t\"index\": %d,\n", int(bytes[BufferView::Kind_Index]));
	fprintf(out, "\t\t\t\"animation\": %d,\n", int(bytes[BufferView::Kind_Time] + bytes[BufferView::Kind_Keyframe]));
	fprintf(out, "\t\t\t\"transform\": %d,\n", int(bytes[BufferView::Kind_Skin] + bytes[BufferView::Kind_Instance]));
	fprintf(out, "\t\t\t\"image\": %d\n", int(bytes[BufferView::Kind_Image]));
	fprintf(out, "\t\t}\n");
	fprintf(out, "\t}\n");
	fprintf(out, "}\n");

	int rc = fclose(out);
	return rc == 0;
}

static bool canTransformMesh(const Mesh& mesh)
{
	// volume thickness is specified in mesh coordinate space; to avoid modifying materials we prohibit transforming meshes with volume materials
	if (mesh.material && mesh.material->has_volume && mesh.material->volume.thickness_factor > 0.f)
		return false;

	return true;
}

static void detachMesh(Mesh& mesh, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings)
{
	// mesh is already instanced, skip
	if (!mesh.instances.empty())
		return;

	// mesh is already world space, skip
	if (mesh.nodes.empty())
		return;

	// note: when -kn is specified, we keep mesh-node attachment so that named nodes can be transformed
	if (settings.keep_nodes)
		return;

	// we keep skinned meshes or meshes with morph targets as is
	// in theory we could transform both, but in practice transforming morph target meshes is more involved,
	// and reparenting skinned meshes leads to incorrect bounding box generated in three.js
	if (mesh.skin || mesh.targets)
		return;

	bool any_animated = false;
	for (size_t j = 0; j < mesh.nodes.size(); ++j)
		any_animated |= nodes[mesh.nodes[j] - data->nodes].animated;

	// animated meshes will be anchored to the same node that they used to be in to retain the animation
	if (any_animated)
		return;

	int scene = nodes[mesh.nodes[0] - data->nodes].scene;
	bool any_other_scene = false;
	for (size_t j = 0; j < mesh.nodes.size(); ++j)
		any_other_scene |= scene != nodes[mesh.nodes[j] - data->nodes].scene;

	// we only merge instances when all nodes have a single consistent scene
	if (scene < 0 || any_other_scene)
		return;

	// we only merge multiple instances together if requested
	// this often makes the scenes faster to render by reducing the draw call count, but can result in larger files
	if (mesh.nodes.size() > 1 && !settings.mesh_merge && !settings.mesh_instancing)
		return;

	// mesh has duplicate geometry; detaching it would increase the size due to unique world-space transforms
	if (mesh.nodes.size() == 1 && mesh.geometry_duplicate && !settings.mesh_merge)
		return;

	// prefer instancing if possible, use merging otherwise
	if (mesh.nodes.size() > 1 && settings.mesh_instancing)
	{
		mesh.instances.resize(mesh.nodes.size());

		for (size_t j = 0; j < mesh.nodes.size(); ++j)
			cgltf_node_transform_world(mesh.nodes[j], mesh.instances[j].data);

		mesh.nodes.clear();
		mesh.scene = scene;
	}
	else if (canTransformMesh(mesh))
	{
		mergeMeshInstances(mesh);

		assert(mesh.nodes.empty());
		mesh.scene = scene;
	}
}

static bool isExtensionSupported(const ExtensionInfo* extensions, size_t count, const char* name)
{
	for (size_t i = 0; i < count; ++i)
		if (strcmp(extensions[i].name, name) == 0)
			return true;

	return false;
}

namespace std
{
template <>
struct hash<std::pair<uint64_t, uint64_t> >
{
	size_t operator()(const std::pair<uint64_t, uint64_t>& x) const
	{
		return std::hash<uint64_t>()(x.first ^ x.second);
	}
};
} // namespace std

static void process(cgltf_data* data, const char* input_path, const char* output_path, const char* report_path, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const Settings& settings, std::string& json, std::string& bin, std::string& fallback, size_t& fallback_size)
{
	if (settings.verbose)
	{
		printf("input: %d nodes, %d meshes (%d primitives), %d materials, %d skins, %d animations, %d images\n",
		    int(data->nodes_count), int(data->meshes_count), int(meshes.size()), int(data->materials_count), int(data->skins_count), int(animations.size()), int(data->images_count));
		printMeshStats(meshes, "input");
	}

	for (size_t i = 0; i < animations.size(); ++i)
		processAnimation(animations[i], settings);

	std::vector<NodeInfo> nodes(data->nodes_count);

	markScenes(data, nodes);
	markAnimated(data, nodes, animations);

	mergeMeshMaterials(data, meshes, settings);
	if (settings.mesh_dedup)
		dedupMeshes(meshes);

	for (size_t i = 0; i < meshes.size(); ++i)
		detachMesh(meshes[i], data, nodes, settings);

	// material information is required for mesh and image processing
	std::vector<MaterialInfo> materials(data->materials_count);
	std::vector<TextureInfo> textures(data->textures_count);
	std::vector<ImageInfo> images(data->images_count);

	analyzeMaterials(data, materials, textures, images);

	mergeTextures(data, textures);

	optimizeMaterials(data, input_path, images);

	// streams need to be filtered before mesh merging (or processing) to make sure we can merge meshes with redundant streams
	for (size_t i = 0; i < meshes.size(); ++i)
	{
		Mesh& mesh = meshes[i];
		MaterialInfo mi = mesh.material ? materials[mesh.material - data->materials] : MaterialInfo();

		// merge material requirements across all variants
		for (size_t j = 0; j < mesh.variants.size(); ++j)
		{
			MaterialInfo vi = materials[mesh.variants[j].material - data->materials];

			mi.needs_tangents |= vi.needs_tangents;
			mi.texture_set_mask |= vi.texture_set_mask;
			mi.unlit &= vi.unlit;
		}

		if (!settings.keep_attributes)
			filterStreams(mesh, mi);
	}

	mergeMeshes(meshes, settings);
	filterEmptyMeshes(meshes);

	markNeededNodes(data, nodes, meshes, animations, settings);
	markNeededMaterials(data, materials, meshes, settings);


	for (size_t i = 0; i < meshes.size(); ++i)
	{
		Mesh& mesh = meshes[i];
		processMesh(mesh, settings);

		if (mesh.geometry_duplicate)
			hashMesh(mesh);
	}


	filterEmptyMeshes(meshes); // some meshes may become empty after processing

	QuantizationPosition qp = prepareQuantizationPosition(meshes, settings);

	std::vector<QuantizationTexture> qt_materials(materials.size());
	std::vector<size_t> qt_meshes(meshes.size(), size_t(-1));
	prepareQuantizationTexture(data, qt_materials, qt_meshes, meshes, settings);

	QuantizationTexture qt_dummy = {};
	qt_dummy.bits = settings.tex_bits;

	std::string json_images;
	std::string json_samplers;
	std::string json_textures;
	std::string json_materials;
	std::string json_accessors;
	std::string json_meshes;
	std::string json_nodes;
	std::string json_skins;
	std::vector<std::string> json_roots(data->scenes_count);
	std::string json_animations;
	std::string json_cameras;
	std::string json_extensions;

	std::vector<BufferView> views;

	bool ext_pbr_specular_glossiness = false;
	bool ext_clearcoat = false;
	bool ext_transmission = false;
	bool ext_ior = false;
	bool ext_specular = false;
	bool ext_sheen = false;
	bool ext_volume = false;
	bool ext_emissive_strength = false;
	bool ext_iridescence = false;
	bool ext_anisotropy = false;
	bool ext_dispersion = false;
	bool ext_unlit = false;
	bool ext_instancing = false;
	bool ext_texture_transform = false;
	bool ext_texture_basisu = false;
	bool ext_texture_webp = false;

	size_t accr_offset = 0;
	size_t node_offset = 0;
	size_t mesh_offset = 0;
	size_t texture_offset = 0;
	size_t material_offset = 0;

	for (size_t i = 0; i < data->samplers_count; ++i)
	{
		const cgltf_sampler& sampler = data->samplers[i];

		comma(json_samplers);
		append(json_samplers, "{");
		writeSampler(json_samplers, sampler);
		append(json_samplers, "}");
	}

	std::vector<std::string> encoded_images;

#ifdef WITH_BASISU
	if (data->images_count && settings.texture_ktx2)
	{
		encoded_images.resize(data->images_count);

		encodeImages(encoded_images.data(), data, images, input_path, settings);
	}
#endif

	for (size_t i = 0; i < data->images_count; ++i)
	{
		const cgltf_image& image = data->images[i];

		std::string* encoded = (encoded_images.size() && !encoded_images[i].empty()) ? &encoded_images[i] : NULL;

		comma(json_images);
		append(json_images, "{");
		writeImage(json_images, views, image, images[i], encoded, i, input_path, output_path, settings);
		append(json_images, "}");

		if (encoded)
			*encoded = std::string(); // reclaim memory early
	}

	for (size_t i = 0; i < data->textures_count; ++i)
	{
		const cgltf_texture& texture = data->textures[i];

		if (!textures[i].keep)
			continue;

		comma(json_textures);
		append(json_textures, "{");
		writeTexture(json_textures, texture, texture.image ? &images[texture.image - data->images] : NULL, data, settings);
		append(json_textures, "}");

		assert(textures[i].remap == int(texture_offset));
		texture_offset++;
		ext_texture_basisu = ext_texture_basisu || texture.has_basisu;
		ext_texture_webp = ext_texture_webp || texture.has_webp;
	}

	for (size_t i = 0; i < data->materials_count; ++i)
	{
		MaterialInfo& mi = materials[i];

		if (!mi.keep)
			continue;

		const cgltf_material& material = data->materials[i];

		comma(json_materials);
		append(json_materials, "{");
		writeMaterial(json_materials, data, material, settings.quantize && !settings.pos_float ? &qp : NULL, settings.quantize && !settings.tex_float ? &qt_materials[i] : NULL, textures);
		if (settings.keep_extras)
			writeExtras(json_materials, material.extras);
		append(json_materials, "}");

		mi.remap = int(material_offset);
		material_offset++;

		ext_pbr_specular_glossiness = ext_pbr_specular_glossiness || material.has_pbr_specular_glossiness;
		ext_clearcoat = ext_clearcoat || material.has_clearcoat;
		ext_transmission = ext_transmission || material.has_transmission;
		ext_ior = ext_ior || material.has_ior;
		ext_specular = ext_specular || material.has_specular;
		ext_sheen = ext_sheen || material.has_sheen;
		ext_volume = ext_volume || material.has_volume;
		ext_emissive_strength = ext_emissive_strength || material.has_emissive_strength;
		ext_iridescence = ext_iridescence || material.has_iridescence;
		ext_anisotropy = ext_anisotropy || material.has_anisotropy;
		ext_dispersion = ext_dispersion || material.has_dispersion;
		ext_unlit = ext_unlit || material.unlit;
		ext_texture_transform = ext_texture_transform || mi.uses_texture_transform;
	}

	std::unordered_map<std::pair<uint64_t, uint64_t>, std::pair<size_t, size_t> > primitive_cache;

	for (size_t i = 0; i < meshes.size(); ++i)
	{
		const Mesh& mesh = meshes[i];

		comma(json_meshes);
		append(json_meshes, "{\"primitives\":[");

		size_t pi = i;
		for (; pi < meshes.size(); ++pi)
		{
			const Mesh& prim = meshes[pi];

			if (prim.scene != mesh.scene || prim.skin != mesh.skin || prim.targets != mesh.targets)
				break;

			if (pi > i && (mesh.instances.size() || prim.instances.size()))
				break;

			if (!compareMeshNodes(mesh, prim))
				break;

			if (!compareMeshTargets(mesh, prim))
				break;

			const QuantizationTexture& qt = qt_meshes[pi] == size_t(-1) ? qt_dummy : qt_materials[qt_meshes[pi]];

			comma(json_meshes);

			if (prim.geometry_duplicate)
			{
				std::pair<size_t, size_t>& primitive_json = primitive_cache[std::make_pair(prim.geometry_hash[0], prim.geometry_hash[1])];

				if (primitive_json.second)
				{
					// reuse previously written accessors
					json_meshes.append(json_meshes, primitive_json.first, primitive_json.second);
				}
				else
				{
					primitive_json.first = json_meshes.size();
					writeMeshGeometry(json_meshes, views, json_accessors, accr_offset, prim, qp, qt, settings);
					primitive_json.second = json_meshes.size() - primitive_json.first;
				}
			}
			else
			{
				writeMeshGeometry(json_meshes, views, json_accessors, accr_offset, prim, qp, qt, settings);
			}

			if (prim.material)
			{
				MaterialInfo& mi = materials[prim.material - data->materials];

				assert(mi.keep);
				append(json_meshes, ",\"material\":");
				append(json_meshes, size_t(mi.remap));
			}

			if (prim.variants.size())
			{
				append(json_meshes, ",\"extensions\":{\"KHR_materials_variants\":{\"mappings\":[");

				for (size_t j = 0; j < prim.variants.size(); ++j)
				{
					const cgltf_material_mapping& variant = prim.variants[j];
					MaterialInfo& mi = materials[variant.material - data->materials];

					assert(mi.keep);
					comma(json_meshes);
					append(json_meshes, "{\"material\":");
					append(json_meshes, size_t(mi.remap));
					append(json_meshes, ",\"variants\":[");
					append(json_meshes, size_t(variant.variant));
					append(json_meshes, "]}");
				}

				append(json_meshes, "]}}");
			}

			append(json_meshes, "}");
		}

		append(json_meshes, "]");

		if (mesh.target_weights.size())
		{
			append(json_meshes, ",\"weights\":[");
			for (size_t j = 0; j < mesh.target_weights.size(); ++j)
			{
				comma(json_meshes);
				append(json_meshes, mesh.target_weights[j]);
			}
			append(json_meshes, "]");
		}

		if (mesh.target_names.size())
		{
			append(json_meshes, ",\"extras\":{\"targetNames\":[");
			for (size_t j = 0; j < mesh.target_names.size(); ++j)
			{
				comma(json_meshes);
				append(json_meshes, "\"");
				append(json_meshes, mesh.target_names[j]);
				append(json_meshes, "\"");
			}
			append(json_meshes, "]}");
		}

		append(json_meshes, "}");

		if (mesh.nodes.size())
		{
			for (size_t j = 0; j < mesh.nodes.size(); ++j)
			{
				NodeInfo& ni = nodes[mesh.nodes[j] - data->nodes];
				assert(ni.keep);

				// if we don't use position quantization, prefer attaching the mesh to its node directly
				if (!ni.has_mesh && (!settings.quantize || settings.pos_float || (qp.offset[0] == 0.f && qp.offset[1] == 0.f && qp.offset[2] == 0 && qp.node_scale == 1.f)))
				{
					ni.has_mesh = true;
					ni.mesh_index = mesh_offset;
					ni.mesh_skin = mesh.skin;
				}
				else
				{
					ni.mesh_nodes.push_back(node_offset);

					writeMeshNode(json_nodes, mesh_offset, mesh.nodes[j], mesh.skin, data, settings.quantize && !settings.pos_float ? &qp : NULL);

					node_offset++;
				}
			}
		}

		if (mesh.instances.size())
		{
			assert(mesh.scene >= 0);
			comma(json_roots[mesh.scene]);
			append(json_roots[mesh.scene], node_offset);

			size_t instance_accr = writeInstances(views, json_accessors, accr_offset, mesh.instances, qp, settings);

			assert(!mesh.skin);
			writeMeshNodeInstanced(json_nodes, mesh_offset, instance_accr);

			node_offset++;
		}

		if (mesh.nodes.empty() && mesh.instances.empty())
		{
			assert(mesh.scene >= 0);
			comma(json_roots[mesh.scene]);
			append(json_roots[mesh.scene], node_offset);

			writeMeshNode(json_nodes, mesh_offset, NULL, mesh.skin, data, settings.quantize && !settings.pos_float ? &qp : NULL);

			node_offset++;
		}

		mesh_offset++;
		ext_instancing = ext_instancing || !mesh.instances.empty();

		// skip all meshes that we've written in this iteration
		assert(pi > i);
		i = pi - 1;
	}

	remapNodes(data, nodes, node_offset);

	for (size_t i = 0; i < data->nodes_count; ++i)
	{
		NodeInfo& ni = nodes[i];

		if (!ni.keep)
			continue;

		const cgltf_node& node = data->nodes[i];

		comma(json_nodes);
		append(json_nodes, "{");
		writeNode(json_nodes, node, nodes, data);
		if (settings.keep_extras)
			writeExtras(json_nodes, node.extras);
		append(json_nodes, "}");
	}

	for (size_t i = 0; i < data->scenes_count; ++i)
	{
		for (size_t j = 0; j < data->scenes[i].nodes_count; ++j)
		{
			NodeInfo& ni = nodes[data->scenes[i].nodes[j] - data->nodes];

			if (ni.keep)
			{
				comma(json_roots[i]);
				append(json_roots[i], size_t(ni.remap));
			}
		}
	}

	for (size_t i = 0; i < data->skins_count; ++i)
	{
		const cgltf_skin& skin = data->skins[i];

		size_t matrix_accr = writeJointBindMatrices(views, json_accessors, accr_offset, skin, qp, settings);

		writeSkin(json_skins, skin, matrix_accr, nodes, data);
	}

	for (size_t i = 0; i < animations.size(); ++i)
	{
		const Animation& animation = animations[i];

		writeAnimation(json_animations, views, json_accessors, accr_offset, animation, i, data, nodes, settings);
	}

	for (size_t i = 0; i < data->cameras_count; ++i)
	{
		const cgltf_camera& camera = data->cameras[i];

		writeCamera(json_cameras, camera);
	}

	if (data->lights_count > 0)
	{
		comma(json_extensions);
		append(json_extensions, "\"KHR_lights_punctual\":{\"lights\":[");

		for (size_t i = 0; i < data->lights_count; ++i)
		{
			const cgltf_light& light = data->lights[i];

			writeLight(json_extensions, light);
		}

		append(json_extensions, "]}");
	}

	if (data->variants_count > 0)
	{
		comma(json_extensions);
		append(json_extensions, "\"KHR_materials_variants\":{\"variants\":[");

		for (size_t i = 0; i < data->variants_count; ++i)
		{
			const cgltf_material_variant& variant = data->variants[i];

			comma(json_extensions);
			append(json_extensions, "{\"name\":\"");
			append(json_extensions, variant.name);
			append(json_extensions, "\"}");
		}

		append(json_extensions, "]}");
	}

	append(json, "\"asset\":{");
	append(json, "\"version\":\"2.0\",\"generator\":\"gltfpack ");
	append(json, getVersion());
	append(json, "\"");
	writeExtras(json, data->asset.extras);
	append(json, "}");

	const ExtensionInfo extensions[] = {
	    {"KHR_mesh_quantization", settings.quantize, true},
	    {"EXT_meshopt_compression", settings.compress, !settings.fallback},
	    {"KHR_texture_transform", (settings.quantize && !settings.tex_float && !json_textures.empty()) || ext_texture_transform, false},
	    {"KHR_materials_pbrSpecularGlossiness", ext_pbr_specular_glossiness, false},
	    {"KHR_materials_clearcoat", ext_clearcoat, false},
	    {"KHR_materials_transmission", ext_transmission, false},
	    {"KHR_materials_ior", ext_ior, false},
	    {"KHR_materials_specular", ext_specular, false},
	    {"KHR_materials_sheen", ext_sheen, false},
	    {"KHR_materials_volume", ext_volume, false},
	    {"KHR_materials_emissive_strength", ext_emissive_strength, false},
	    {"KHR_materials_iridescence", ext_iridescence, false},
	    {"KHR_materials_anisotropy", ext_anisotropy, false},
	    {"KHR_materials_dispersion", ext_dispersion, false},
	    {"KHR_materials_unlit", ext_unlit, false},
	    {"KHR_materials_variants", data->variants_count > 0, false},
	    {"KHR_lights_punctual", data->lights_count > 0, false},
	    {"KHR_texture_basisu", (!json_textures.empty() && settings.texture_ktx2) || ext_texture_basisu, true},
	    {"EXT_texture_webp", ext_texture_webp, true},
	    {"EXT_mesh_gpu_instancing", ext_instancing, true},
	};

	for (size_t i = 0; i < data->extensions_required_count; ++i)
	{
		const char* ext = data->extensions_required[i];

		if (!isExtensionSupported(extensions, sizeof(extensions) / sizeof(extensions[0]), ext))
			fprintf(stderr, "Warning: required extension %s is not supported and will be skipped\n", ext);
	}

	writeExtensions(json, extensions, sizeof(extensions) / sizeof(extensions[0]));

	std::string json_views;
	finalizeBufferViews(json_views, views, bin, settings.fallback ? &fallback : NULL, fallback_size);

	writeArray(json, "bufferViews", json_views);
	writeArray(json, "accessors", json_accessors);
	writeArray(json, "samplers", json_samplers);
	writeArray(json, "images", json_images);
	writeArray(json, "textures", json_textures);
	writeArray(json, "materials", json_materials);
	writeArray(json, "meshes", json_meshes);
	writeArray(json, "skins", json_skins);
	writeArray(json, "animations", json_animations);
	writeArray(json, "nodes", json_nodes);

	if (!json_roots.empty())
	{
		append(json, ",\"scenes\":[");

		for (size_t i = 0; i < data->scenes_count; ++i)
			writeScene(json, data->scenes[i], json_roots[i]);

		append(json, "]");
	}

	writeArray(json, "cameras", json_cameras);

	if (data->scene)
	{
		append(json, ",\"scene\":");
		append(json, size_t(data->scene - data->scenes));
	}

	if (!json_extensions.empty())
	{
		append(json, ",\"extensions\":{");
		append(json, json_extensions);
		append(json, "}");
	}

	if (settings.verbose)
	{
		printMeshStats(meshes, "output");
		printSceneStats(views, meshes, node_offset, mesh_offset, material_offset, json.size(), bin.size());
	}

	if (settings.verbose > 1)
	{
		printAttributeStats(views, BufferView::Kind_Vertex, "vertex");
		printAttributeStats(views, BufferView::Kind_Index, "index");
		printAttributeStats(views, BufferView::Kind_Keyframe, "keyframe");
		printAttributeStats(views, BufferView::Kind_Instance, "instance");

		printImageStats(views, TextureKind_Generic, "generic");
		printImageStats(views, TextureKind_Color, "color");
		printImageStats(views, TextureKind_Normal, "normal");
		printImageStats(views, TextureKind_Attrib, "attrib");
	}

	if (report_path)
	{
		if (!printReport(report_path, views, meshes, node_offset, mesh_offset, texture_offset, material_offset, animations.size(), json.size(), bin.size()))
		{
			fprintf(stderr, "Warning: cannot save report to %s\n", report_path);
		}
	}
}

static void writeU32(FILE* out, uint32_t data)
{
	fwrite(&data, 4, 1, out);
}

static const char* getBaseName(const char* path)
{
	const char* slash = strrchr(path, '/');
	const char* backslash = strrchr(path, '\\');

	const char* rs = slash ? slash + 1 : path;
	const char* bs = backslash ? backslash + 1 : path;

	return std::max(rs, bs);
}

static std::string getBufferSpec(const char* bin_path, size_t bin_size, const char* fallback_path, size_t fallback_size, bool fallback_ref)
{
	std::string json;
	append(json, "\"buffers\":[");
	append(json, "{");
	if (bin_path)
	{
		append(json, "\"uri\":\"");
		append(json, bin_path);
		append(json, "\"");
	}
	comma(json);
	append(json, "\"byteLength\":");
	append(json, bin_size);
	append(json, "}");
	if (fallback_ref)
	{
		comma(json);
		append(json, "{");
		if (fallback_path)
		{
			append(json, "\"uri\":\"");
			append(json, fallback_path);
			append(json, "\"");
		}
		comma(json);
		append(json, "\"byteLength\":");
		append(json, fallback_size);
		append(json, ",\"extensions\":{");
		append(json, "\"EXT_meshopt_compression\":{");
		append(json, "\"fallback\":true");
		append(json, "}}");
		append(json, "}");
	}
	append(json, "]");

	return json;
}

int gltfpack(const char* input, const char* output, const char* report, Settings settings)
{
	cgltf_data* data = NULL;
	std::vector<Mesh> meshes;
	std::vector<Animation> animations;

	std::string iext = getExtension(input);
	std::string oext = output ? getExtension(output) : "";

	if (iext == ".gltf" || iext == ".glb")
	{
		const char* error = NULL;
		data = parseGltf(input, meshes, animations, &error);

		if (error)
		{
			fprintf(stderr, "Error loading %s: %s\n", input, error);
			return 2;
		}
	}
	else if (iext == ".obj")
	{
		const char* error = NULL;
		data = parseObj(input, meshes, &error);

		if (!data)
		{
			fprintf(stderr, "Error loading %s: %s\n", input, error);
			return 2;
		}
	}
	else
	{
		fprintf(stderr, "Error loading %s: unknown extension (expected .gltf or .glb or .obj)\n", input);
		return 2;
	}

#ifndef WITH_BASISU
	if (data->images_count && settings.texture_ktx2)
	{
		fprintf(stderr, "Error: gltfpack was built without BasisU support, texture compression is not available\n");
#ifdef __wasi__
		fprintf(stderr, "Note: node.js builds do not support BasisU due to lack of platform features; download a native build from https://github.com/zeux/meshoptimizer/releases\n");
#endif
		return 3;
	}
#endif

	if (oext == ".glb")
	{
		settings.texture_embed = true;
	}

	if (data->images_count && !settings.texture_ref && !settings.texture_embed)
	{
		for (size_t i = 0; i < data->images_count; ++i)
		{
			const char* uri = data->images[i].uri;
			if (!uri || strncmp(uri, "data:", 5) == 0)
				continue;

			for (size_t j = 0; j < i; ++j)
			{
				const char* urj = data->images[j].uri;
				if (!urj || strncmp(urj, "data:", 5) == 0)
					continue;

				if (strcmp(uri, urj) != 0 && strcmp(getBaseName(uri), getBaseName(urj)) == 0)
				{
					fprintf(stderr, "Warning: images %s and %s share the same base name and will overwrite each other\n", uri, urj);
					break;
				}
			}
		}
	}

	std::string json, bin, fallback;
	size_t fallback_size = 0;
	process(data, input, output, report, meshes, animations, settings, json, bin, fallback, fallback_size);

	cgltf_free(data);

	if (!output)
	{
		return 0;
	}

	if (oext == ".gltf")
	{
		std::string binpath = output;
		binpath.replace(binpath.size() - 5, 5, ".bin");

		std::string fbpath = output;
		fbpath.replace(fbpath.size() - 5, 5, ".fallback.bin");

		FILE* outjson = fopen(output, "wb");
		FILE* outbin = fopen(binpath.c_str(), "wb");
		FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
		if (!outjson || !outbin || (!outfb && settings.fallback))
		{
			fprintf(stderr, "Error saving %s\n", output);
			return 4;
		}

		std::string bufferspec = getBufferSpec(getBaseName(binpath.c_str()), bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback_size, settings.compress);

		fprintf(outjson, "{");
		fwrite(bufferspec.c_str(), bufferspec.size(), 1, outjson);
		fprintf(outjson, ",");
		fwrite(json.c_str(), json.size(), 1, outjson);
		fprintf(outjson, "}");

		fwrite(bin.c_str(), bin.size(), 1, outbin);

		if (settings.fallback)
			fwrite(fallback.c_str(), fallback.size(), 1, outfb);

		int rc = 0;
		rc |= fclose(outjson);
		rc |= fclose(outbin);
		if (outfb)
			rc |= fclose(outfb);

		if (rc)
		{
			fprintf(stderr, "Error saving %s\n", output);
			return 4;
		}
	}
	else if (oext == ".glb")
	{
		std::string fbpath = output;
		fbpath.replace(fbpath.size() - 4, 4, ".fallback.bin");

		FILE* out = fopen(output, "wb");
		FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
		if (!out || (!outfb && settings.fallback))
		{
			fprintf(stderr, "Error saving %s\n", output);
			return 4;
		}

		std::string bufferspec = getBufferSpec(NULL, bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback_size, settings.compress);

		json.insert(0, "{" + bufferspec + ",");
		json.push_back('}');

		while (json.size() % 4)
			json.push_back(' ');

		while (bin.size() % 4)
			bin.push_back('\0');

		writeU32(out, 0x46546C67);
		writeU32(out, 2);
		writeU32(out, uint32_t(12 + 8 + json.size() + 8 + bin.size()));

		writeU32(out, uint32_t(json.size()));
		writeU32(out, 0x4E4F534A);
		fwrite(json.c_str(), json.size(), 1, out);

		writeU32(out, uint32_t(bin.size()));
		writeU32(out, 0x004E4942);
		fwrite(bin.c_str(), bin.size(), 1, out);

		if (settings.fallback)
			fwrite(fallback.c_str(), fallback.size(), 1, outfb);

		int rc = 0;
		rc |= fclose(out);
		if (outfb)
			rc |= fclose(outfb);

		if (rc)
		{
			fprintf(stderr, "Error saving %s\n", output);
			return 4;
		}
	}
	else
	{
		fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output);
		return 4;
	}

	return 0;
}

Settings defaults()
{
	Settings settings = {};
	settings.quantize = true;
	settings.pos_bits = 14;
	settings.tex_bits = 12;
	settings.nrm_bits = 8;
	settings.col_bits = 8;
	settings.trn_bits = 16;
	settings.rot_bits = 12;
	settings.scl_bits = 16;
	settings.anim_freq = 30;
	settings.mesh_dedup = true;
	settings.simplify_ratio = 1.f;
	settings.simplify_error = 1e-2f;
	settings.texture_scale = 1.f;
	for (int kind = 0; kind < TextureKind__Count; ++kind)
		settings.texture_quality[kind] = 8;

	return settings;
}

template <typename T>
T clamp(T v, T min, T max)
{
	return v < min ? min : (v > max ? max : v);
}

unsigned int textureMask(const char* arg)
{
	unsigned int result = 0;

	while (arg)
	{
		const char* comma = strchr(arg, ',');
		size_t seg = comma ? comma - arg - 1 : strlen(arg);

		if (strncmp(arg, "color", seg) == 0)
			result |= 1 << TextureKind_Color;
		else if (strncmp(arg, "normal", seg) == 0)
			result |= 1 << TextureKind_Normal;
		else if (strncmp(arg, "attrib", seg) == 0)
			result |= 1 << TextureKind_Attrib;
		else
			fprintf(stderr, "Warning: unrecognized texture class %.*s\n", int(seg), arg);

		arg = comma ? comma + 1 : NULL;
	}

	return result;
}

#ifndef GLTFFUZZ
int main(int argc, char** argv)
{
#ifndef __wasi__
	setlocale(LC_ALL, "C"); // disable locale specific convention for number parsing/printing
#endif

	meshopt_encodeVertexVersion(0);
	meshopt_encodeIndexVersion(1);

	Settings settings = defaults();

	const char* input = NULL;
	const char* output = NULL;
	const char* report = NULL;
	bool help = false;
	bool test = false;

	std::vector<const char*> testinputs;

	for (int i = 1; i < argc; ++i)
	{
		const char* arg = argv[i];

		if (strcmp(arg, "-vp") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.pos_bits = clamp(atoi(argv[++i]), 1, 16);
		}
		else if (strcmp(arg, "-vt") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.tex_bits = clamp(atoi(argv[++i]), 1, 16);
		}
		else if (strcmp(arg, "-vn") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.nrm_bits = clamp(atoi(argv[++i]), 1, 16);
		}
		else if (strcmp(arg, "-vc") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.col_bits = clamp(atoi(argv[++i]), 1, 16);
		}
		else if (strcmp(arg, "-vpi") == 0)
		{
			settings.pos_float = false;
			settings.pos_normalized = false;
		}
		else if (strcmp(arg, "-vpn") == 0)
		{
			settings.pos_float = false;
			settings.pos_normalized = true;
		}
		else if (strcmp(arg, "-vpf") == 0)
		{
			settings.pos_float = true;
		}
		else if (strcmp(arg, "-vtf") == 0)
		{
			settings.tex_float = true;
		}
		else if (strcmp(arg, "-vnf") == 0)
		{
			settings.nrm_float = true;
		}
		else if (strcmp(arg, "-at") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.trn_bits = clamp(atoi(argv[++i]), 1, 24);
		}
		else if (strcmp(arg, "-ar") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.rot_bits = clamp(atoi(argv[++i]), 4, 16);
		}
		else if (strcmp(arg, "-as") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.scl_bits = clamp(atoi(argv[++i]), 1, 24);
		}
		else if (strcmp(arg, "-af") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.anim_freq = clamp(atoi(argv[++i]), 1, 100);
		}
		else if (strcmp(arg, "-ac") == 0)
		{
			settings.anim_const = true;
		}
		else if (strcmp(arg, "-kn") == 0)
		{
			settings.keep_nodes = true;
		}
		else if (strcmp(arg, "-km") == 0)
		{
			settings.keep_materials = true;
		}
		else if (strcmp(arg, "-ke") == 0)
		{
			settings.keep_extras = true;
		}
		else if (strcmp(arg, "-kv") == 0)
		{
			settings.keep_attributes = true;
		}
		else if (strcmp(arg, "-mdd") == 0)
		{
			fprintf(stderr, "Warning: option -mdd disables mesh deduplication and is only provided as a safety measure; it will be removed in the future\n");
			settings.mesh_dedup = false;
		}
		else if (strcmp(arg, "-mm") == 0)
		{
			settings.mesh_merge = true;
		}
		else if (strcmp(arg, "-mi") == 0)
		{
			settings.mesh_instancing = true;
		}
		else if (strcmp(arg, "-si") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.simplify_ratio = clamp(float(atof(argv[++i])), 0.f, 1.f);
		}
		else if (strcmp(arg, "-se") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.simplify_error = clamp(float(atof(argv[++i])), 0.f, 1.f);
		}
		else if (strcmp(arg, "-sa") == 0)
		{
			settings.simplify_aggressive = true;
		}
		else if (strcmp(arg, "-slb") == 0)
		{
			settings.simplify_lock_borders = true;
		}
		else if (strcmp(arg, "-sv") == 0)
		{
			settings.simplify_attributes = true;
		}
		else if (strcmp(arg, "-tu") == 0)
		{
			settings.texture_ktx2 = true;

			unsigned int mask = ~0u;
			if (i + 1 < argc && isalpha(argv[i + 1][0]))
				mask = textureMask(argv[++i]);

			for (int kind = 0; kind < TextureKind__Count; ++kind)
				if (mask & (1 << kind))
					settings.texture_mode[kind] = TextureMode_UASTC;
		}
		else if (strcmp(arg, "-tc") == 0)
		{
			settings.texture_ktx2 = true;

			unsigned int mask = ~0u;
			if (i + 1 < argc && isalpha(argv[i + 1][0]))
				mask = textureMask(argv[++i]);

			for (int kind = 0; kind < TextureKind__Count; ++kind)
				if (mask & (1 << kind))
					settings.texture_mode[kind] = TextureMode_ETC1S;
		}
		else if (strcmp(arg, "-tq") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			int quality = clamp(atoi(argv[++i]), 1, 10);
			for (int kind = 0; kind < TextureKind__Count; ++kind)
				settings.texture_quality[kind] = quality;
		}
		else if (strcmp(arg, "-tq") == 0 && i + 2 < argc && isalpha(argv[i + 1][0]) && isdigit(argv[i + 2][0]))
		{
			unsigned int mask = textureMask(argv[++i]);
			int quality = clamp(atoi(argv[++i]), 1, 10);

			for (int kind = 0; kind < TextureKind__Count; ++kind)
				if (mask & (1 << kind))
					settings.texture_quality[kind] = quality;
		}
		else if (strcmp(arg, "-ts") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.texture_scale = clamp(float(atof(argv[++i])), 0.f, 1.f);
		}
		else if (strcmp(arg, "-tl") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.texture_limit = atoi(argv[++i]);
		}
		else if (strcmp(arg, "-tp") == 0)
		{
			settings.texture_pow2 = true;
		}
		else if (strcmp(arg, "-tfy") == 0)
		{
			settings.texture_flipy = true;
		}
		else if (strcmp(arg, "-tr") == 0)
		{
			settings.texture_ref = true;
		}
		else if (strcmp(arg, "-tj") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
		{
			settings.texture_jobs = clamp(atoi(argv[++i]), 0, 128);
		}
		else if (strcmp(arg, "-noq") == 0)
		{
			// TODO: Warn if -noq is used and suggest -vpf instead; use -noqq to silence
			settings.quantize = false;
		}
		else if (strcmp(arg, "-i") == 0 && i + 1 < argc && !input)
		{
			input = argv[++i];
		}
		else if (strcmp(arg, "-o") == 0 && i + 1 < argc && !output)
		{
			output = argv[++i];
		}
		else if (strcmp(arg, "-r") == 0 && i + 1 < argc && !report)
		{
			report = argv[++i];
		}
		else if (strcmp(arg, "-c") == 0)
		{
			settings.compress = true;
		}
		else if (strcmp(arg, "-cc") == 0)
		{
			settings.compress = true;
			settings.compressmore = true;
		}
		else if (strcmp(arg, "-cf") == 0)
		{
			settings.compress = true;
			settings.fallback = true;
		}
		else if (strcmp(arg, "-v") == 0)
		{
			settings.verbose = 1;
		}
		else if (strcmp(arg, "-vv") == 0)
		{
			settings.verbose = 2;
		}
		else if (strcmp(arg, "-h") == 0)
		{
			help = true;
		}
		else if (strcmp(arg, "-test") == 0)
		{
			test = true;
		}
		else if (arg[0] == '-')
		{
			fprintf(stderr, "Unrecognized option %s\n", arg);
			return 1;
		}
		else if (test)
		{
			testinputs.push_back(arg);
		}
		else
		{
			fprintf(stderr, "Expected option, got %s instead\n", arg);
			return 1;
		}
	}

	// shortcut for gltfpack -v
	if (settings.verbose && argc == 2)
	{
		printf("gltfpack %s\n", getVersion().c_str());
		return 0;
	}

	if (test)
	{
		for (size_t i = 0; i < testinputs.size(); ++i)
		{
			const char* path = testinputs[i];

			printf("%s\n", path);
			gltfpack(path, NULL, NULL, settings);
		}

		return 0;
	}

	if (!input || !output || help)
	{
		fprintf(stderr, "gltfpack %s\n", getVersion().c_str());
		fprintf(stderr, "Usage: gltfpack [options] -i input -o output\n");

		if (help)
		{
			fprintf(stderr, "\nBasics:\n");
			fprintf(stderr, "\t-i file: input file to process, .obj/.gltf/.glb\n");
			fprintf(stderr, "\t-o file: output file path, .gltf/.glb\n");
			fprintf(stderr, "\t-c: produce compressed gltf/glb files (-cc for higher compression ratio)\n");
			fprintf(stderr, "\nTextures:\n");
			fprintf(stderr, "\t-tc: convert all textures to KTX2 with BasisU supercompression\n");
			fprintf(stderr, "\t-tu: use UASTC when encoding textures (much higher quality and much larger size)\n");
			fprintf(stderr, "\t-tq N: set texture encoding quality (default: 8; N should be between 1 and 10\n");
			fprintf(stderr, "\t-ts R: scale texture dimensions by the ratio R (default: 1; R should be between 0 and 1)\n");
			fprintf(stderr, "\t-tl N: limit texture dimensions to N pixels (default: 0 = no limit)\n");
			fprintf(stderr, "\t-tp: resize textures to nearest power of 2 to conform to WebGL1 restrictions\n");
			fprintf(stderr, "\t-tfy: flip textures along Y axis during BasisU supercompression\n");
			fprintf(stderr, "\t-tj N: use N threads when compressing textures\n");
			fprintf(stderr, "\t-tr: keep referring to original texture paths instead of copying/embedding images\n");
			fprintf(stderr, "\tTexture classes:\n");
			fprintf(stderr, "\t-tc C: use ETC1S when encoding textures of class C\n");
			fprintf(stderr, "\t-tu C: use UASTC when encoding textures of class C\n");
			fprintf(stderr, "\t-tq C N: set texture encoding quality for class C\n");
			fprintf(stderr, "\t... where C is a comma-separated list (no spaces) with valid values color,normal,attrib\n");
			fprintf(stderr, "\nSimplification:\n");
			fprintf(stderr, "\t-si R: simplify meshes targeting triangle/point count ratio R (default: 1; R should be between 0 and 1)\n");
			fprintf(stderr, "\t-se E: limit simplification error to E (default: 0.01 = 1%% deviation; E should be between 0 and 1)\n");
			fprintf(stderr, "\t-sa: aggressively simplify to the target ratio disregarding quality\n");
			fprintf(stderr, "\t-sv: take vertex attributes into account when simplifying meshes\n");
			fprintf(stderr, "\t-slb: lock border vertices during simplification to avoid gaps on connected meshes\n");
			fprintf(stderr, "\nVertex precision:\n");
			fprintf(stderr, "\t-vp N: use N-bit quantization for positions (default: 14; N should be between 1 and 16)\n");
			fprintf(stderr, "\t-vt N: use N-bit quantization for texture coordinates (default: 12; N should be between 1 and 16)\n");
			fprintf(stderr, "\t-vn N: use N-bit quantization for normals (default: 8; N should be between 1 and 16) and tangents (up to 8-bit)\n");
			fprintf(stderr, "\t-vc N: use N-bit quantization for colors (default: 8; N should be between 1 and 16)\n");
			fprintf(stderr, "\nVertex positions:\n");
			fprintf(stderr, "\t-vpi: use integer attributes for positions (default)\n");
			fprintf(stderr, "\t-vpn: use normalized attributes for positions\n");
			fprintf(stderr, "\t-vpf: use floating point attributes for positions\n");
			fprintf(stderr, "\nVertex attributes:\n");
			fprintf(stderr, "\t-vtf: use floating point attributes for texture coordinates\n");
			fprintf(stderr, "\t-vnf: use floating point attributes for normals\n");
			fprintf(stderr, "\t-kv: keep source vertex attributes even if they aren't used\n");
			fprintf(stderr, "\nAnimations:\n");
			fprintf(stderr, "\t-at N: use N-bit quantization for translations (default: 16; N should be between 1 and 24)\n");
			fprintf(stderr, "\t-ar N: use N-bit quantization for rotations (default: 12; N should be between 4 and 16)\n");
			fprintf(stderr, "\t-as N: use N-bit quantization for scale (default: 16; N should be between 1 and 24)\n");
			fprintf(stderr, "\t-af N: resample animations at N Hz (default: 30)\n");
			fprintf(stderr, "\t-ac: keep constant animation tracks even if they don't modify the node transform\n");
			fprintf(stderr, "\nScene:\n");
			fprintf(stderr, "\t-kn: keep named nodes and meshes attached to named nodes so that named nodes can be transformed externally\n");
			fprintf(stderr, "\t-km: keep named materials and disable named material merging\n");
			fprintf(stderr, "\t-ke: keep extras data\n");
			fprintf(stderr, "\t-mm: merge instances of the same mesh together when possible\n");
			fprintf(stderr, "\t-mi: use EXT_mesh_gpu_instancing when serializing multiple mesh instances\n");
			fprintf(stderr, "\nMiscellaneous:\n");
			fprintf(stderr, "\t-cf: produce compressed gltf/glb files with fallback for loaders that don't support compression\n");
			fprintf(stderr, "\t-noq: disable quantization; produces much larger glTF files with no extensions\n");
			fprintf(stderr, "\t-v: verbose output (print version when used without other options)\n");
			fprintf(stderr, "\t-r file: output a JSON report to file\n");
			fprintf(stderr, "\t-h: display this help and exit\n");
		}
		else
		{
			fprintf(stderr, "\nBasics:\n");
			fprintf(stderr, "\t-i file: input file to process, .obj/.gltf/.glb\n");
			fprintf(stderr, "\t-o file: output file path, .gltf/.glb\n");
			fprintf(stderr, "\t-c: produce compressed gltf/glb files (-cc for higher compression ratio)\n");
			fprintf(stderr, "\t-tc: convert all textures to KTX2 with BasisU supercompression\n");
			fprintf(stderr, "\t-si R: simplify meshes targeting triangle/point count ratio R (between 0 and 1)\n");
			fprintf(stderr, "\nRun gltfpack -h to display a full list of options\n");
		}

		return 1;
	}

	if (settings.texture_limit && !settings.texture_ktx2)
	{
		fprintf(stderr, "Option -tl is only supported when -tc is set as well\n");
		return 1;
	}

	if (settings.texture_pow2 && (settings.texture_limit & (settings.texture_limit - 1)) != 0)
	{
		fprintf(stderr, "Option -tp requires the limit specified via -tl to be a power of 2\n");
		return 1;
	}

	if (settings.texture_scale < 1 && !settings.texture_ktx2)
	{
		fprintf(stderr, "Option -ts is only supported when -tc is set as well\n");
		return 1;
	}

	if (settings.texture_pow2 && !settings.texture_ktx2)
	{
		fprintf(stderr, "Option -tp is only supported when -tc is set as well\n");
		return 1;
	}

	if (settings.texture_flipy && !settings.texture_ktx2)
	{
		fprintf(stderr, "Option -tfy is only supported when -tc is set as well\n");
		return 1;
	}

	if (settings.texture_ref && settings.texture_ktx2)
	{
		fprintf(stderr, "Option -tr currently can not be used together with -tc\n");
		return 1;
	}

	if (settings.fallback && settings.compressmore)
	{
		fprintf(stderr, "Option -cf can not be used together with -cc\n");
		return 1;
	}

	if (settings.fallback && (settings.pos_float || settings.tex_float || settings.nrm_float))
	{
		fprintf(stderr, "Option -cf can not be used together with -vpf, -vtf or -vnf\n");
		return 1;
	}

	if (settings.keep_nodes && (settings.mesh_merge || settings.mesh_instancing))
	{
		fprintf(stderr, "Warning: option -kn disables mesh merge (-mm) and mesh instancing (-mi) optimizations\n");
	}

	return gltfpack(input, output, report, settings);
}
#endif

#ifdef __wasi__
extern "C" int pack(int argc, char** argv)
{
	chdir("/gltfpack-$pwd");

	int result = main(argc, argv);
	fflush(NULL);
	return result;
}
#endif

#ifdef GLTFFUZZ
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* buffer, size_t size)
{
	Settings settings = defaults();

	settings.texture_embed = true;

	std::vector<Mesh> meshes;
	std::vector<Animation> animations;

	const char* error = NULL;
	cgltf_data* data = parseGlb(buffer, size, meshes, animations, &error);

	// this is a difficult tradeoff
	// returning 0 on files that fail to parse means that fuzzing is more incremental: files with errors are put into the corpus,
	// and the subsequent mutations may lead to discovering more interesting inputs, including valid ones that are difficult to find otherwise.
	// however, this leads to most of the corpus being invalid, and we very rarely get useful coverage for actual gltfpack processing.
	// for now we just focus on valid files, as we expect cgltf parser itself to be bulletproof as it's fuzzed separately.
	if (error)
		return -1;

	std::string json, bin, fallback;
	size_t fallback_size = 0;
	process(data, NULL, NULL, NULL, meshes, animations, settings, json, bin, fallback, fallback_size);

	cgltf_free(data);

	return 0;
}
#endif