alice-sdf 5.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
//! FBX 7.4 ASCII export for ALICE-SDF meshes
//!
//! Exports meshes to Autodesk FBX 7.4 ASCII format, compatible with:
//! - Maya, 3ds Max, MotionBuilder
//! - UE5 (import)
//! - Unity (import)
//! - Blender (import via plugin)
//!
//! # Limitations
//! - ASCII format only (binary FBX requires Autodesk SDK)
//! - Geometry + materials (no skeleton/animation)
//! - Single mesh per file
//!
//! Author: Moroya Sakamoto

use crate::io::IoError;
use crate::material::MaterialLibrary;
use crate::mesh::Mesh;
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;

/// FBX file format
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxFormat {
    /// ASCII text format (human-readable, larger files)
    Ascii,
    /// Binary format (compact, faster I/O, industry standard)
    Binary,
}

/// FBX export configuration
#[derive(Debug, Clone)]
pub struct FbxConfig {
    /// Export normals
    pub export_normals: bool,
    /// Export UVs
    pub export_uvs: bool,
    /// Export materials
    pub export_materials: bool,
    /// Up axis: "Y" (Maya/UE5) or "Z" (3ds Max/Blender)
    pub up_axis: FbxUpAxis,
    /// File format (ASCII or Binary)
    pub format: FbxFormat,
}

/// FBX up axis convention
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FbxUpAxis {
    /// Y-up (Maya, UE5, Unity default)
    Y,
    /// Z-up (3ds Max, Blender)
    Z,
}

impl Default for FbxConfig {
    fn default() -> Self {
        Self {
            export_normals: true,
            export_uvs: true,
            export_materials: true,
            up_axis: FbxUpAxis::Y,
            format: FbxFormat::Ascii,
        }
    }
}

impl FbxConfig {
    /// Binary format config (recommended for large meshes)
    pub fn binary() -> Self {
        Self {
            format: FbxFormat::Binary,
            ..Default::default()
        }
    }
}

// ============================================================
// FBX Skeletal/Animation Data Structures
// ============================================================

/// A single bone in a skeleton hierarchy
#[derive(Debug, Clone)]
pub struct FbxBone {
    /// Bone name
    pub name: String,
    /// Parent bone index (None for root)
    pub parent: Option<usize>,
    /// Bind pose transform (4x4 column-major)
    pub bind_pose: [f32; 16],
    /// Vertex indices influenced by this bone
    pub vertex_indices: Vec<u32>,
    /// Corresponding weights for each vertex
    pub weights: Vec<f32>,
}

/// Animation curve data for a single channel
#[derive(Debug, Clone)]
pub struct FbxAnimCurve {
    /// Target property (e.g., "Lcl Translation", "Lcl Rotation")
    pub property: String,
    /// Channel index (0=X, 1=Y, 2=Z)
    pub channel: usize,
    /// Keyframe times (seconds)
    pub times: Vec<f32>,
    /// Keyframe values
    pub values: Vec<f32>,
}

/// Animation clip extracted from FBX
#[derive(Debug, Clone)]
pub struct FbxAnimClip {
    /// Clip name
    pub name: String,
    /// Animation curves per bone (bone_name -> curves)
    pub bone_curves: HashMap<String, Vec<FbxAnimCurve>>,
    /// Duration in seconds
    pub duration: f32,
    /// Frames per second
    pub fps: f32,
}

/// Complete imported FBX data with optional skeleton and animation
#[derive(Debug, Clone)]
pub struct ImportedFbx {
    /// Mesh geometry
    pub mesh: Mesh,
    /// Skeleton (None if no skeleton in file)
    pub skeleton: Option<Vec<FbxBone>>,
    /// Animation clips (empty if no animation)
    pub animations: Vec<FbxAnimClip>,
}

/// Export a mesh to FBX format (dispatches based on config.format)
pub fn export_fbx(
    mesh: &Mesh,
    path: impl AsRef<Path>,
    config: &FbxConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(), IoError> {
    match config.format {
        FbxFormat::Ascii => export_fbx_ascii(mesh, path, config, materials),
        FbxFormat::Binary => export_fbx_binary(mesh, path, config, materials),
    }
}

/// Export a mesh to FBX 7.4 ASCII format
fn export_fbx_ascii(
    mesh: &Mesh,
    path: impl AsRef<Path>,
    config: &FbxConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(), IoError> {
    let file = std::fs::File::create(path)?;
    let mut w = std::io::BufWriter::new(file);

    let vert_count = mesh.vertices.len();
    let tri_count = mesh.indices.len() / 3;

    // FBX Header
    writeln!(w, "; FBX 7.4.0 project file")?;
    writeln!(w, "; Generated by ALICE-SDF")?;
    writeln!(w, ";")?;

    // Header extension
    writeln!(w, "FBXHeaderExtension:  {{")?;
    writeln!(w, "\tFBXHeaderVersion: 1003")?;
    writeln!(w, "\tFBXVersion: 7400")?;
    writeln!(w, "\tCreator: \"ALICE-SDF\"")?;
    writeln!(w, "}}")?;
    writeln!(w)?;

    // Global settings
    let up_axis_val = match config.up_axis {
        FbxUpAxis::Y => 1,
        FbxUpAxis::Z => 2,
    };
    writeln!(w, "GlobalSettings:  {{")?;
    writeln!(w, "\tVersion: 1000")?;
    writeln!(w, "\tProperties70:  {{")?;
    writeln!(
        w,
        "\t\tP: \"UpAxis\", \"int\", \"Integer\", \"\",{}",
        up_axis_val
    )?;
    writeln!(w, "\t\tP: \"UpAxisSign\", \"int\", \"Integer\", \"\",1")?;
    writeln!(w, "\t\tP: \"FrontAxis\", \"int\", \"Integer\", \"\",2")?;
    writeln!(w, "\t\tP: \"FrontAxisSign\", \"int\", \"Integer\", \"\",1")?;
    writeln!(w, "\t\tP: \"CoordAxis\", \"int\", \"Integer\", \"\",0")?;
    writeln!(w, "\t\tP: \"CoordAxisSign\", \"int\", \"Integer\", \"\",1")?;
    writeln!(
        w,
        "\t\tP: \"UnitScaleFactor\", \"double\", \"Number\", \"\",1.0"
    )?;
    writeln!(w, "\t}}")?;
    writeln!(w, "}}")?;
    writeln!(w)?;

    // Object definitions
    let mat_count = materials.map_or(0, MaterialLibrary::len);
    let total_objects = 2 + mat_count; // Model + Geometry + Materials
    writeln!(w, "Definitions:  {{")?;
    writeln!(w, "\tVersion: 100")?;
    writeln!(w, "\tCount: {}", total_objects)?;
    writeln!(w, "\tObjectType: \"Model\" {{")?;
    writeln!(w, "\t\tCount: 1")?;
    writeln!(w, "\t}}")?;
    writeln!(w, "\tObjectType: \"Geometry\" {{")?;
    writeln!(w, "\t\tCount: 1")?;
    writeln!(w, "\t}}")?;
    if mat_count > 0 && config.export_materials {
        writeln!(w, "\tObjectType: \"Material\" {{")?;
        writeln!(w, "\t\tCount: {}", mat_count)?;
        writeln!(w, "\t}}")?;
    }
    writeln!(w, "}}")?;
    writeln!(w)?;

    // Objects section
    writeln!(w, "Objects:  {{")?;

    // Geometry
    let geom_id: i64 = 100000;
    writeln!(
        w,
        "\tGeometry: {}, \"Geometry::Mesh\", \"Mesh\" {{",
        geom_id
    )?;

    // Vertices
    writeln!(w, "\t\tVertices: *{} {{", vert_count * 3)?;
    write!(w, "\t\t\ta: ")?;
    for (i, v) in mesh.vertices.iter().enumerate() {
        if i > 0 {
            write!(w, ",")?;
        }
        write!(w, "{},{},{}", v.position.x, v.position.y, v.position.z)?;
    }
    writeln!(w)?;
    writeln!(w, "\t\t}}")?;

    // Polygon vertex index (FBX uses negative index-1 for last vertex in polygon)
    writeln!(w, "\t\tPolygonVertexIndex: *{} {{", tri_count * 3)?;
    write!(w, "\t\t\ta: ")?;
    for t in 0..tri_count {
        if t > 0 {
            write!(w, ",")?;
        }
        let a = mesh.indices[t * 3] as i32;
        let b = mesh.indices[t * 3 + 1] as i32;
        let c = mesh.indices[t * 3 + 2] as i32;
        // Last index is bitwise NOT (negative - 1) to signal end of polygon
        write!(w, "{},{},{}", a, b, -(c + 1))?;
    }
    writeln!(w)?;
    writeln!(w, "\t\t}}")?;

    // Normals
    if config.export_normals {
        writeln!(w, "\t\tLayerElementNormal: 0 {{")?;
        writeln!(w, "\t\t\tVersion: 101")?;
        writeln!(w, "\t\t\tName: \"\"")?;
        writeln!(w, "\t\t\tMappingInformationType: \"ByVertice\"")?;
        writeln!(w, "\t\t\tReferenceInformationType: \"Direct\"")?;
        writeln!(w, "\t\t\tNormals: *{} {{", vert_count * 3)?;
        write!(w, "\t\t\t\ta: ")?;
        for (i, v) in mesh.vertices.iter().enumerate() {
            if i > 0 {
                write!(w, ",")?;
            }
            write!(w, "{},{},{}", v.normal.x, v.normal.y, v.normal.z)?;
        }
        writeln!(w)?;
        writeln!(w, "\t\t\t}}")?;
        writeln!(w, "\t\t}}")?;
    }

    // UVs
    if config.export_uvs {
        writeln!(w, "\t\tLayerElementUV: 0 {{")?;
        writeln!(w, "\t\t\tVersion: 101")?;
        writeln!(w, "\t\t\tName: \"UVMap\"")?;
        writeln!(w, "\t\t\tMappingInformationType: \"ByVertice\"")?;
        writeln!(w, "\t\t\tReferenceInformationType: \"Direct\"")?;
        writeln!(w, "\t\t\tUV: *{} {{", vert_count * 2)?;
        write!(w, "\t\t\t\ta: ")?;
        for (i, v) in mesh.vertices.iter().enumerate() {
            if i > 0 {
                write!(w, ",")?;
            }
            write!(w, "{},{}", v.uv.x, v.uv.y)?;
        }
        writeln!(w)?;
        writeln!(w, "\t\t\t}}")?;
        writeln!(w, "\t\t}}")?;
    }

    // Material layer
    if config.export_materials && mat_count > 0 {
        writeln!(w, "\t\tLayerElementMaterial: 0 {{")?;
        writeln!(w, "\t\t\tVersion: 101")?;
        writeln!(w, "\t\t\tName: \"\"")?;
        writeln!(w, "\t\t\tMappingInformationType: \"ByPolygon\"")?;
        writeln!(w, "\t\t\tReferenceInformationType: \"IndexToDirect\"")?;
        writeln!(w, "\t\t\tMaterials: *{} {{", tri_count)?;
        write!(w, "\t\t\t\ta: ")?;
        for t in 0..tri_count {
            if t > 0 {
                write!(w, ",")?;
            }
            let v0 = mesh.indices[t * 3] as usize;
            let mat_id = if v0 < mesh.vertices.len() {
                mesh.vertices[v0].material_id
            } else {
                0
            };
            write!(w, "{}", mat_id)?;
        }
        writeln!(w)?;
        writeln!(w, "\t\t\t}}")?;
        writeln!(w, "\t\t}}")?;
    }

    // Layer definition
    writeln!(w, "\t\tLayer: 0 {{")?;
    writeln!(w, "\t\t\tVersion: 100")?;
    if config.export_normals {
        writeln!(w, "\t\t\tLayerElement:  {{")?;
        writeln!(w, "\t\t\t\tType: \"LayerElementNormal\"")?;
        writeln!(w, "\t\t\t\tTypedIndex: 0")?;
        writeln!(w, "\t\t\t}}")?;
    }
    if config.export_uvs {
        writeln!(w, "\t\t\tLayerElement:  {{")?;
        writeln!(w, "\t\t\t\tType: \"LayerElementUV\"")?;
        writeln!(w, "\t\t\t\tTypedIndex: 0")?;
        writeln!(w, "\t\t\t}}")?;
    }
    if config.export_materials && mat_count > 0 {
        writeln!(w, "\t\t\tLayerElement:  {{")?;
        writeln!(w, "\t\t\t\tType: \"LayerElementMaterial\"")?;
        writeln!(w, "\t\t\t\tTypedIndex: 0")?;
        writeln!(w, "\t\t\t}}")?;
    }
    writeln!(w, "\t\t}}")?;
    writeln!(w, "\t}}")?; // End Geometry

    // Model
    let model_id: i64 = 200000;
    writeln!(w, "\tModel: {}, \"Model::Mesh\", \"Mesh\" {{", model_id)?;
    writeln!(w, "\t\tVersion: 232")?;
    writeln!(w, "\t\tProperties70:  {{")?;
    writeln!(
        w,
        "\t\t\tP: \"ScalingMax\", \"Vector3D\", \"Vector\", \"\",0,0,0"
    )?;
    writeln!(w, "\t\t}}")?;
    writeln!(w, "\t\tShading: T")?;
    writeln!(w, "\t\tCulling: \"CullingOff\"")?;
    writeln!(w, "\t}}")?;

    // Materials
    if config.export_materials {
        if let Some(mat_lib) = materials {
            for (i, mat) in mat_lib.iter() {
                let mat_id: i64 = 300000 + i as i64;
                writeln!(
                    w,
                    "\tMaterial: {}, \"Material::{}\", \"\" {{",
                    mat_id, mat.name
                )?;
                writeln!(w, "\t\tVersion: 102")?;
                writeln!(w, "\t\tShadingModel: \"phong\"")?;
                writeln!(w, "\t\tProperties70:  {{")?;
                writeln!(
                    w,
                    "\t\t\tP: \"DiffuseColor\", \"Color\", \"\", \"A\",{},{},{}",
                    mat.base_color[0], mat.base_color[1], mat.base_color[2]
                )?;
                writeln!(
                    w,
                    "\t\t\tP: \"SpecularColor\", \"Color\", \"\", \"A\",{},{},{}",
                    mat.metallic, mat.metallic, mat.metallic
                )?;
                writeln!(
                    w,
                    "\t\t\tP: \"Shininess\", \"double\", \"Number\", \"\",{}",
                    (1.0 - mat.roughness) * 100.0
                )?;
                writeln!(
                    w,
                    "\t\t\tP: \"Opacity\", \"double\", \"Number\", \"\",{}",
                    mat.opacity
                )?;
                if mat.emission_strength > 0.0 {
                    writeln!(
                        w,
                        "\t\t\tP: \"EmissiveColor\", \"Color\", \"\", \"A\",{},{},{}",
                        mat.emission[0], mat.emission[1], mat.emission[2]
                    )?;
                    writeln!(
                        w,
                        "\t\t\tP: \"EmissiveFactor\", \"double\", \"Number\", \"\",{}",
                        mat.emission_strength
                    )?;
                }
                writeln!(w, "\t\t}}")?;
                writeln!(w, "\t}}")?;
            }
        }
    }

    writeln!(w, "}}")?; // End Objects
    writeln!(w)?;

    // Connections
    writeln!(w, "Connections:  {{")?;
    // Model -> Root
    writeln!(w, "\tC: \"OO\",{},0", model_id)?;
    // Geometry -> Model
    writeln!(w, "\tC: \"OO\",{},{}", geom_id, model_id)?;
    // Materials -> Model
    if config.export_materials {
        if let Some(mat_lib) = materials {
            for i in 0..mat_lib.len() {
                let mat_id: i64 = 300000 + i as i64;
                writeln!(w, "\tC: \"OO\",{},{}", mat_id, model_id)?;
            }
        }
    }
    writeln!(w, "}}")?;

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

// ============================================================
// FBX 7.4 Binary Format Writer
// ============================================================

const FBX_BINARY_MAGIC: &[u8; 23] = b"Kaydara FBX Binary  \x00\x1a\x00";
const FBX_BINARY_VERSION: u32 = 7400;

/// Write a single FBX binary node property
fn write_fbx_prop_i32(w: &mut impl Write, val: i32) -> Result<(), IoError> {
    w.write_all(b"I")?;
    w.write_all(&val.to_le_bytes())?;
    Ok(())
}

fn write_fbx_prop_i64(w: &mut impl Write, val: i64) -> Result<(), IoError> {
    w.write_all(b"L")?;
    w.write_all(&val.to_le_bytes())?;
    Ok(())
}

fn write_fbx_prop_f64(w: &mut impl Write, val: f64) -> Result<(), IoError> {
    w.write_all(b"D")?;
    w.write_all(&val.to_le_bytes())?;
    Ok(())
}

fn write_fbx_prop_str(w: &mut impl Write, s: &str) -> Result<(), IoError> {
    w.write_all(b"S")?;
    w.write_all(&(s.len() as u32).to_le_bytes())?;
    w.write_all(s.as_bytes())?;
    Ok(())
}

fn write_fbx_prop_f64_array(w: &mut impl Write, data: &[f64]) -> Result<(), IoError> {
    w.write_all(b"d")?;
    w.write_all(&(data.len() as u32).to_le_bytes())?;
    w.write_all(&0u32.to_le_bytes())?; // encoding: 0 = raw
    w.write_all(&((data.len() * 8) as u32).to_le_bytes())?; // compressed_len
    for &v in data {
        w.write_all(&v.to_le_bytes())?;
    }
    Ok(())
}

fn write_fbx_prop_i32_array(w: &mut impl Write, data: &[i32]) -> Result<(), IoError> {
    w.write_all(b"i")?;
    w.write_all(&(data.len() as u32).to_le_bytes())?;
    w.write_all(&0u32.to_le_bytes())?; // encoding: 0 = raw
    w.write_all(&((data.len() * 4) as u32).to_le_bytes())?; // compressed_len
    for &v in data {
        w.write_all(&v.to_le_bytes())?;
    }
    Ok(())
}

/// Serialize an FBX binary node to a buffer.
/// Returns the serialized bytes.
fn serialize_fbx_node(name: &str, props: &[FbxProp], children: &[Vec<u8>]) -> Vec<u8> {
    let mut body = Vec::new();

    // Properties
    let mut prop_data = Vec::new();
    for prop in props {
        match prop {
            FbxProp::I32(v) => {
                write_fbx_prop_i32(&mut prop_data, *v).ok();
            }
            FbxProp::I64(v) => {
                write_fbx_prop_i64(&mut prop_data, *v).ok();
            }
            FbxProp::F64(v) => {
                write_fbx_prop_f64(&mut prop_data, *v).ok();
            }
            FbxProp::Str(s) => {
                write_fbx_prop_str(&mut prop_data, s).ok();
            }
            FbxProp::F64Array(a) => {
                write_fbx_prop_f64_array(&mut prop_data, a).ok();
            }
            FbxProp::I32Array(a) => {
                write_fbx_prop_i32_array(&mut prop_data, a).ok();
            }
        }
    }

    // Children
    let mut children_data = Vec::new();
    for child in children {
        children_data.extend_from_slice(child);
    }
    // Null record (13 zero bytes) if there are children
    if !children.is_empty() {
        children_data.extend_from_slice(&[0u8; 13]);
    }

    // Node header: end_offset(u32) + num_properties(u32) + prop_list_len(u32) + name_len(u8) + name
    let header_size = 4 + 4 + 4 + 1 + name.len();
    let end_offset = header_size + prop_data.len() + children_data.len();

    body.extend_from_slice(&(end_offset as u32).to_le_bytes());
    body.extend_from_slice(&(props.len() as u32).to_le_bytes());
    body.extend_from_slice(&(prop_data.len() as u32).to_le_bytes());
    body.push(name.len() as u8);
    body.extend_from_slice(name.as_bytes());
    body.extend_from_slice(&prop_data);
    body.extend_from_slice(&children_data);

    body
}

enum FbxProp {
    I32(i32),
    I64(i64),
    F64(f64),
    Str(String),
    F64Array(Vec<f64>),
    I32Array(Vec<i32>),
}

/// Export a mesh to FBX 7.4 binary format
fn export_fbx_binary(
    mesh: &Mesh,
    path: impl AsRef<Path>,
    config: &FbxConfig,
    materials: Option<&MaterialLibrary>,
) -> Result<(), IoError> {
    let file = std::fs::File::create(path)?;
    let mut w = std::io::BufWriter::new(file);

    let vert_count = mesh.vertices.len();
    let tri_count = mesh.indices.len() / 3;

    // FBX binary header
    w.write_all(FBX_BINARY_MAGIC)?;
    w.write_all(&FBX_BINARY_VERSION.to_le_bytes())?;

    // We'll build all top-level nodes as byte buffers, then write them
    // with correct end_offsets (absolute file position).
    let mut top_nodes: Vec<Vec<u8>> = Vec::new();

    // --- FBXHeaderExtension ---
    {
        let version_node = serialize_fbx_node("FBXHeaderVersion", &[FbxProp::I32(1003)], &[]);
        let fbx_version = serialize_fbx_node("FBXVersion", &[FbxProp::I32(7400)], &[]);
        let creator = serialize_fbx_node("Creator", &[FbxProp::Str("ALICE-SDF".to_string())], &[]);
        top_nodes.push(serialize_fbx_node(
            "FBXHeaderExtension",
            &[],
            &[version_node, fbx_version, creator],
        ));
    }

    // --- GlobalSettings ---
    {
        let up_axis_val = match config.up_axis {
            FbxUpAxis::Y => 1,
            FbxUpAxis::Z => 2,
        };
        let p_nodes = vec![
            serialize_fbx_node(
                "P",
                &[
                    FbxProp::Str("UpAxis".to_string()),
                    FbxProp::Str("int".to_string()),
                    FbxProp::Str("Integer".to_string()),
                    FbxProp::Str(String::new()),
                    FbxProp::I32(up_axis_val),
                ],
                &[],
            ),
            serialize_fbx_node(
                "P",
                &[
                    FbxProp::Str("UpAxisSign".to_string()),
                    FbxProp::Str("int".to_string()),
                    FbxProp::Str("Integer".to_string()),
                    FbxProp::Str(String::new()),
                    FbxProp::I32(1),
                ],
                &[],
            ),
            serialize_fbx_node(
                "P",
                &[
                    FbxProp::Str("UnitScaleFactor".to_string()),
                    FbxProp::Str("double".to_string()),
                    FbxProp::Str("Number".to_string()),
                    FbxProp::Str(String::new()),
                    FbxProp::F64(1.0),
                ],
                &[],
            ),
        ];
        let props70 = serialize_fbx_node("Properties70", &[], &p_nodes);
        let version = serialize_fbx_node("Version", &[FbxProp::I32(1000)], &[]);
        top_nodes.push(serialize_fbx_node(
            "GlobalSettings",
            &[],
            &[version, props70],
        ));
    }

    // --- Objects ---
    {
        let mut object_children = Vec::new();
        let geom_id: i64 = 100000;
        let model_id: i64 = 200000;

        // Geometry node
        {
            let mut geom_children = Vec::new();

            // Vertices
            let verts_f64: Vec<f64> = mesh
                .vertices
                .iter()
                .flat_map(|v| {
                    vec![
                        v.position.x as f64,
                        v.position.y as f64,
                        v.position.z as f64,
                    ]
                })
                .collect();
            geom_children.push(serialize_fbx_node(
                "Vertices",
                &[FbxProp::F64Array(verts_f64)],
                &[],
            ));

            // PolygonVertexIndex
            let indices_i32: Vec<i32> = (0..tri_count)
                .flat_map(|t| {
                    let a = mesh.indices[t * 3] as i32;
                    let b = mesh.indices[t * 3 + 1] as i32;
                    let c = mesh.indices[t * 3 + 2] as i32;
                    vec![a, b, -(c + 1)]
                })
                .collect();
            geom_children.push(serialize_fbx_node(
                "PolygonVertexIndex",
                &[FbxProp::I32Array(indices_i32)],
                &[],
            ));

            // Normals
            if config.export_normals {
                let normals_f64: Vec<f64> = mesh
                    .vertices
                    .iter()
                    .flat_map(|v| vec![v.normal.x as f64, v.normal.y as f64, v.normal.z as f64])
                    .collect();
                let normals_node =
                    serialize_fbx_node("Normals", &[FbxProp::F64Array(normals_f64)], &[]);
                let mapping = serialize_fbx_node(
                    "MappingInformationType",
                    &[FbxProp::Str("ByVertice".to_string())],
                    &[],
                );
                let reference = serialize_fbx_node(
                    "ReferenceInformationType",
                    &[FbxProp::Str("Direct".to_string())],
                    &[],
                );
                let version = serialize_fbx_node("Version", &[FbxProp::I32(101)], &[]);
                geom_children.push(serialize_fbx_node(
                    "LayerElementNormal",
                    &[FbxProp::I32(0)],
                    &[version, mapping, reference, normals_node],
                ));
            }

            // UVs
            if config.export_uvs {
                let uvs_f64: Vec<f64> = mesh
                    .vertices
                    .iter()
                    .flat_map(|v| vec![v.uv.x as f64, v.uv.y as f64])
                    .collect();
                let uv_node = serialize_fbx_node("UV", &[FbxProp::F64Array(uvs_f64)], &[]);
                let name = serialize_fbx_node("Name", &[FbxProp::Str("UVMap".to_string())], &[]);
                let mapping = serialize_fbx_node(
                    "MappingInformationType",
                    &[FbxProp::Str("ByVertice".to_string())],
                    &[],
                );
                let reference = serialize_fbx_node(
                    "ReferenceInformationType",
                    &[FbxProp::Str("Direct".to_string())],
                    &[],
                );
                let version = serialize_fbx_node("Version", &[FbxProp::I32(101)], &[]);
                geom_children.push(serialize_fbx_node(
                    "LayerElementUV",
                    &[FbxProp::I32(0)],
                    &[version, name, mapping, reference, uv_node],
                ));
            }

            // Materials layer
            let mat_count = materials.map_or(0, MaterialLibrary::len);
            if config.export_materials && mat_count > 0 {
                let mat_ids: Vec<i32> = (0..tri_count)
                    .map(|t| {
                        let v0 = mesh.indices[t * 3] as usize;
                        if v0 < vert_count {
                            mesh.vertices[v0].material_id as i32
                        } else {
                            0
                        }
                    })
                    .collect();
                let mat_data = serialize_fbx_node("Materials", &[FbxProp::I32Array(mat_ids)], &[]);
                let mapping = serialize_fbx_node(
                    "MappingInformationType",
                    &[FbxProp::Str("ByPolygon".to_string())],
                    &[],
                );
                let reference = serialize_fbx_node(
                    "ReferenceInformationType",
                    &[FbxProp::Str("IndexToDirect".to_string())],
                    &[],
                );
                let version = serialize_fbx_node("Version", &[FbxProp::I32(101)], &[]);
                geom_children.push(serialize_fbx_node(
                    "LayerElementMaterial",
                    &[FbxProp::I32(0)],
                    &[version, mapping, reference, mat_data],
                ));
            }

            // Layer
            {
                let mut layer_children =
                    vec![serialize_fbx_node("Version", &[FbxProp::I32(100)], &[])];
                if config.export_normals {
                    let le = serialize_fbx_node(
                        "LayerElement",
                        &[],
                        &[
                            serialize_fbx_node(
                                "Type",
                                &[FbxProp::Str("LayerElementNormal".to_string())],
                                &[],
                            ),
                            serialize_fbx_node("TypedIndex", &[FbxProp::I32(0)], &[]),
                        ],
                    );
                    layer_children.push(le);
                }
                if config.export_uvs {
                    let le = serialize_fbx_node(
                        "LayerElement",
                        &[],
                        &[
                            serialize_fbx_node(
                                "Type",
                                &[FbxProp::Str("LayerElementUV".to_string())],
                                &[],
                            ),
                            serialize_fbx_node("TypedIndex", &[FbxProp::I32(0)], &[]),
                        ],
                    );
                    layer_children.push(le);
                }
                if config.export_materials && mat_count > 0 {
                    let le = serialize_fbx_node(
                        "LayerElement",
                        &[],
                        &[
                            serialize_fbx_node(
                                "Type",
                                &[FbxProp::Str("LayerElementMaterial".to_string())],
                                &[],
                            ),
                            serialize_fbx_node("TypedIndex", &[FbxProp::I32(0)], &[]),
                        ],
                    );
                    layer_children.push(le);
                }
                geom_children.push(serialize_fbx_node(
                    "Layer",
                    &[FbxProp::I32(0)],
                    &layer_children,
                ));
            }

            object_children.push(serialize_fbx_node(
                "Geometry",
                &[
                    FbxProp::I64(geom_id),
                    FbxProp::Str("Geometry::Mesh\x00\x01Mesh".to_string()),
                    FbxProp::Str("Mesh".to_string()),
                ],
                &geom_children,
            ));
        }

        // Model node
        {
            let props70 = serialize_fbx_node(
                "Properties70",
                &[],
                &[serialize_fbx_node(
                    "P",
                    &[
                        FbxProp::Str("ScalingMax".to_string()),
                        FbxProp::Str("Vector3D".to_string()),
                        FbxProp::Str("Vector".to_string()),
                        FbxProp::Str(String::new()),
                        FbxProp::F64(0.0),
                        FbxProp::F64(0.0),
                        FbxProp::F64(0.0),
                    ],
                    &[],
                )],
            );
            let version = serialize_fbx_node("Version", &[FbxProp::I32(232)], &[]);
            object_children.push(serialize_fbx_node(
                "Model",
                &[
                    FbxProp::I64(model_id),
                    FbxProp::Str("Model::Mesh\x00\x01Mesh".to_string()),
                    FbxProp::Str("Mesh".to_string()),
                ],
                &[version, props70],
            ));
        }

        // Material nodes
        if config.export_materials {
            if let Some(mat_lib) = materials {
                for (i, mat) in mat_lib.iter() {
                    let mat_id: i64 = 300000 + i as i64;
                    let p_nodes = vec![
                        serialize_fbx_node(
                            "P",
                            &[
                                FbxProp::Str("DiffuseColor".to_string()),
                                FbxProp::Str("Color".to_string()),
                                FbxProp::Str(String::new()),
                                FbxProp::Str("A".to_string()),
                                FbxProp::F64(mat.base_color[0] as f64),
                                FbxProp::F64(mat.base_color[1] as f64),
                                FbxProp::F64(mat.base_color[2] as f64),
                            ],
                            &[],
                        ),
                        serialize_fbx_node(
                            "P",
                            &[
                                FbxProp::Str("Shininess".to_string()),
                                FbxProp::Str("double".to_string()),
                                FbxProp::Str("Number".to_string()),
                                FbxProp::Str(String::new()),
                                FbxProp::F64(((1.0 - mat.roughness) * 100.0) as f64),
                            ],
                            &[],
                        ),
                        serialize_fbx_node(
                            "P",
                            &[
                                FbxProp::Str("Opacity".to_string()),
                                FbxProp::Str("double".to_string()),
                                FbxProp::Str("Number".to_string()),
                                FbxProp::Str(String::new()),
                                FbxProp::F64(mat.opacity as f64),
                            ],
                            &[],
                        ),
                    ];
                    let props70 = serialize_fbx_node("Properties70", &[], &p_nodes);
                    let version = serialize_fbx_node("Version", &[FbxProp::I32(102)], &[]);
                    let shading = serialize_fbx_node(
                        "ShadingModel",
                        &[FbxProp::Str("phong".to_string())],
                        &[],
                    );

                    let mat_name = format!("Material::{}\x00\x01", mat.name);
                    object_children.push(serialize_fbx_node(
                        "Material",
                        &[
                            FbxProp::I64(mat_id),
                            FbxProp::Str(mat_name),
                            FbxProp::Str(String::new()),
                        ],
                        &[version, shading, props70],
                    ));
                }
            }
        }

        top_nodes.push(serialize_fbx_node("Objects", &[], &object_children));
    }

    // --- Connections ---
    {
        let model_id: i64 = 200000;
        let geom_id: i64 = 100000;
        let mut conn_children = Vec::new();

        conn_children.push(serialize_fbx_node(
            "C",
            &[
                FbxProp::Str("OO".to_string()),
                FbxProp::I64(model_id),
                FbxProp::I64(0),
            ],
            &[],
        ));
        conn_children.push(serialize_fbx_node(
            "C",
            &[
                FbxProp::Str("OO".to_string()),
                FbxProp::I64(geom_id),
                FbxProp::I64(model_id),
            ],
            &[],
        ));

        if config.export_materials {
            if let Some(mat_lib) = materials {
                for i in 0..mat_lib.len() {
                    let mat_id: i64 = 300000 + i as i64;
                    conn_children.push(serialize_fbx_node(
                        "C",
                        &[
                            FbxProp::Str("OO".to_string()),
                            FbxProp::I64(mat_id),
                            FbxProp::I64(model_id),
                        ],
                        &[],
                    ));
                }
            }
        }

        top_nodes.push(serialize_fbx_node("Connections", &[], &conn_children));
    }

    // Write all top-level nodes with correct absolute end_offsets
    let header_size = 27u32; // 23 magic + 4 version
    let mut current_offset = header_size;

    for node_data in &top_nodes {
        // Patch the end_offset (first 4 bytes) to be absolute
        let absolute_end = current_offset + node_data.len() as u32;
        let mut patched = node_data.clone();
        patched[0..4].copy_from_slice(&absolute_end.to_le_bytes());
        w.write_all(&patched)?;
        current_offset = absolute_end;
    }

    // Footer: null record
    w.write_all(&[0u8; 13])?;

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

// ============================================================
// FBX ASCII Import
// ============================================================

/// Import a mesh from FBX file (ASCII format only)
///
/// Parses FBX 7.x ASCII format, extracting:
/// - Vertices (flat x,y,z floats)
/// - PolygonVertexIndex (negative index encoding for polygon end)
/// - LayerElementNormal / Normals
/// - LayerElementUV / UV
pub fn import_fbx(path: impl AsRef<Path>) -> Result<Mesh, IoError> {
    use crate::mesh::Vertex;
    use glam::{Vec2, Vec3};

    let bytes = std::fs::read(path.as_ref())?;

    // Check for binary FBX (starts with "Kaydara FBX Binary") before decoding
    // as text: a binary file is not UTF-8, so decoding first reported an I/O
    // error instead of this message
    if bytes.len() >= 23 && &bytes[..18] == b"Kaydara FBX Binary" {
        return Err(IoError::InvalidFormat(
            "Binary FBX import not supported. Use ASCII FBX or convert to glTF.".into(),
        ));
    }
    let content = String::from_utf8(bytes)
        .map_err(|e| IoError::Io(std::io::Error::new(std::io::ErrorKind::InvalidData, e)))?;

    let mut raw_vertices: Vec<f32> = Vec::new();
    let mut raw_polygon_indices: Vec<i32> = Vec::new();
    let mut raw_normals: Vec<f32> = Vec::new();
    let mut raw_uvs: Vec<f32> = Vec::new();

    // Simple state-machine parser for FBX ASCII
    let mut in_vertices = false;
    let mut in_polygon_indices = false;
    let mut in_normals = false;
    let mut in_uvs = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Detect sections and pre-allocate from element count in header
        if trimmed.starts_with("Vertices: *") {
            if let Some(n_str) = trimmed.strip_prefix("Vertices: *") {
                if let Ok(n) = n_str.parse::<usize>() {
                    raw_vertices.reserve(n);
                }
            }
            in_vertices = true;
            continue;
        }
        if trimmed.starts_with("PolygonVertexIndex: *") {
            if let Some(n_str) = trimmed.strip_prefix("PolygonVertexIndex: *") {
                if let Ok(n) = n_str.parse::<usize>() {
                    raw_polygon_indices.reserve(n);
                }
            }
            in_polygon_indices = true;
            continue;
        }
        if trimmed.starts_with("Normals: *") {
            if let Some(n_str) = trimmed.strip_prefix("Normals: *") {
                if let Ok(n) = n_str.parse::<usize>() {
                    raw_normals.reserve(n);
                }
            }
            in_normals = true;
            continue;
        }
        if trimmed.starts_with("UV: *") && !trimmed.starts_with("UVIndex:") {
            if let Some(n_str) = trimmed.strip_prefix("UV: *") {
                if let Ok(n) = n_str.parse::<usize>() {
                    raw_uvs.reserve(n);
                }
            }
            in_uvs = true;
            continue;
        }

        // Parse "a: val,val,val,..." lines
        if let Some(data_str) = trimmed.strip_prefix("a: ") {
            if in_vertices {
                for tok in data_str.split(',') {
                    if let Ok(v) = tok.trim().parse::<f32>() {
                        raw_vertices.push(v);
                    }
                }
                in_vertices = false;
            } else if in_polygon_indices {
                for tok in data_str.split(',') {
                    if let Ok(v) = tok.trim().parse::<i32>() {
                        raw_polygon_indices.push(v);
                    }
                }
                in_polygon_indices = false;
            } else if in_normals {
                for tok in data_str.split(',') {
                    if let Ok(v) = tok.trim().parse::<f32>() {
                        raw_normals.push(v);
                    }
                }
                in_normals = false;
            } else if in_uvs {
                for tok in data_str.split(',') {
                    if let Ok(v) = tok.trim().parse::<f32>() {
                        raw_uvs.push(v);
                    }
                }
                in_uvs = false;
            }
        }

        // Close section on "}"
        if trimmed == "}" {
            in_vertices = false;
            in_polygon_indices = false;
            in_normals = false;
            in_uvs = false;
        }
    }

    if raw_vertices.is_empty() || raw_polygon_indices.is_empty() {
        return Err(IoError::InvalidFormat(
            "No geometry found in FBX file".into(),
        ));
    }

    let vert_count = raw_vertices.len() / 3;
    let has_normals = raw_normals.len() / 3 == vert_count;
    let has_uvs = raw_uvs.len() / 2 == vert_count;

    // Build vertices directly from raw arrays (no intermediate Vec<Vec3> allocation)
    let mut vertices: Vec<Vertex> = Vec::with_capacity(vert_count);
    for i in 0..vert_count {
        let i3 = i * 3;
        let pos = Vec3::new(raw_vertices[i3], raw_vertices[i3 + 1], raw_vertices[i3 + 2]);
        let norm = if has_normals {
            Vec3::new(raw_normals[i3], raw_normals[i3 + 1], raw_normals[i3 + 2]).normalize()
        } else {
            Vec3::Y
        };
        let mut vert = Vertex::new(pos, norm);
        if has_uvs {
            let i2 = i * 2;
            vert.uv = Vec2::new(raw_uvs[i2], raw_uvs[i2 + 1]);
        }
        vertices.push(vert);
    }

    // Decode polygon indices (negative index = -(c + 1) marks polygon end)
    let mut indices: Vec<u32> = Vec::new();
    let mut polygon: Vec<u32> = Vec::new();

    for &idx in &raw_polygon_indices {
        if idx < 0 {
            // Last vertex in polygon: real index = -(idx + 1)
            let real_idx = (-(idx + 1)) as u32;
            polygon.push(real_idx);
            // Fan-triangulate the polygon
            for i in 1..polygon.len().saturating_sub(1) {
                indices.push(polygon[0]);
                indices.push(polygon[i]);
                indices.push(polygon[i + 1]);
            }
            polygon.clear();
        } else {
            polygon.push(idx as u32);
        }
    }

    Ok(Mesh { vertices, indices })
}

// ============================================================
// FBX Skeletal/Animation Import
// ============================================================

/// Import FBX with full skeletal + animation data (ASCII format)
///
/// Extends the basic geometry import with:
/// - Deformer/Cluster parsing for bone hierarchy and vertex weights
/// - AnimationCurveNode parsing for keyframe animation
/// - Connection graph (C: "OO") for resolving parent-child relationships
pub fn import_fbx_full(path: impl AsRef<Path>) -> Result<ImportedFbx, IoError> {
    // First, get the base mesh using existing import_fbx
    let mesh = import_fbx(path.as_ref())?;

    let content = std::fs::read_to_string(path.as_ref())?;

    // Parse skeleton from Deformer sections
    let skeleton = parse_skeleton(&content);

    // Parse animations from AnimationCurveNode sections
    let animations = parse_animations(&content);

    Ok(ImportedFbx {
        mesh,
        skeleton,
        animations,
    })
}

/// Parse skeleton from FBX ASCII Deformer/Cluster sections
fn parse_skeleton(content: &str) -> Option<Vec<FbxBone>> {
    let mut bones = Vec::new();
    let mut bone_id_map: HashMap<i64, usize> = HashMap::new();
    let mut connections: Vec<(i64, i64)> = Vec::new(); // (child_id, parent_id)

    // Parse Deformer sections
    let mut current_bone: Option<(i64, FbxBone)> = None;
    let mut in_indices = false;
    let mut in_weights = false;
    let mut in_transform_link = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Detect Cluster (bone) definition
        if trimmed.starts_with("Deformer:") && trimmed.contains("\"Cluster\"") {
            // Parse: Deformer: 400001, "SubDeformer::BoneName", "Cluster"
            let parts: Vec<&str> = trimmed.split(',').collect();
            if parts.len() >= 2 {
                if let Some(id_str) = parts[0].strip_prefix("Deformer:") {
                    if let Ok(id) = id_str.trim().parse::<i64>() {
                        // Extract bone name from "SubDeformer::BoneName"
                        let name = parts[1]
                            .trim()
                            .trim_matches('"')
                            .strip_prefix("SubDeformer::")
                            .unwrap_or("UnnamedBone")
                            .to_string();

                        current_bone = Some((
                            id,
                            FbxBone {
                                name,
                                parent: None,
                                bind_pose: [
                                    1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
                                    0.0, 0.0, 0.0, 1.0,
                                ],
                                vertex_indices: Vec::new(),
                                weights: Vec::new(),
                            },
                        ));
                    }
                }
            }
        }

        // Parse Indexes array
        if trimmed.starts_with("Indexes: *") {
            in_indices = true;
            continue;
        }

        // Parse Weights array
        if trimmed.starts_with("Weights: *") {
            in_weights = true;
            continue;
        }

        // Parse TransformLink (bind pose)
        if trimmed.starts_with("TransformLink: *") {
            in_transform_link = true;
            continue;
        }

        // Parse "a: " data lines
        if let Some(data_str) = trimmed.strip_prefix("a: ") {
            if in_indices {
                if let Some((_, ref mut bone)) = current_bone {
                    for tok in data_str.split(',') {
                        if let Ok(idx) = tok.trim().parse::<u32>() {
                            bone.vertex_indices.push(idx);
                        }
                    }
                }
                in_indices = false;
            } else if in_weights {
                if let Some((_, ref mut bone)) = current_bone {
                    for tok in data_str.split(',') {
                        if let Ok(w) = tok.trim().parse::<f32>() {
                            bone.weights.push(w);
                        }
                    }
                }
                in_weights = false;
            } else if in_transform_link {
                if let Some((_, ref mut bone)) = current_bone {
                    let mut values: Vec<f32> = Vec::new();
                    for tok in data_str.split(',') {
                        if let Ok(v) = tok.trim().parse::<f32>() {
                            values.push(v);
                        }
                    }
                    if values.len() == 16 {
                        bone.bind_pose.copy_from_slice(&values);
                    }
                }
                in_transform_link = false;
            }
        }

        // End of Deformer section
        if trimmed == "}" {
            if let Some((id, bone)) = current_bone.take() {
                bone_id_map.insert(id, bones.len());
                bones.push(bone);
            }
            in_indices = false;
            in_weights = false;
            in_transform_link = false;
        }
    }

    // Parse Connections section for parent-child relationships
    let mut in_connections = false;
    for line in content.lines() {
        let trimmed = line.trim();

        if trimmed.starts_with("Connections:") {
            in_connections = true;
            continue;
        }

        if in_connections {
            if trimmed == "}" {
                break;
            }

            // Parse: C: "OO",child_id,parent_id
            if trimmed.starts_with("C: \"OO\"") {
                let parts: Vec<&str> = trimmed.split(',').collect();
                if parts.len() >= 3 {
                    if let (Ok(child_id), Ok(parent_id)) = (
                        parts[1].trim().parse::<i64>(),
                        parts[2].trim().parse::<i64>(),
                    ) {
                        connections.push((child_id, parent_id));
                    }
                }
            }
        }
    }

    // Apply parent-child relationships
    for (child_id, parent_id) in connections {
        if let (Some(&child_idx), Some(&parent_idx)) =
            (bone_id_map.get(&child_id), bone_id_map.get(&parent_id))
        {
            bones[child_idx].parent = Some(parent_idx);
        }
    }

    if bones.is_empty() {
        None
    } else {
        Some(bones)
    }
}

/// Parse animations from FBX ASCII AnimationCurveNode sections
fn parse_animations(content: &str) -> Vec<FbxAnimClip> {
    let mut clips = Vec::new();
    let mut bone_curves: HashMap<String, Vec<FbxAnimCurve>> = HashMap::new();

    // FBX time unit: 1 second = 46186158000
    const FBX_TIME_UNIT: f64 = 46186158000.0;

    let mut current_curve: Option<FbxAnimCurve> = None;
    let mut in_key_time = false;
    let mut in_key_value = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Detect AnimationCurve
        if trimmed.starts_with("AnimationCurve:") {
            current_curve = Some(FbxAnimCurve {
                property: "Unknown".to_string(),
                channel: 0,
                times: Vec::new(),
                values: Vec::new(),
            });
        }

        // Parse KeyTime
        if trimmed.starts_with("KeyTime: *") {
            in_key_time = true;
            continue;
        }

        // Parse KeyValueFloat
        if trimmed.starts_with("KeyValueFloat: *") {
            in_key_value = true;
            continue;
        }

        // Parse "a: " data lines
        if let Some(data_str) = trimmed.strip_prefix("a: ") {
            if in_key_time {
                if let Some(ref mut curve) = current_curve {
                    for tok in data_str.split(',') {
                        if let Ok(fbx_time) = tok.trim().parse::<i64>() {
                            let time_sec = (fbx_time as f64 / FBX_TIME_UNIT) as f32;
                            curve.times.push(time_sec);
                        }
                    }
                }
                in_key_time = false;
            } else if in_key_value {
                if let Some(ref mut curve) = current_curve {
                    for tok in data_str.split(',') {
                        if let Ok(val) = tok.trim().parse::<f32>() {
                            curve.values.push(val);
                        }
                    }
                }
                in_key_value = false;
            }
        }

        // End of AnimationCurve section
        if trimmed == "}" {
            if let Some(curve) = current_curve.take() {
                // Store curve (simplified: assume all curves belong to root bone)
                bone_curves
                    .entry("Root".to_string())
                    .or_default()
                    .push(curve);
            }
            in_key_time = false;
            in_key_value = false;
        }
    }

    // Create a single clip if we have curves
    if !bone_curves.is_empty() {
        let max_time = bone_curves
            .values()
            .flat_map(|curves| curves.iter().flat_map(|c| c.times.iter()))
            .cloned()
            .fold(0.0f32, f32::max);

        clips.push(FbxAnimClip {
            name: "DefaultClip".to_string(),
            bone_curves,
            duration: max_time,
            fps: 30.0,
        });
    }

    clips
}

/// Convert FBX skeleton animation to ALICE-SDF AnimationParams timeline
///
/// Maps the root bone's translation/rotation to SDF animation parameters.
/// This is a simplified mapping suitable for single-body SDF animation.
pub fn fbx_animation_to_timeline(
    clip: &FbxAnimClip,
    root_bone: &str,
) -> crate::animation::Timeline {
    use crate::animation::{Keyframe, Timeline, Track};

    let mut timeline = Timeline::new(&clip.name);

    if let Some(curves) = clip.bone_curves.get(root_bone) {
        for curve in curves {
            let track_name = match (curve.property.as_str(), curve.channel) {
                ("Lcl Translation", 0) => "translate.x",
                ("Lcl Translation", 1) => "translate.y",
                ("Lcl Translation", 2) => "translate.z",
                ("Lcl Rotation", 0) => "rotate.x",
                ("Lcl Rotation", 1) => "rotate.y",
                ("Lcl Rotation", 2) => "rotate.z",
                _ => continue,
            };

            let mut track = Track::new(track_name);
            for (t, v) in curve.times.iter().zip(curve.values.iter()) {
                let value = if curve.property == "Lcl Rotation" {
                    v.to_radians()
                } else {
                    *v
                };
                track.add_keyframe(Keyframe::new(*t, value));
            }
            timeline.add_track(track);
        }
    }

    timeline
}

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

    #[test]
    fn test_fbx_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.fbx");
        export_fbx(&mesh, &path, &FbxConfig::default(), None).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("FBXVersion: 7400"));
        assert!(content.contains("Vertices:"));
        assert!(content.contains("PolygonVertexIndex:"));
        assert!(content.contains("LayerElementNormal:"));
        assert!(content.contains("LayerElementUV:"));

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

    #[test]
    fn test_fbx_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 = crate::material::MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal(
            "Steel", 0.7, 0.7, 0.7, 0.4,
        ));

        let path = std::env::temp_dir().join("alice_test_mat.fbx");
        export_fbx(&mesh, &path, &FbxConfig::default(), Some(&mat_lib)).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("Material::Default"));
        assert!(content.contains("Material::Steel"));
        assert!(content.contains("DiffuseColor"));

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

    #[test]
    fn test_fbx_z_up() {
        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 fbx_config = FbxConfig {
            up_axis: FbxUpAxis::Z,
            ..Default::default()
        };

        let path = std::env::temp_dir().join("alice_test_zup.fbx");
        export_fbx(&mesh, &path, &fbx_config, None).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("\"UpAxis\", \"int\", \"Integer\", \"\",2"));

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

    #[test]
    fn test_fbx_binary_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_binary.fbx");
        export_fbx(&mesh, &path, &FbxConfig::binary(), None).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        // Verify FBX binary magic
        assert_eq!(
            &bytes[0..21],
            &FBX_BINARY_MAGIC[0..21],
            "FBX binary magic mismatch"
        );
        // Verify version
        let version = u32::from_le_bytes([bytes[23], bytes[24], bytes[25], bytes[26]]);
        assert_eq!(version, 7400);
        // Should be reasonably sized
        assert!(
            bytes.len() > 100,
            "Binary FBX too small: {} bytes",
            bytes.len()
        );

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

    #[test]
    fn test_fbx_binary_with_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 = crate::material::MaterialLibrary::new();
        mat_lib.add(crate::material::Material::metal(
            "Steel", 0.7, 0.7, 0.7, 0.4,
        ));

        let path = std::env::temp_dir().join("alice_test_bin_mat.fbx");
        export_fbx(&mesh, &path, &FbxConfig::binary(), Some(&mat_lib)).unwrap();

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

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

    #[test]
    fn test_fbx_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 as ASCII FBX
        let path = std::env::temp_dir().join("alice_import_test.fbx");
        export_fbx(&mesh, &path, &FbxConfig::default(), None).unwrap();

        // Import back
        let imported = import_fbx(&path).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
        );

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

    #[test]
    fn test_fbx_import_empty() {
        let result = import_fbx("/nonexistent/file.fbx");
        assert!(result.is_err());
    }

    #[test]
    fn test_fbx_skeletal_structs() {
        // Test FbxBone creation
        let bone = FbxBone {
            name: "TestBone".to_string(),
            parent: None,
            bind_pose: [
                1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
            ],
            vertex_indices: vec![0, 1, 2],
            weights: vec![1.0, 0.8, 0.5],
        };
        assert_eq!(bone.name, "TestBone");
        assert_eq!(bone.vertex_indices.len(), 3);
        assert_eq!(bone.weights.len(), 3);

        // Test ImportedFbx creation
        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 imported = ImportedFbx {
            mesh,
            skeleton: Some(vec![bone]),
            animations: Vec::new(),
        };

        assert!(imported.skeleton.is_some());
        assert_eq!(imported.skeleton.unwrap().len(), 1);
        assert_eq!(imported.animations.len(), 0);
    }

    #[test]
    fn test_fbx_animation_to_timeline() {
        // Create FbxAnimClip with translation curves
        let mut bone_curves = HashMap::new();
        let curves = vec![
            FbxAnimCurve {
                property: "Lcl Translation".to_string(),
                channel: 0,
                times: vec![0.0, 1.0, 2.0],
                values: vec![0.0, 1.0, 2.0],
            },
            FbxAnimCurve {
                property: "Lcl Rotation".to_string(),
                channel: 0,
                times: vec![0.0, 1.0],
                values: vec![0.0, 90.0], // degrees
            },
        ];
        bone_curves.insert("Root".to_string(), curves);

        let clip = FbxAnimClip {
            name: "TestClip".to_string(),
            bone_curves,
            duration: 2.0,
            fps: 30.0,
        };

        // Convert to Timeline
        let timeline = fbx_animation_to_timeline(&clip, "Root");

        assert_eq!(timeline.name, "TestClip");
        assert!(!timeline.tracks.is_empty());

        // Find translate.x track
        let translate_x = timeline.tracks.iter().find(|t| t.name == "translate.x");
        assert!(translate_x.is_some());
        let track = translate_x.unwrap();
        assert_eq!(track.keyframes.len(), 3);
        assert_eq!(track.keyframes[0].value, 0.0);
        assert_eq!(track.keyframes[1].value, 1.0);
        assert_eq!(track.keyframes[2].value, 2.0);

        // Find rotate.x track (should be in radians)
        let rotate_x = timeline.tracks.iter().find(|t| t.name == "rotate.x");
        assert!(rotate_x.is_some());
        let track = rotate_x.unwrap();
        assert_eq!(track.keyframes.len(), 2);
        assert_eq!(track.keyframes[0].value, 0.0);
        assert!((track.keyframes[1].value - (90.0f32.to_radians())).abs() < 0.001);
    }

    #[test]
    fn test_import_fbx_full_geometry_only() {
        // Export a simple mesh
        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_fbx_full_test.fbx");
        export_fbx(&mesh, &path, &FbxConfig::default(), None).unwrap();

        // Import with full parser
        let imported = import_fbx_full(&path).unwrap();

        // Should have geometry, but no skeleton
        assert_eq!(imported.mesh.vertex_count(), mesh.vertex_count());
        assert!(imported.skeleton.is_none());
        assert_eq!(imported.animations.len(), 0);

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