alice-sdf 6.0.0

ALICE-SDF: 3D/Spatial Data Specialist — Store laws, not polygons. GLSL/WGSL/HLSL transpile, SVO, GPU marching cubes, texture-fit, procedural CSG. Optional bridges to alice-physics / alice-codec / libasp / alice-cache behind features.
Documentation
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
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
//! glTF 2.0 export for ALICE-SDF meshes
//!
//! Exports meshes to glTF 2.0 binary (.glb) format with PBR materials.
//! Compatible with UE5, Unity, Blender, Godot, and web viewers.
//!
//! Implements minimal glTF spec without external dependencies:
//! - Binary buffer with vertex/index data
//! - PBR metallic-roughness material model
//! - Single-mesh, single-scene structure
//!
//! Author: Moroya Sakamoto

use crate::compiled::real::LawMinMax;
use crate::io::IoError;
use crate::material::MaterialLibrary;
use crate::mesh::Mesh;
use std::io::Write;
use std::path::Path;

/// glTF export configuration
#[derive(Debug, Clone)]
pub struct GltfConfig {
    /// Export normals
    pub export_normals: bool,
    /// Export UVs (TEXCOORD_0)
    pub export_uvs: bool,
    /// Export lightmap UVs (TEXCOORD_1)
    pub export_uv2: bool,
    /// Export vertex colors
    pub export_colors: bool,
    /// Export tangents
    pub export_tangents: bool,
    /// Export materials with PBR properties
    pub export_materials: bool,
    /// Quantize positions to 16-bit (reduces file size ~50%)
    pub quantize_positions: bool,
    /// Embed textures in GLB binary buffer (self-contained assets)
    pub embed_textures: bool,
    /// Export extended PBR material extensions (clearcoat, sheen, etc.)
    pub export_extensions: bool,
    /// Force `"doubleSided":true` for all materials.
    ///
    /// glTF default is `false`, which causes back-face culling in Unity / Unreal /
    /// Blender solid view / `three.js` default. When a mesh is generated (e.g.,
    /// from Dual Contouring / Marching Cubes) with mixed face orientation,
    /// the back-culled faces disappear and the model looks like it has
    /// missing surfaces. Setting this to `true` guarantees both sides are drawn.
    ///
    /// Reference: dotneet/image-to-3d §5 「面が欠けて見える問題」
    pub double_sided: bool,
    /// Quantize normals to `SBYTE snorm` (i8, 3 bytes/vertex).
    ///
    /// Requires `KHR_mesh_quantization` extension. Precision ~0.8% (1/127),
    /// acceptable for game / real-time use where normal accuracy is not critical.
    /// Reduces normal storage from 12 bytes/vertex to 3 bytes/vertex (~75% savings).
    pub quantize_normals: bool,
    /// Quantize UVs to `USHORT unorm` (u16, 4 bytes/vertex).
    ///
    /// Requires `KHR_mesh_quantization` extension. Precision ~0.0015% (1/65535),
    /// nearly imperceptible for texture sampling. Reduces UV storage from
    /// 8 bytes/vertex to 4 bytes/vertex (~50% savings).
    pub quantize_uvs: bool,
    /// Quantize vertex colors to `UBYTE unorm` (u8, 4 bytes/vertex).
    ///
    /// Requires `KHR_mesh_quantization` extension. Precision ~0.4% (1/255),
    /// same as typical 8-bit texture colors. Reduces color storage from
    /// 16 bytes/vertex to 4 bytes/vertex (~75% savings).
    pub quantize_colors: bool,
    /// Quantize tangents to `SBYTE snorm` (i8, 4 bytes/vertex).
    ///
    /// Requires `KHR_mesh_quantization` extension. Same pattern as normals but with
    /// 4th component (handedness sign, snorm [-1, 1] where -1 = flipped, +1 = normal).
    /// Reduces tangent storage from 16 bytes/vertex to 4 bytes/vertex (~75% savings).
    pub quantize_tangents: bool,
    /// Apply `EXT_meshopt_compression` on all bufferViews (indices + attributes)
    ///
    /// When enabled, `export_glb` / `export_glb_bytes` internally delegate to
    /// [`crate::io::meshopt_gltf::export_glb_meshopt_bytes`] which produces
    /// a compact GLB compatible with meshopt-aware loaders (typical size
    /// reduction: 30-60% of raw payload for real meshes).
    ///
    /// # Limitations when enabled
    ///
    /// - PBR material extensions (clearcoat/sheen/anisotropy) are NOT applied
    /// - Vertex quantization (`quantize_*`) is NOT combined with meshopt
    /// - Only POSITION / NORMAL / TEXCOORD_0 / indices are emitted
    /// - `MaterialLibrary` textures are NOT embedded
    ///
    /// For AAA workflows requiring both PBR and compression, apply meshopt
    /// compression as a separate pipeline step after gltf export
    pub meshopt_compress: bool,
    /// Meshopt compression level (0=scalar / 2=u16 estimate / 3=u32 XOR estimate)
    ///
    /// Only used when `meshopt_compress` is `true` Default: 2 (good balance
    /// between compression ratio and encoding time)
    pub meshopt_level: u8,
}

impl Default for GltfConfig {
    fn default() -> Self {
        Self {
            export_normals: true,
            export_uvs: true,
            export_uv2: false,
            export_colors: false,
            export_tangents: false,
            export_materials: true,
            quantize_positions: false,
            embed_textures: false,
            export_extensions: false,
            double_sided: false,
            quantize_normals: false,
            quantize_uvs: false,
            quantize_colors: false,
            quantize_tangents: false,
            meshopt_compress: false,
            meshopt_level: 2,
        }
    }
}

impl GltfConfig {
    /// Full AAA config with all attributes
    pub const fn aaa() -> Self {
        Self {
            export_normals: true,
            export_uvs: true,
            export_uv2: true,
            export_colors: true,
            export_tangents: true,
            export_materials: true,
            quantize_positions: false,
            embed_textures: true,
            export_extensions: true,
            double_sided: true,
            quantize_normals: false,
            quantize_uvs: false,
            quantize_colors: false,
            quantize_tangents: false,
            meshopt_compress: false,
            meshopt_level: 2,
        }
    }
}

// GLB constants
const GLB_MAGIC: u32 = 0x46546C67; // "glTF"
const GLB_VERSION: u32 = 2;
const GLB_CHUNK_JSON: u32 = 0x4E4F534A; // "JSON"
const GLB_CHUNK_BIN: u32 = 0x004E4942; // "BIN\0"

// Component types
const FLOAT: u32 = 5126;
const UNSIGNED_INT: u32 = 5125;
const UNSIGNED_SHORT: u32 = 5123;
const SHORT: u32 = 5122;
const UNSIGNED_BYTE: u32 = 5121;
const BYTE: u32 = 5120;

// Buffer view targets
const ARRAY_BUFFER: u32 = 34962;
const ELEMENT_ARRAY_BUFFER: u32 = 34963;

/// Export a mesh to glTF 2.0 Binary (.glb) format
pub fn export_glb(
    mesh: &Mesh,
    path: impl AsRef<Path>,
    config: &GltfConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(), IoError> {
    // meshopt compression path: delegate to meshopt_gltf module
    // (see GltfConfig::meshopt_compress docs for limitations)
    if config.meshopt_compress {
        use crate::io::meshopt_gltf::{export_glb_meshopt, MeshoptGltfConfig};
        let mo_config = MeshoptGltfConfig {
            export_normals: config.export_normals,
            export_uvs: config.export_uvs,
            level: config.meshopt_level,
            double_sided: config.double_sided,
        };
        return export_glb_meshopt(mesh, path, &mo_config);
    }

    let (json_bytes, bin_bytes) = build_glb_data(mesh, config, materials)?;

    let file = std::fs::File::create(path)?;
    let mut w = std::io::BufWriter::new(file);

    // Pad JSON to 4-byte alignment
    let json_padded_len = (json_bytes.len() + 3) & !3;
    let bin_padded_len = (bin_bytes.len() + 3) & !3;

    let total_len = 12 + 8 + json_padded_len + 8 + bin_padded_len;

    // GLB header (12 bytes)
    w.write_all(&GLB_MAGIC.to_le_bytes())?;
    w.write_all(&GLB_VERSION.to_le_bytes())?;
    w.write_all(&(total_len as u32).to_le_bytes())?;

    // JSON chunk
    w.write_all(&(json_padded_len as u32).to_le_bytes())?;
    w.write_all(&GLB_CHUNK_JSON.to_le_bytes())?;
    w.write_all(&json_bytes)?;
    // Pad with spaces
    for _ in 0..(json_padded_len - json_bytes.len()) {
        w.write_all(b" ")?;
    }

    // BIN chunk
    w.write_all(&(bin_padded_len as u32).to_le_bytes())?;
    w.write_all(&GLB_CHUNK_BIN.to_le_bytes())?;
    w.write_all(&bin_bytes)?;
    // Pad with zeros
    for _ in 0..(bin_padded_len - bin_bytes.len()) {
        w.write_all(&[0u8])?;
    }

    w.flush()?;
    Ok(())
}

/// Export a mesh to GLB 2.0 binary format in memory (no file I/O).
///
/// Returns the complete GLB byte buffer.
pub fn export_glb_bytes(
    mesh: &Mesh,
    config: &GltfConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<Vec<u8>, IoError> {
    // meshopt compression path: delegate to meshopt_gltf module
    // (see GltfConfig::meshopt_compress docs for limitations)
    if config.meshopt_compress {
        use crate::io::meshopt_gltf::{export_glb_meshopt_bytes, MeshoptGltfConfig};
        let mo_config = MeshoptGltfConfig {
            export_normals: config.export_normals,
            export_uvs: config.export_uvs,
            level: config.meshopt_level,
            double_sided: config.double_sided,
        };
        return export_glb_meshopt_bytes(mesh, &mo_config);
    }

    let (json_bytes, bin_bytes) = build_glb_data(mesh, config, materials)?;

    let json_padded_len = (json_bytes.len() + 3) & !3;
    let bin_padded_len = (bin_bytes.len() + 3) & !3;
    let total_len = 12 + 8 + json_padded_len + 8 + bin_padded_len;

    let mut buf = Vec::with_capacity(total_len);

    // GLB header
    buf.extend_from_slice(&GLB_MAGIC.to_le_bytes());
    buf.extend_from_slice(&GLB_VERSION.to_le_bytes());
    buf.extend_from_slice(&(total_len as u32).to_le_bytes());

    // JSON chunk
    buf.extend_from_slice(&(json_padded_len as u32).to_le_bytes());
    buf.extend_from_slice(&GLB_CHUNK_JSON.to_le_bytes());
    buf.extend_from_slice(&json_bytes);
    buf.resize(buf.len() + json_padded_len - json_bytes.len(), b' ');

    // BIN chunk
    buf.extend_from_slice(&(bin_padded_len as u32).to_le_bytes());
    buf.extend_from_slice(&GLB_CHUNK_BIN.to_le_bytes());
    buf.extend_from_slice(&bin_bytes);
    buf.resize(buf.len() + bin_padded_len - bin_bytes.len(), 0u8);

    Ok(buf)
}

/// Export a mesh to glTF 2.0 JSON (.gltf) with embedded base64 buffer
pub fn export_gltf_json(
    mesh: &Mesh,
    path: impl AsRef<Path>,
    config: &GltfConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(), IoError> {
    let (json_bytes, bin) = build_glb_data(mesh, config, materials)?;

    // A .gltf has no BIN chunk: the buffer must carry its bytes in `uri`
    // (glTF 2.0 §3.6.1.1), here as a base64 data URI
    let mut doc: serde_json::Value =
        serde_json::from_slice(&json_bytes).map_err(|e| IoError::Serialization(e.to_string()))?;
    let buffer = doc
        .get_mut("buffers")
        .and_then(|b| b.get_mut(0))
        .and_then(serde_json::Value::as_object_mut)
        .ok_or_else(|| IoError::Serialization("glTF JSON has no buffers[0]".to_string()))?;
    buffer.insert(
        "uri".to_string(),
        serde_json::Value::String(format!(
            "data:application/octet-stream;base64,{}",
            base64_encode(&bin)
        )),
    );
    let out = serde_json::to_vec(&doc).map_err(|e| IoError::Serialization(e.to_string()))?;
    std::fs::write(path, out)?;
    Ok(())
}

/// `,"texCoord":n` for a texture slot sampled with `TEXCOORD_n`, n > 0
/// (glTF 2.0 §5.36 `textureInfo.texCoord`, default 0, so it is left out for
/// the primary UV set).
fn tex_coord_field(slot: &crate::material::TextureSlot) -> String {
    if slot.uv_channel == 0 {
        String::new()
    } else {
        format!(r#","texCoord":{}"#, slot.uv_channel)
    }
}

/// Standard base64 (RFC 4648 §4, `+/` alphabet, `=` padding).
fn base64_encode(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            chunk.get(1).copied().unwrap_or(0),
            chunk.get(2).copied().unwrap_or(0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        let sextets = [(n >> 18) & 63, (n >> 12) & 63, (n >> 6) & 63, n & 63];
        for (i, &s) in sextets.iter().enumerate() {
            // a chunk of k bytes yields k + 1 symbols; the rest is padding
            if i <= chunk.len() {
                out.push(ALPHABET[s as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

fn build_glb_data(
    mesh: &Mesh,
    config: &GltfConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(Vec<u8>, Vec<u8>), IoError> {
    let vert_count = mesh.vertices.len();
    let use_u16 = vert_count <= 65535;

    // Build binary buffer
    let mut bin = Vec::new();
    let mut buffer_views = Vec::new();
    let mut accessors = Vec::new();
    let mut attributes = Vec::new();

    // Compute AABB for positions
    let mut min_pos = [f32::MAX; 3];
    let mut max_pos = [f32::MIN; 3];
    for v in &mesh.vertices {
        min_pos[0] = min_pos[0].law_min(v.position.x);
        min_pos[1] = min_pos[1].law_min(v.position.y);
        min_pos[2] = min_pos[2].law_min(v.position.z);
        max_pos[0] = max_pos[0].law_max(v.position.x);
        max_pos[1] = max_pos[1].law_max(v.position.y);
        max_pos[2] = max_pos[2].law_max(v.position.z);
    }

    // --- Positions (accessor 0) ---
    // Track if we need KHR_mesh_quantization extension
    let mut needs_quantization_ext = false;

    let pos_offset = bin.len();
    if config.quantize_positions {
        // Position quantization: snorm i16 (SHORT) with center-based mapping
        // Uses full i16 range [-32767, 32767] via `snorm_i16_encode` for
        // 2x precision compared to the legacy [0, 32767] half-range mapping
        //
        // Dequantization: pos_world = (q_norm) * half_extent + center
        //   where q_norm = q / 32767 in [-1, 1]
        // Node transform: scale = half_extent, translation = center
        needs_quantization_ext = true;
        let half_ext = [
            (max_pos[0] - min_pos[0]) * 0.5,
            (max_pos[1] - min_pos[1]) * 0.5,
            (max_pos[2] - min_pos[2]) * 0.5,
        ];
        let center = [
            f32::midpoint(max_pos[0], min_pos[0]),
            f32::midpoint(max_pos[1], min_pos[1]),
            f32::midpoint(max_pos[2], min_pos[2]),
        ];
        for v in &mesh.vertices {
            let qx = if half_ext[0] > 1e-6 {
                crate::mesh::quantization::snorm_i16_encode(
                    (v.position.x - center[0]) / half_ext[0],
                )
            } else {
                0
            };
            let qy = if half_ext[1] > 1e-6 {
                crate::mesh::quantization::snorm_i16_encode(
                    (v.position.y - center[1]) / half_ext[1],
                )
            } else {
                0
            };
            let qz = if half_ext[2] > 1e-6 {
                crate::mesh::quantization::snorm_i16_encode(
                    (v.position.z - center[2]) / half_ext[2],
                )
            } else {
                0
            };
            bin.extend_from_slice(&qx.to_le_bytes());
            bin.extend_from_slice(&qy.to_le_bytes());
            bin.extend_from_slice(&qz.to_le_bytes());
        }
        let pos_len = bin.len() - pos_offset;
        // byteStride = 6 (3 * sizeof(i16))
        buffer_views.push(format!(
            r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"byteStride":6,"target":{}}}"#,
            pos_offset, pos_len, ARRAY_BUFFER
        ));
        // SHORT (5122) normalized:true → dequantized to [-1, 1] float on load
        accessors.push(format!(
            r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC3","normalized":true,"min":[-1,-1,-1],"max":[1,1,1]}}"#,
            buffer_views.len() - 1, SHORT, vert_count
        ));
    } else {
        for v in &mesh.vertices {
            bin.extend_from_slice(&v.position.x.to_le_bytes());
            bin.extend_from_slice(&v.position.y.to_le_bytes());
            bin.extend_from_slice(&v.position.z.to_le_bytes());
        }
        let pos_len = bin.len() - pos_offset;
        buffer_views.push(format!(
            r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
            pos_offset, pos_len, ARRAY_BUFFER
        ));
        accessors.push(format!(
            r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC3","min":[{},{},{}],"max":[{},{},{}]}}"#,
            buffer_views.len() - 1, FLOAT, vert_count,
            min_pos[0], min_pos[1], min_pos[2],
            max_pos[0], max_pos[1], max_pos[2]
        ));
    }
    attributes.push(format!(r#""POSITION":{}"#, accessors.len() - 1));

    // --- Normals ---
    if config.export_normals {
        let offset = bin.len();
        if config.quantize_normals {
            // SBYTE snorm (i8): 3 bytes/vertex + 1 padding for 4-byte alignment
            // glTF spec: SBYTE VEC3 padded to 4 bytes (byteStride 4)
            needs_quantization_ext = true;
            for v in &mesh.vertices {
                let qx = crate::mesh::quantization::snorm_i8_encode(v.normal.x);
                let qy = crate::mesh::quantization::snorm_i8_encode(v.normal.y);
                let qz = crate::mesh::quantization::snorm_i8_encode(v.normal.z);
                bin.extend_from_slice(&qx.to_le_bytes());
                bin.extend_from_slice(&qy.to_le_bytes());
                bin.extend_from_slice(&qz.to_le_bytes());
                bin.push(0); // padding to 4-byte stride
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"byteStride":4,"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC3","normalized":true}}"#,
                buffer_views.len() - 1, BYTE, vert_count
            ));
        } else {
            for v in &mesh.vertices {
                bin.extend_from_slice(&v.normal.x.to_le_bytes());
                bin.extend_from_slice(&v.normal.y.to_le_bytes());
                bin.extend_from_slice(&v.normal.z.to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC3"}}"#,
                buffer_views.len() - 1,
                FLOAT,
                vert_count
            ));
        }
        attributes.push(format!(r#""NORMAL":{}"#, accessors.len() - 1));
    }

    // --- UVs (TEXCOORD_0) ---
    if config.export_uvs {
        let offset = bin.len();
        if config.quantize_uvs {
            // USHORT unorm (u16): 4 bytes/vertex
            needs_quantization_ext = true;
            for v in &mesh.vertices {
                let qu = crate::mesh::quantization::unorm_u16_encode(v.uv.x);
                let qv = crate::mesh::quantization::unorm_u16_encode(v.uv.y);
                bin.extend_from_slice(&qu.to_le_bytes());
                bin.extend_from_slice(&qv.to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"byteStride":4,"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC2","normalized":true}}"#,
                buffer_views.len() - 1, UNSIGNED_SHORT, vert_count
            ));
        } else {
            for v in &mesh.vertices {
                bin.extend_from_slice(&v.uv.x.to_le_bytes());
                bin.extend_from_slice(&v.uv.y.to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC2"}}"#,
                buffer_views.len() - 1,
                FLOAT,
                vert_count
            ));
        }
        attributes.push(format!(r#""TEXCOORD_0":{}"#, accessors.len() - 1));
    }

    // --- Lightmap UVs (TEXCOORD_1) ---
    if config.export_uv2 {
        let offset = bin.len();
        for v in &mesh.vertices {
            bin.extend_from_slice(&v.uv2.x.to_le_bytes());
            bin.extend_from_slice(&v.uv2.y.to_le_bytes());
        }
        let len = bin.len() - offset;
        buffer_views.push(format!(
            r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
            offset, len, ARRAY_BUFFER
        ));
        accessors.push(format!(
            r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC2"}}"#,
            buffer_views.len() - 1,
            FLOAT,
            vert_count
        ));
        attributes.push(format!(r#""TEXCOORD_1":{}"#, accessors.len() - 1));
    }

    // --- Tangents ---
    if config.export_tangents {
        let offset = bin.len();
        if config.quantize_tangents {
            // SBYTE snorm (i8): 4 bytes/vertex (VEC4)
            needs_quantization_ext = true;
            for v in &mesh.vertices {
                let qx = crate::mesh::quantization::snorm_i8_encode(v.tangent.x);
                let qy = crate::mesh::quantization::snorm_i8_encode(v.tangent.y);
                let qz = crate::mesh::quantization::snorm_i8_encode(v.tangent.z);
                let qw = crate::mesh::quantization::snorm_i8_encode(v.tangent.w);
                bin.extend_from_slice(&qx.to_le_bytes());
                bin.extend_from_slice(&qy.to_le_bytes());
                bin.extend_from_slice(&qz.to_le_bytes());
                bin.extend_from_slice(&qw.to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"byteStride":4,"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC4","normalized":true}}"#,
                buffer_views.len() - 1, BYTE, vert_count
            ));
        } else {
            for v in &mesh.vertices {
                bin.extend_from_slice(&v.tangent.x.to_le_bytes());
                bin.extend_from_slice(&v.tangent.y.to_le_bytes());
                bin.extend_from_slice(&v.tangent.z.to_le_bytes());
                bin.extend_from_slice(&v.tangent.w.to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC4"}}"#,
                buffer_views.len() - 1,
                FLOAT,
                vert_count
            ));
        }
        attributes.push(format!(r#""TANGENT":{}"#, accessors.len() - 1));
    }

    // --- Vertex Colors ---
    if config.export_colors {
        let offset = bin.len();
        if config.quantize_colors {
            // UBYTE unorm (u8): 4 bytes/vertex
            needs_quantization_ext = true;
            for v in &mesh.vertices {
                let qr = crate::mesh::quantization::unorm_u8_encode(v.color[0]);
                let qg = crate::mesh::quantization::unorm_u8_encode(v.color[1]);
                let qb = crate::mesh::quantization::unorm_u8_encode(v.color[2]);
                let qa = crate::mesh::quantization::unorm_u8_encode(v.color[3]);
                bin.push(qr);
                bin.push(qg);
                bin.push(qb);
                bin.push(qa);
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"byteStride":4,"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC4","normalized":true}}"#,
                buffer_views.len() - 1, UNSIGNED_BYTE, vert_count
            ));
        } else {
            for v in &mesh.vertices {
                bin.extend_from_slice(&v.color[0].to_le_bytes());
                bin.extend_from_slice(&v.color[1].to_le_bytes());
                bin.extend_from_slice(&v.color[2].to_le_bytes());
                bin.extend_from_slice(&v.color[3].to_le_bytes());
            }
            let len = bin.len() - offset;
            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
                offset, len, ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"VEC4"}}"#,
                buffer_views.len() - 1,
                FLOAT,
                vert_count
            ));
        }
        attributes.push(format!(r#""COLOR_0":{}"#, accessors.len() - 1));
    }

    // --- Texture collection (images, textures, samplers) ---
    let mut image_paths: Vec<String> = Vec::new();
    let mut path_to_tex_idx: std::collections::HashMap<String, usize> =
        std::collections::HashMap::new();

    if config.export_materials {
        if let Some(mat_lib) = materials {
            for (_, mat) in mat_lib.iter() {
                let slots: [&Option<crate::material::TextureSlot>; 8] = [
                    &mat.albedo_map,
                    &mat.normal_map,
                    &mat.metallic_map,
                    &mat.roughness_map,
                    &mat.ao_map,
                    &mat.emissive_map,
                    &mat.metallic_roughness_map,
                    &mat.clearcoat_normal_map,
                ];
                for slot in slots.iter().copied().flatten() {
                    if !path_to_tex_idx.contains_key(&slot.path) {
                        path_to_tex_idx.insert(slot.path.clone(), image_paths.len());
                        image_paths.push(slot.path.clone());
                    }
                }
            }
        }
    }

    // --- Materials ---
    let mut materials_json = Vec::new();
    let mut used_extensions: Vec<String> = Vec::new();
    if config.export_materials {
        if let Some(mat_lib) = materials {
            for (_, mat) in mat_lib.iter() {
                // Build PBR metallic-roughness object
                let mut pbr = format!(
                    r#"{{"baseColorFactor":[{},{},{},{}],"metallicFactor":{},"roughnessFactor":{}"#,
                    mat.base_color[0],
                    mat.base_color[1],
                    mat.base_color[2],
                    mat.base_color[3],
                    mat.metallic,
                    mat.roughness
                );

                if let Some(ref tex) = mat.albedo_map {
                    if let Some(&idx) = path_to_tex_idx.get(&tex.path) {
                        pbr += &format!(
                            r#","baseColorTexture":{{"index":{}{}}}"#,
                            idx,
                            tex_coord_field(tex)
                        );
                    }
                }
                if let Some(ref tex) = mat.metallic_roughness_map {
                    if let Some(&idx) = path_to_tex_idx.get(&tex.path) {
                        pbr += &format!(
                            r#","metallicRoughnessTexture":{{"index":{}{}}}"#,
                            idx,
                            tex_coord_field(tex)
                        );
                    }
                }

                pbr += "}"; // close pbrMetallicRoughness

                let mut mat_str =
                    format!(r#"{{"name":"{}","pbrMetallicRoughness":{}"#, mat.name, pbr);

                // Normal map
                if let Some(ref tex) = mat.normal_map {
                    if let Some(&idx) = path_to_tex_idx.get(&tex.path) {
                        mat_str += &format!(
                            r#","normalTexture":{{"index":{}{},"scale":{}}}"#,
                            idx,
                            tex_coord_field(tex),
                            mat.normal_scale
                        );
                    }
                }

                // AO map
                if let Some(ref tex) = mat.ao_map {
                    if let Some(&idx) = path_to_tex_idx.get(&tex.path) {
                        mat_str += &format!(
                            r#","occlusionTexture":{{"index":{}{}}}"#,
                            idx,
                            tex_coord_field(tex)
                        );
                    }
                }

                // Emissive
                if mat.emission_strength > 0.0 {
                    mat_str += &format!(
                        r#","emissiveFactor":[{},{},{}]"#,
                        mat.emission[0] * mat.emission_strength,
                        mat.emission[1] * mat.emission_strength,
                        mat.emission[2] * mat.emission_strength,
                    );
                }
                if let Some(ref tex) = mat.emissive_map {
                    if let Some(&idx) = path_to_tex_idx.get(&tex.path) {
                        mat_str += &format!(
                            r#","emissiveTexture":{{"index":{}{}}}"#,
                            idx,
                            tex_coord_field(tex)
                        );
                    }
                }

                if mat.opacity < 1.0 {
                    mat_str += r#","alphaMode":"BLEND""#;
                }

                if config.double_sided {
                    mat_str += r#","doubleSided":true"#;
                }

                // --- Extended PBR extensions ---
                if config.export_extensions {
                    let mut ext_parts = Vec::new();

                    // KHR_materials_clearcoat
                    if mat.clearcoat > 0.0 {
                        ext_parts.push(format!(
                            r#""KHR_materials_clearcoat":{{"clearcoatFactor":{},"clearcoatRoughnessFactor":{}}}"#,
                            mat.clearcoat, mat.clearcoat_roughness
                        ));
                        if !used_extensions.contains(&"KHR_materials_clearcoat".to_string()) {
                            used_extensions.push("KHR_materials_clearcoat".to_string());
                        }
                    }

                    // KHR_materials_sheen
                    if mat.sheen_color != [0.0, 0.0, 0.0] || mat.sheen_roughness > 0.0 {
                        ext_parts.push(format!(
                            r#""KHR_materials_sheen":{{"sheenColorFactor":[{},{},{}],"sheenRoughnessFactor":{}}}"#,
                            mat.sheen_color[0], mat.sheen_color[1], mat.sheen_color[2],
                            mat.sheen_roughness
                        ));
                        if !used_extensions.contains(&"KHR_materials_sheen".to_string()) {
                            used_extensions.push("KHR_materials_sheen".to_string());
                        }
                    }

                    // KHR_materials_transmission
                    if mat.transmission > 0.0 {
                        ext_parts.push(format!(
                            r#""KHR_materials_transmission":{{"transmissionFactor":{}}}"#,
                            mat.transmission
                        ));
                        if !used_extensions.contains(&"KHR_materials_transmission".to_string()) {
                            used_extensions.push("KHR_materials_transmission".to_string());
                        }
                    }

                    // KHR_materials_ior (only if not default 1.5)
                    if (mat.ior - 1.5).abs() > 0.001 {
                        ext_parts.push(format!(r#""KHR_materials_ior":{{"ior":{}}}"#, mat.ior));
                        if !used_extensions.contains(&"KHR_materials_ior".to_string()) {
                            used_extensions.push("KHR_materials_ior".to_string());
                        }
                    }

                    // KHR_materials_volume
                    if mat.thickness > 0.0 {
                        let mut vol = format!(
                            r#""KHR_materials_volume":{{"thicknessFactor":{}"#,
                            mat.thickness
                        );
                        if mat.attenuation_distance.is_finite() {
                            vol +=
                                &format!(r#","attenuationDistance":{}"#, mat.attenuation_distance);
                        }
                        if mat.attenuation_color != [1.0, 1.0, 1.0] {
                            vol += &format!(
                                r#","attenuationColor":[{},{},{}]"#,
                                mat.attenuation_color[0],
                                mat.attenuation_color[1],
                                mat.attenuation_color[2]
                            );
                        }
                        vol += "}";
                        ext_parts.push(vol);
                        if !used_extensions.contains(&"KHR_materials_volume".to_string()) {
                            used_extensions.push("KHR_materials_volume".to_string());
                        }
                    }

                    // KHR_materials_anisotropy
                    if mat.anisotropy.abs() > 0.001 {
                        ext_parts.push(format!(
                            r#""KHR_materials_anisotropy":{{"anisotropyStrength":{},"anisotropyRotation":{}}}"#,
                            mat.anisotropy, mat.anisotropy_rotation
                        ));
                        if !used_extensions.contains(&"KHR_materials_anisotropy".to_string()) {
                            used_extensions.push("KHR_materials_anisotropy".to_string());
                        }
                    }

                    if !ext_parts.is_empty() {
                        mat_str += &format!(r#","extensions":{{{}}}"#, ext_parts.join(","));
                    }
                }

                mat_str += "}";
                materials_json.push(mat_str);
            }
        }
    }

    // --- Indices: group by material for multi-material splitting ---
    let idx_comp_type = if use_u16 {
        UNSIGNED_SHORT
    } else {
        UNSIGNED_INT
    };
    let attr_str = attributes.join(",");
    let mut primitives = Vec::new();

    if config.export_materials && materials.is_some() && !materials_json.is_empty() {
        // Group triangles by material_id
        let mut mat_groups: std::collections::BTreeMap<u32, Vec<u32>> =
            std::collections::BTreeMap::new();
        let tri_count = mesh.indices.len() / 3;
        for t in 0..tri_count {
            let v0 = mesh.indices[t * 3] as usize;
            let mat_id = if v0 < mesh.vertices.len() {
                mesh.vertices[v0].material_id
            } else {
                0
            };
            let group = mat_groups.entry(mat_id).or_default();
            group.push(mesh.indices[t * 3]);
            group.push(mesh.indices[t * 3 + 1]);
            group.push(mesh.indices[t * 3 + 2]);
        }

        // Create separate index buffer + accessor + primitive for each material
        for (mat_id, group_indices) in &mat_groups {
            while bin.len() % 4 != 0 {
                bin.push(0);
            }
            let idx_offset = bin.len();

            if use_u16 {
                for &idx in group_indices {
                    bin.extend_from_slice(&(idx as u16).to_le_bytes());
                }
            } else {
                for &idx in group_indices {
                    bin.extend_from_slice(&idx.to_le_bytes());
                }
            }
            let idx_len = bin.len() - idx_offset;

            buffer_views.push(format!(
                r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
                idx_offset, idx_len, ELEMENT_ARRAY_BUFFER
            ));
            accessors.push(format!(
                r#"{{"bufferView":{},"componentType":{},"count":{},"type":"SCALAR"}}"#,
                buffer_views.len() - 1,
                idx_comp_type,
                group_indices.len()
            ));

            let mat_ref = if (*mat_id as usize) < materials_json.len() {
                *mat_id
            } else {
                0
            };

            primitives.push(format!(
                r#"{{"attributes":{{{}}},"indices":{},"material":{}}}"#,
                attr_str,
                accessors.len() - 1,
                mat_ref
            ));
        }
    } else {
        // Single primitive, no material grouping
        while bin.len() % 4 != 0 {
            bin.push(0);
        }
        let idx_offset = bin.len();

        if use_u16 {
            for &idx in &mesh.indices {
                bin.extend_from_slice(&(idx as u16).to_le_bytes());
            }
        } else {
            for &idx in &mesh.indices {
                bin.extend_from_slice(&idx.to_le_bytes());
            }
        }
        let idx_len = bin.len() - idx_offset;

        buffer_views.push(format!(
            r#"{{"buffer":0,"byteOffset":{},"byteLength":{},"target":{}}}"#,
            idx_offset, idx_len, ELEMENT_ARRAY_BUFFER
        ));
        accessors.push(format!(
            r#"{{"bufferView":{},"componentType":{},"count":{},"type":"SCALAR"}}"#,
            buffer_views.len() - 1,
            idx_comp_type,
            mesh.indices.len()
        ));

        primitives.push(format!(
            r#"{{"attributes":{{{}}},"indices":{}}}"#,
            attr_str,
            accessors.len() - 1
        ));
    }

    // Build JSON
    let mut json = String::from(r#"{"asset":{"version":"2.0","generator":"ALICE-SDF"}"#);

    // Extensions
    if needs_quantization_ext && !used_extensions.contains(&"KHR_mesh_quantization".to_string()) {
        used_extensions.push("KHR_mesh_quantization".to_string());
    }
    if !used_extensions.is_empty() {
        let ext_list: Vec<String> = used_extensions
            .iter()
            .map(|e| format!(r#""{}""#, e))
            .collect();
        json += &format!(r#","extensionsUsed":[{}]"#, ext_list.join(","));
        // Only KHR_mesh_quantization is required
        if needs_quantization_ext {
            json += r#","extensionsRequired":["KHR_mesh_quantization"]"#;
        }
    }

    // Buffers
    json += &format!(r#","buffers":[{{"byteLength":{}}}]"#, bin.len());

    // Buffer views
    json += &format!(r#","bufferViews":[{}]"#, buffer_views.join(","));

    // Accessors
    json += &format!(r#","accessors":[{}]"#, accessors.join(","));

    // Meshes
    json += &format!(r#","meshes":[{{"primitives":[{}]}}]"#, primitives.join(","));

    // Nodes (with dequantization transform if positions were quantized)
    // For snorm i16 with normalized:true, accessor loads to [-1, 1] float.
    // World position = local * scale + translation
    //   scale = half_extent (per axis)
    //   translation = center (per axis)
    if config.quantize_positions {
        let half_ext = [
            (max_pos[0] - min_pos[0]) * 0.5,
            (max_pos[1] - min_pos[1]) * 0.5,
            (max_pos[2] - min_pos[2]) * 0.5,
        ];
        let center = [
            f32::midpoint(max_pos[0], min_pos[0]),
            f32::midpoint(max_pos[1], min_pos[1]),
            f32::midpoint(max_pos[2], min_pos[2]),
        ];
        let sx = if half_ext[0] > 1e-6 { half_ext[0] } else { 1.0 };
        let sy = if half_ext[1] > 1e-6 { half_ext[1] } else { 1.0 };
        let sz = if half_ext[2] > 1e-6 { half_ext[2] } else { 1.0 };
        json += &format!(
            r#","nodes":[{{"mesh":0,"translation":[{},{},{}],"scale":[{},{},{}]}}]"#,
            center[0], center[1], center[2], sx, sy, sz
        );
    } else {
        json += r#","nodes":[{"mesh":0}]"#;
    }

    // Scene
    json += r#","scenes":[{"nodes":[0]}],"scene":0"#;

    // Materials
    if !materials_json.is_empty() {
        json += &format!(r#","materials":[{}]"#, materials_json.join(","));
    }

    // Textures, images, samplers
    if !image_paths.is_empty() {
        if config.embed_textures {
            // Embed textures in binary buffer (self-contained GLB)
            let mut images_json = Vec::new();
            for p in &image_paths {
                let mime = if p.ends_with(".png") {
                    "image/png"
                } else if p.ends_with(".jpg") || p.ends_with(".jpeg") {
                    "image/jpeg"
                } else if p.ends_with(".webp") {
                    "image/webp"
                } else {
                    "application/octet-stream"
                };

                match std::fs::read(p) {
                    Ok(image_data) => {
                        // Align to 4 bytes
                        while bin.len() % 4 != 0 {
                            bin.push(0);
                        }
                        let offset = bin.len();
                        let len = image_data.len();
                        bin.extend_from_slice(&image_data);

                        buffer_views.push(format!(
                            r#"{{"buffer":0,"byteOffset":{},"byteLength":{}}}"#,
                            offset, len
                        ));
                        images_json.push(format!(
                            r#"{{"bufferView":{},"mimeType":"{}"}}"#,
                            buffer_views.len() - 1,
                            mime
                        ));
                    }
                    Err(_) => {
                        // Fallback to URI if file not found
                        images_json.push(format!(r#"{{"uri":"{}"}}"#, p));
                    }
                }
            }
            json += &format!(r#","images":[{}]"#, images_json.join(","));
        } else {
            // URI references to external texture files
            let images: Vec<String> = image_paths
                .iter()
                .map(|p| format!(r#"{{"uri":"{}"}}"#, p))
                .collect();
            json += &format!(r#","images":[{}]"#, images.join(","));
        }

        // Textures (each image gets a texture entry with default sampler)
        let textures: Vec<String> = (0..image_paths.len())
            .map(|i| format!(r#"{{"sampler":0,"source":{}}}"#, i))
            .collect();
        json += &format!(r#","textures":[{}]"#, textures.join(","));

        // Default sampler (linear filtering, repeat wrap)
        json += r#","samplers":[{"magFilter":9729,"minFilter":9987,"wrapS":10497,"wrapT":10497}]"#;
    }

    json += "}";

    Ok((json.into_bytes(), bin))
}

// ============================================================
// GLB Import
// ============================================================

/// Import a mesh from glTF 2.0 Binary (.glb) file
///
/// Parses GLB header, JSON chunk, and BIN chunk. Extracts positions,
/// normals, UVs, and indices from the binary buffer.
///
/// # Supported accessor types
/// - Positions: VEC3 / FLOAT
/// - Normals: VEC3 / FLOAT
/// - UVs (TEXCOORD_0): VEC2 / FLOAT
/// - Indices: SCALAR / UNSIGNED_SHORT or UNSIGNED_INT
pub fn import_glb(path: impl AsRef<Path>) -> Result<Mesh, IoError> {
    let data = std::fs::read(path)?;
    import_glb_bytes(&data)
}

/// A JSON array element by index, or an `IoError` when the index is out of range
fn gltf_item<'a>(
    items: &'a [serde_json::Value],
    index: usize,
    what: &str,
) -> Result<&'a serde_json::Value, IoError> {
    items.get(index).ok_or_else(|| {
        IoError::InvalidFormat(format!(
            "{what} index {index} out of range ({} present)",
            items.len()
        ))
    })
}

/// A JSON number as `usize`, or an `IoError` when it does not fit
fn gltf_usize(value: u64) -> Result<usize, IoError> {
    usize::try_from(value)
        .map_err(|_| IoError::InvalidFormat(format!("Value {value} does not fit in usize")))
}

/// `(byte offset into the BIN chunk, element count, componentType, type)` of accessor `index`
///
/// The byte offset is the bufferView's plus the accessor's, added with overflow checking.
fn accessor_layout<'a>(
    accessors: &'a [serde_json::Value],
    buffer_views: &[serde_json::Value],
    index: usize,
) -> Result<(usize, usize, u32, &'a str), IoError> {
    let acc = gltf_item(accessors, index, "accessor")?;
    let bv = gltf_item(
        buffer_views,
        gltf_usize(acc["bufferView"].as_u64().unwrap_or(0))?,
        "bufferView",
    )?;
    let byte_offset = gltf_usize(bv["byteOffset"].as_u64().unwrap_or(0))?
        .checked_add(gltf_usize(acc["byteOffset"].as_u64().unwrap_or(0))?)
        .ok_or_else(|| IoError::InvalidFormat("Accessor byte offset overflow".into()))?;
    let count = gltf_usize(acc["count"].as_u64().unwrap_or(0))?;
    // componentType is a small enum (5120..5126); anything wider than u32 is invalid anyway
    let comp_type = u32::try_from(acc["componentType"].as_u64().unwrap_or(0)).unwrap_or(0);
    let acc_type = acc["type"].as_str().unwrap_or("");
    Ok((byte_offset, count, comp_type, acc_type))
}

/// Import a mesh from in-memory GLB bytes
pub fn import_glb_bytes(data: &[u8]) -> Result<Mesh, IoError> {
    use crate::mesh::Vertex;
    use glam::{Vec2, Vec3};

    if data.len() < 12 {
        return Err(IoError::InvalidFormat("GLB too short for header".into()));
    }

    // Parse GLB header (12 bytes)
    let magic = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
    if magic != GLB_MAGIC {
        return Err(IoError::InvalidFormat(format!(
            "Not a GLB file (magic: 0x{:08X}, expected 0x{:08X})",
            magic, GLB_MAGIC
        )));
    }
    let _version = u32::from_le_bytes([data[4], data[5], data[6], data[7]]);
    let _total_len = u32::from_le_bytes([data[8], data[9], data[10], data[11]]);

    // Parse chunks
    let mut json_data: Option<&[u8]> = None;
    let mut bin_data: Option<&[u8]> = None;
    let mut offset = 12usize;

    while offset + 8 <= data.len() {
        let chunk_len = u32::from_le_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]) as usize;
        let chunk_type = u32::from_le_bytes([
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        if offset + chunk_len > data.len() {
            break;
        }

        match chunk_type {
            GLB_CHUNK_JSON => json_data = Some(&data[offset..offset + chunk_len]),
            GLB_CHUNK_BIN => bin_data = Some(&data[offset..offset + chunk_len]),
            _ => {} // skip unknown chunks
        }
        offset += chunk_len;
    }

    let json_bytes =
        json_data.ok_or_else(|| IoError::InvalidFormat("Missing JSON chunk".into()))?;
    let bin_bytes = bin_data.ok_or_else(|| IoError::InvalidFormat("Missing BIN chunk".into()))?;

    // Parse JSON using serde_json::Value (minimal parsing)
    let root: serde_json::Value = serde_json::from_slice(json_bytes)
        .map_err(|e| IoError::InvalidFormat(format!("Invalid glTF JSON: {}", e)))?;

    let buffer_views = root["bufferViews"]
        .as_array()
        .ok_or_else(|| IoError::InvalidFormat("Missing bufferViews".into()))?;
    let accessors = root["accessors"]
        .as_array()
        .ok_or_else(|| IoError::InvalidFormat("Missing accessors".into()))?;

    // Get first mesh, first primitive
    let meshes = root["meshes"]
        .as_array()
        .ok_or_else(|| IoError::InvalidFormat("Missing meshes".into()))?;
    if meshes.is_empty() {
        return Err(IoError::InvalidFormat("No meshes in glTF".into()));
    }
    let primitives = meshes[0]["primitives"]
        .as_array()
        .ok_or_else(|| IoError::InvalidFormat("Missing primitives".into()))?;
    if primitives.is_empty() {
        return Err(IoError::InvalidFormat("No primitives in mesh".into()));
    }

    let prim = &primitives[0];
    let attrs = &prim["attributes"];

    // Helper: read accessor data from BIN chunk
    //
    // Every reference in a glTF file (accessor -> bufferView -> byte range) is untrusted: an index,
    // an offset or a count that is out of range must be an `IoError`, never a panic (a slice or
    // array index out of bounds), a wrapped offset (integer overflow) or a huge allocation.
    let read_accessor_f32 = |acc_idx: usize| -> Result<Vec<f32>, IoError> {
        let (byte_offset, count, comp_type, acc_type) =
            accessor_layout(accessors, buffer_views, acc_idx)?;
        let bv = gltf_item(
            buffer_views,
            gltf_usize(
                gltf_item(accessors, acc_idx, "accessor")?["bufferView"]
                    .as_u64()
                    .unwrap_or(0),
            )?,
            "bufferView",
        )?;

        let components = match acc_type {
            "SCALAR" => 1,
            "VEC2" => 2,
            "VEC3" => 3,
            "VEC4" => 4,
            _ => {
                return Err(IoError::InvalidFormat(format!(
                    "Unknown accessor type: {}",
                    acc_type
                )))
            }
        };

        if comp_type != FLOAT {
            return Err(IoError::InvalidFormat(format!(
                "Expected FLOAT component, got {}",
                comp_type
            )));
        }

        let total = count
            .checked_mul(components)
            .ok_or_else(|| IoError::InvalidFormat("Accessor count overflow".into()))?;
        let stride = gltf_usize(bv.get("byteStride").and_then(|v| v.as_u64()).unwrap_or(0))?;
        let elem_size = components * 4;
        let overrun = || IoError::InvalidFormat("Buffer overrun".into());

        if stride == 0 || stride == elem_size {
            // Tightly packed: one range check, then bulk convert
            let end = total
                .checked_mul(4)
                .and_then(|len| byte_offset.checked_add(len))
                .ok_or_else(overrun)?;
            let bytes = bin_bytes.get(byte_offset..end).ok_or_else(overrun)?;
            // `total * 4 <= bytes.len()` here, so this allocation is bounded by the BIN chunk
            let mut result = Vec::with_capacity(total);
            for chunk in bytes.chunks_exact(4) {
                result.push(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]));
            }
            Ok(result)
        } else {
            // Strided: check that the last element fits before allocating anything
            if count > 0 {
                (count - 1)
                    .checked_mul(stride)
                    .and_then(|len| byte_offset.checked_add(len))
                    .and_then(|start| start.checked_add(elem_size))
                    .filter(|&end| end <= bin_bytes.len())
                    .ok_or_else(overrun)?;
            }
            let mut result = Vec::with_capacity(total);
            for i in 0..count {
                let base = byte_offset + i * stride; // bounded by the check above
                for c in 0..components {
                    let off = base + c * 4;
                    let word = bin_bytes.get(off..off + 4).ok_or_else(overrun)?;
                    result.push(f32::from_le_bytes([word[0], word[1], word[2], word[3]]));
                }
            }
            Ok(result)
        }
    };

    // Read positions (required)
    let pos_idx = gltf_usize(
        attrs["POSITION"]
            .as_u64()
            .ok_or_else(|| IoError::InvalidFormat("Missing POSITION attribute".into()))?,
    )?;
    let positions = read_accessor_f32(pos_idx)?;
    let vert_count = positions.len() / 3;

    // Read normals (optional)
    let normals = if let Some(idx) = attrs["NORMAL"].as_u64() {
        Some(read_accessor_f32(gltf_usize(idx)?)?)
    } else {
        None
    };

    // Read UVs (optional)
    let uvs = if let Some(idx) = attrs["TEXCOORD_0"].as_u64() {
        Some(read_accessor_f32(gltf_usize(idx)?)?)
    } else {
        None
    };

    // NORMAL / TEXCOORD_0 must describe at least as many vertices as POSITION
    if normals.as_ref().is_some_and(|n| n.len() < vert_count * 3) {
        return Err(IoError::InvalidFormat(
            "NORMAL accessor has fewer elements than POSITION".into(),
        ));
    }
    if uvs.as_ref().is_some_and(|uv| uv.len() < vert_count * 2) {
        return Err(IoError::InvalidFormat(
            "TEXCOORD_0 accessor has fewer elements than POSITION".into(),
        ));
    }

    // Build vertices
    let mut vertices = Vec::with_capacity(vert_count);
    for i in 0..vert_count {
        let pos = Vec3::new(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
        let norm = normals
            .as_ref()
            .map_or(Vec3::Y, |n| Vec3::new(n[i * 3], n[i * 3 + 1], n[i * 3 + 2]));
        let mut vert = Vertex::new(pos, norm);
        if let Some(ref uv_data) = uvs {
            vert.uv = Vec2::new(uv_data[i * 2], uv_data[i * 2 + 1]);
        }
        vertices.push(vert);
    }

    // Read indices
    let mut indices = Vec::new();
    if let Some(idx_acc) = prim["indices"].as_u64() {
        let idx_acc = gltf_usize(idx_acc)?;
        let (byte_offset, count, comp_type, _) = accessor_layout(accessors, buffer_views, idx_acc)?;
        let size = match comp_type {
            UNSIGNED_SHORT => 2,
            UNSIGNED_INT => 4,
            _ => {
                return Err(IoError::InvalidFormat(format!(
                    "Unsupported index type: {}",
                    comp_type
                )));
            }
        };
        let end = count
            .checked_mul(size)
            .and_then(|len| byte_offset.checked_add(len))
            .ok_or_else(|| IoError::InvalidFormat("Buffer overrun".into()))?;
        let bytes = bin_bytes
            .get(byte_offset..end)
            .ok_or_else(|| IoError::InvalidFormat("Buffer overrun".into()))?;
        // `count * size <= bytes.len()` here, so the reservation is bounded by the BIN chunk
        indices.reserve(count);
        for chunk in bytes.chunks_exact(size) {
            indices.push(if size == 2 {
                u32::from(u16::from_le_bytes([chunk[0], chunk[1]]))
            } else {
                u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])
            });
        }
        // An index past the last vertex would panic in every consumer (and in `Mesh` users that
        // trust `indices`): reject it at the boundary
        if let Some(&bad) = indices.iter().find(|&&i| i as usize >= vert_count) {
            return Err(IoError::InvalidFormat(format!(
                "Index {bad} out of range for {vert_count} vertices"
            )));
        }
    } else {
        // No indices: generate sequential indices
        indices = (0..vert_count as u32).collect();
    }

    Ok(Mesh { vertices, indices })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mesh::{sdf_to_mesh, MarchingCubesConfig};
    use crate::types::SdfNode;
    use glam::Vec3;

    #[test]
    fn test_glb_export() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 8,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let path = std::env::temp_dir().join("alice_test.glb");
        export_glb(&mesh, &path, &GltfConfig::default(), None).unwrap();

        // Verify GLB header
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(&bytes[0..4], &GLB_MAGIC.to_le_bytes());
        assert_eq!(&bytes[4..8], &GLB_VERSION.to_le_bytes());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_with_materials() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 8,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal(
            "chrome", 0.9, 0.9, 0.9, 0.2,
        ));

        let path = std::env::temp_dir().join("alice_test_mat.glb");
        export_glb(&mesh, &path, &GltfConfig::default(), Some(&mat_lib)).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        assert!(bytes.len() > 20);

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_aaa_config() {
        let sphere = SdfNode::sphere(1.0);
        let mc_config = MarchingCubesConfig::aaa(8);
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &mc_config);

        let path = std::env::temp_dir().join("alice_test_aaa.glb");
        export_glb(&mesh, &path, &GltfConfig::aaa(), None).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        assert!(bytes.len() > 100);

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_texture_references() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 8,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(
            crate::material::Material::metal("Textured", 0.9, 0.9, 0.9, 0.2)
                .with_albedo_map("textures/albedo.png")
                .with_normal_map("textures/normal.png")
                .with_metallic_roughness_map("textures/mr.png")
                .with_ao_map("textures/ao.png"),
        );

        let (json_bytes, _bin) =
            build_glb_data(&mesh, &GltfConfig::default(), Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();

        // Verify texture pipeline is present
        assert!(
            json_str.contains(r#""images":[{"uri":"textures/albedo.png"}"#),
            "Missing images array. JSON: {}",
            json_str
        );
        assert!(
            json_str.contains(r#""textures":["#),
            "Missing textures array"
        );
        assert!(
            json_str.contains(r#""samplers":["#),
            "Missing samplers array"
        );
        assert!(
            json_str.contains(r#""baseColorTexture":"#),
            "Missing baseColorTexture in material"
        );
        assert!(
            json_str.contains(r#""normalTexture":"#),
            "Missing normalTexture in material"
        );
        assert!(
            json_str.contains(r#""occlusionTexture":"#),
            "Missing occlusionTexture"
        );
    }

    #[test]
    fn test_glb_quantized_positions() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 8,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let gltf_config = GltfConfig {
            quantize_positions: true,
            ..Default::default()
        };

        let (json_bytes, bin) = build_glb_data(&mesh, &gltf_config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();

        // Should declare the extension
        assert!(
            json_str.contains("KHR_mesh_quantization"),
            "Missing quantization extension. JSON: {}",
            json_str
        );
        // Should have node transform for dequantization
        assert!(
            json_str.contains("\"translation\":["),
            "Missing dequantization translation"
        );
        assert!(
            json_str.contains("\"scale\":["),
            "Missing dequantization scale"
        );
        // Compare with non-quantized version to verify size reduction
        let (_, bin_float) = build_glb_data(&mesh, &GltfConfig::default(), None).unwrap();
        assert!(
            bin.len() < bin_float.len(),
            "Quantized buffer ({}) should be smaller than float ({})",
            bin.len(),
            bin_float.len()
        );

        // Export as file to verify GLB integrity
        let path = std::env::temp_dir().join("alice_test_quantized.glb");
        export_glb(&mesh, &path, &gltf_config, None).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(&bytes[0..4], &GLB_MAGIC.to_le_bytes());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_u16_indices() {
        // Small mesh should use u16 indices
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);
        assert!(mesh.vertex_count() <= 65535);

        let path = std::env::temp_dir().join("alice_test_u16.glb");
        export_glb(&mesh, &path, &GltfConfig::default(), None).unwrap();

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_texture_embedding() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        // Create a tiny test PNG
        let test_dir = std::env::temp_dir().join("alice_tex_test");
        std::fs::create_dir_all(&test_dir).ok();
        let tex_path = test_dir.join("test_albedo.png");
        // Minimal valid PNG (1x1 red pixel)
        let png_data: Vec<u8> = vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
            0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, // IHDR chunk
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
            0x77, 0x53, 0xDE, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41, // IDAT chunk
            0x54, 0x08, 0xD7, 0x63, 0xF8, 0xCF, 0xC0, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x36,
            0x28, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, // IEND chunk
            0x44, 0xAE, 0x42, 0x60, 0x82,
        ];
        std::fs::write(&tex_path, &png_data).unwrap();

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(
            crate::material::Material::metal("Textured", 0.9, 0.9, 0.9, 0.2)
                .with_albedo_map(tex_path.to_string_lossy().to_string()),
        );

        let gltf_config = GltfConfig {
            embed_textures: true,
            ..Default::default()
        };

        let (json_bytes, bin) = build_glb_data(&mesh, &gltf_config, Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();

        // Should use bufferView instead of URI
        assert!(
            json_str.contains(r#""bufferView""#),
            "Should embed via bufferView, got: {}",
            json_str
        );
        assert!(
            json_str.contains(r#""mimeType":"image/png""#),
            "Should have mimeType"
        );
        // Binary buffer should contain the PNG data
        assert!(
            bin.len() >= png_data.len(),
            "Binary buffer should contain embedded image"
        );

        std::fs::remove_dir_all(&test_dir).ok();
    }

    #[test]
    fn test_glb_extended_materials() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(
            crate::material::Material::new("CarPaint")
                .with_color(0.8, 0.0, 0.0, 1.0)
                .with_clearcoat(1.0, 0.1)
                .with_metallic(0.9)
                .with_roughness(0.3),
        );
        mat_lib.add(
            crate::material::Material::glass("GlassPanel", 1.52)
                .with_transmission(0.95)
                .with_volume(0.01, 0.5, 0.9, 0.95, 1.0),
        );
        mat_lib.add(crate::material::Material::new("Velvet").with_sheen(0.5, 0.3, 0.8, 0.7));

        let gltf_config = GltfConfig {
            export_extensions: true,
            ..Default::default()
        };

        let (json_bytes, _) = build_glb_data(&mesh, &gltf_config, Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();

        assert!(
            json_str.contains("KHR_materials_clearcoat"),
            "Missing clearcoat extension: {}",
            json_str
        );
        assert!(
            json_str.contains("KHR_materials_transmission"),
            "Missing transmission extension"
        );
        assert!(
            json_str.contains("KHR_materials_ior"),
            "Missing IOR extension"
        );
        assert!(
            json_str.contains("KHR_materials_volume"),
            "Missing volume extension"
        );
        assert!(
            json_str.contains("KHR_materials_sheen"),
            "Missing sheen extension"
        );
        assert!(
            json_str.contains("extensionsUsed"),
            "Missing extensionsUsed"
        );
    }

    #[test]
    fn test_glb_import_roundtrip() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 8,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);
        let orig_verts = mesh.vertex_count();
        let orig_tris = mesh.indices.len() / 3;

        // Export to GLB bytes
        let glb_bytes = export_glb_bytes(&mesh, &GltfConfig::default(), None).unwrap();

        // Import back
        let imported = import_glb_bytes(&glb_bytes).unwrap();

        assert_eq!(imported.vertex_count(), orig_verts, "Vertex count mismatch");
        assert_eq!(
            imported.indices.len() / 3,
            orig_tris,
            "Triangle count mismatch"
        );

        // Check first vertex position is close
        let orig_pos = mesh.vertices[0].position;
        let imp_pos = imported.vertices[0].position;
        assert!(
            (orig_pos - imp_pos).length() < 0.001,
            "Position mismatch: {:?} vs {:?}",
            orig_pos,
            imp_pos
        );
    }

    #[test]
    fn test_glb_import_file_roundtrip() {
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let path = std::env::temp_dir().join("alice_import_test.glb");
        export_glb(&mesh, &path, &GltfConfig::default(), None).unwrap();

        let imported = import_glb(&path).unwrap();
        assert_eq!(imported.vertex_count(), mesh.vertex_count());
        assert_eq!(imported.indices.len(), mesh.indices.len());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn test_glb_import_invalid() {
        assert!(import_glb_bytes(&[]).is_err());
        assert!(import_glb_bytes(&[0u8; 12]).is_err());
        assert!(import_glb_bytes(b"not a glb file at all").is_err());
    }

    // ------------------------------------------------------------------------
    // doubleSided / alphaMode カバレッジ (image-to-3d §5 対策)
    // ------------------------------------------------------------------------

    #[test]
    fn test_gltf_double_sided_default_is_false() {
        // GltfConfig::default() では double_sided = false、glTF 側にも
        // "doubleSided":true が出力されない (glTF 仕様上 default は false)
        let sphere = SdfNode::sphere(1.0);
        let config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal("m", 0.5, 0.5, 0.5, 0.2));

        let (json_bytes, _bin) =
            build_glb_data(&mesh, &GltfConfig::default(), Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        assert!(
            !json_str.contains(r#""doubleSided":true"#),
            "default config should not emit doubleSided:true, got: {json_str}"
        );
    }

    #[test]
    fn test_gltf_double_sided_opt_in_emits_field() {
        let sphere = SdfNode::sphere(1.0);
        let mc_config = MarchingCubesConfig {
            resolution: 4,
            iso_level: 0.0,
            compute_normals: true,
            ..Default::default()
        };
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &mc_config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal("m", 0.5, 0.5, 0.5, 0.2));

        let config = GltfConfig {
            double_sided: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        assert!(
            json_str.contains(r#""doubleSided":true"#),
            "double_sided=true should emit doubleSided:true, got: {json_str}"
        );
    }

    #[test]
    fn test_gltf_aaa_config_enables_double_sided() {
        // AAA config は doubleSided を有効化 (mesh 生成の Dual Contouring / MC で
        // 面向き乱れが起きる可能性があるため、AAA 出力は defensive に両面描画)
        let sphere = SdfNode::sphere(1.0);
        let mc_config = MarchingCubesConfig::aaa(4);
        let mesh = sdf_to_mesh(&sphere, Vec3::splat(-2.0), Vec3::splat(2.0), &mc_config);

        let mut mat_lib = MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal("m", 0.5, 0.5, 0.5, 0.2));

        let (json_bytes, _bin) = build_glb_data(&mesh, &GltfConfig::aaa(), Some(&mat_lib)).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        assert!(
            json_str.contains(r#""doubleSided":true"#),
            "aaa() config should emit doubleSided:true, got: {json_str}"
        );
    }

    // ------------------------------------------------------------------------
    // meshoptimizer §quantization 統合テスト (2026-07-28 追加)
    // ------------------------------------------------------------------------

    fn make_test_mesh() -> Mesh {
        let sphere = SdfNode::sphere(1.0);
        sdf_to_mesh(
            &sphere,
            Vec3::splat(-2.0),
            Vec3::splat(2.0),
            &MarchingCubesConfig {
                resolution: 4,
                iso_level: 0.0,
                compute_normals: true,
                ..Default::default()
            },
        )
    }

    #[test]
    fn test_gltf_position_snorm_i16_full_range() {
        // 新実装: snorm i16 で center-based mapping、SHORT (5122) + normalized:true
        let mesh = make_test_mesh();
        let config = GltfConfig {
            quantize_positions: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        // componentType 5122 = SHORT
        assert!(
            json_str.contains(r#""componentType":5122"#),
            "position quantization: expected SHORT (5122)"
        );
        // normalized:true で load 時に [-1, 1] float 復元される
        assert!(
            json_str.contains(r#""normalized":true"#),
            "position quantization: expected normalized:true"
        );
        // KHR_mesh_quantization extension 使用
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_quantize_normals_sbyte() {
        let mesh = make_test_mesh();
        let config = GltfConfig {
            quantize_normals: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        // BYTE (5120) componentType (SBYTE snorm)
        assert!(
            json_str.contains(r#""componentType":5120"#),
            "normal quantization: expected BYTE (5120), got: {json_str}"
        );
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_quantize_uvs_ushort() {
        let mesh = make_test_mesh();
        let config = GltfConfig {
            quantize_uvs: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        // UNSIGNED_SHORT (5123) componentType, normalized:true
        assert!(
            json_str.contains(r#""componentType":5123"#),
            "UV quantization: expected UNSIGNED_SHORT (5123)"
        );
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_quantize_colors_ubyte() {
        // Vertex colors export 有効化 + quantize_colors 有効化
        let mesh = make_test_mesh();
        let config = GltfConfig {
            export_colors: true,
            quantize_colors: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        // UNSIGNED_BYTE (5121) componentType
        assert!(
            json_str.contains(r#""componentType":5121"#),
            "color quantization: expected UNSIGNED_BYTE (5121)"
        );
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_all_quantization_combined() {
        // 全 attribute 量子化 + colors export
        let mesh = make_test_mesh();
        let config = GltfConfig {
            export_colors: true,
            quantize_positions: true,
            quantize_normals: true,
            quantize_uvs: true,
            quantize_colors: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        assert!(
            json_str.contains(r#""componentType":5122"#),
            "position SHORT"
        );
        assert!(json_str.contains(r#""componentType":5120"#), "normal BYTE");
        assert!(json_str.contains(r#""componentType":5123"#), "UV USHORT");
        assert!(json_str.contains(r#""componentType":5121"#), "color UBYTE");
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_quantize_tangents_sbyte() {
        // Tangents export 有効化 + quantize_tangents 有効化 → SBYTE snorm VEC4
        let mesh = make_test_mesh();
        let config = GltfConfig {
            export_tangents: true,
            quantize_tangents: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        // BYTE (5120) componentType (SBYTE snorm)
        assert!(
            json_str.contains(r#""componentType":5120"#),
            "tangent quantization: expected BYTE (5120)"
        );
        // VEC4 type (tangent は 4 component: xyz + handedness w)
        assert!(json_str.contains(r#""type":"VEC4""#), "tangent VEC4");
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_all_5_quantizations_with_tangents() {
        // 全 5 attribute 量子化 (position + normal + UV + color + tangent)
        let mesh = make_test_mesh();
        let config = GltfConfig {
            export_colors: true,
            export_tangents: true,
            quantize_positions: true,
            quantize_normals: true,
            quantize_uvs: true,
            quantize_colors: true,
            quantize_tangents: true,
            ..Default::default()
        };
        let (json_bytes, _bin) = build_glb_data(&mesh, &config, None).unwrap();
        let json_str = String::from_utf8(json_bytes).unwrap();
        assert!(
            json_str.contains(r#""componentType":5122"#),
            "position SHORT"
        );
        assert!(
            json_str.contains(r#""componentType":5120"#),
            "normal or tangent BYTE"
        );
        assert!(json_str.contains(r#""componentType":5123"#), "UV USHORT");
        assert!(json_str.contains(r#""componentType":5121"#), "color UBYTE");
        assert!(json_str.contains(r"KHR_mesh_quantization"));
    }

    #[test]
    fn test_gltf_meshopt_compress_option_delegates() {
        // meshopt_compress=true → meshopt_gltf 出力に切替
        let mesh = make_test_mesh();
        let cfg_std = GltfConfig::default();
        let cfg_moc = GltfConfig {
            meshopt_compress: true,
            meshopt_level: 2,
            ..Default::default()
        };

        let std_bytes = export_glb_bytes(&mesh, &cfg_std, None).unwrap();
        let moc_bytes = export_glb_bytes(&mesh, &cfg_moc, None).unwrap();

        // Standard 出力は EXT_meshopt_compression を含まない
        assert!(!String::from_utf8_lossy(&std_bytes).contains("EXT_meshopt_compression"));
        // meshopt_compress=true は EXT_meshopt_compression を含む
        assert!(String::from_utf8_lossy(&moc_bytes).contains("EXT_meshopt_compression"));
        assert!(String::from_utf8_lossy(&moc_bytes)
            .contains(r#""extensionsRequired":["EXT_meshopt_compression"]"#));
    }
}