lib3mf 0.1.6

Pure Rust implementation for 3MF (3D Manufacturing Format) parsing and writing
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
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
//! Material validation functions

use crate::error::{Error, Result};
use crate::model::Model;
use std::collections::{HashMap, HashSet};

use super::sorted_ids_from_set;

/// Validates material property group references and uniqueness
pub fn validate_material_references(model: &Model) -> Result<()> {
    // Validate that all property group IDs are unique across all property group types
    // Property groups include: color groups, base material groups, multiproperties,
    // texture2d groups, and composite materials
    let mut seen_property_group_ids: HashMap<usize, String> = HashMap::new();

    // Check color group IDs
    for colorgroup in &model.resources.color_groups {
        if let Some(existing_type) =
            seen_property_group_ids.insert(colorgroup.id, "colorgroup".to_string())
        {
            return Err(Error::InvalidModel(format!(
                "Duplicate resource ID: {}. \
                 This ID is used by both a {} and a colorgroup. \
                 Each resource must have a unique id attribute. \
                 Check your material definitions for duplicate IDs.",
                colorgroup.id, existing_type
            )));
        }
    }

    // Check base material group IDs
    for basematerialgroup in &model.resources.base_material_groups {
        if let Some(existing_type) =
            seen_property_group_ids.insert(basematerialgroup.id, "basematerials".to_string())
        {
            return Err(Error::InvalidModel(format!(
                "Duplicate resource ID: {}. \
                 This ID is used by both a {} and a basematerials group. \
                 Each resource must have a unique id attribute. \
                 Check your material definitions for duplicate IDs.",
                basematerialgroup.id, existing_type
            )));
        }
    }

    // Check multiproperties IDs
    for multiprop in &model.resources.multi_properties {
        if let Some(existing_type) =
            seen_property_group_ids.insert(multiprop.id, "multiproperties".to_string())
        {
            return Err(Error::InvalidModel(format!(
                "Duplicate resource ID: {}. \
                 This ID is used by both a {} and a multiproperties group. \
                 Each resource must have a unique id attribute. \
                 Check your material definitions for duplicate IDs.",
                multiprop.id, existing_type
            )));
        }
    }

    // Check texture2d group IDs
    for tex2dgroup in &model.resources.texture2d_groups {
        if let Some(existing_type) =
            seen_property_group_ids.insert(tex2dgroup.id, "texture2dgroup".to_string())
        {
            return Err(Error::InvalidModel(format!(
                "Duplicate resource ID: {}. \
                 This ID is used by both a {} and a texture2dgroup. \
                 Each resource must have a unique id attribute. \
                 Check your material definitions for duplicate IDs.",
                tex2dgroup.id, existing_type
            )));
        }
    }

    // Check composite materials IDs
    for composite in &model.resources.composite_materials {
        if let Some(existing_type) =
            seen_property_group_ids.insert(composite.id, "compositematerials".to_string())
        {
            return Err(Error::InvalidModel(format!(
                "Duplicate resource ID: {}. \
                 This ID is used by both a {} and a compositematerials group. \
                 Each resource must have a unique id attribute. \
                 Check your material definitions for duplicate IDs.",
                composite.id, existing_type
            )));
        }
    }

    // Keep separate base material IDs set for basematerialid validation
    let valid_basematerial_ids: HashSet<usize> = model
        .resources
        .base_material_groups
        .iter()
        .map(|bg| bg.id)
        .collect();

    // Validate multiproperties: each multi element's pindices must be valid for the referenced property groups
    for multiprop in &model.resources.multi_properties {
        for (multi_idx, multi) in multiprop.multis.iter().enumerate() {
            // Validate each pindex against the corresponding property group
            // Note: pindices.len() can be less than pids.len() - unspecified indices default to 0
            for (layer_idx, (&pid, &pindex)) in
                multiprop.pids.iter().zip(multi.pindices.iter()).enumerate()
            {
                // Check if it's a color group
                if let Some(colorgroup) =
                    model.resources.color_groups.iter().find(|cg| cg.id == pid)
                {
                    if pindex >= colorgroup.colors.len() {
                        let max_index = colorgroup.colors.len().saturating_sub(1);
                        return Err(Error::InvalidModel(format!(
                            "MultiProperties group {}: Multi element {} layer {} references pindex {} which is out of bounds.\n\
                             Color group {} has {} colors (valid indices: 0-{}).\n\
                             Hint: Each pindex in a multi element must be less than the number of items in the corresponding property group.",
                            multiprop.id,
                            multi_idx,
                            layer_idx,
                            pindex,
                            pid,
                            colorgroup.colors.len(),
                            max_index
                        )));
                    }
                }
                // Check if it's a base material group
                else if let Some(basematerialgroup) = model
                    .resources
                    .base_material_groups
                    .iter()
                    .find(|bg| bg.id == pid)
                {
                    if pindex >= basematerialgroup.materials.len() {
                        let max_index = basematerialgroup.materials.len().saturating_sub(1);
                        return Err(Error::InvalidModel(format!(
                            "MultiProperties group {}: Multi element {} layer {} references pindex {} which is out of bounds.\n\
                             Base material group {} has {} materials (valid indices: 0-{}).\n\
                             Hint: Each pindex in a multi element must be less than the number of items in the corresponding property group.",
                            multiprop.id,
                            multi_idx,
                            layer_idx,
                            pindex,
                            pid,
                            basematerialgroup.materials.len(),
                            max_index
                        )));
                    }
                }
                // Check if it's a texture2d group
                else if let Some(tex2dgroup) = model
                    .resources
                    .texture2d_groups
                    .iter()
                    .find(|tg| tg.id == pid)
                {
                    if pindex >= tex2dgroup.tex2coords.len() {
                        let max_index = tex2dgroup.tex2coords.len().saturating_sub(1);
                        return Err(Error::InvalidModel(format!(
                            "MultiProperties group {}: Multi element {} layer {} references pindex {} which is out of bounds.\n\
                             Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                             Hint: Each pindex in a multi element must be less than the number of items in the corresponding property group.",
                            multiprop.id,
                            multi_idx,
                            layer_idx,
                            pindex,
                            pid,
                            tex2dgroup.tex2coords.len(),
                            max_index
                        )));
                    }
                }
                // Check if it's a composite materials group
                else if let Some(composite) = model
                    .resources
                    .composite_materials
                    .iter()
                    .find(|cm| cm.id == pid)
                    && pindex >= composite.composites.len()
                {
                    let max_index = composite.composites.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "MultiProperties group {}: Multi element {} layer {} references pindex {} which is out of bounds.\n\
                             Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                             Hint: Each pindex in a multi element must be less than the number of items in the corresponding property group.",
                        multiprop.id,
                        multi_idx,
                        layer_idx,
                        pindex,
                        pid,
                        composite.composites.len(),
                        max_index
                    )));
                }
                // If the pid is another multiproperties, we don't need to validate here
                // as nested multiproperties would be validated separately
            }
        }
    }

    for object in &model.resources.objects {
        if let Some(pid) = object.pid {
            // If object has a pid, it should reference a valid property group
            // Only validate if there are property groups defined, otherwise pid might be unused
            if !seen_property_group_ids.is_empty() && !seen_property_group_ids.contains_key(&pid) {
                let available_ids: Vec<usize> = {
                    let mut ids: Vec<usize> = seen_property_group_ids.keys().copied().collect();
                    ids.sort();
                    ids
                };
                return Err(Error::InvalidModel(format!(
                    "Object {} references non-existent property group ID: {}.\n\
                     Available property group IDs: {:?}\n\
                     Hint: Check that all referenced property groups are defined in the <resources> section.",
                    object.id, pid, available_ids
                )));
            }
        }

        // Validate basematerialid references
        if let Some(basematerialid) = object.basematerialid {
            // basematerialid should reference a valid base material group
            if !valid_basematerial_ids.contains(&basematerialid) {
                let available_ids = sorted_ids_from_set(&valid_basematerial_ids);
                return Err(Error::InvalidModel(format!(
                    "Object {} references non-existent base material group ID: {}.\n\
                     Available base material group IDs: {:?}\n\
                     Hint: Check that a basematerials group with this ID exists in the <resources> section.",
                    object.id, basematerialid, available_ids
                )));
            }
        }

        // Validate object pindex references for color groups
        if let Some(obj_pid) = object.pid {
            if let Some(colorgroup) = model
                .resources
                .color_groups
                .iter()
                .find(|cg| cg.id == obj_pid)
            {
                // Validate object-level pindex
                if let Some(pindex) = object.pindex
                    && pindex >= colorgroup.colors.len()
                {
                    let max_index = colorgroup.colors.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "Object {}: pindex {} is out of bounds.\n\
                             Color group {} has {} colors (valid indices: 0-{}).\n\
                             Hint: pindex must be less than the number of colors in the color group.",
                        object.id,
                        pindex,
                        obj_pid,
                        colorgroup.colors.len(),
                        max_index
                    )));
                }
            }
            // Validate object pindex references for base material groups
            else if let Some(basematerialgroup) = model
                .resources
                .base_material_groups
                .iter()
                .find(|bg| bg.id == obj_pid)
            {
                // Validate object-level pindex
                if let Some(pindex) = object.pindex
                    && pindex >= basematerialgroup.materials.len()
                {
                    let max_index = basematerialgroup.materials.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "Object {}: pindex {} is out of bounds.\n\
                             Base material group {} has {} materials (valid indices: 0-{}).\n\
                             Hint: pindex must be less than the number of materials in the base material group.",
                        object.id,
                        pindex,
                        obj_pid,
                        basematerialgroup.materials.len(),
                        max_index
                    )));
                }
            }
            // Validate object pindex references for texture2d groups
            else if let Some(tex2dgroup) = model
                .resources
                .texture2d_groups
                .iter()
                .find(|tg| tg.id == obj_pid)
            {
                // Validate object-level pindex
                if let Some(pindex) = object.pindex
                    && pindex >= tex2dgroup.tex2coords.len()
                {
                    let max_index = tex2dgroup.tex2coords.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "Object {}: pindex {} is out of bounds.\n\
                             Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                             Hint: pindex must be less than the number of texture coordinates in the texture2d group.",
                        object.id,
                        pindex,
                        obj_pid,
                        tex2dgroup.tex2coords.len(),
                        max_index
                    )));
                }
            }
            // Validate object pindex references for multiproperties
            else if let Some(multiprop) = model
                .resources
                .multi_properties
                .iter()
                .find(|mp| mp.id == obj_pid)
            {
                // Validate object-level pindex
                if let Some(pindex) = object.pindex
                    && pindex >= multiprop.multis.len()
                {
                    let max_index = multiprop.multis.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "Object {}: pindex {} is out of bounds.\n\
                             MultiProperties group {} has {} multi elements (valid indices: 0-{}).\n\
                             Hint: pindex must be less than the number of multi elements in the multiproperties group.",
                        object.id,
                        pindex,
                        obj_pid,
                        multiprop.multis.len(),
                        max_index
                    )));
                }
            }
            // Validate object pindex references for composite materials
            else if let Some(composite) = model
                .resources
                .composite_materials
                .iter()
                .find(|cm| cm.id == obj_pid)
            {
                // Validate object-level pindex
                if let Some(pindex) = object.pindex
                    && pindex >= composite.composites.len()
                {
                    let max_index = composite.composites.len().saturating_sub(1);
                    return Err(Error::InvalidModel(format!(
                        "Object {}: pindex {} is out of bounds.\n\
                             Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                             Hint: pindex must be less than the number of composite elements in the composite materials group.",
                        object.id,
                        pindex,
                        obj_pid,
                        composite.composites.len(),
                        max_index
                    )));
                }
            }
        }

        // Validate triangle property index references for color groups and base materials
        if let Some(ref mesh) = object.mesh {
            for (tri_idx, triangle) in mesh.triangles.iter().enumerate() {
                // Determine which color group or base material to use for validation
                let pid_to_check = triangle.pid.or(object.pid);

                if let Some(pid) = pid_to_check {
                    // Check if it's a color group
                    if let Some(colorgroup) =
                        model.resources.color_groups.iter().find(|cg| cg.id == pid)
                    {
                        let num_colors = colorgroup.colors.len();

                        // Validate triangle-level pindex
                        if let Some(pindex) = triangle.pindex
                            && pindex >= num_colors
                        {
                            let max_index = num_colors.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} pindex {} is out of bounds.\n\
                                     Color group {} has {} colors (valid indices: 0-{}).\n\
                                     Hint: pindex must be less than the number of colors in the color group.",
                                object.id, tri_idx, pindex, pid, num_colors, max_index
                            )));
                        }

                        // Validate per-vertex property indices (p1, p2, p3)
                        if let Some(p1) = triangle.p1
                            && p1 >= num_colors
                        {
                            let max_index = num_colors.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p1 {} is out of bounds.\n\
                                     Color group {} has {} colors (valid indices: 0-{}).\n\
                                     Hint: p1 must be less than the number of colors in the color group.",
                                object.id, tri_idx, p1, pid, num_colors, max_index
                            )));
                        }

                        if let Some(p2) = triangle.p2
                            && p2 >= num_colors
                        {
                            let max_index = num_colors.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p2 {} is out of bounds.\n\
                                     Color group {} has {} colors (valid indices: 0-{}).\n\
                                     Hint: p2 must be less than the number of colors in the color group.",
                                object.id, tri_idx, p2, pid, num_colors, max_index
                            )));
                        }

                        if let Some(p3) = triangle.p3
                            && p3 >= num_colors
                        {
                            let max_index = num_colors.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p3 {} is out of bounds.\n\
                                     Color group {} has {} colors (valid indices: 0-{}).\n\
                                     Hint: p3 must be less than the number of colors in the color group.",
                                object.id, tri_idx, p3, pid, num_colors, max_index
                            )));
                        }
                    }
                    // Check if it's a base material group
                    else if let Some(basematerialgroup) = model
                        .resources
                        .base_material_groups
                        .iter()
                        .find(|bg| bg.id == pid)
                    {
                        let num_materials = basematerialgroup.materials.len();

                        // Validate triangle-level pindex
                        if let Some(pindex) = triangle.pindex
                            && pindex >= num_materials
                        {
                            let max_index = num_materials.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} pindex {} is out of bounds.\n\
                                     Base material group {} has {} materials (valid indices: 0-{}).\n\
                                     Hint: pindex must be less than the number of materials in the base material group.",
                                object.id, tri_idx, pindex, pid, num_materials, max_index
                            )));
                        }

                        // Validate per-vertex property indices (p1, p2, p3)
                        if let Some(p1) = triangle.p1
                            && p1 >= num_materials
                        {
                            let max_index = num_materials.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p1 {} is out of bounds.\n\
                                     Base material group {} has {} materials (valid indices: 0-{}).\n\
                                     Hint: p1 must be less than the number of materials in the base material group.",
                                object.id, tri_idx, p1, pid, num_materials, max_index
                            )));
                        }

                        if let Some(p2) = triangle.p2
                            && p2 >= num_materials
                        {
                            let max_index = num_materials.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p2 {} is out of bounds.\n\
                                     Base material group {} has {} materials (valid indices: 0-{}).\n\
                                     Hint: p2 must be less than the number of materials in the base material group.",
                                object.id, tri_idx, p2, pid, num_materials, max_index
                            )));
                        }

                        if let Some(p3) = triangle.p3
                            && p3 >= num_materials
                        {
                            let max_index = num_materials.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p3 {} is out of bounds.\n\
                                     Base material group {} has {} materials (valid indices: 0-{}).\n\
                                     Hint: p3 must be less than the number of materials in the base material group.",
                                object.id, tri_idx, p3, pid, num_materials, max_index
                            )));
                        }
                    }
                    // Check if it's a texture2d group
                    else if let Some(tex2dgroup) = model
                        .resources
                        .texture2d_groups
                        .iter()
                        .find(|tg| tg.id == pid)
                    {
                        let num_coords = tex2dgroup.tex2coords.len();

                        // Validate triangle-level pindex
                        if let Some(pindex) = triangle.pindex
                            && pindex >= num_coords
                        {
                            let max_index = num_coords.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} pindex {} is out of bounds.\n\
                                     Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                                     Hint: pindex must be less than the number of texture coordinates in the texture2d group.",
                                object.id, tri_idx, pindex, pid, num_coords, max_index
                            )));
                        }

                        // Validate per-vertex property indices (p1, p2, p3)
                        if let Some(p1) = triangle.p1
                            && p1 >= num_coords
                        {
                            let max_index = num_coords.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p1 {} is out of bounds.\n\
                                     Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                                     Hint: p1 must be less than the number of texture coordinates in the texture2d group.",
                                object.id, tri_idx, p1, pid, num_coords, max_index
                            )));
                        }

                        if let Some(p2) = triangle.p2
                            && p2 >= num_coords
                        {
                            let max_index = num_coords.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p2 {} is out of bounds.\n\
                                     Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                                     Hint: p2 must be less than the number of texture coordinates in the texture2d group.",
                                object.id, tri_idx, p2, pid, num_coords, max_index
                            )));
                        }

                        if let Some(p3) = triangle.p3
                            && p3 >= num_coords
                        {
                            let max_index = num_coords.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p3 {} is out of bounds.\n\
                                     Texture2D group {} has {} texture coordinates (valid indices: 0-{}).\n\
                                     Hint: p3 must be less than the number of texture coordinates in the texture2d group.",
                                object.id, tri_idx, p3, pid, num_coords, max_index
                            )));
                        }
                    }
                    // Check if it's a multiproperties group
                    else if let Some(multiprop) = model
                        .resources
                        .multi_properties
                        .iter()
                        .find(|mp| mp.id == pid)
                    {
                        let num_multis = multiprop.multis.len();

                        // Validate triangle-level pindex
                        if let Some(pindex) = triangle.pindex
                            && pindex >= num_multis
                        {
                            let max_index = num_multis.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} pindex {} is out of bounds.\n\
                                     MultiProperties group {} has {} multi elements (valid indices: 0-{}).\n\
                                     Hint: pindex must be less than the number of multi elements in the multiproperties group.",
                                object.id, tri_idx, pindex, pid, num_multis, max_index
                            )));
                        }

                        // Validate per-vertex property indices (p1, p2, p3)
                        if let Some(p1) = triangle.p1
                            && p1 >= num_multis
                        {
                            let max_index = num_multis.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p1 {} is out of bounds.\n\
                                     MultiProperties group {} has {} multi elements (valid indices: 0-{}).\n\
                                     Hint: p1 must be less than the number of multi elements in the multiproperties group.",
                                object.id, tri_idx, p1, pid, num_multis, max_index
                            )));
                        }

                        if let Some(p2) = triangle.p2
                            && p2 >= num_multis
                        {
                            let max_index = num_multis.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p2 {} is out of bounds.\n\
                                     MultiProperties group {} has {} multi elements (valid indices: 0-{}).\n\
                                     Hint: p2 must be less than the number of multi elements in the multiproperties group.",
                                object.id, tri_idx, p2, pid, num_multis, max_index
                            )));
                        }

                        if let Some(p3) = triangle.p3
                            && p3 >= num_multis
                        {
                            let max_index = num_multis.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p3 {} is out of bounds.\n\
                                     MultiProperties group {} has {} multi elements (valid indices: 0-{}).\n\
                                     Hint: p3 must be less than the number of multi elements in the multiproperties group.",
                                object.id, tri_idx, p3, pid, num_multis, max_index
                            )));
                        }
                    }
                    // Check if it's a composite materials group
                    else if let Some(composite) = model
                        .resources
                        .composite_materials
                        .iter()
                        .find(|cm| cm.id == pid)
                    {
                        let num_composites = composite.composites.len();

                        // Validate triangle-level pindex
                        if let Some(pindex) = triangle.pindex
                            && pindex >= num_composites
                        {
                            let max_index = num_composites.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} pindex {} is out of bounds.\n\
                                     Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                                     Hint: pindex must be less than the number of composite elements in the composite materials group.",
                                object.id, tri_idx, pindex, pid, num_composites, max_index
                            )));
                        }

                        // Validate per-vertex property indices (p1, p2, p3)
                        if let Some(p1) = triangle.p1
                            && p1 >= num_composites
                        {
                            let max_index = num_composites.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p1 {} is out of bounds.\n\
                                     Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                                     Hint: p1 must be less than the number of composite elements in the composite materials group.",
                                object.id, tri_idx, p1, pid, num_composites, max_index
                            )));
                        }

                        if let Some(p2) = triangle.p2
                            && p2 >= num_composites
                        {
                            let max_index = num_composites.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p2 {} is out of bounds.\n\
                                     Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                                     Hint: p2 must be less than the number of composite elements in the composite materials group.",
                                object.id, tri_idx, p2, pid, num_composites, max_index
                            )));
                        }

                        if let Some(p3) = triangle.p3
                            && p3 >= num_composites
                        {
                            let max_index = num_composites.saturating_sub(1);
                            return Err(Error::InvalidModel(format!(
                                "Object {}: Triangle {} p3 {} is out of bounds.\n\
                                     Composite materials group {} has {} composite elements (valid indices: 0-{}).\n\
                                     Hint: p3 must be less than the number of composite elements in the composite materials group.",
                                object.id, tri_idx, p3, pid, num_composites, max_index
                            )));
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

/// Validate boolean operation references
///
/// Per 3MF Boolean Operations Extension spec:
/// - Objects referenced in boolean operations exist (unless they're external via path attribute)
/// - Objects don't have more than one booleanshape element (checked during parsing)
/// - Boolean operand objects exist (unless they're external via path attribute)
/// - Base object and operand objects must be of type "model" (not support, solidsupport, etc.)
/// - Referenced objects must be defined before the object containing the booleanshape (forward reference rule)
/// - Base object must define a shape (mesh or booleanshape), not components
/// - Operand objects must be triangle meshes only
///
/// Validates that texture paths are in /3D/Textures/ directory
pub fn validate_texture_paths(model: &Model) -> Result<()> {
    // Get list of encrypted files to skip validation for them
    let encrypted_files: Vec<String> = model
        .secure_content
        .as_ref()
        .map(|sc| sc.encrypted_files.clone())
        .unwrap_or_default();

    for texture in &model.resources.texture2d_resources {
        // Skip validation for encrypted files (they may not follow standard paths)
        if encrypted_files.contains(&texture.path) {
            continue;
        }

        // N_XXM_0610_01: Check for empty or invalid texture paths
        if texture.path.is_empty() {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Path is empty.\n\
                 Per 3MF Material Extension spec, texture path must reference a valid file in the package.",
                texture.id
            )));
        }

        // Check for obviously invalid path patterns (e.g., paths with null bytes, backslashes)
        if texture.path.contains('\0') {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Path '{}' contains null bytes.\n\
                 Per 3MF Material Extension spec, texture paths must be valid OPC part names.",
                texture.id, texture.path
            )));
        }

        // Per OPC spec, part names should use forward slashes, not backslashes
        if texture.path.contains('\\') {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Path '{}' contains backslashes.\n\
                 Per OPC specification, part names must use forward slashes ('/') as path separators, not backslashes ('\\').",
                texture.id, texture.path
            )));
        }

        // Check that the path contains only ASCII characters
        if !texture.path.is_ascii() {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Path '{}' contains non-ASCII characters.\n\
                 Per 3MF Material Extension specification, texture paths must contain only ASCII characters.\n\
                 Hint: Remove Unicode or special characters from the texture path.",
                texture.id, texture.path
            )));
        }

        // Note: The 3MF Materials Extension spec does NOT require texture paths to be in
        // /3D/Texture/ or /3D/Textures/ directories. The spec only requires that:
        // 1. The path attribute specifies the part name of the texture data
        // 2. The texture must be the target of a 3D Texture relationship from the 3D Model part
        // Therefore, we do not validate the directory path here.

        // Validate content type
        let valid_content_types = ["image/png", "image/jpeg"];
        if !valid_content_types.contains(&texture.contenttype.as_str()) {
            return Err(Error::InvalidModel(format!(
                "Texture2D resource {}: Invalid contenttype '{}'.\n\
                 Per 3MF Material Extension spec, texture content type must be 'image/png' or 'image/jpeg'.\n\
                 Update the contenttype attribute to one of the supported values.",
                texture.id, texture.contenttype
            )));
        }
    }
    Ok(())
}

/// Validate color formats in color groups
///
/// Per 3MF Material Extension spec, colors are stored as RGBA tuples (u8, u8, u8, u8).
/// The parser already validates format during parsing, but this provides an additional check.
/// Validates that multiproperties reference valid property groups
pub fn validate_multiproperties_references(model: &Model) -> Result<()> {
    // Build sets of valid resource IDs
    let base_mat_ids: HashSet<usize> = model
        .resources
        .base_material_groups
        .iter()
        .map(|b| b.id)
        .collect();

    let color_group_ids: HashSet<usize> =
        model.resources.color_groups.iter().map(|c| c.id).collect();

    let tex_group_ids: HashSet<usize> = model
        .resources
        .texture2d_groups
        .iter()
        .map(|t| t.id)
        .collect();

    let composite_ids: HashSet<usize> = model
        .resources
        .composite_materials
        .iter()
        .map(|c| c.id)
        .collect();

    // Validate each multiproperties group
    for multi_props in &model.resources.multi_properties {
        // Track basematerials and colorgroup IDs to detect duplicates
        let mut base_mat_count: HashMap<usize, usize> = HashMap::new();
        let mut color_group_count: HashMap<usize, usize> = HashMap::new();

        for (idx, &pid) in multi_props.pids.iter().enumerate() {
            // Check if PID references a valid resource
            let is_valid = base_mat_ids.contains(&pid)
                || color_group_ids.contains(&pid)
                || tex_group_ids.contains(&pid)
                || composite_ids.contains(&pid);

            if !is_valid {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: PID {} at index {} does not reference a valid resource.\n\
                     Per 3MF spec, multiproperties pids must reference existing basematerials, \
                     colorgroup, texture2dgroup, or compositematerials resources.\n\
                     Ensure resource with ID {} exists in the <resources> section.",
                    multi_props.id, pid, idx, pid
                )));
            }

            // Track basematerials references
            if base_mat_ids.contains(&pid) {
                *base_mat_count.entry(pid).or_insert(0) += 1;

                // N_XXM_0604_03: basematerials MUST be at layer 0 (first position) if included
                // Per 3MF Material Extension spec Chapter 5: "A material, if included, MUST be
                // positioned as the first element in the list forming the first layer"
                if idx != 0 {
                    return Err(Error::InvalidModel(format!(
                        "MultiProperties {}: basematerials group {} referenced at layer {}.\n\
                         Per 3MF Material Extension spec, basematerials MUST be positioned as the first element \
                         (layer 0) in multiproperties pids when included.\n\
                         Move the basematerials reference to layer 0.",
                        multi_props.id, pid, idx
                    )));
                }
            }

            // Track colorgroup references
            if color_group_ids.contains(&pid) {
                *color_group_count.entry(pid).or_insert(0) += 1;
            }
        }

        // N_XXM_0604_01: Check that at most one colorgroup is referenced
        // Per 3MF Material Extension spec Chapter 5: "The pids list MUST NOT contain
        // more than one reference to a colorgroup"
        if color_group_count.len() > 1 {
            let color_ids: Vec<usize> = color_group_count.keys().copied().collect();
            return Err(Error::InvalidModel(format!(
                "MultiProperties {}: References multiple colorgroups {:?} in pids.\n\
                 Per 3MF Material Extension spec, multiproperties pids list MUST NOT contain \
                 more than one reference to a colorgroup.\n\
                 Remove all but one colorgroup reference from the pids list.",
                multi_props.id, color_ids
            )));
        }

        // Also check for duplicate references to the same colorgroup
        for (&color_id, &count) in &color_group_count {
            if count > 1 {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: References colorgroup {} multiple times in pids.\n\
                     Per 3MF Material Extension spec, multiproperties cannot reference the same colorgroup \
                     more than once in the pids list.",
                    multi_props.id, color_id
                )));
            }
        }

        // Check for duplicate basematerials references
        for (&base_id, &count) in &base_mat_count {
            if count > 1 {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: References basematerials group {} multiple times in pids.\n\
                     Per 3MF spec, multiproperties cannot reference the same basematerials group \
                     more than once in the pids list.",
                    multi_props.id, base_id
                )));
            }
        }
    }

    Ok(())
}

/// Validate triangle property attributes
///
/// Per 3MF Materials Extension spec section 4.1.1 (Triangle Properties):
/// - Triangles can have per-vertex properties (p1/p2/p3) to specify different properties for each vertex
/// - Partial specification (e.g., only p1 or only p1 and p2) is allowed and commonly used
/// - When unspecified, vertices inherit the default property from pid/pindex or object-level properties
///
/// Real-world usage: Files like kinect_scan.3mf use partial specification extensively (8,682 triangles
/// with only p1 specified), demonstrating this is valid and intentional usage per the spec.
///
/// Note: Earlier interpretation that ALL THREE must be specified was too strict and rejected
/// valid real-world files.
/// Helper function to validate triangle material properties for a single object
///
/// Checks:
/// - N_XXM_0601_02: Mixed material assignment requires default pid
/// - N_XXM_0601_01: Per-vertex properties require pid context
///
/// # Arguments
/// * `object_id` - The ID of the object being validated
/// * `object_pid` - The object's default pid (if any)
/// * `mesh` - The mesh containing triangles to validate
/// * `context` - Context string for error messages (e.g., "Object 1" or "External file 'x.model': Object 1")
///
/// # Returns
/// `Ok(())` if validation passes, `Err` with detailed message if validation fails
/// Validates that triangle material properties are correctly assigned
pub fn validate_triangle_properties(model: &Model) -> Result<()> {
    // Per 3MF Materials Extension spec:
    // - Triangles can have triangle-level properties (pid and/or pindex)
    // - Triangles can have per-vertex properties (p1, p2, p3) which work WITH pid for interpolation
    // - Having both pid and p1/p2/p3 is ALLOWED and is used for per-vertex material interpolation
    //
    // NOTE: After testing against positive test cases, we found that partial per-vertex
    // properties are actually allowed in some scenarios. The validation has been relaxed.

    // Validate object-level properties
    for object in &model.resources.objects {
        // Validate object-level pid/pindex
        if let (Some(pid), Some(pindex)) = (object.pid, object.pindex) {
            // Get the size of the property resource
            let property_size = get_property_resource_size(model, pid)?;

            // Validate pindex is within bounds
            if pindex >= property_size {
                return Err(Error::InvalidModel(format!(
                    "Object {} has pindex {} which is out of bounds. \
                     Property resource {} has only {} elements (valid indices: 0-{}).",
                    object.id,
                    pindex,
                    pid,
                    property_size,
                    property_size - 1
                )));
            }
        }

        // Validate triangle-level properties
        if let Some(ref mesh) = object.mesh {
            // Use helper function for triangle material validation
            validate_object_triangle_materials(
                object.id,
                object.pid,
                mesh,
                &format!("Object {}", object.id),
            )?;

            for triangle in &mesh.triangles {
                // Validate triangle pindex is within bounds for multi-properties
                if let (Some(pid), Some(pindex)) = (triangle.pid, triangle.pindex) {
                    // Check if pid references a multiproperties resource
                    if let Some(multi_props) = model
                        .resources
                        .multi_properties
                        .iter()
                        .find(|m| m.id == pid)
                    {
                        // pindex must be within bounds of the multiproperties entries
                        if pindex >= multi_props.multis.len() {
                            return Err(Error::InvalidModel(format!(
                                "Triangle in object {} has pindex {} which is out of bounds. \
                                 MultiProperties resource {} has only {} entries (valid indices: 0-{}).",
                                object.id,
                                pindex,
                                pid,
                                multi_props.multis.len(),
                                multi_props.multis.len() - 1
                            )));
                        }
                    }
                }
            }
        }
    }

    Ok(())
}

/// Validates triangle material properties for a specific object
pub fn validate_object_triangle_materials(
    object_id: usize,
    object_pid: Option<usize>,
    mesh: &crate::model::Mesh,
    context: &str,
) -> Result<()> {
    // N_XXM_0601_02: If some triangles have material properties (pid or per-vertex)
    // and others don't, object must have a default pid to provide material for
    // triangles without explicit material properties
    let mut has_triangles_with_material = false;
    let mut has_triangles_without_material = false;

    for triangle in &mesh.triangles {
        let triangle_has_material = triangle.pid.is_some()
            || triangle.p1.is_some()
            || triangle.p2.is_some()
            || triangle.p3.is_some();

        if triangle_has_material {
            has_triangles_with_material = true;
        } else {
            has_triangles_without_material = true;
        }
    }

    // If we have mixed material assignment and no default pid on object, this is invalid
    let has_mixed_assignment_without_default_pid =
        has_triangles_with_material && has_triangles_without_material && object_pid.is_none();

    if has_mixed_assignment_without_default_pid {
        return Err(Error::InvalidModel(format!(
            "{} has some triangles with material properties and some without. \
             When triangles in an object have mixed material assignment, \
             the object must have a default pid attribute to provide material \
             for triangles without explicit material properties. \
             Add a pid attribute to object {}.",
            context, object_id
        )));
    }

    // N_XXM_0601_01: Validate per-vertex properties
    for triangle in &mesh.triangles {
        let has_per_vertex_properties =
            triangle.p1.is_some() || triangle.p2.is_some() || triangle.p3.is_some();

        if has_per_vertex_properties && triangle.pid.is_none() && object_pid.is_none() {
            return Err(Error::InvalidModel(format!(
                "{} has a triangle with per-vertex material properties (p1/p2/p3) \
                 but neither the triangle nor the object has a pid to provide material context.\n\
                 Per 3MF Material Extension spec, per-vertex properties require a pid, \
                 either on the triangle or as a default on the object.\n\
                 Add a pid attribute to either the triangle or object {}.",
                context, object_id
            )));
        }
    }

    Ok(())
}

/// Gets the size (number of properties) in a property resource group
pub fn get_property_resource_size(model: &Model, resource_id: usize) -> Result<usize> {
    // Check colorgroup
    if let Some(color_group) = model
        .resources
        .color_groups
        .iter()
        .find(|c| c.id == resource_id)
    {
        if color_group.colors.is_empty() {
            return Err(Error::InvalidModel(format!(
                "ColorGroup {} has no colors. Per 3MF Materials Extension spec, \
                 color groups must contain at least one color element.",
                resource_id
            )));
        }
        return Ok(color_group.colors.len());
    }

    // Check texture2dgroup
    if let Some(tex_group) = model
        .resources
        .texture2d_groups
        .iter()
        .find(|t| t.id == resource_id)
    {
        if tex_group.tex2coords.is_empty() {
            return Err(Error::InvalidModel(format!(
                "Texture2DGroup {} has no texture coordinates. Per 3MF Materials Extension spec, \
                 texture2dgroup must contain at least one tex2coord element.",
                resource_id
            )));
        }
        return Ok(tex_group.tex2coords.len());
    }

    // Check compositematerials
    if let Some(composite) = model
        .resources
        .composite_materials
        .iter()
        .find(|c| c.id == resource_id)
    {
        if composite.composites.is_empty() {
            return Err(Error::InvalidModel(format!(
                "CompositeMaterials {} has no composite elements. Per 3MF Materials Extension spec, \
                 compositematerials must contain at least one composite element.",
                resource_id
            )));
        }
        return Ok(composite.composites.len());
    }

    // Check basematerials
    if let Some(base_mat) = model
        .resources
        .base_material_groups
        .iter()
        .find(|b| b.id == resource_id)
    {
        if base_mat.materials.is_empty() {
            return Err(Error::InvalidModel(format!(
                "BaseMaterials {} has no base material elements. Per 3MF spec, \
                 basematerials must contain at least one base element.",
                resource_id
            )));
        }
        return Ok(base_mat.materials.len());
    }

    // Check multiproperties
    if let Some(multi_props) = model
        .resources
        .multi_properties
        .iter()
        .find(|m| m.id == resource_id)
    {
        if multi_props.multis.is_empty() {
            return Err(Error::InvalidModel(format!(
                "MultiProperties {} has no multi elements. Per 3MF Materials Extension spec, \
                 multiproperties must contain at least one multi element.",
                resource_id
            )));
        }
        return Ok(multi_props.multis.len());
    }

    // Resource not found or not a property resource
    Err(Error::InvalidModel(format!(
        "Property resource {} not found or is not a valid property resource type",
        resource_id
    )))
}

/// Validates color formats in color groups
///
/// Ensures that all color groups contain at least one color.
/// Note: Individual color format validation is done during parsing.
pub fn validate_color_formats(model: &Model) -> Result<()> {
    // Colors are already validated during parsing (stored as (u8, u8, u8, u8) tuples)
    // This function is a placeholder for any additional color validation needs

    // Validate that color groups have at least one color
    for color_group in &model.resources.color_groups {
        if color_group.colors.is_empty() {
            return Err(Error::InvalidModel(format!(
                "Color group {}: Must contain at least one color.\n\
                 A color group without colors is invalid.",
                color_group.id
            )));
        }
    }

    Ok(())
}

/// Validate resource ordering
///
/// Per 3MF spec, resources must be defined before they are referenced.
/// For example, texture2d must be defined before texture2dgroup that references it.
/// This validation checks for forward references using parse order.
pub fn validate_resource_ordering(model: &Model) -> Result<()> {
    // N_XXM_0606_01: Texture2dgroup must not reference texture2d that appears later in XML
    for tex_group in &model.resources.texture2d_groups {
        if let Some(tex2d) = model
            .resources
            .texture2d_resources
            .iter()
            .find(|t| t.id == tex_group.texid)
        {
            if tex_group.parse_order < tex2d.parse_order {
                return Err(Error::InvalidModel(format!(
                    "Texture2DGroup {}: Forward reference to texture2d {} which appears later in the resources.\n\
                     Per 3MF Material Extension spec, texture2d resources must be defined before \
                     texture2dgroups that reference them.\n\
                     Move the texture2d element before the texture2dgroup element in the resources section.",
                    tex_group.id, tex_group.texid
                )));
            }
        } else {
            return Err(Error::InvalidModel(format!(
                "Texture2DGroup {}: References texture2d with ID {} which is not defined.\n\
                 Per 3MF spec, texture2d resources must be defined before texture2dgroups that reference them.\n\
                 Ensure texture2d with ID {} exists in the <resources> section before this texture2dgroup.",
                tex_group.id, tex_group.texid, tex_group.texid
            )));
        }
    }

    // N_XXM_0606_02, N_XXM_0606_03, N_XXM_0607_01: Multiproperties must not have forward references
    for multi_props in &model.resources.multi_properties {
        for &pid in &multi_props.pids {
            // Check if PID references a texture2dgroup
            if let Some(tex_group) = model
                .resources
                .texture2d_groups
                .iter()
                .find(|t| t.id == pid)
                && multi_props.parse_order < tex_group.parse_order
            {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: Forward reference to texture2dgroup {} which appears later in the resources.\n\
                         Per 3MF Material Extension spec, property resources must be defined before \
                         multiproperties that reference them.\n\
                         Move the texture2dgroup element before the multiproperties element in the resources section.",
                    multi_props.id, pid
                )));
            }

            // Check if PID references a colorgroup
            if let Some(color_group) = model.resources.color_groups.iter().find(|c| c.id == pid)
                && multi_props.parse_order < color_group.parse_order
            {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: Forward reference to colorgroup {} which appears later in the resources.\n\
                         Per 3MF Material Extension spec, property resources must be defined before \
                         multiproperties that reference them.\n\
                         Move the colorgroup element before the multiproperties element in the resources section.",
                    multi_props.id, pid
                )));
            }

            // Check if PID references a basematerials group
            if let Some(base_mat) = model
                .resources
                .base_material_groups
                .iter()
                .find(|b| b.id == pid)
                && multi_props.parse_order < base_mat.parse_order
            {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: Forward reference to basematerials group {} which appears later in the resources.\n\
                         Per 3MF Material Extension spec, property resources must be defined before \
                         multiproperties that reference them.\n\
                         Move the basematerials element before the multiproperties element in the resources section.",
                    multi_props.id, pid
                )));
            }

            // Check if PID references a compositematerials group
            if let Some(composite) = model
                .resources
                .composite_materials
                .iter()
                .find(|c| c.id == pid)
                && multi_props.parse_order < composite.parse_order
            {
                return Err(Error::InvalidModel(format!(
                    "MultiProperties {}: Forward reference to compositematerials group {} which appears later in the resources.\n\
                         Per 3MF Material Extension spec, property resources must be defined before \
                         multiproperties that reference them.\n\
                         Move the compositematerials element before the multiproperties element in the resources section.",
                    multi_props.id, pid
                )));
            }
        }
    }

    // N_XPM_0607_01: Objects must not be intermingled with property resources
    // Per 3MF spec, the resources section should have a consistent ordering:
    // either all property resources first then all objects, or vice versa.
    // Intermingling objects between property resources is invalid.

    // Get parse orders for all property resources
    let mut property_resource_orders = Vec::new();

    for tex2d in &model.resources.texture2d_resources {
        property_resource_orders.push(("Texture2D", tex2d.id, tex2d.parse_order));
    }
    for tex_group in &model.resources.texture2d_groups {
        property_resource_orders.push(("Texture2DGroup", tex_group.id, tex_group.parse_order));
    }
    for color_group in &model.resources.color_groups {
        property_resource_orders.push(("ColorGroup", color_group.id, color_group.parse_order));
    }
    for base_mat in &model.resources.base_material_groups {
        property_resource_orders.push(("BaseMaterials", base_mat.id, base_mat.parse_order));
    }
    for composite in &model.resources.composite_materials {
        property_resource_orders.push(("CompositeMaterials", composite.id, composite.parse_order));
    }
    for multi_props in &model.resources.multi_properties {
        property_resource_orders.push(("MultiProperties", multi_props.id, multi_props.parse_order));
    }

    // Get parse orders for all objects
    let mut object_orders = Vec::new();
    for obj in &model.resources.objects {
        object_orders.push((obj.id, obj.parse_order));
    }

    // Check if there are objects intermingled with property resources
    // This is only an issue if we have both objects and property resources
    if !property_resource_orders.is_empty() && !object_orders.is_empty() {
        // Find min and max parse order for property resources
        let min_prop_order = property_resource_orders
            .iter()
            .map(|(_, _, order)| order)
            .min()
            .unwrap();
        let max_prop_order = property_resource_orders
            .iter()
            .map(|(_, _, order)| order)
            .max()
            .unwrap();

        // If property resources and objects have overlapping ranges, they're intermingled
        // Valid: all properties [0-10], all objects [11-20] OR all objects [0-10], all properties [11-20]
        // Invalid: properties [0-5], objects [6-10], properties [11-15] (intermingled)

        // Check if there's an object between two property resources
        for (prop_type, prop_id, prop_order) in &property_resource_orders {
            for (obj_id, obj_order) in &object_orders {
                // If an object appears between the min and max property resource orders,
                // and there are property resources both before and after it
                if *obj_order > *min_prop_order && *obj_order < *max_prop_order {
                    // Find a property resource that comes after this object
                    if let Some((later_prop_type, later_prop_id, later_prop_order)) =
                        property_resource_orders
                            .iter()
                            .find(|(_, _, order)| *order > *obj_order)
                    {
                        return Err(Error::InvalidModel(format!(
                            "Invalid resource ordering: Object {} appears between property resources.\n\
                             The object is at position {}, between {} {} (position {}) and {} {} (position {}).\n\
                             Per 3MF specification, objects must not be intermingled with property resources.\n\
                             Either place all objects after all property resources, or all property resources after all objects.",
                            obj_id,
                            obj_order,
                            prop_type,
                            prop_id,
                            prop_order,
                            later_prop_type,
                            later_prop_id,
                            later_prop_order
                        )));
                    }
                }
            }
        }
    }

    Ok(())
}

/// Validate that resource IDs are unique within their namespaces
///
/// Per 3MF spec:
/// - Object IDs must be unique among objects
/// - Property resource IDs (basematerials, colorgroups, texture2d, texture2dgroups,
///   compositematerials, multiproperties) must be unique among property resources
/// - Objects and property resources have SEPARATE ID namespaces and can reuse IDs
pub fn validate_duplicate_resource_ids(model: &Model) -> Result<()> {
    // Check object IDs for duplicates (separate namespace)
    let mut seen_object_ids: HashSet<usize> = HashSet::new();
    for obj in &model.resources.objects {
        if !seen_object_ids.insert(obj.id) {
            return Err(Error::InvalidModel(format!(
                "Duplicate object ID {}: Multiple objects use the same ID.\n\
                 Per 3MF spec, each object must have a unique ID within the objects namespace.\n\
                 Change the ID to a unique value.",
                obj.id
            )));
        }
    }

    // Check property resource IDs for duplicates (separate namespace from objects)
    // Property resources include: basematerials, colorgroups, texture2d, texture2dgroups,
    // compositematerials, and multiproperties
    let mut seen_property_ids: HashSet<usize> = HashSet::new();

    // Helper to check and add property resource ID
    let mut check_property_id = |id: usize, resource_type: &str| -> Result<()> {
        if !seen_property_ids.insert(id) {
            return Err(Error::InvalidModel(format!(
                "Duplicate property resource ID {}: {} resource uses an ID that is already in use by another property resource.\n\
                 Per 3MF spec, property resource IDs must be unique among all property resources \
                 (basematerials, colorgroups, texture2d, texture2dgroups, compositematerials, multiproperties).\n\
                 Note: Objects have a separate ID namespace and can reuse property resource IDs.",
                id, resource_type
            )));
        }
        Ok(())
    };

    // Check all property resource types
    for base_mat in &model.resources.base_material_groups {
        check_property_id(base_mat.id, "BaseMaterials")?;
    }

    for color_group in &model.resources.color_groups {
        check_property_id(color_group.id, "ColorGroup")?;
    }

    for texture in &model.resources.texture2d_resources {
        check_property_id(texture.id, "Texture2D")?;
    }

    for tex_group in &model.resources.texture2d_groups {
        check_property_id(tex_group.id, "Texture2DGroup")?;
    }

    for composite in &model.resources.composite_materials {
        check_property_id(composite.id, "CompositeMaterials")?;
    }

    for multi in &model.resources.multi_properties {
        check_property_id(multi.id, "MultiProperties")?;
    }

    // Check slice stack IDs (Slice Extension)
    // Slicestacks are extension resources but share the property resource ID namespace
    for slice_stack in &model.resources.slice_stacks {
        check_property_id(slice_stack.id, "SliceStack")?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{
        BaseMaterial, BaseMaterialGroup, ColorGroup, CompositeMaterials, Mesh, Multi,
        MultiProperties, Object, Tex2Coord, Texture2D, Texture2DGroup, Triangle, Vertex,
    };

    // ===================== validate_material_references =====================

    #[test]
    fn test_duplicate_color_group_ids() {
        let mut model = Model::new();
        model.resources.color_groups.push(ColorGroup::new(1));
        model.resources.color_groups.push(ColorGroup::new(1)); // duplicate
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Duplicate resource ID")
        );
    }

    #[test]
    fn test_duplicate_base_material_ids() {
        let mut model = Model::new();
        model
            .resources
            .base_material_groups
            .push(BaseMaterialGroup::new(5));
        model
            .resources
            .base_material_groups
            .push(BaseMaterialGroup::new(5)); // dup
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Duplicate resource ID")
        );
    }

    #[test]
    fn test_color_group_and_base_material_same_id() {
        let mut model = Model::new();
        model.resources.color_groups.push(ColorGroup::new(7));
        model
            .resources
            .base_material_groups
            .push(BaseMaterialGroup::new(7)); // conflict
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Duplicate resource ID")
        );
    }

    #[test]
    fn test_duplicate_multiproperties_id_with_color_group() {
        let mut model = Model::new();
        model.resources.color_groups.push(ColorGroup::new(3));
        model
            .resources
            .multi_properties
            .push(MultiProperties::new(3, vec![])); // conflict
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Duplicate resource ID")
        );
    }

    #[test]
    fn test_object_invalid_pid() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);
        let mut obj = Object::new(1);
        obj.pid = Some(99); // doesn't exist
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("non-existent property group")
        );
    }

    #[test]
    fn test_object_invalid_basematerialid() {
        let mut model = Model::new();
        model
            .resources
            .base_material_groups
            .push(BaseMaterialGroup::new(5));
        let mut obj = Object::new(1);
        obj.basematerialid = Some(99); // doesn't exist
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("non-existent base material group")
        );
    }

    #[test]
    fn test_object_pindex_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);
        let mut obj = Object::new(1);
        obj.pid = Some(10);
        obj.pindex = Some(99); // out of bounds
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_object_pindex_out_of_bounds_base_material() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);
        let mut obj = Object::new(1);
        obj.pid = Some(5);
        obj.pindex = Some(99); // out of bounds
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_object_pindex_out_of_bounds_texture2d_group() {
        let mut model = Model::new();
        let mut tg = Texture2DGroup::new(5, 10);
        tg.tex2coords.push(Tex2Coord::new(0.0, 0.0));
        model.resources.texture2d_groups.push(tg);
        let mut obj = Object::new(1);
        obj.pid = Some(5);
        obj.pindex = Some(99); // out of bounds
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_object_pindex_out_of_bounds_multiproperties() {
        let mut model = Model::new();
        let mp = MultiProperties::new(5, vec![]);
        model.resources.multi_properties.push(mp);
        let mut obj = Object::new(1);
        obj.pid = Some(5);
        obj.pindex = Some(99); // out of bounds
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_object_pindex_out_of_bounds_composite_materials() {
        let mut model = Model::new();
        let cm = CompositeMaterials::new(5, 0, vec![]);
        model.resources.composite_materials.push(cm);
        let mut obj = Object::new(1);
        obj.pid = Some(5);
        obj.pindex = Some(99); // out of bounds
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_triangle_pindex_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(10);
        tri.pindex = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[test]
    fn test_triangle_p1_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(10);
        tri.p1 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("p1"));
    }

    #[test]
    fn test_triangle_p2_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(10);
        tri.p2 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("p2"));
    }

    #[test]
    fn test_triangle_p3_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(10);
        tri.p3 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("p3"));
    }

    #[test]
    fn test_triangle_p1_out_of_bounds_base_material() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(5);
        tri.p1 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("p1"));
    }

    #[test]
    fn test_triangle_p2_out_of_bounds_base_material() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(5);
        tri.p2 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
    }

    #[test]
    fn test_triangle_p3_out_of_bounds_base_material() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);

        let mut obj = Object::new(1);
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.pid = Some(5);
        tri.p3 = Some(99); // out of bounds
        mesh.triangles.push(tri);
        obj.mesh = Some(mesh);
        model.resources.objects.push(obj);
        let result = validate_material_references(&model);
        assert!(result.is_err());
    }

    #[test]
    fn test_multiproperties_pindex_out_of_bounds_color_group() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        let mp = MultiProperties::new(5, vec![10]);
        let mut multi = Multi::new(vec![]);
        multi.pindices = vec![99]; // out of bounds
        model.resources.multi_properties.push({
            let mut mp = mp;
            mp.multis.push(multi);
            mp
        });
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("pindex"));
    }

    #[test]
    fn test_multiproperties_pindex_out_of_bounds_base_material() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);

        let mut mp = MultiProperties::new(99, vec![5]);
        let mut multi = Multi::new(vec![]);
        multi.pindices = vec![99]; // out of bounds
        mp.multis.push(multi);
        model.resources.multi_properties.push(mp);
        let result = validate_material_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("pindex"));
    }

    #[test]
    fn test_valid_empty_model() {
        let model = Model::new();
        assert!(validate_material_references(&model).is_ok());
    }

    // ===================== validate_texture_paths =====================

    #[test]
    fn test_texture_empty_path() {
        let mut model = Model::new();
        let tex = Texture2D::new(1, "".to_string(), "image/png".to_string());
        model.resources.texture2d_resources.push(tex);
        let result = validate_texture_paths(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));
    }

    #[test]
    fn test_texture_path_with_null_byte() {
        let mut model = Model::new();
        let tex = Texture2D::new(1, "/path/tex\0.png".to_string(), "image/png".to_string());
        model.resources.texture2d_resources.push(tex);
        let result = validate_texture_paths(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("null bytes"));
    }

    #[test]
    fn test_texture_path_with_backslash() {
        let mut model = Model::new();
        let tex = Texture2D::new(1, r"\path\tex.png".to_string(), "image/png".to_string());
        model.resources.texture2d_resources.push(tex);
        let result = validate_texture_paths(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("backslash"));
    }

    #[test]
    fn test_texture_invalid_content_type() {
        let mut model = Model::new();
        let tex = Texture2D::new(
            1,
            "/3D/Textures/tex.bmp".to_string(),
            "image/bmp".to_string(),
        );
        model.resources.texture2d_resources.push(tex);
        let result = validate_texture_paths(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("contenttype"));
    }

    #[test]
    fn test_texture_valid_jpeg() {
        let mut model = Model::new();
        let tex = Texture2D::new(
            1,
            "/3D/Textures/tex.jpg".to_string(),
            "image/jpeg".to_string(),
        );
        model.resources.texture2d_resources.push(tex);
        assert!(validate_texture_paths(&model).is_ok());
    }

    #[test]
    fn test_texture_valid_png() {
        let mut model = Model::new();
        let tex = Texture2D::new(
            1,
            "/3D/Textures/tex.png".to_string(),
            "image/png".to_string(),
        );
        model.resources.texture2d_resources.push(tex);
        assert!(validate_texture_paths(&model).is_ok());
    }

    // ===================== validate_multiproperties_references =====================

    #[test]
    fn test_multiproperties_invalid_pid() {
        let mut model = Model::new();
        let mp = MultiProperties::new(5, vec![99]); // pid 99 doesn't exist
        model.resources.multi_properties.push(mp);
        let result = validate_multiproperties_references(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("does not reference a valid resource")
        );
    }

    #[test]
    fn test_multiproperties_basematerials_not_first() {
        let mut model = Model::new();
        let mut bg = BaseMaterialGroup::new(5);
        bg.materials
            .push(BaseMaterial::new("m".to_string(), (255, 0, 0, 255)));
        model.resources.base_material_groups.push(bg);
        let mut cg = ColorGroup::new(10);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);

        // basematerials at layer 1, not 0
        let mp = MultiProperties::new(20, vec![10, 5]); // color first, base material second
        model.resources.multi_properties.push(mp);
        let result = validate_multiproperties_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("first element"));
    }

    #[test]
    fn test_multiproperties_multiple_colorgroups() {
        let mut model = Model::new();
        let mut cg1 = ColorGroup::new(10);
        cg1.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg1);
        let mut cg2 = ColorGroup::new(20);
        cg2.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg2);

        // Two different colorgroups in pids
        let mp = MultiProperties::new(30, vec![10, 20]);
        model.resources.multi_properties.push(mp);
        let result = validate_multiproperties_references(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("colorgroup"));
    }

    // ===================== validate_color_formats =====================

    #[test]
    fn test_color_group_empty() {
        let mut model = Model::new();
        model.resources.color_groups.push(ColorGroup::new(1)); // no colors
        let result = validate_color_formats(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("at least one color")
        );
    }

    #[test]
    fn test_color_group_with_color_valid() {
        let mut model = Model::new();
        let mut cg = ColorGroup::new(1);
        cg.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg);
        assert!(validate_color_formats(&model).is_ok());
    }

    // ===================== validate_resource_ordering =====================

    #[test]
    fn test_texture2d_group_references_nonexistent_texture() {
        let mut model = Model::new();
        let tg = Texture2DGroup::new(1, 99); // texid 99 doesn't exist
        model.resources.texture2d_groups.push(tg);
        let result = validate_resource_ordering(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not defined"));
    }

    #[test]
    fn test_texture2d_group_forward_reference() {
        let mut model = Model::new();
        let mut tg = Texture2DGroup::new(1, 2);
        tg.parse_order = 1; // texture group comes first in parse order
        model.resources.texture2d_groups.push(tg);

        let mut tex = Texture2D::new(
            2,
            "/3D/Textures/tex.png".to_string(),
            "image/png".to_string(),
        );
        tex.parse_order = 2; // but texture2d comes after
        model.resources.texture2d_resources.push(tex);
        let result = validate_resource_ordering(&model);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Forward reference")
        );
    }

    #[test]
    fn test_valid_texture2d_then_group() {
        let mut model = Model::new();
        let mut tex = Texture2D::new(
            2,
            "/3D/Textures/tex.png".to_string(),
            "image/png".to_string(),
        );
        tex.parse_order = 1; // texture2d comes first
        model.resources.texture2d_resources.push(tex);

        let mut tg = Texture2DGroup::new(1, 2);
        tg.parse_order = 2; // texture group comes after
        model.resources.texture2d_groups.push(tg);
        assert!(validate_resource_ordering(&model).is_ok());
    }

    #[test]
    fn test_object_intermingled_with_property_resources() {
        let mut model = Model::new();
        let mut cg1 = ColorGroup::new(1);
        cg1.parse_order = 1;
        cg1.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg1);

        // Object appears between two property resources
        let mut obj = Object::new(10);
        obj.parse_order = 5;
        model.resources.objects.push(obj);

        let mut cg2 = ColorGroup::new(2);
        cg2.parse_order = 10;
        cg2.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg2);

        let result = validate_resource_ordering(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("intermingled"));
    }

    // ===================== validate_duplicate_resource_ids =====================

    #[test]
    fn test_duplicate_object_ids() {
        let mut model = Model::new();
        model.resources.objects.push(Object::new(1));
        model.resources.objects.push(Object::new(1)); // duplicate
        let result = validate_duplicate_resource_ids(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Duplicate"));
    }

    #[test]
    fn test_duplicate_color_group_in_namespace() {
        let mut model = Model::new();
        let mut cg1 = ColorGroup::new(5);
        cg1.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg1);
        let mut cg2 = ColorGroup::new(5); // duplicate
        cg2.colors.push((255u8, 0u8, 0u8, 255u8));
        model.resources.color_groups.push(cg2);
        let result = validate_duplicate_resource_ids(&model);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Duplicate"));
    }

    // ===================== validate_object_triangle_materials =====================

    #[test]
    fn test_mixed_assignment_without_pid() {
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri1 = Triangle::new(0, 1, 2);
        tri1.pid = Some(10);
        let tri2 = Triangle::new(0, 1, 2); // no material
        mesh.triangles.push(tri1);
        mesh.triangles.push(tri2);

        let result = validate_object_triangle_materials(1, None, &mesh, "Object 1");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("mixed material"));
    }

    #[test]
    fn test_per_vertex_without_pid() {
        let mut mesh = Mesh::new();
        mesh.vertices.push(Vertex::new(0.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(1.0, 0.0, 0.0));
        mesh.vertices.push(Vertex::new(0.0, 1.0, 0.0));
        let mut tri = Triangle::new(0, 1, 2);
        tri.p1 = Some(0); // per-vertex but no pid
        mesh.triangles.push(tri);

        let result = validate_object_triangle_materials(1, None, &mesh, "Object 1");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("per-vertex material")
        );
    }

    // ===================== get_property_resource_size =====================

    #[test]
    fn test_get_property_size_empty_color_group() {
        let mut model = Model::new();
        model.resources.color_groups.push(ColorGroup::new(5)); // no colors
        let result = get_property_resource_size(&model, 5);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("no colors"));
    }

    #[test]
    fn test_get_property_size_nonexistent() {
        let model = Model::new();
        let result = get_property_resource_size(&model, 99);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }
}