threecrate-io 0.8.0

I/O operations for point clouds and meshes in threecrate
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
//! Robust PLY format support
//! 
//! This module provides comprehensive PLY (Polygon File Format) reading and writing
//! capabilities including:
//! - ASCII and binary (little/big endian) format support
//! - Vertex, face, normal, color, and generic property parsing
//! - Metadata and comment preservation
//! - Streaming support for large files
//! - Structured error handling

use crate::{PointCloudReader, PointCloudWriter, MeshReader, MeshWriter};
use threecrate_core::{PointCloud, TriangleMesh, Result, Point3f, Vector3f, Error};
use std::path::Path;
use std::fs::File;
use std::io::{BufRead, BufReader, BufWriter, Read};
use std::collections::HashMap;
use byteorder::{LittleEndian, BigEndian, ReadBytesExt};
#[cfg(feature = "io-mmap")]
use crate::mmap::MmapReader;

/// PLY file format variants
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlyFormat {
    Ascii,
    BinaryLittleEndian,
    BinaryBigEndian,
}

/// PLY property data types
#[derive(Debug, Clone, PartialEq)]
pub enum PlyPropertyType {
    Char,
    UChar,
    Short,
    UShort,
    Int,
    UInt,
    Float,
    Double,
    List(Box<PlyPropertyType>, Box<PlyPropertyType>), // count type, item type
}

/// PLY property definition
#[derive(Debug, Clone)]
pub struct PlyProperty {
    pub name: String,
    pub property_type: PlyPropertyType,
}

/// PLY element definition
#[derive(Debug, Clone)]
pub struct PlyElement {
    pub name: String,
    pub count: usize,
    pub properties: Vec<PlyProperty>,
}

/// PLY property value
#[derive(Debug, Clone)]
pub enum PlyValue {
    Char(i8),
    UChar(u8),
    Short(i16),
    UShort(u16),
    Int(i32),
    UInt(u32),
    Float(f32),
    Double(f64),
    List(Vec<PlyValue>),
}

/// PLY header information
#[derive(Debug, Clone)]
pub struct PlyHeader {
    pub format: PlyFormat,
    pub version: String,
    pub elements: Vec<PlyElement>,
    pub comments: Vec<String>,
    pub obj_info: Vec<String>,
}

/// Complete PLY file data
#[derive(Debug)]
pub struct PlyData {
    pub header: PlyHeader,
    pub elements: HashMap<String, Vec<HashMap<String, PlyValue>>>,
}

/// Enhanced PLY reader with comprehensive format support
pub struct RobustPlyReader;

/// PLY writer configuration options
#[derive(Debug, Clone)]
pub struct PlyWriteOptions {
    /// Output format (ASCII or binary)
    pub format: PlyFormat,
    /// Comments to include in the header
    pub comments: Vec<String>,
    /// Object info to include in the header
    pub obj_info: Vec<String>,
    /// Custom properties to include for vertices
    pub custom_vertex_properties: Vec<(String, Vec<PlyValue>)>,
    /// Custom properties to include for faces
    pub custom_face_properties: Vec<(String, Vec<PlyValue>)>,
    /// Whether to include normals if available
    pub include_normals: bool,
    /// Whether to include colors if available
    pub include_colors: bool,
    /// Custom property ordering for vertices
    pub vertex_property_order: Option<Vec<String>>,
}

impl Default for PlyWriteOptions {
    fn default() -> Self {
        Self {
            format: PlyFormat::Ascii,
            comments: Vec::new(),
            obj_info: Vec::new(),
            custom_vertex_properties: Vec::new(),
            custom_face_properties: Vec::new(),
            include_normals: true,
            include_colors: false,
            vertex_property_order: None,
        }
    }
}

impl PlyWriteOptions {
    /// Create new options with ASCII format
    pub fn ascii() -> Self {
        Self {
            format: PlyFormat::Ascii,
            ..Default::default()
        }
    }
    
    /// Create new options with binary little endian format
    pub fn binary_little_endian() -> Self {
        Self {
            format: PlyFormat::BinaryLittleEndian,
            ..Default::default()
        }
    }
    
    /// Create new options with binary big endian format
    pub fn binary_big_endian() -> Self {
        Self {
            format: PlyFormat::BinaryBigEndian,
            ..Default::default()
        }
    }
    
    /// Add a comment to the header
    pub fn with_comment<S: Into<String>>(mut self, comment: S) -> Self {
        self.comments.push(comment.into());
        self
    }
    
    /// Add object info to the header
    pub fn with_obj_info<S: Into<String>>(mut self, info: S) -> Self {
        self.obj_info.push(info.into());
        self
    }
    
    /// Include normals in output
    pub fn with_normals(mut self, include: bool) -> Self {
        self.include_normals = include;
        self
    }
    
    /// Include colors in output
    pub fn with_colors(mut self, include: bool) -> Self {
        self.include_colors = include;
        self
    }
    
    /// Set custom vertex property ordering
    pub fn with_vertex_property_order(mut self, order: Vec<String>) -> Self {
        self.vertex_property_order = Some(order);
        self
    }
    
    /// Add custom vertex property
    pub fn with_custom_vertex_property<S: Into<String>>(mut self, name: S, values: Vec<PlyValue>) -> Self {
        self.custom_vertex_properties.push((name.into(), values));
        self
    }
}

/// Enhanced PLY writer with comprehensive format support
pub struct RobustPlyWriter;

impl RobustPlyWriter {
    /// Write point cloud to PLY file with options
    pub fn write_point_cloud<P: AsRef<Path>>(
        cloud: &PointCloud<Point3f>, 
        path: P, 
        options: &PlyWriteOptions
    ) -> Result<()> {
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        Self::write_point_cloud_to_writer(cloud, &mut writer, options)
    }
    
    /// Write point cloud to writer with options
    pub fn write_point_cloud_to_writer<W: std::io::Write>(
        cloud: &PointCloud<Point3f>,
        writer: &mut W,
        options: &PlyWriteOptions,
    ) -> Result<()> {
        // Build PLY data structure
        let mut ply_data = PlyData {
            header: PlyHeader {
                format: options.format,
                version: "1.0".to_string(),
                elements: Vec::new(),
                comments: options.comments.clone(),
                obj_info: options.obj_info.clone(),
            },
            elements: HashMap::new(),
        };
        
        // Build vertex element definition
        let mut vertex_properties = Vec::new();
        let mut vertex_data = Vec::new();
        
        // Always include x, y, z
        vertex_properties.push(PlyProperty {
            name: "x".to_string(),
            property_type: PlyPropertyType::Float,
        });
        vertex_properties.push(PlyProperty {
            name: "y".to_string(),
            property_type: PlyPropertyType::Float,
        });
        vertex_properties.push(PlyProperty {
            name: "z".to_string(),
            property_type: PlyPropertyType::Float,
        });
        
        // Add custom properties if specified
        for (prop_name, _) in &options.custom_vertex_properties {
            // Determine property type from first value
            if let Some(first_values) = options.custom_vertex_properties.iter()
                .find(|(name, _)| name == prop_name)
                .map(|(_, values)| values)
            {
                if let Some(first_value) = first_values.first() {
                    let prop_type = Self::value_to_property_type(first_value);
                    vertex_properties.push(PlyProperty {
                        name: prop_name.clone(),
                        property_type: prop_type,
                    });
                }
            }
        }
        
        // Reorder properties if custom order is specified
        if let Some(order) = &options.vertex_property_order {
            vertex_properties.sort_by_key(|prop| {
                order.iter().position(|name| name == &prop.name)
                    .unwrap_or(order.len())
            });
        }
        
        // Build vertex data
        for (i, point) in cloud.iter().enumerate() {
            let mut vertex_instance = HashMap::new();
            vertex_instance.insert("x".to_string(), PlyValue::Float(point.x));
            vertex_instance.insert("y".to_string(), PlyValue::Float(point.y));
            vertex_instance.insert("z".to_string(), PlyValue::Float(point.z));
            
            // Add custom properties
            for (prop_name, values) in &options.custom_vertex_properties {
                if i < values.len() {
                    vertex_instance.insert(prop_name.clone(), values[i].clone());
                }
            }
            
            vertex_data.push(vertex_instance);
        }
        
        // Add vertex element
        ply_data.header.elements.push(PlyElement {
            name: "vertex".to_string(),
            count: cloud.len(),
            properties: vertex_properties,
        });
        ply_data.elements.insert("vertex".to_string(), vertex_data);
        
        // Write PLY data
        Self::write_ply_data(writer, &ply_data)
    }
    
    /// Write triangle mesh to PLY file with options
    pub fn write_mesh<P: AsRef<Path>>(
        mesh: &TriangleMesh,
        path: P,
        options: &PlyWriteOptions,
    ) -> Result<()> {
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        Self::write_mesh_to_writer(mesh, &mut writer, options)
    }
    
    /// Write triangle mesh to writer with options
    pub fn write_mesh_to_writer<W: std::io::Write>(
        mesh: &TriangleMesh,
        writer: &mut W,
        options: &PlyWriteOptions,
    ) -> Result<()> {
        // Build PLY data structure
        let mut ply_data = PlyData {
            header: PlyHeader {
                format: options.format,
                version: "1.0".to_string(),
                elements: Vec::new(),
                comments: options.comments.clone(),
                obj_info: options.obj_info.clone(),
            },
            elements: HashMap::new(),
        };
        
        // Build vertex element
        let mut vertex_properties = Vec::new();
        let mut vertex_data = Vec::new();
        
        // Always include x, y, z
        vertex_properties.push(PlyProperty {
            name: "x".to_string(),
            property_type: PlyPropertyType::Float,
        });
        vertex_properties.push(PlyProperty {
            name: "y".to_string(),
            property_type: PlyPropertyType::Float,
        });
        vertex_properties.push(PlyProperty {
            name: "z".to_string(),
            property_type: PlyPropertyType::Float,
        });
        
        // Add normals if requested and available
        if options.include_normals && mesh.normals.is_some() {
            vertex_properties.push(PlyProperty {
                name: "nx".to_string(),
                property_type: PlyPropertyType::Float,
            });
            vertex_properties.push(PlyProperty {
                name: "ny".to_string(),
                property_type: PlyPropertyType::Float,
            });
            vertex_properties.push(PlyProperty {
                name: "nz".to_string(),
                property_type: PlyPropertyType::Float,
            });
        }
        
        // Add custom vertex properties
        for (prop_name, _) in &options.custom_vertex_properties {
            if let Some(first_values) = options.custom_vertex_properties.iter()
                .find(|(name, _)| name == prop_name)
                .map(|(_, values)| values)
            {
                if let Some(first_value) = first_values.first() {
                    let prop_type = Self::value_to_property_type(first_value);
                    vertex_properties.push(PlyProperty {
                        name: prop_name.clone(),
                        property_type: prop_type,
                    });
                }
            }
        }
        
        // Reorder properties if specified
        if let Some(order) = &options.vertex_property_order {
            vertex_properties.sort_by_key(|prop| {
                order.iter().position(|name| name == &prop.name)
                    .unwrap_or(order.len())
            });
        }
        
        // Build vertex data
        for (i, vertex) in mesh.vertices.iter().enumerate() {
            let mut vertex_instance = HashMap::new();
            vertex_instance.insert("x".to_string(), PlyValue::Float(vertex.x));
            vertex_instance.insert("y".to_string(), PlyValue::Float(vertex.y));
            vertex_instance.insert("z".to_string(), PlyValue::Float(vertex.z));
            
            // Add normals if available and requested
            if options.include_normals {
                if let Some(normals) = &mesh.normals {
                    if i < normals.len() {
                        vertex_instance.insert("nx".to_string(), PlyValue::Float(normals[i].x));
                        vertex_instance.insert("ny".to_string(), PlyValue::Float(normals[i].y));
                        vertex_instance.insert("nz".to_string(), PlyValue::Float(normals[i].z));
                    }
                }
            }
            
            // Add custom properties
            for (prop_name, values) in &options.custom_vertex_properties {
                if i < values.len() {
                    vertex_instance.insert(prop_name.clone(), values[i].clone());
                }
            }
            
            vertex_data.push(vertex_instance);
        }
        
        // Add vertex element
        ply_data.header.elements.push(PlyElement {
            name: "vertex".to_string(),
            count: mesh.vertices.len(),
            properties: vertex_properties,
        });
        ply_data.elements.insert("vertex".to_string(), vertex_data);
        
        // Build face element
        if !mesh.faces.is_empty() {
            let face_properties = vec![
                PlyProperty {
                    name: "vertex_indices".to_string(),
                    property_type: PlyPropertyType::List(
                        Box::new(PlyPropertyType::UChar),
                        Box::new(PlyPropertyType::Int),
                    ),
                },
            ];
            
            let mut face_data = Vec::new();
            for face in &mesh.faces {
                let mut face_instance = HashMap::new();
                let indices = vec![
                    PlyValue::Int(face[0] as i32),
                    PlyValue::Int(face[1] as i32),
                    PlyValue::Int(face[2] as i32),
                ];
                face_instance.insert("vertex_indices".to_string(), PlyValue::List(indices));
                face_data.push(face_instance);
            }
            
            ply_data.header.elements.push(PlyElement {
                name: "face".to_string(),
                count: mesh.faces.len(),
                properties: face_properties,
            });
            ply_data.elements.insert("face".to_string(), face_data);
        }
        
        // Write PLY data
        Self::write_ply_data(writer, &ply_data)
    }
    
    /// Write PLY data to writer
    fn write_ply_data<W: std::io::Write>(writer: &mut W, ply_data: &PlyData) -> Result<()> {
        // Write header
        Self::write_header(writer, &ply_data.header)?;
        
        // Write element data
        match ply_data.header.format {
            PlyFormat::Ascii => Self::write_ascii_data(writer, ply_data)?,
            PlyFormat::BinaryLittleEndian => Self::write_binary_data::<LittleEndian, _>(writer, ply_data)?,
            PlyFormat::BinaryBigEndian => Self::write_binary_data::<BigEndian, _>(writer, ply_data)?,
        }
        
        Ok(())
    }
    
    /// Write PLY header
    fn write_header<W: std::io::Write>(writer: &mut W, header: &PlyHeader) -> Result<()> {
        writeln!(writer, "ply")?;
        
        let format_str = match header.format {
            PlyFormat::Ascii => "ascii",
            PlyFormat::BinaryLittleEndian => "binary_little_endian",
            PlyFormat::BinaryBigEndian => "binary_big_endian",
        };
        writeln!(writer, "format {} {}", format_str, header.version)?;
        
        // Write comments
        for comment in &header.comments {
            writeln!(writer, "comment {}", comment)?;
        }
        
        // Write obj_info
        for info in &header.obj_info {
            writeln!(writer, "obj_info {}", info)?;
        }
        
        // Write elements and properties
        for element in &header.elements {
            writeln!(writer, "element {} {}", element.name, element.count)?;
            for property in &element.properties {
                Self::write_property_definition(writer, property)?;
            }
        }
        
        writeln!(writer, "end_header")?;
        Ok(())
    }
    
    /// Write property definition
    fn write_property_definition<W: std::io::Write>(writer: &mut W, property: &PlyProperty) -> Result<()> {
        match &property.property_type {
            PlyPropertyType::List(count_type, item_type) => {
                let count_str = Self::property_type_to_string(count_type);
                let item_str = Self::property_type_to_string(item_type);
                writeln!(writer, "property list {} {} {}", count_str, item_str, property.name)?;
            }
            _ => {
                let type_str = Self::property_type_to_string(&property.property_type);
                writeln!(writer, "property {} {}", type_str, property.name)?;
            }
        }
        Ok(())
    }
    
    /// Convert property type to string
    fn property_type_to_string(prop_type: &PlyPropertyType) -> &'static str {
        match prop_type {
            PlyPropertyType::Char => "char",
            PlyPropertyType::UChar => "uchar",
            PlyPropertyType::Short => "short",
            PlyPropertyType::UShort => "ushort",
            PlyPropertyType::Int => "int",
            PlyPropertyType::UInt => "uint",
            PlyPropertyType::Float => "float",
            PlyPropertyType::Double => "double",
            PlyPropertyType::List(_, _) => "list", // Should not be called directly for lists
        }
    }
    
    /// Write ASCII format data
    fn write_ascii_data<W: std::io::Write>(writer: &mut W, ply_data: &PlyData) -> Result<()> {
        for element_def in &ply_data.header.elements {
            if let Some(element_data) = ply_data.elements.get(&element_def.name) {
                for instance in element_data {
                    let mut values = Vec::new();
                    
                    for property in &element_def.properties {
                        if let Some(value) = instance.get(&property.name) {
                            Self::format_ascii_value(value, &mut values)?;
                        }
                    }
                    
                    writeln!(writer, "{}", values.join(" "))?;
                }
            }
        }
        Ok(())
    }
    
    /// Format a value for ASCII output
    fn format_ascii_value(value: &PlyValue, output: &mut Vec<String>) -> Result<()> {
        match value {
            PlyValue::Char(v) => output.push(v.to_string()),
            PlyValue::UChar(v) => output.push(v.to_string()),
            PlyValue::Short(v) => output.push(v.to_string()),
            PlyValue::UShort(v) => output.push(v.to_string()),
            PlyValue::Int(v) => output.push(v.to_string()),
            PlyValue::UInt(v) => output.push(v.to_string()),
            PlyValue::Float(v) => output.push(v.to_string()),
            PlyValue::Double(v) => output.push(v.to_string()),
            PlyValue::List(values) => {
                output.push(values.len().to_string());
                for item in values {
                    Self::format_ascii_value(item, output)?;
                }
            }
        }
        Ok(())
    }
    
    /// Write binary format data
    fn write_binary_data<E: byteorder::ByteOrder, W: std::io::Write>(
        writer: &mut W,
        ply_data: &PlyData,
    ) -> Result<()> {
        
        for element_def in &ply_data.header.elements {
            if let Some(element_data) = ply_data.elements.get(&element_def.name) {
                for instance in element_data {
                    for property in &element_def.properties {
                        if let Some(value) = instance.get(&property.name) {
                            Self::write_binary_value::<E, _>(writer, value)?;
                        }
                    }
                }
            }
        }
        Ok(())
    }
    
    /// Write a binary value
    fn write_binary_value<E: byteorder::ByteOrder, W: std::io::Write>(
        writer: &mut W,
        value: &PlyValue,
    ) -> Result<()> {
        use byteorder::WriteBytesExt;
        
        match value {
            PlyValue::Char(v) => writer.write_i8(*v)?,
            PlyValue::UChar(v) => writer.write_u8(*v)?,
            PlyValue::Short(v) => writer.write_i16::<E>(*v)?,
            PlyValue::UShort(v) => writer.write_u16::<E>(*v)?,
            PlyValue::Int(v) => writer.write_i32::<E>(*v)?,
            PlyValue::UInt(v) => writer.write_u32::<E>(*v)?,
            PlyValue::Float(v) => writer.write_f32::<E>(*v)?,
            PlyValue::Double(v) => writer.write_f64::<E>(*v)?,
            PlyValue::List(values) => {
                // Write count as uchar (assuming list count type is uchar)
                writer.write_u8(values.len() as u8)?;
                for item in values {
                    Self::write_binary_value::<E, _>(writer, item)?;
                }
            }
        }
        Ok(())
    }
    
    /// Determine property type from PLY value
    fn value_to_property_type(value: &PlyValue) -> PlyPropertyType {
        match value {
            PlyValue::Char(_) => PlyPropertyType::Char,
            PlyValue::UChar(_) => PlyPropertyType::UChar,
            PlyValue::Short(_) => PlyPropertyType::Short,
            PlyValue::UShort(_) => PlyPropertyType::UShort,
            PlyValue::Int(_) => PlyPropertyType::Int,
            PlyValue::UInt(_) => PlyPropertyType::UInt,
            PlyValue::Float(_) => PlyPropertyType::Float,
            PlyValue::Double(_) => PlyPropertyType::Double,
            PlyValue::List(values) => {
                let item_type = if let Some(first_item) = values.first() {
                    Self::value_to_property_type(first_item)
                } else {
                    PlyPropertyType::Int
                };
                PlyPropertyType::List(Box::new(PlyPropertyType::UChar), Box::new(item_type))
            }
        }
    }
}

impl RobustPlyReader {
    /// Read a complete PLY file with all metadata and elements
    pub fn read_ply_data<R: BufRead>(reader: &mut R) -> Result<PlyData> {
        let header = Self::read_header(reader)?;
        let elements = Self::read_elements(reader, &header)?;
        
        Ok(PlyData { header, elements })
    }
    
    /// Read PLY file from path
    pub fn read_ply_file<P: AsRef<Path>>(path: P) -> Result<PlyData> {
        let path = path.as_ref();
        
        // Try memory-mapped reading for binary files if feature is enabled
        #[cfg(feature = "io-mmap")]
        {
            if let Some(ply_data) = Self::try_read_ply_mmap(path)? {
                return Ok(ply_data);
            }
        }
        
        // Fall back to standard buffered reading
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);
        Self::read_ply_data(&mut reader)
    }

    /// Try to read PLY file using memory mapping (binary files only)
    #[cfg(feature = "io-mmap")]
    fn try_read_ply_mmap<P: AsRef<Path>>(path: P) -> Result<Option<PlyData>> {
        let path = path.as_ref();
        
        // Check if we should use memory mapping
        if !crate::mmap::should_use_mmap(path) {
            return Ok(None);
        }
        
        // First, read the header using standard I/O to determine format
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);
        let header = Self::read_header(&mut reader)?;
        
        // Only use mmap for binary formats
        match header.format {
            PlyFormat::BinaryLittleEndian | PlyFormat::BinaryBigEndian => {
                // Calculate header size by reading until "end_header"
                let file = File::open(path)?;
                let mut reader = BufReader::new(file);
                let mut header_size = 0;
                let mut line = String::new();
                
                loop {
                    let line_start = header_size;
                    line.clear();
                    let bytes_read = reader.read_line(&mut line)?;
                    if bytes_read == 0 {
                        return Err(Error::InvalidData("Unexpected end of file in header".to_string()));
                    }
                    header_size += bytes_read;
                    
                    if line.trim() == "end_header" {
                        break;
                    }
                }
                
                // Now use memory mapping for the data section
                if let Some(mut mmap_reader) = MmapReader::new(path)? {
                    // Skip to the data section
                    mmap_reader.seek(header_size)?;
                    
                    // Read elements using memory mapping
                    let elements = Self::read_elements_mmap(&mut mmap_reader, &header)?;
                    
                    return Ok(Some(PlyData { header, elements }));
                }
            }
            PlyFormat::Ascii => {
                // ASCII format - use standard buffered I/O
                return Ok(None);
            }
        }
        
        Ok(None)
    }

    /// Read elements using memory mapping
    #[cfg(feature = "io-mmap")]
    fn read_elements_mmap(
        reader: &mut MmapReader, 
        header: &PlyHeader
    ) -> Result<HashMap<String, Vec<HashMap<String, PlyValue>>>> {
        let mut elements = HashMap::new();
        
        for element_def in &header.elements {
            let mut element_data = Vec::with_capacity(element_def.count);
            
            for _ in 0..element_def.count {
                let mut instance = HashMap::new();
                
                match header.format {
                    PlyFormat::BinaryLittleEndian => {
                        for property in &element_def.properties {
                            let value = Self::read_binary_property_value_mmap_le(reader, &property.property_type)?;
                            instance.insert(property.name.clone(), value);
                        }
                    }
                    PlyFormat::BinaryBigEndian => {
                        for property in &element_def.properties {
                            let value = Self::read_binary_property_value_mmap_be(reader, &property.property_type)?;
                            instance.insert(property.name.clone(), value);
                        }
                    }
                    PlyFormat::Ascii => {
                        return Err(Error::InvalidData("ASCII format should not use mmap reader".to_string()));
                    }
                }
                
                element_data.push(instance);
            }
            
            elements.insert(element_def.name.clone(), element_data);
        }
        
        Ok(elements)
    }

    /// Read binary property value using memory mapping (little endian)
    #[cfg(feature = "io-mmap")]
    fn read_binary_property_value_mmap_le(reader: &mut MmapReader, property_type: &PlyPropertyType) -> Result<PlyValue> {
        match property_type {
            PlyPropertyType::Char => Ok(PlyValue::Char(reader.read_u8()? as i8)),
            PlyPropertyType::UChar => Ok(PlyValue::UChar(reader.read_u8()?)),
            PlyPropertyType::Short => Ok(PlyValue::Short(reader.read_u16_le()? as i16)),
            PlyPropertyType::UShort => Ok(PlyValue::UShort(reader.read_u16_le()?)),
            PlyPropertyType::Int => Ok(PlyValue::Int(reader.read_u32_le()? as i32)),
            PlyPropertyType::UInt => Ok(PlyValue::UInt(reader.read_u32_le()?)),
            PlyPropertyType::Float => Ok(PlyValue::Float(reader.read_f32_le()?)),
            PlyPropertyType::Double => Ok(PlyValue::Double(reader.read_f64_le()?)),
            PlyPropertyType::List(count_type, item_type) => {
                let count_value = Self::read_binary_property_value_mmap_le(reader, count_type)?;
                let count = count_value.as_usize()?;
                
                let mut list = Vec::with_capacity(count);
                for _ in 0..count {
                    let item = Self::read_binary_property_value_mmap_le(reader, item_type)?;
                    list.push(item);
                }
                
                Ok(PlyValue::List(list))
            }
        }
    }

    /// Read binary property value using memory mapping (big endian)
    #[cfg(feature = "io-mmap")]
    fn read_binary_property_value_mmap_be(reader: &mut MmapReader, property_type: &PlyPropertyType) -> Result<PlyValue> {
        match property_type {
            PlyPropertyType::Char => Ok(PlyValue::Char(reader.read_u8()? as i8)),
            PlyPropertyType::UChar => Ok(PlyValue::UChar(reader.read_u8()?)),
            PlyPropertyType::Short => Ok(PlyValue::Short(reader.read_u16_be()? as i16)),
            PlyPropertyType::UShort => Ok(PlyValue::UShort(reader.read_u16_be()?)),
            PlyPropertyType::Int => Ok(PlyValue::Int(reader.read_u32_be()? as i32)),
            PlyPropertyType::UInt => Ok(PlyValue::UInt(reader.read_u32_be()?)),
            PlyPropertyType::Float => Ok(PlyValue::Float(reader.read_f32_be()?)),
            PlyPropertyType::Double => Ok(PlyValue::Double(reader.read_f64_be()?)),
            PlyPropertyType::List(count_type, item_type) => {
                let count_value = Self::read_binary_property_value_mmap_be(reader, count_type)?;
                let count = count_value.as_usize()?;
                
                let mut list = Vec::with_capacity(count);
                for _ in 0..count {
                    let item = Self::read_binary_property_value_mmap_be(reader, item_type)?;
                    list.push(item);
                }
                
                Ok(PlyValue::List(list))
            }
        }
    }
    
    /// Read and parse PLY header
    fn read_header<R: BufRead>(reader: &mut R) -> Result<PlyHeader> {
        let mut format = None;
        let mut version = "1.0".to_string();
        let mut elements = Vec::new();
        let mut comments = Vec::new();
        let mut obj_info = Vec::new();
        
        let mut line = String::new();
        
        // Read magic number
        reader.read_line(&mut line)?;
        if line.trim() != "ply" {
            return Err(Error::InvalidData("Not a PLY file - missing magic number".to_string()));
        }
        
        // Parse header lines
        loop {
            line.clear();
            if reader.read_line(&mut line)? == 0 {
                return Err(Error::InvalidData("Unexpected end of file in header".to_string()));
            }
            
            let line = line.trim();
            if line == "end_header" {
                break;
            }
            
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.is_empty() {
                continue;
            }
            
            match parts[0] {
                "format" => {
                    if parts.len() < 3 {
                        return Err(Error::InvalidData("Invalid format line".to_string()));
                    }
                    format = Some(match parts[1] {
                        "ascii" => PlyFormat::Ascii,
                        "binary_little_endian" => PlyFormat::BinaryLittleEndian,
                        "binary_big_endian" => PlyFormat::BinaryBigEndian,
                        _ => return Err(Error::InvalidData(format!("Unknown format: {}", parts[1]))),
                    });
                    version = parts[2].to_string();
                }
                "comment" => {
                    if parts.len() > 1 {
                        comments.push(parts[1..].join(" "));
                    }
                }
                "obj_info" => {
                    if parts.len() > 1 {
                        obj_info.push(parts[1..].join(" "));
                    }
                }
                "element" => {
                    if parts.len() < 3 {
                        return Err(Error::InvalidData("Invalid element line".to_string()));
                    }
                    let name = parts[1].to_string();
                    let count: usize = parts[2].parse()
                        .map_err(|_| Error::InvalidData("Invalid element count".to_string()))?;
                    elements.push(PlyElement {
                        name,
                        count,
                        properties: Vec::new(),
                    });
                }
                "property" => {
                    if elements.is_empty() {
                        return Err(Error::InvalidData("Property without element".to_string()));
                    }
                    let property = Self::parse_property(&parts[1..])?;
                    elements.last_mut().unwrap().properties.push(property);
                }
                _ => {
                    // Ignore unknown header lines
                }
            }
        }
        
        let format = format.ok_or_else(|| Error::InvalidData("Missing format specification".to_string()))?;
        
        Ok(PlyHeader {
            format,
            version,
            elements,
            comments,
            obj_info,
        })
    }
    
    /// Parse a property definition
    fn parse_property(parts: &[&str]) -> Result<PlyProperty> {
        if parts.is_empty() {
            return Err(Error::InvalidData("Empty property definition".to_string()));
        }
        
        let property_type = if parts[0] == "list" {
            if parts.len() < 4 {
                return Err(Error::InvalidData("Invalid list property definition".to_string()));
            }
            let count_type = Self::parse_scalar_type(parts[1])?;
            let item_type = Self::parse_scalar_type(parts[2])?;
            PlyPropertyType::List(Box::new(count_type), Box::new(item_type))
        } else {
            if parts.len() < 2 {
                return Err(Error::InvalidData("Invalid property definition".to_string()));
            }
            Self::parse_scalar_type(parts[0])?
        };
        
        let name = parts.last().unwrap().to_string();
        
        Ok(PlyProperty { name, property_type })
    }
    
    /// Parse a scalar type
    fn parse_scalar_type(type_str: &str) -> Result<PlyPropertyType> {
        match type_str {
            "char" | "int8" => Ok(PlyPropertyType::Char),
            "uchar" | "uint8" => Ok(PlyPropertyType::UChar),
            "short" | "int16" => Ok(PlyPropertyType::Short),
            "ushort" | "uint16" => Ok(PlyPropertyType::UShort),
            "int" | "int32" => Ok(PlyPropertyType::Int),
            "uint" | "uint32" => Ok(PlyPropertyType::UInt),
            "float" | "float32" => Ok(PlyPropertyType::Float),
            "double" | "float64" => Ok(PlyPropertyType::Double),
            _ => Err(Error::InvalidData(format!("Unknown property type: {}", type_str))),
        }
    }
    
    /// Read all elements according to header specification
    fn read_elements<R: BufRead>(reader: &mut R, header: &PlyHeader) -> Result<HashMap<String, Vec<HashMap<String, PlyValue>>>> {
        let mut elements = HashMap::new();
        
        for element_def in &header.elements {
            let mut element_data = Vec::with_capacity(element_def.count);
            
            for _ in 0..element_def.count {
                let mut instance = HashMap::new();
                
                match header.format {
                    PlyFormat::Ascii => {
                        let mut line = String::new();
                        reader.read_line(&mut line)?;
                        let values = line.trim().split_whitespace().collect::<Vec<_>>();
                        let mut value_idx = 0;
                        
                        for property in &element_def.properties {
                            let value = Self::read_ascii_property_value(&values, &mut value_idx, &property.property_type)?;
                            instance.insert(property.name.clone(), value);
                        }
                    }
                    PlyFormat::BinaryLittleEndian => {
                        for property in &element_def.properties {
                            let value = Self::read_binary_property_value::<LittleEndian, _>(reader, &property.property_type)?;
                            instance.insert(property.name.clone(), value);
                        }
                    }
                    PlyFormat::BinaryBigEndian => {
                        for property in &element_def.properties {
                            let value = Self::read_binary_property_value::<BigEndian, _>(reader, &property.property_type)?;
                            instance.insert(property.name.clone(), value);
                        }
                    }
                }
                
                element_data.push(instance);
            }
            
            elements.insert(element_def.name.clone(), element_data);
        }
        
        Ok(elements)
    }
    
    /// Read ASCII property value
    fn read_ascii_property_value(values: &[&str], value_idx: &mut usize, property_type: &PlyPropertyType) -> Result<PlyValue> {
        if *value_idx >= values.len() {
            return Err(Error::InvalidData("Not enough values in line".to_string()));
        }
        
        match property_type {
            PlyPropertyType::Char => {
                let val = values[*value_idx].parse::<i8>()
                    .map_err(|_| Error::InvalidData("Invalid char value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::Char(val))
            }
            PlyPropertyType::UChar => {
                let val = values[*value_idx].parse::<u8>()
                    .map_err(|_| Error::InvalidData("Invalid uchar value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::UChar(val))
            }
            PlyPropertyType::Short => {
                let val = values[*value_idx].parse::<i16>()
                    .map_err(|_| Error::InvalidData("Invalid short value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::Short(val))
            }
            PlyPropertyType::UShort => {
                let val = values[*value_idx].parse::<u16>()
                    .map_err(|_| Error::InvalidData("Invalid ushort value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::UShort(val))
            }
            PlyPropertyType::Int => {
                let val = values[*value_idx].parse::<i32>()
                    .map_err(|_| Error::InvalidData("Invalid int value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::Int(val))
            }
            PlyPropertyType::UInt => {
                let val = values[*value_idx].parse::<u32>()
                    .map_err(|_| Error::InvalidData("Invalid uint value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::UInt(val))
            }
            PlyPropertyType::Float => {
                let val = values[*value_idx].parse::<f32>()
                    .map_err(|_| Error::InvalidData("Invalid float value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::Float(val))
            }
            PlyPropertyType::Double => {
                let val = values[*value_idx].parse::<f64>()
                    .map_err(|_| Error::InvalidData("Invalid double value".to_string()))?;
                *value_idx += 1;
                Ok(PlyValue::Double(val))
            }
            PlyPropertyType::List(count_type, item_type) => {
                let count_value = Self::read_ascii_property_value(values, value_idx, count_type)?;
                let count = count_value.as_usize()?;
                
                let mut list = Vec::with_capacity(count);
                for _ in 0..count {
                    let item = Self::read_ascii_property_value(values, value_idx, item_type)?;
                    list.push(item);
                }
                
                Ok(PlyValue::List(list))
            }
        }
    }
    
    /// Read binary property value
    fn read_binary_property_value<E: byteorder::ByteOrder, R: Read>(reader: &mut R, property_type: &PlyPropertyType) -> Result<PlyValue> {
        match property_type {
            PlyPropertyType::Char => Ok(PlyValue::Char(reader.read_i8()?)),
            PlyPropertyType::UChar => Ok(PlyValue::UChar(reader.read_u8()?)),
            PlyPropertyType::Short => Ok(PlyValue::Short(reader.read_i16::<E>()?)),
            PlyPropertyType::UShort => Ok(PlyValue::UShort(reader.read_u16::<E>()?)),
            PlyPropertyType::Int => Ok(PlyValue::Int(reader.read_i32::<E>()?)),
            PlyPropertyType::UInt => Ok(PlyValue::UInt(reader.read_u32::<E>()?)),
            PlyPropertyType::Float => Ok(PlyValue::Float(reader.read_f32::<E>()?)),
            PlyPropertyType::Double => Ok(PlyValue::Double(reader.read_f64::<E>()?)),
            PlyPropertyType::List(count_type, item_type) => {
                let count_value = Self::read_binary_property_value::<E, _>(reader, count_type)?;
                let count = count_value.as_usize()?;
                
                let mut list = Vec::with_capacity(count);
                for _ in 0..count {
                    let item = Self::read_binary_property_value::<E, _>(reader, item_type)?;
                    list.push(item);
                }
                
                Ok(PlyValue::List(list))
            }
        }
    }
}

impl PlyValue {
    /// Convert PLY value to f32
    pub fn as_f32(&self) -> Result<f32> {
        match self {
            PlyValue::Char(v) => Ok(*v as f32),
            PlyValue::UChar(v) => Ok(*v as f32),
            PlyValue::Short(v) => Ok(*v as f32),
            PlyValue::UShort(v) => Ok(*v as f32),
            PlyValue::Int(v) => Ok(*v as f32),
            PlyValue::UInt(v) => Ok(*v as f32),
            PlyValue::Float(v) => Ok(*v),
            PlyValue::Double(v) => Ok(*v as f32),
            _ => Err(Error::InvalidData("Cannot convert list to f32".to_string())),
        }
    }
    
    /// Convert PLY value to usize
    pub fn as_usize(&self) -> Result<usize> {
        match self {
            PlyValue::UChar(v) => Ok(*v as usize),
            PlyValue::UShort(v) => Ok(*v as usize),
            PlyValue::UInt(v) => Ok(*v as usize),
            PlyValue::Int(v) if *v >= 0 => Ok(*v as usize),
            _ => Err(Error::InvalidData("Cannot convert value to usize".to_string())),
        }
    }
    
    /// Convert PLY value to Vec<usize> (for face indices)
    pub fn as_usize_list(&self) -> Result<Vec<usize>> {
        match self {
            PlyValue::List(values) => {
                values.iter().map(|v| v.as_usize()).collect()
            }
            _ => Err(Error::InvalidData("Value is not a list".to_string())),
        }
    }
}

// Legacy PLY reader/writer using ply-rs for backward compatibility
pub struct PlyReader;
pub struct PlyWriter;

// Implement the new unified traits
impl crate::registry::PointCloudReader for PlyReader {
    fn read_point_cloud(&self, path: &Path) -> Result<PointCloud<Point3f>> {
        // Use the robust reader for better format support
        let ply_data = RobustPlyReader::read_ply_file(path)?;
        
        let mut points = Vec::new();
        
        if let Some(vertex_elements) = ply_data.elements.get("vertex") {
            for vertex in vertex_elements {
                let x = vertex.get("x")
                    .ok_or_else(|| Error::InvalidData("Missing x coordinate".to_string()))?
                    .as_f32()?;
                let y = vertex.get("y")
                    .ok_or_else(|| Error::InvalidData("Missing y coordinate".to_string()))?
                    .as_f32()?;
                let z = vertex.get("z")
                    .ok_or_else(|| Error::InvalidData("Missing z coordinate".to_string()))?
                    .as_f32()?;
                
                points.push(Point3f::new(x, y, z));
            }
        }
        
        Ok(PointCloud::from_points(points))
    }
    
    fn can_read(&self, path: &Path) -> bool {
        // Check if file starts with "ply"
        if let Ok(mut file) = File::open(path) {
            let mut header = [0u8; 4];
            if let Ok(_) = file.read(&mut header) {
                return header.starts_with(b"ply");
            }
        }
        false
    }
    
    fn format_name(&self) -> &'static str {
        "ply"
    }
}

impl crate::registry::MeshReader for PlyReader {
    fn read_mesh(&self, path: &Path) -> Result<TriangleMesh> {
        let ply_data = RobustPlyReader::read_ply_file(path)?;
        
        // Extract vertices
        let mut vertices = Vec::new();
        if let Some(vertex_elements) = ply_data.elements.get("vertex") {
            for vertex in vertex_elements {
                let x = vertex.get("x")
                    .ok_or_else(|| Error::InvalidData("Missing x coordinate".to_string()))?
                    .as_f32()?;
                let y = vertex.get("y")
                    .ok_or_else(|| Error::InvalidData("Missing y coordinate".to_string()))?
                    .as_f32()?;
                let z = vertex.get("z")
                    .ok_or_else(|| Error::InvalidData("Missing z coordinate".to_string()))?
                    .as_f32()?;
                
                vertices.push(Point3f::new(x, y, z));
            }
        }
        
        // Extract faces
        let mut faces = Vec::new();
        if let Some(face_elements) = ply_data.elements.get("face") {
            for face in face_elements {
                // Look for vertex_indices or vertex_index property
                let indices = if let Some(vertex_indices) = face.get("vertex_indices") {
                    vertex_indices.as_usize_list()?
                } else if let Some(vertex_index) = face.get("vertex_index") {
                    vertex_index.as_usize_list()?
                } else {
                    return Err(Error::InvalidData("Face missing vertex indices".to_string()));
                };
                
                // Convert to triangles (assuming triangular faces or taking first 3 vertices)
                if indices.len() >= 3 {
                    faces.push([indices[0], indices[1], indices[2]]);
                }
                // For quads and other polygons, we could triangulate here
                if indices.len() == 4 {
                    faces.push([indices[0], indices[2], indices[3]]);
                }
            }
        }
        
        // Extract normals if available
        let normals = if let Some(vertex_elements) = ply_data.elements.get("vertex") {
            let mut normals = Vec::new();
            let mut has_normals = true;
            
            for vertex in vertex_elements {
                if let (Some(nx), Some(ny), Some(nz)) = (
                    vertex.get("nx"),
                    vertex.get("ny"), 
                    vertex.get("nz"),
                ) {
                    normals.push(Vector3f::new(
                        nx.as_f32()?,
                        ny.as_f32()?,
                        nz.as_f32()?,
                    ));
                } else {
                    has_normals = false;
                    break;
                }
            }
            
            if has_normals {
                Some(normals)
            } else {
                None
            }
        } else {
            None
        };
        
        let mut mesh = TriangleMesh::from_vertices_and_faces(vertices, faces);
        if let Some(normals) = normals {
            mesh.set_normals(normals);
        }
        
        Ok(mesh)
    }
    
    fn can_read(&self, path: &Path) -> bool {
        // Check if file starts with "ply"
        if let Ok(mut file) = File::open(path) {
            let mut header = [0u8; 4];
            if let Ok(_) = file.read(&mut header) {
                return header.starts_with(b"ply");
            }
        }
        false
    }
    
    fn format_name(&self) -> &'static str {
        "ply"
    }
}

impl crate::registry::PointCloudWriter for PlyWriter {
    fn write_point_cloud(&self, cloud: &PointCloud<Point3f>, path: &Path) -> Result<()> {
        // Use the legacy ply-rs for writing for now
        use ply_rs::{
            writer::Writer,
            ply::{Property, PropertyDef, PropertyType, ScalarType, ElementDef, Ply, Addable, DefaultElement},
        };
        
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        
        // Create PLY structure
        let mut ply = Ply::<DefaultElement>::new();
        
        // Define vertex element
        let mut vertex_element = ElementDef::new("vertex".to_string());
        vertex_element.count = cloud.len();
        vertex_element.properties.add(PropertyDef::new(
            "x".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        vertex_element.properties.add(PropertyDef::new(
            "y".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        vertex_element.properties.add(PropertyDef::new(
            "z".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        
        ply.header.elements.add(vertex_element);
        
        // Add vertex data
        let mut vertices = Vec::new();
        for point in &cloud.points {
            let mut vertex = DefaultElement::new();
            vertex.insert("x".to_string(), Property::Float(point.x));
            vertex.insert("y".to_string(), Property::Float(point.y));
            vertex.insert("z".to_string(), Property::Float(point.z));
            vertices.push(vertex);
        }
        ply.payload.insert("vertex".to_string(), vertices);
        
        // Write PLY file
        let writer_instance = Writer::new();
        writer_instance.write_ply(&mut writer, &mut ply)?;
        
        Ok(())
    }
    
    fn format_name(&self) -> &'static str {
        "ply"
    }
}

impl crate::registry::MeshWriter for PlyWriter {
    fn write_mesh(&self, mesh: &TriangleMesh, path: &Path) -> Result<()> {
        // Use the legacy ply-rs for writing for now
        use ply_rs::{
            writer::Writer,
            ply::{Property, PropertyDef, PropertyType, ScalarType, ElementDef, Ply, Addable, DefaultElement},
        };
        
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        
        // Create PLY structure
        let mut ply = Ply::<DefaultElement>::new();
        
        // Define vertex element
        let mut vertex_element = ElementDef::new("vertex".to_string());
        vertex_element.count = mesh.vertices.len();
        vertex_element.properties.add(PropertyDef::new(
            "x".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        vertex_element.properties.add(PropertyDef::new(
            "y".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        vertex_element.properties.add(PropertyDef::new(
            "z".to_string(),
            PropertyType::Scalar(ScalarType::Float),
        ));
        
        // Add normal properties if available
        if mesh.normals.is_some() {
            vertex_element.properties.add(PropertyDef::new(
                "nx".to_string(),
                PropertyType::Scalar(ScalarType::Float),
            ));
            vertex_element.properties.add(PropertyDef::new(
                "ny".to_string(),
                PropertyType::Scalar(ScalarType::Float),
            ));
            vertex_element.properties.add(PropertyDef::new(
                "nz".to_string(),
                PropertyType::Scalar(ScalarType::Float),
            ));
        }
        
        ply.header.elements.add(vertex_element);
        
        // Add vertex data
        let mut vertices = Vec::new();
        for (i, point) in mesh.vertices.iter().enumerate() {
            let mut vertex = DefaultElement::new();
            vertex.insert("x".to_string(), Property::Float(point.x));
            vertex.insert("y".to_string(), Property::Float(point.y));
            vertex.insert("z".to_string(), Property::Float(point.z));
            
            // Add normals if available
            if let Some(ref normals) = mesh.normals {
                if i < normals.len() {
                    vertex.insert("nx".to_string(), Property::Float(normals[i].x));
                    vertex.insert("ny".to_string(), Property::Float(normals[i].y));
                    vertex.insert("nz".to_string(), Property::Float(normals[i].z));
                }
            }
            
            vertices.push(vertex);
        }
        ply.payload.insert("vertex".to_string(), vertices);
        
        // Define face element if we have faces
        if !mesh.faces.is_empty() {
            let mut face_element = ElementDef::new("face".to_string());
            face_element.count = mesh.faces.len();
            face_element.properties.add(PropertyDef::new(
                "vertex_indices".to_string(),
                PropertyType::List(ScalarType::UChar, ScalarType::Int),
            ));
            
            ply.header.elements.add(face_element);
            
            // Add face data
            let mut faces = Vec::new();
            for face in &mesh.faces {
                let mut face_data = DefaultElement::new();
                let indices = vec![
                    face[0] as i32,
                    face[1] as i32,
                    face[2] as i32,
                ];
                face_data.insert("vertex_indices".to_string(), Property::ListInt(indices));
                faces.push(face_data);
            }
            ply.payload.insert("face".to_string(), faces);
        }
        
        // Write PLY file
        let writer_instance = Writer::new();
        writer_instance.write_ply(&mut writer, &mut ply)?;
        
        Ok(())
    }
    
    fn format_name(&self) -> &'static str {
        "ply"
    }
}

// Keep the legacy trait implementations for backward compatibility
impl PointCloudReader for PlyReader {
    fn read_point_cloud<P: AsRef<Path>>(path: P) -> Result<PointCloud<Point3f>> {
        let reader = PlyReader;
        crate::registry::PointCloudReader::read_point_cloud(&reader, path.as_ref())
    }
}

impl MeshReader for PlyReader {
    fn read_mesh<P: AsRef<Path>>(path: P) -> Result<TriangleMesh> {
        let reader = PlyReader;
        crate::registry::MeshReader::read_mesh(&reader, path.as_ref())
    }
}

impl PointCloudWriter for PlyWriter {
    fn write_point_cloud<P: AsRef<Path>>(cloud: &PointCloud<Point3f>, path: P) -> Result<()> {
        let writer = PlyWriter;
        crate::registry::PointCloudWriter::write_point_cloud(&writer, cloud, path.as_ref())
    }
}

impl MeshWriter for PlyWriter {
    fn write_mesh<P: AsRef<Path>>(mesh: &TriangleMesh, path: P) -> Result<()> {
        let writer = PlyWriter;
        crate::registry::MeshWriter::write_mesh(&writer, mesh, path.as_ref())
    }
}

/// Streaming PLY reader for point clouds
pub struct PlyStreamingReader {
    reader: BufReader<File>,
    current_count: usize,
    current_index: usize,
    chunk_size: usize,
    buffer: Vec<u8>,
    format: PlyFormat,
}

impl PlyStreamingReader {
    /// Create a new streaming PLY reader
    pub fn new<P: AsRef<Path>>(path: P, chunk_size: usize) -> Result<Self> {
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);
        let header = RobustPlyReader::read_header(&mut reader)?;
        
        // Find vertex element
        let vertex_element = header.elements.iter()
            .find(|e| e.name == "vertex")
            .ok_or_else(|| Error::InvalidData("No vertex element found in PLY file".to_string()))?;
        
        Ok(Self {
            reader,
            current_count: vertex_element.count,
            current_index: 0,
            chunk_size,
            buffer: Vec::with_capacity(chunk_size * 12), // Estimate 12 bytes per vertex
            format: header.format,
        })
    }
}

impl Iterator for PlyStreamingReader {
    type Item = Result<Point3f>;
    
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index >= self.current_count {
            return None;
        }
        
        // Read a chunk if buffer is empty
        if self.buffer.is_empty() {
            let remaining = self.current_count - self.current_index;
            let to_read = std::cmp::min(remaining, self.chunk_size);
            
            match self.format {
                PlyFormat::Ascii => {
                    // For ASCII, we need to read line by line
                    let mut line = String::new();
                    if let Err(e) = self.reader.read_line(&mut line) {
                        return Some(Err(Error::Io(e)));
                    }
                    
                    let values: Vec<&str> = line.trim().split_whitespace().collect();
                    if values.len() < 3 {
                        return Some(Err(Error::InvalidData("Not enough coordinates in vertex line".to_string())));
                    }
                    
                    let x = match values[0].parse::<f32>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid x coordinate".to_string()))),
                    };
                    let y = match values[1].parse::<f32>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid y coordinate".to_string()))),
                    };
                    let z = match values[2].parse::<f32>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid z coordinate".to_string()))),
                    };
                    
                    self.current_index += 1;
                    return Some(Ok(Point3f::new(x, y, z)));
                }
                PlyFormat::BinaryLittleEndian => {
                    // For binary, read the chunk
                    let bytes_per_vertex = 12; // 3 * f32
                    let chunk_bytes = to_read * bytes_per_vertex;
                    self.buffer.resize(chunk_bytes, 0);
                    
                    if let Err(e) = self.reader.read_exact(&mut self.buffer[..chunk_bytes]) {
                        return Some(Err(Error::Io(e)));
                    }
                }
                PlyFormat::BinaryBigEndian => {
                    // For binary, read the chunk
                    let bytes_per_vertex = 12; // 3 * f32
                    let chunk_bytes = to_read * bytes_per_vertex;
                    self.buffer.resize(chunk_bytes, 0);
                    
                    if let Err(e) = self.reader.read_exact(&mut self.buffer[..chunk_bytes]) {
                        return Some(Err(Error::Io(e)));
                    }
                }
            }
        }
        
        // Extract point from buffer
        match self.format {
            PlyFormat::Ascii => {
                // Already handled above
                unreachable!()
            }
            PlyFormat::BinaryLittleEndian => {
                if self.buffer.len() < 12 {
                    return Some(Err(Error::InvalidData("Insufficient data in buffer".to_string())));
                }
                
                let x = f32::from_le_bytes([
                    self.buffer[0], self.buffer[1], self.buffer[2], self.buffer[3]
                ]);
                let y = f32::from_le_bytes([
                    self.buffer[4], self.buffer[5], self.buffer[6], self.buffer[7]
                ]);
                let z = f32::from_le_bytes([
                    self.buffer[8], self.buffer[9], self.buffer[10], self.buffer[11]
                ]);
                
                // Remove processed data from buffer
                self.buffer.drain(0..12);
                self.current_index += 1;
                
                Some(Ok(Point3f::new(x, y, z)))
            }
            PlyFormat::BinaryBigEndian => {
                if self.buffer.len() < 12 {
                    return Some(Err(Error::InvalidData("Insufficient data in buffer".to_string())));
                }
                
                let x = f32::from_be_bytes([
                    self.buffer[0], self.buffer[1], self.buffer[2], self.buffer[3]
                ]);
                let y = f32::from_be_bytes([
                    self.buffer[4], self.buffer[5], self.buffer[6], self.buffer[7]
                ]);
                let z = f32::from_be_bytes([
                    self.buffer[8], self.buffer[9], self.buffer[10], self.buffer[11]
                ]);
                
                // Remove processed data from buffer
                self.buffer.drain(0..12);
                self.current_index += 1;
                
                Some(Ok(Point3f::new(x, y, z)))
            }
        }
    }
}

/// Streaming PLY reader for mesh faces
pub struct PlyMeshStreamingReader {
    reader: BufReader<File>,
    current_count: usize,
    current_index: usize,
    chunk_size: usize,
    buffer: Vec<u8>,
    format: PlyFormat,
    vertices: Vec<Point3f>, // We need to store vertices to convert face indices
}

impl PlyMeshStreamingReader {
    /// Create a new streaming PLY mesh reader
    pub fn new<P: AsRef<Path>>(path: P, chunk_size: usize) -> Result<Self> {
        let file = File::open(path)?;
        let mut reader = BufReader::new(file);
        let header = RobustPlyReader::read_header(&mut reader)?;
        
        // Find face element
        let face_element = header.elements.iter()
            .find(|e| e.name == "face")
            .ok_or_else(|| Error::InvalidData("No face element found in PLY file".to_string()))?;
        
        // First, we need to read all vertices to convert face indices
        let vertex_element = header.elements.iter()
            .find(|e| e.name == "vertex")
            .ok_or_else(|| Error::InvalidData("No vertex element found in PLY file".to_string()))?;
        
        let mut vertices = Vec::with_capacity(vertex_element.count);
        
        // Read vertices first
        for _ in 0..vertex_element.count {
            let mut line = String::new();
            reader.read_line(&mut line)?;
            let values: Vec<&str> = line.trim().split_whitespace().collect();
            if values.len() >= 3 {
                let x = values[0].parse::<f32>()
                    .map_err(|_| Error::InvalidData("Invalid x coordinate".to_string()))?;
                let y = values[1].parse::<f32>()
                    .map_err(|_| Error::InvalidData("Invalid y coordinate".to_string()))?;
                let z = values[2].parse::<f32>()
                    .map_err(|_| Error::InvalidData("Invalid z coordinate".to_string()))?;
                vertices.push(Point3f::new(x, y, z));
            }
        }
        
        Ok(Self {
            reader,
            current_count: face_element.count,
            current_index: 0,
            chunk_size,
            buffer: Vec::with_capacity(chunk_size * 16), // Estimate 16 bytes per face
            format: header.format,
            vertices,
        })
    }
}

impl Iterator for PlyMeshStreamingReader {
    type Item = Result<[usize; 3]>;
    
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index >= self.current_count {
            return None;
        }
        
        // Read a chunk if buffer is empty
        if self.buffer.is_empty() {
            let remaining = self.current_count - self.current_index;
            let to_read = std::cmp::min(remaining, self.chunk_size);
            
            match self.format {
                PlyFormat::Ascii => {
                    // For ASCII, we need to read line by line
                    let mut line = String::new();
                    if let Err(e) = self.reader.read_line(&mut line) {
                        return Some(Err(Error::Io(e)));
                    }
                    
                    let values: Vec<&str> = line.trim().split_whitespace().collect();
                    if values.len() < 4 { // count + 3 indices
                        return Some(Err(Error::InvalidData("Not enough values in face line".to_string())));
                    }
                    
                    let count = match values[0].parse::<usize>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid face count".to_string()))),
                    };
                    
                    if count != 3 {
                        return Some(Err(Error::InvalidData("Only triangular faces supported".to_string())));
                    }
                    
                    let i1 = match values[1].parse::<usize>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid face index".to_string()))),
                    };
                    let i2 = match values[2].parse::<usize>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid face index".to_string()))),
                    };
                    let i3 = match values[3].parse::<usize>() {
                        Ok(v) => v,
                        Err(_) => return Some(Err(Error::InvalidData("Invalid face index".to_string()))),
                    };
                    
                    // Validate indices
                    if i1 >= self.vertices.len() || i2 >= self.vertices.len() || i3 >= self.vertices.len() {
                        return Some(Err(Error::InvalidData("Face index out of range".to_string())));
                    }
                    
                    self.current_index += 1;
                    return Some(Ok([i1, i2, i3]));
                }
                PlyFormat::BinaryLittleEndian | PlyFormat::BinaryBigEndian => {
                    // For binary, read the chunk
                    let bytes_per_face = 16; // 1 uchar count + 3 * u32 indices
                    let chunk_bytes = to_read * bytes_per_face;
                    self.buffer.resize(chunk_bytes, 0);
                    
                    if let Err(e) = self.reader.read_exact(&mut self.buffer[..chunk_bytes]) {
                        return Some(Err(Error::Io(e)));
                    }
                }
            }
        }
        
        // Extract face from buffer
        match self.format {
            PlyFormat::Ascii => {
                // Already handled above
                unreachable!()
            }
            PlyFormat::BinaryLittleEndian => {
                if self.buffer.len() < 16 {
                    return Some(Err(Error::InvalidData("Insufficient data in buffer".to_string())));
                }
                
                let count = self.buffer[0] as usize;
                if count != 3 {
                    return Some(Err(Error::InvalidData("Only triangular faces supported".to_string())));
                }
                
                let i1 = u32::from_le_bytes([
                    self.buffer[1], self.buffer[2], self.buffer[3], self.buffer[4]
                ]) as usize;
                let i2 = u32::from_le_bytes([
                    self.buffer[5], self.buffer[6], self.buffer[7], self.buffer[8]
                ]) as usize;
                let i3 = u32::from_le_bytes([
                    self.buffer[9], self.buffer[10], self.buffer[11], self.buffer[12]
                ]) as usize;
                
                // Validate indices
                if i1 >= self.vertices.len() || i2 >= self.vertices.len() || i3 >= self.vertices.len() {
                    return Some(Err(Error::InvalidData("Face index out of range".to_string())));
                }
                
                // Remove processed data from buffer
                self.buffer.drain(0..16);
                self.current_index += 1;
                
                Some(Ok([i1, i2, i3]))
            }
            PlyFormat::BinaryBigEndian => {
                if self.buffer.len() < 16 {
                    return Some(Err(Error::InvalidData("Insufficient data in buffer".to_string())));
                }
                
                let count = self.buffer[0] as usize;
                if count != 3 {
                    return Some(Err(Error::InvalidData("Only triangular faces supported".to_string())));
                }
                
                let i1 = u32::from_be_bytes([
                    self.buffer[1], self.buffer[2], self.buffer[3], self.buffer[4]
                ]) as usize;
                let i2 = u32::from_be_bytes([
                    self.buffer[5], self.buffer[6], self.buffer[7], self.buffer[8]
                ]) as usize;
                let i3 = u32::from_be_bytes([
                    self.buffer[9], self.buffer[10], self.buffer[11], self.buffer[12]
                ]) as usize;
                
                // Validate indices
                if i1 >= self.vertices.len() || i2 >= self.vertices.len() || i3 >= self.vertices.len() {
                    return Some(Err(Error::InvalidData("Face index out of range".to_string())));
                }
                
                // Remove processed data from buffer
                self.buffer.drain(0..16);
                self.current_index += 1;
                
                Some(Ok([i1, i2, i3]))
            }
        }
    }
}