draco-core 1.0.1

Pure Rust core encoder and decoder for Draco geometry compression
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
use crate::attribute_quantization_transform::AttributeQuantizationTransform;
use crate::attribute_transform::AttributeTransform;
use crate::compression_config::EncodedGeometryType;
use crate::compression_config::MeshEncodingMethod;
use crate::corner_table::CornerTable;
use crate::draco_types::DataType;
use crate::encoder_buffer::EncoderBuffer;
use crate::encoder_options::EncoderOptions;
use crate::geometry_attribute::{GeometryAttributeType, PointAttribute};
use crate::geometry_indices::{FaceIndex, PointIndex, INVALID_ATTRIBUTE_VALUE_INDEX};
use crate::mesh::Mesh;
use crate::mesh_edgebreaker_encoder::{EdgebreakerAttributeConnectivity, MeshEdgebreakerEncoder};
use crate::metadata::METADATA_FLAG_MASK;
use crate::point_cloud::PointCloud;
use crate::point_cloud_encoder::GeometryEncoder;
use crate::sequential_attribute_encoder::SequentialAttributeEncoder;
use crate::sequential_integer_attribute_encoder::SequentialIntegerAttributeEncoder;
use crate::sequential_normal_attribute_encoder::SequentialNormalAttributeEncoder;
use crate::status::{DracoError, Status};
use crate::version::{
    has_header_flags, uses_varint_encoding, uses_varint_unique_id, DEFAULT_MESH_VERSION,
};

/// `(min, max)` per-component position bounds, each present when computable.
type PositionBounds = (Option<Vec<f64>>, Option<Vec<f64>>);

/// Encoder for Draco triangle mesh bitstreams.
///
/// A `MeshEncoder` takes a [`Mesh`] plus [`EncoderOptions`] and writes a
/// self-contained `.drc` bitstream (header, optional metadata, connectivity,
/// and attributes) into an [`EncoderBuffer`]. The encoding method (EdgeBreaker or
/// sequential), prediction schemes, and quantization are selected from the
/// options, mirroring the C++ `MeshEncoder`/`ExpertEncoder` configuration.
///
/// After a successful [`encode`](MeshEncoder::encode), per-attribute and
/// per-face details are available via
/// [`encoded_mesh_info`](MeshEncoder::encoded_mesh_info).
///
/// # Examples
///
/// Build a single-triangle mesh, encode it, and decode it back:
///
/// ```
/// use draco_core::{
///     DataType, DecoderBuffer, EncoderBuffer, EncoderOptions, FaceIndex,
///     GeometryAttributeType, Mesh, MeshDecoder, MeshEncoder, PointAttribute,
/// };
///
/// // One triangle with a float32 position attribute (3 vertices).
/// let mut mesh = Mesh::new();
/// let mut position = PointAttribute::new();
/// position.init(GeometryAttributeType::Position, 3, DataType::Float32, false, 3);
/// let coords: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
/// for (i, value) in coords.iter().enumerate() {
///     position.buffer_mut().write(i * 4, &value.to_le_bytes());
/// }
/// mesh.add_attribute(position);
/// mesh.set_num_faces(1);
/// mesh.set_face(FaceIndex(0), [0u32.into(), 1u32.into(), 2u32.into()]);
///
/// // Encode to a Draco bitstream.
/// let mut encoder = MeshEncoder::new();
/// encoder.set_mesh(mesh);
/// let mut buffer = EncoderBuffer::new();
/// encoder.encode(&EncoderOptions::new(), &mut buffer)?;
///
/// // Decode it back.
/// let mut decoded = Mesh::new();
/// MeshDecoder::new().decode(&mut DecoderBuffer::new(buffer.data()), &mut decoded)?;
/// assert_eq!(decoded.num_faces(), 1);
/// # Ok::<(), draco_core::DracoError>(())
/// ```
pub struct MeshEncoder {
    mesh: Option<Mesh>,
    options: EncoderOptions,
    num_encoded_faces: usize,
    corner_table: Option<CornerTable>,
    point_ids: Vec<PointIndex>,
    data_to_corner_map: Option<Vec<u32>>,
    vertex_to_data_map: Option<Vec<i32>>,
    edgebreaker_attribute_connectivity: Vec<EdgebreakerAttributeConnectivity>,
    active_corner_table: Option<CornerTable>,
    active_data_to_corner_map: Option<Vec<u32>>,
    active_vertex_to_data_map: Option<Vec<i32>>,
    method: i32,
    /// Maps point indices to vertex indices in the corner table.
    /// Used when position-based deduplication is enabled.
    point_to_vertex_map: Option<Vec<u32>>,
    /// Whether we're using single connectivity (all attributes share same corner table).
    use_single_connectivity: bool,
    encoded_mesh_info: Option<EncodedMeshInfo>,
}

/// Geometry shape and attribute metadata produced by a successful mesh encode.
#[derive(Debug, Clone, PartialEq)]
pub struct EncodedMeshInfo {
    /// Numeric Draco mesh encoding method used for the output.
    pub encoding_method: i32,
    /// Number of faces encoded into the bitstream.
    pub num_encoded_faces: usize,
    /// Number of points encoded into the bitstream.
    pub num_encoded_points: usize,
    /// Per-attribute information captured during encoding.
    pub attributes: Vec<EncodedAttributeInfo>,
}

/// Attribute metadata produced by a successful mesh encode.
#[derive(Debug, Clone, PartialEq)]
pub struct EncodedAttributeInfo {
    /// Source attribute id in the input mesh.
    pub source_attribute_id: i32,
    /// Semantic type of the encoded attribute.
    pub attribute_type: GeometryAttributeType,
    /// Scalar data type of the encoded attribute.
    pub data_type: DataType,
    /// Number of scalar components per encoded value.
    pub num_components: u8,
    /// Whether integer values are normalized.
    pub normalized: bool,
    /// Draco unique id assigned to the attribute.
    pub unique_id: u32,
    /// Number of unique values encoded for the attribute.
    pub num_encoded_values: usize,
    /// Minimum position components when known for position attributes.
    pub position_min: Option<Vec<f64>>,
    /// Maximum position components when known for position attributes.
    pub position_max: Option<Vec<f64>>,
}

impl GeometryEncoder for MeshEncoder {
    fn point_cloud(&self) -> Option<&PointCloud> {
        self.mesh.as_ref().map(|m| m as &PointCloud)
    }

    fn mesh(&self) -> Option<&Mesh> {
        self.mesh.as_ref()
    }

    fn corner_table(&self) -> Option<&CornerTable> {
        self.active_corner_table
            .as_ref()
            .or(self.corner_table.as_ref())
    }

    fn options(&self) -> &EncoderOptions {
        &self.options
    }

    fn get_geometry_type(&self) -> EncodedGeometryType {
        EncodedGeometryType::TriangularMesh
    }

    fn get_encoding_method(&self) -> Option<i32> {
        Some(self.method)
    }

    fn get_data_to_corner_map(&self) -> Option<&[u32]> {
        self.active_data_to_corner_map
            .as_deref()
            .or(self.data_to_corner_map.as_deref())
    }

    fn get_vertex_to_data_map(&self) -> Option<&[i32]> {
        self.active_vertex_to_data_map
            .as_deref()
            .or(self.vertex_to_data_map.as_deref())
    }
}

impl MeshEncoder {
    /// Creates an encoder without an assigned mesh.
    pub fn new() -> Self {
        Self {
            mesh: None,
            options: EncoderOptions::default(),
            num_encoded_faces: 0,
            corner_table: None,
            point_ids: Vec::new(),
            data_to_corner_map: None,
            vertex_to_data_map: None,
            edgebreaker_attribute_connectivity: Vec::new(),
            active_corner_table: None,
            active_data_to_corner_map: None,
            active_vertex_to_data_map: None,
            method: 0,
            point_to_vertex_map: None,
            use_single_connectivity: false,
            encoded_mesh_info: None,
        }
    }

    /// Assigns the mesh to encode.
    pub fn set_mesh(&mut self, mesh: Mesh) {
        self.mesh = Some(mesh);
    }

    /// Returns the assigned mesh, if any.
    pub fn mesh(&self) -> Option<&Mesh> {
        self.mesh.as_ref()
    }

    /// Returns the number of faces encoded by the last successful encode.
    pub fn num_encoded_faces(&self) -> usize {
        self.num_encoded_faces
    }

    /// Returns the corner table built during the last mesh encode, if any.
    pub fn corner_table(&self) -> Option<&CornerTable> {
        self.corner_table.as_ref()
    }

    /// Returns information captured during the last successful mesh encode.
    pub fn encoded_mesh_info(&self) -> Option<&EncodedMeshInfo> {
        self.encoded_mesh_info.as_ref()
    }

    /// Encodes the assigned mesh into an output buffer.
    ///
    /// A mesh must have been provided with [`set_mesh`](MeshEncoder::set_mesh)
    /// first. On success the bitstream is appended to `out_buffer` and
    /// [`encoded_mesh_info`](MeshEncoder::encoded_mesh_info) is populated.
    ///
    /// # Errors
    ///
    /// Returns an error if no mesh was set, if the requested encoding method or
    /// options are unsupported, or if attribute encoding fails.
    pub fn encode(&mut self, options: &EncoderOptions, out_buffer: &mut EncoderBuffer) -> Status {
        self.options = options.clone();
        self.encoded_mesh_info = None;

        if self.mesh.is_none() {
            return Err(DracoError::DracoError("Mesh not set".to_string()));
        }

        // 1. Encode Header
        self.encode_header(out_buffer)?;
        self.encode_metadata(out_buffer)?;

        // 2. Encode geometry data (connectivity + attributes)
        self.encode_geometry_data(out_buffer)?;

        Ok(())
    }

    fn encode_metadata(&self, buffer: &mut EncoderBuffer) -> Status {
        if let Some(metadata) = self
            .mesh
            .as_ref()
            .and_then(|mesh| mesh.metadata())
            .filter(|metadata| !metadata.is_empty())
        {
            metadata.encode(buffer)?;
        }
        Ok(())
    }

    fn encode_header(&self, buffer: &mut EncoderBuffer) -> Status {
        let (mut major, mut minor) = self.options.get_version();
        if major == 0 && minor == 0 {
            // Default to latest mesh version
            (major, minor) = DEFAULT_MESH_VERSION;
        }
        let has_metadata = self
            .mesh
            .as_ref()
            .and_then(|mesh| mesh.metadata())
            .is_some_and(|metadata| !metadata.is_empty());

        if has_metadata && !has_header_flags(major, minor) {
            return Err(DracoError::UnsupportedVersion(
                "Metadata requires Draco bitstream version 1.3 or newer".to_string(),
            ));
        }

        // C++ default behavior: Edgebreaker if speed != 10, Sequential if speed == 10
        let method_int = self.options.get_global_int("encoding_method", -1);
        let method = if method_int == -1 {
            if self.options.get_speed() == 10 {
                0
            } else {
                1
            }
        } else if method_int == 1 {
            1
        } else {
            0
        };

        #[cfg(not(feature = "legacy_bitstream_encode"))]
        if method == 1 {
            let bitstream_version = crate::version::bitstream_version(major, minor);
            if bitstream_version < 0x0202 {
                return Err(DracoError::UnsupportedVersion(
                    "EdgeBreaker mesh encoding before bitstream 2.2 requires the \
                     legacy_bitstream_encode feature"
                        .to_string(),
                ));
            }
            if self.options.get_global_int("force_predictive_traversal", 0) != 0 {
                return Err(DracoError::UnsupportedFeature(
                    "force_predictive_traversal requires the legacy_bitstream_encode feature"
                        .to_string(),
                ));
            }
        }
        #[cfg(not(feature = "legacy_bitstream_encode"))]
        match self.options.get_prediction_scheme() {
            2 | 3 => {
                return Err(DracoError::UnsupportedFeature(
                    "legacy prediction schemes require the legacy_bitstream_encode feature"
                        .to_string(),
                ));
            }
            _ => {}
        }

        buffer.encode_data(b"DRACO");

        buffer.encode_u8(major);
        buffer.encode_u8(minor);
        buffer.set_version(major, minor);
        buffer.encode_u8(self.get_geometry_type() as u8);
        buffer.encode_u8(method);

        // The flags field is always present in the binary header (the decoder reads
        // it unconditionally); only the metadata bit gains meaning at v1.3+, which
        // is guarded by the metadata check above. Emitting it only for >= 1.3 left
        // pre-1.3 streams two bytes short, misaligning the rest of the stream.
        let flags = if has_metadata { METADATA_FLAG_MASK } else { 0 };
        buffer.encode_u16(flags);
        Ok(())
    }

    fn encode_geometry_data(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        // First encode connectivity
        self.encode_connectivity(out_buffer)?;

        // Check if we should store the number of encoded faces
        if self
            .options
            .get_global_int("store_number_of_encoded_faces", 0)
            != 0
        {
            self.compute_number_of_encoded_faces();
        }

        // Then encode attributes
        self.encode_attributes(out_buffer)?;
        self.build_encoded_mesh_info()?;

        Ok(())
    }

    fn encode_connectivity(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");

        // Determine encoding method FIRST (before building corner table)
        let method_int = self.options.get_global_int("encoding_method", -1);
        let method = if method_int == -1 {
            if self.options.get_speed() == 10 {
                MeshEncodingMethod::MeshSequentialEncoding
            } else {
                MeshEncodingMethod::MeshEdgebreakerEncoding
            }
        } else if method_int == 1 {
            MeshEncodingMethod::MeshEdgebreakerEncoding
        } else {
            MeshEncodingMethod::MeshSequentialEncoding
        };
        self.method = if method == MeshEncodingMethod::MeshEdgebreakerEncoding {
            1
        } else {
            0
        };

        // C++ behavior: use_single_connectivity_ when speed >= 6
        // When false (speed < 6), use position attribute to deduplicate vertices
        let speed = self.options.get_speed();
        // Check if split_mesh_on_seams is explicitly set, otherwise use speed-based default
        let split_on_seams_explicit = self.options.get_global_int("split_mesh_on_seams", -1);
        let use_single_connectivity = if split_on_seams_explicit >= 0 {
            split_on_seams_explicit != 0
        } else {
            speed >= 6
        };

        // Only build corner table if needed (not for sequential encoding)
        if method == MeshEncodingMethod::MeshEdgebreakerEncoding {
            let (faces, point_to_vertex_map) = if use_single_connectivity {
                // CreateCornerTableFromAllAttributes: use point indices directly
                let faces: Vec<[crate::geometry_indices::VertexIndex; 3]> = (0..mesh.num_faces())
                    .map(|i| {
                        let face = mesh.face(FaceIndex(i as u32));
                        [
                            crate::geometry_indices::VertexIndex(face[0].0),
                            crate::geometry_indices::VertexIndex(face[1].0),
                            crate::geometry_indices::VertexIndex(face[2].0),
                        ]
                    })
                    .collect();
                // Identity mapping
                let point_to_vertex: Vec<u32> = (0..mesh.num_points() as u32).collect();
                (faces, point_to_vertex)
            } else {
                // CreateCornerTableFromPositionAttribute: use position attribute to deduplicate
                self.create_corner_table_from_position_attribute(mesh)
            };

            // Initialize corner table for the mesh
            let mut corner_table = CornerTable::new(0);
            corner_table.init(&faces);

            self.corner_table = Some(corner_table);
            self.point_to_vertex_map = Some(point_to_vertex_map);
            self.edgebreaker_attribute_connectivity.clear();
            if !use_single_connectivity {
                if let Some(ref ct) = self.corner_table {
                    for i in 0..mesh.num_attributes() {
                        let att = mesh.attribute(i);
                        if att.attribute_type() != GeometryAttributeType::Position {
                            self.edgebreaker_attribute_connectivity
                                .push(EdgebreakerAttributeConnectivity::build(mesh, ct, i));
                        }
                    }
                }
            }
        } else {
            // Sequential encoding: no corner table needed, use identity mapping
            let point_to_vertex: Vec<u32> = (0..mesh.num_points() as u32).collect();
            self.point_to_vertex_map = Some(point_to_vertex);
            self.edgebreaker_attribute_connectivity.clear();
        }
        self.use_single_connectivity = use_single_connectivity;

        match method {
            MeshEncodingMethod::MeshSequentialEncoding => {
                self.encode_sequential_connectivity(out_buffer)
            }
            MeshEncodingMethod::MeshEdgebreakerEncoding => {
                self.encode_edgebreaker_connectivity(out_buffer)
            }
        }
    }

    fn encode_edgebreaker_connectivity(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let corner_table = self
            .corner_table
            .as_ref()
            .expect("corner_table must be set before edgebreaker encoding");

        let mut encoder = MeshEdgebreakerEncoder::new(mesh.num_faces(), mesh.num_points());
        // Opt-in legacy predictive (type-1) traversal, for round-tripping the
        // pre-0.10.0 connectivity. Requires a < 2.0 target version.
        #[cfg(feature = "legacy_bitstream_encode")]
        encoder.set_force_predictive(
            self.options.get_global_int("force_predictive_traversal", 0) == 1,
        );
        let (point_ids, data_to_corner_map, vertex_to_data_map) = encoder.encode_connectivity(
            mesh,
            corner_table,
            &self.edgebreaker_attribute_connectivity,
            out_buffer,
            self.options.get_speed() as usize,
        )?;
        #[cfg(feature = "debug_logs")]
        {
            debug_log!("DEBUG: encode_edgebreaker_connectivity: point_ids.len()={}, data_to_corner_map.len()={}, vertex_to_data_map.len()={}",
                 point_ids.len(), data_to_corner_map.len(), vertex_to_data_map.len());
        }
        self.point_ids = point_ids;

        // Draco stores corner mapping in attribute (data) order.
        self.data_to_corner_map = Some(data_to_corner_map);
        self.vertex_to_data_map = Some(vertex_to_data_map);

        Ok(())
    }

    /// Creates faces array using position attribute to deduplicate vertices.
    /// This mimics C++ CreateCornerTableFromPositionAttribute.
    /// Returns (faces, point_to_vertex_map) where:
    /// - faces: vertex indices (deduplicated based on position values)
    /// - point_to_vertex_map: maps each point index to its vertex index in the corner table
    fn create_corner_table_from_position_attribute(
        &self,
        mesh: &Mesh,
    ) -> (Vec<[crate::geometry_indices::VertexIndex; 3]>, Vec<u32>) {
        use crate::geometry_attribute::GeometryAttributeType;

        let pos_att_id = mesh.named_attribute_id(GeometryAttributeType::Position);
        if pos_att_id < 0 {
            // No position attribute, fall back to identity mapping
            let faces: Vec<[crate::geometry_indices::VertexIndex; 3]> = (0..mesh.num_faces())
                .map(|i| {
                    let face = mesh.face(FaceIndex(i as u32));
                    [
                        crate::geometry_indices::VertexIndex(face[0].0),
                        crate::geometry_indices::VertexIndex(face[1].0),
                        crate::geometry_indices::VertexIndex(face[2].0),
                    ]
                })
                .collect();
            let point_to_vertex: Vec<u32> = (0..mesh.num_points() as u32).collect();
            return (faces, point_to_vertex);
        }

        let pos_att = mesh.attribute(pos_att_id);
        let _buffer = pos_att.buffer();
        let num_components = pos_att.num_components() as usize;
        let _byte_stride = match pos_att.data_type() {
            crate::draco_types::DataType::Float32 => num_components * 4,
            crate::draco_types::DataType::Float64 => num_components * 8,
            crate::draco_types::DataType::Int8 | crate::draco_types::DataType::Uint8 => {
                num_components
            }
            crate::draco_types::DataType::Int16 | crate::draco_types::DataType::Uint16 => {
                num_components * 2
            }
            crate::draco_types::DataType::Int32 | crate::draco_types::DataType::Uint32 => {
                num_components * 4
            }
            crate::draco_types::DataType::Int64 | crate::draco_types::DataType::Uint64 => {
                num_components * 8
            }
            _ => num_components * 4, // Default to 4 bytes per component
        };

        // Use attribute mapped indices directly to build point->vertex map. This mirrors
        // C++ CreateCornerTableFromAttribute which uses att->mapped_index(face[j]).
        let mut point_to_vertex: Vec<u32> = vec![0; mesh.num_points()];
        for i in 0..mesh.num_points() {
            let pt = PointIndex(i as u32);
            let val_idx = pos_att.mapped_index(pt);
            point_to_vertex[i] = val_idx.0;
        }

        // Build faces using attribute mapped indices (exact same mapping as C++).
        let faces: Vec<[crate::geometry_indices::VertexIndex; 3]> = (0..mesh.num_faces())
            .map(|i| {
                let face = mesh.face(FaceIndex(i as u32));
                [
                    crate::geometry_indices::VertexIndex(point_to_vertex[face[0].0 as usize]),
                    crate::geometry_indices::VertexIndex(point_to_vertex[face[1].0 as usize]),
                    crate::geometry_indices::VertexIndex(point_to_vertex[face[2].0 as usize]),
                ]
            })
            .collect();

        #[cfg(feature = "debug_logs")]
        {
            debug_log!(
                "Rust created faces (first 12): {:?}",
                faces
                    .iter()
                    .take(12)
                    .map(|f| [f[0].0, f[1].0, f[2].0])
                    .collect::<Vec<_>>()
            );
            debug_log!(
                "Rust point_to_vertex (first 25): {:?}",
                point_to_vertex.iter().take(25).cloned().collect::<Vec<_>>()
            );
        }
        (faces, point_to_vertex)
    }

    fn encode_sequential_connectivity(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");

        // Encode the number of faces and points
        // Use the buffer's version (set in encode_header) for version checks
        let major = out_buffer.version_major();
        let minor = out_buffer.version_minor();
        if !uses_varint_encoding(major, minor) {
            out_buffer.encode_u32(mesh.num_faces() as u32);
            out_buffer.encode_u32(mesh.num_points() as u32);
        } else {
            out_buffer.encode_varint(mesh.num_faces() as u64);
            out_buffer.encode_varint(mesh.num_points() as u64);
        }

        if mesh.num_faces() > 0 && mesh.num_points() > 0 {
            out_buffer.encode_u8(1); // Raw connectivity
            if mesh.num_points() < 256 {
                for face_id in 0..mesh.num_faces() {
                    let face = mesh.face(FaceIndex(face_id as u32));
                    for i in 0..3 {
                        out_buffer.encode_u8(face[i].0 as u8);
                    }
                }
            } else if mesh.num_points() < 65536 {
                for face_id in 0..mesh.num_faces() {
                    let face = mesh.face(FaceIndex(face_id as u32));
                    for i in 0..3 {
                        out_buffer.encode_u16(face[i].0 as u16);
                    }
                }
            } else if mesh.num_points() < (1 << 21) {
                // Use varint encoding for indices when points fit in 21 bits
                // This matches C++ behavior for better compression
                for face_id in 0..mesh.num_faces() {
                    let face = mesh.face(FaceIndex(face_id as u32));
                    for i in 0..3 {
                        out_buffer.encode_varint(face[i].0 as u64);
                    }
                }
            } else {
                // Default: use u32 for very large meshes
                for face_id in 0..mesh.num_faces() {
                    let face = mesh.face(FaceIndex(face_id as u32));
                    for i in 0..3 {
                        out_buffer.encode_u32(face[i].0);
                    }
                }
            }
        }

        // Identity permutation for sequential encoding
        self.point_ids = (0..mesh.num_points())
            .map(|i| PointIndex(i as u32))
            .collect();

        Ok(())
    }

    fn encode_attributes(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        // NOTE: Unlike the decoder, the encoder does NOT need to apply UpdatePointToAttributeIndexMapping
        // because the attribute still has identity mapping. The encoder uses the point_ids array
        // (from edgebreaker traversal) to determine the order in which to process points, and
        // mapped_index with identity mapping just returns the point index directly.

        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");

        let method_int = self.options.get_global_int("encoding_method", -1);
        // Match C++ behavior: if encoding_method is not set (-1),
        // use Edgebreaker for all options except speed == 10
        let is_edgebreaker = if method_int == -1 {
            self.options.get_speed() != 10
        } else {
            method_int == 1
        };

        if is_edgebreaker && !self.use_single_connectivity {
            return self.encode_edgebreaker_attributes_split(out_buffer);
        }

        // Encode number of attribute decoders (u8).
        // For both sequential and edgebreaker with single-connectivity mode:
        // there's only ONE attribute encoder containing ALL attributes.
        // This matches C++ behavior when use_single_connectivity_ = true (speed >= 6).
        let num_attributes = mesh.num_attributes();
        let num_encoders = if num_attributes > 0 { 1 } else { 0 };
        // Use the buffer's version (set in encode_header) for version checks.
        let major = out_buffer.version_major();
        let minor = out_buffer.version_minor();

        out_buffer.encode_u8(num_encoders as u8);

        // Phase 1: attributes decoder identifiers.
        // For single-encoder mode: one encoder with att_data_id = -1 (uses position connectivity)
        if num_encoders > 0 && is_edgebreaker {
            // att_data_id (i8), encoder_type (u8), traversal_method (u8)
            // -1 means use position connectivity (single connectivity mode)
            out_buffer.encode_u8((-1i8) as u8); // att_data_id = -1
            out_buffer.encode_u8(0); // element_type = MESH_VERTEX_ATTRIBUTE

            // Traversal method was added in bitstream 1.2. Older streams
            // default to DEPTH_FIRST on decode and must not carry the byte.
            if crate::version::bitstream_version(major, minor) >= 0x0102 {
                // PREDICTION_DEGREE (1) for speed 0, DEPTH_FIRST (0) otherwise.
                // This must match the traversal used in MeshEdgebreakerEncoder.
                let encoding_speed = self.options.get_speed();
                let traversal_method: u8 = if encoding_speed == 0 { 1 } else { 0 };
                out_buffer.encode_u8(traversal_method);
            }
        }
        // For sequential, nothing is written in phase 1 (EncodeAttributesEncoderIdentifier does nothing)

        let mut decoder_types: Vec<u8> = Vec::with_capacity(mesh.num_attributes() as usize);

        // Phase 2: Encode attribute encoder data
        // Both sequential and edgebreaker now use single-encoder mode:
        //   - Write num_attrs = total attributes
        //   - Write all attribute metadata
        //   - Write all decoder types

        if num_encoders > 0 {
            // Single encoder with all attributes (single-connectivity mode for edgebreaker)
            // Write num_attrs = total number of attributes
            if !uses_varint_encoding(major, minor) {
                out_buffer.encode_u32(mesh.num_attributes() as u32);
            } else {
                out_buffer.encode_varint(mesh.num_attributes() as u64);
            }

            // Write all attribute metadata first
            for i in 0..mesh.num_attributes() {
                let att = mesh.attribute(i);

                #[cfg(feature = "debug_logs")]
                {
                    debug_log!("DEBUG: Encoder encoding attribute {} metadata. Type: {:?}, Components: {}, Data: {:?}", i, att.attribute_type(), att.num_components(), att.data_type());
                }
                out_buffer.encode_u8(att.attribute_type() as u8);
                out_buffer.encode_u8(att.data_type() as u8);
                out_buffer.encode_u8(att.num_components());
                out_buffer.encode_u8(if att.normalized() { 1 } else { 0 });

                if !uses_varint_unique_id(major, minor) {
                    out_buffer.encode_u16(att.unique_id() as u16);
                } else {
                    out_buffer.encode_varint(att.unique_id() as u64);
                }
            }

            // Write all decoder types after all metadata (SequentialAttributeEncodersController pattern)
            for i in 0..mesh.num_attributes() {
                let att = mesh.attribute(i);
                let quantization_bits = self.options.get_attribute_int(i, "quantization_bits", -1);
                let is_quantized = quantization_bits > 0
                    && (att.data_type() == DataType::Float32
                        || att.data_type() == DataType::Float64);
                let is_normal = att.attribute_type() == GeometryAttributeType::Normal;

                let decoder_type: u8 = if is_quantized {
                    if is_normal {
                        3
                    } else {
                        2
                    }
                } else if att.data_type() != DataType::Float32 {
                    1
                } else {
                    0
                };
                out_buffer.encode_u8(decoder_type);
                decoder_types.push(decoder_type);
            }
        }

        // Phase 3: Encode attribute values (all attributes first)
        // C++ order: all EncodePortableAttribute calls, then all EncodeDataNeededByPortableTransform calls

        // Store transforms and encoders for later use in transform data encoding
        let mut quantization_transforms: Vec<Option<AttributeQuantizationTransform>> = Vec::new();
        let mut portable_attributes: Vec<Option<PointAttribute>> = Vec::new();
        let mut normal_encoders: Vec<Option<SequentialNormalAttributeEncoder>> = Vec::new();

        // First pass: encode all attribute VALUES
        for i in 0..mesh.num_attributes() {
            let att = mesh.attribute(i);
            let decoder_type = decoder_types[i as usize];
            let quantization_bits = self.options.get_attribute_int(i, "quantization_bits", -1);

            match decoder_type {
                3 => {
                    // Normal attribute with octahedral encoding
                    let mut encoder = SequentialNormalAttributeEncoder::new();
                    if !encoder.init(
                        self.point_cloud().expect("point_cloud set"),
                        i,
                        &self.options,
                    ) {
                        return Err(DracoError::DracoError(
                            "Failed to init normal encoder".to_string(),
                        ));
                    }
                    if !encoder.encode_values(
                        self.point_cloud().expect("point_cloud set"),
                        &self.point_ids,
                        out_buffer,
                        &self.options,
                        self,
                    ) {
                        return Err(DracoError::DracoError(
                            "Failed to encode normal values".to_string(),
                        ));
                    }
                    normal_encoders.push(Some(encoder));
                    quantization_transforms.push(None);
                    portable_attributes.push(None);
                }
                2 => {
                    // Quantized attribute (mapping already applied at start of encode_attributes)
                    let mut q_transform = AttributeQuantizationTransform::new();
                    if !q_transform.compute_parameters(att, quantization_bits) {
                        return Err(DracoError::DracoError(
                            "Failed to compute quantization parameters".to_string(),
                        ));
                    }
                    let mut portable = PointAttribute::default();
                    if !q_transform.transform_attribute(att, &self.point_ids, &mut portable) {
                        return Err(DracoError::DracoError(
                            "Failed to quantize attribute".to_string(),
                        ));
                    }

                    let mut att_encoder = SequentialIntegerAttributeEncoder::new();
                    att_encoder.init(i);
                    if !att_encoder.encode_values(
                        mesh as &PointCloud,
                        &self.point_ids,
                        out_buffer,
                        &self.options,
                        self,
                        Some(&portable),
                        true,
                    ) {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            i
                        )));
                    }

                    quantization_transforms.push(Some(q_transform));
                    portable_attributes.push(Some(portable));
                    normal_encoders.push(None);
                }
                1 => {
                    // Integer attribute
                    let mut att_encoder = SequentialIntegerAttributeEncoder::new();
                    att_encoder.init(i);
                    if !att_encoder.encode_values(
                        mesh as &PointCloud,
                        &self.point_ids,
                        out_buffer,
                        &self.options,
                        self,
                        None,
                        true,
                    ) {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            i
                        )));
                    }
                    quantization_transforms.push(None);
                    portable_attributes.push(None);
                    normal_encoders.push(None);
                }
                0 => {
                    // Generic/float attribute
                    let mut att_encoder = SequentialAttributeEncoder::new();
                    att_encoder.init(i);
                    if !att_encoder.encode_values(mesh as &PointCloud, &self.point_ids, out_buffer)
                    {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            i
                        )));
                    }
                    quantization_transforms.push(None);
                    portable_attributes.push(None);
                    normal_encoders.push(None);
                }
                _ => {
                    return Err(DracoError::DracoError(format!(
                        "Unsupported encoder type {}",
                        decoder_type
                    )));
                }
            }
        }

        // Second pass: encode all TRANSFORM DATA
        for i in 0..mesh.num_attributes() {
            let decoder_type = decoder_types[i as usize];

            match decoder_type {
                3 => {
                    // Normal attribute - encode octahedral transform data
                    let bitstream_version = crate::version::bitstream_version(major, minor);
                    if bitstream_version != 0 && bitstream_version < 0x0200 {
                        continue;
                    }
                    if let Some(ref encoder) = normal_encoders[i as usize] {
                        if !encoder.encode_data_needed_by_portable_transform(out_buffer) {
                            return Err(DracoError::DracoError(
                                "Failed to encode normal transform data".to_string(),
                            ));
                        }
                    }
                }
                2 => {
                    // Quantized attribute - encode quantization parameters
                    if let Some(ref q_transform) = quantization_transforms[i as usize] {
                        if !q_transform.encode_parameters(out_buffer) {
                            return Err(DracoError::DracoError(
                                "Failed to encode quantization parameters".to_string(),
                            ));
                        }
                    }
                }
                1 | 0 => {
                    // No transform data for integer/generic attributes
                }
                _ => {}
            }
        }

        Ok(())
    }

    fn encode_edgebreaker_attributes_split(&mut self, out_buffer: &mut EncoderBuffer) -> Status {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let mut groups: Vec<(i8, Vec<i32>)> = Vec::new();
        let mut position_attrs = Vec::new();
        for i in 0..mesh.num_attributes() {
            if mesh.attribute(i).attribute_type() == GeometryAttributeType::Position {
                position_attrs.push(i);
            }
        }
        if !position_attrs.is_empty() {
            groups.push((-1, position_attrs));
        }
        for (data_id, attr_conn) in self.edgebreaker_attribute_connectivity.iter().enumerate() {
            groups.push((data_id as i8, vec![attr_conn.attribute_id]));
        }

        out_buffer.encode_u8(groups.len() as u8);

        let major = out_buffer.version_major();
        let minor = out_buffer.version_minor();
        let writes_traversal_method = crate::version::bitstream_version(major, minor) >= 0x0102;
        let traversal_method: u8 = if self.options.get_speed() == 0 { 1 } else { 0 };
        for (att_data_id, _) in &groups {
            out_buffer.encode_u8(*att_data_id as u8);
            let element_type = if *att_data_id >= 0
                && !self.edgebreaker_attribute_connectivity[*att_data_id as usize].no_interior_seams
            {
                1 // MESH_CORNER_ATTRIBUTE
            } else {
                0 // MESH_VERTEX_ATTRIBUTE
            };
            out_buffer.encode_u8(element_type);
            if writes_traversal_method {
                out_buffer.encode_u8(traversal_method);
            }
        }

        let mut decoder_types_by_group: Vec<Vec<u8>> = Vec::with_capacity(groups.len());

        for (_, attr_ids) in &groups {
            if !uses_varint_encoding(major, minor) {
                out_buffer.encode_u32(attr_ids.len() as u32);
            } else {
                out_buffer.encode_varint(attr_ids.len() as u64);
            }

            for &att_id in attr_ids {
                let att = mesh.attribute(att_id);
                out_buffer.encode_u8(att.attribute_type() as u8);
                out_buffer.encode_u8(att.data_type() as u8);
                out_buffer.encode_u8(att.num_components());
                out_buffer.encode_u8(if att.normalized() { 1 } else { 0 });
                if !uses_varint_unique_id(major, minor) {
                    out_buffer.encode_u16(att.unique_id() as u16);
                } else {
                    out_buffer.encode_varint(att.unique_id() as u64);
                }
            }

            let mut decoder_types = Vec::with_capacity(attr_ids.len());
            for &att_id in attr_ids {
                let decoder_type = self.decoder_type_for_attribute(att_id);
                out_buffer.encode_u8(decoder_type);
                decoder_types.push(decoder_type);
            }
            decoder_types_by_group.push(decoder_types);
        }

        for (group_i, (att_data_id, attr_ids)) in groups.iter().enumerate() {
            let point_ids = if *att_data_id >= 0 {
                self.prepare_active_attribute_connectivity(*att_data_id as usize)?
            } else {
                self.active_corner_table = None;
                self.active_data_to_corner_map = None;
                self.active_vertex_to_data_map = None;
                self.point_ids.clone()
            };

            self.encode_attribute_group_values(
                attr_ids,
                &decoder_types_by_group[group_i],
                &point_ids,
                out_buffer,
            )?;
        }

        self.active_corner_table = None;
        self.active_data_to_corner_map = None;
        self.active_vertex_to_data_map = None;
        Ok(())
    }

    fn decoder_type_for_attribute(&self, att_id: i32) -> u8 {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let att = mesh.attribute(att_id);
        let quantization_bits = self
            .options
            .get_attribute_int(att_id, "quantization_bits", -1);
        let is_quantized = quantization_bits > 0
            && (att.data_type() == DataType::Float32 || att.data_type() == DataType::Float64);
        let is_normal = att.attribute_type() == GeometryAttributeType::Normal;

        if is_quantized {
            if is_normal {
                3
            } else {
                2
            }
        } else if att.data_type() != DataType::Float32 {
            1
        } else {
            0
        }
    }

    fn prepare_active_attribute_connectivity(
        &mut self,
        data_id: usize,
    ) -> Result<Vec<PointIndex>, DracoError> {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let base_ct = self
            .corner_table
            .as_ref()
            .ok_or_else(|| DracoError::DracoError("corner_table must be set".to_string()))?;
        let attr_conn = self
            .edgebreaker_attribute_connectivity
            .get(data_id)
            .ok_or_else(|| {
                DracoError::DracoError("Invalid attribute connectivity id".to_string())
            })?;

        if attr_conn.no_interior_seams {
            self.active_corner_table = None;
            self.active_data_to_corner_map = None;
            self.active_vertex_to_data_map = None;
            return Ok(self.point_ids.clone());
        }

        let mut attr_ct = base_ct.clone();
        for c_idx in 0..attr_conn.seam_edges.len() {
            if !attr_conn.seam_edges[c_idx] {
                continue;
            }
            let c = crate::geometry_indices::CornerIndex(c_idx as u32);
            let opp = attr_ct.opposite(c);
            if opp != crate::geometry_indices::INVALID_CORNER_INDEX {
                attr_ct.set_opposite(c, crate::geometry_indices::INVALID_CORNER_INDEX);
                attr_ct.set_opposite(opp, crate::geometry_indices::INVALID_CORNER_INDEX);
            }
        }
        let base_num_vertices = attr_ct.num_vertices();
        if !attr_ct.compute_vertex_corners(base_num_vertices) {
            return Err(DracoError::DracoError(
                "Failed to compute attribute seam corner table".to_string(),
            ));
        }

        let mut point_ids = Vec::with_capacity(attr_ct.vertex_corners.len());
        let mut data_to_corner_map = Vec::with_capacity(attr_ct.vertex_corners.len());
        let mut vertex_to_data_map = vec![-1i32; attr_ct.num_vertices()];
        for (data_id, &corner) in attr_ct.vertex_corners.iter().enumerate() {
            if corner == crate::geometry_indices::INVALID_CORNER_INDEX {
                point_ids.push(PointIndex(0));
                data_to_corner_map.push(crate::geometry_indices::INVALID_CORNER_INDEX.0);
                continue;
            }
            let face = mesh.face(FaceIndex(corner.0 / 3));
            let point_id = face[(corner.0 % 3) as usize];
            point_ids.push(point_id);
            data_to_corner_map.push(corner.0);
            let vertex = attr_ct.vertex(corner);
            if vertex != crate::geometry_indices::INVALID_VERTEX_INDEX
                && (vertex.0 as usize) < vertex_to_data_map.len()
            {
                vertex_to_data_map[vertex.0 as usize] = data_id as i32;
            }
        }

        self.active_corner_table = Some(attr_ct);
        self.active_data_to_corner_map = Some(data_to_corner_map);
        self.active_vertex_to_data_map = Some(vertex_to_data_map);
        Ok(point_ids)
    }

    fn encode_attribute_group_values(
        &mut self,
        attr_ids: &[i32],
        decoder_types: &[u8],
        point_ids: &[PointIndex],
        out_buffer: &mut EncoderBuffer,
    ) -> Status {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let mut quantization_transforms: Vec<Option<AttributeQuantizationTransform>> = Vec::new();
        let mut normal_encoders: Vec<Option<SequentialNormalAttributeEncoder>> = Vec::new();

        for (local_i, &att_id) in attr_ids.iter().enumerate() {
            let att = mesh.attribute(att_id);
            let decoder_type = decoder_types[local_i];
            let quantization_bits = self
                .options
                .get_attribute_int(att_id, "quantization_bits", -1);

            match decoder_type {
                3 => {
                    let mut encoder = SequentialNormalAttributeEncoder::new();
                    if !encoder.init(
                        self.point_cloud().expect("point_cloud set"),
                        att_id,
                        &self.options,
                    ) {
                        return Err(DracoError::DracoError(
                            "Failed to init normal encoder".to_string(),
                        ));
                    }
                    if !encoder.encode_values(
                        self.point_cloud().expect("point_cloud set"),
                        point_ids,
                        out_buffer,
                        &self.options,
                        self,
                    ) {
                        return Err(DracoError::DracoError(
                            "Failed to encode normal values".to_string(),
                        ));
                    }
                    normal_encoders.push(Some(encoder));
                    quantization_transforms.push(None);
                }
                2 => {
                    let mut q_transform = AttributeQuantizationTransform::new();
                    if !q_transform.compute_parameters(att, quantization_bits) {
                        return Err(DracoError::DracoError(
                            "Failed to compute quantization parameters".to_string(),
                        ));
                    }
                    let mut portable = PointAttribute::default();
                    if !q_transform.transform_attribute(att, point_ids, &mut portable) {
                        return Err(DracoError::DracoError(
                            "Failed to quantize attribute".to_string(),
                        ));
                    }

                    let mut att_encoder = SequentialIntegerAttributeEncoder::new();
                    att_encoder.init(att_id);
                    if !att_encoder.encode_values(
                        mesh as &PointCloud,
                        point_ids,
                        out_buffer,
                        &self.options,
                        self,
                        Some(&portable),
                        true,
                    ) {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            att_id
                        )));
                    }
                    quantization_transforms.push(Some(q_transform));
                    normal_encoders.push(None);
                }
                1 => {
                    let mut att_encoder = SequentialIntegerAttributeEncoder::new();
                    att_encoder.init(att_id);
                    if !att_encoder.encode_values(
                        mesh as &PointCloud,
                        point_ids,
                        out_buffer,
                        &self.options,
                        self,
                        None,
                        true,
                    ) {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            att_id
                        )));
                    }
                    quantization_transforms.push(None);
                    normal_encoders.push(None);
                }
                0 => {
                    let mut att_encoder = SequentialAttributeEncoder::new();
                    att_encoder.init(att_id);
                    if !att_encoder.encode_values(mesh as &PointCloud, point_ids, out_buffer) {
                        return Err(DracoError::DracoError(format!(
                            "Failed to encode attribute {}",
                            att_id
                        )));
                    }
                    quantization_transforms.push(None);
                    normal_encoders.push(None);
                }
                _ => {
                    return Err(DracoError::DracoError(format!(
                        "Unsupported encoder type {}",
                        decoder_type
                    )));
                }
            }
        }

        for (local_i, &decoder_type) in decoder_types.iter().enumerate() {
            match decoder_type {
                3 => {
                    let major = out_buffer.version_major();
                    let minor = out_buffer.version_minor();
                    let bitstream_version = crate::version::bitstream_version(major, minor);
                    if bitstream_version != 0 && bitstream_version < 0x0200 {
                        continue;
                    }
                    if let Some(ref encoder) = normal_encoders[local_i] {
                        if !encoder.encode_data_needed_by_portable_transform(out_buffer) {
                            return Err(DracoError::DracoError(
                                "Failed to encode normal transform data".to_string(),
                            ));
                        }
                    }
                }
                2 => {
                    if let Some(ref q_transform) = quantization_transforms[local_i] {
                        if !q_transform.encode_parameters(out_buffer) {
                            return Err(DracoError::DracoError(
                                "Failed to encode quantization parameters".to_string(),
                            ));
                        }
                    }
                }
                1 | 0 => {}
                _ => {}
            }
        }

        Ok(())
    }

    fn compute_number_of_encoded_faces(&mut self) {
        if let Some(ref mesh) = self.mesh {
            self.num_encoded_faces = mesh.num_faces();
        }
    }

    fn build_encoded_mesh_info(&mut self) -> Status {
        let num_attributes = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding")
            .num_attributes();
        let mut attributes = Vec::with_capacity(num_attributes as usize);
        let mut encoded_num_points = self.point_ids.len();

        for att_id in 0..num_attributes {
            let point_ids = self.encoded_point_ids_for_attribute(att_id)?;
            let num_encoded_values = point_ids.len();
            encoded_num_points = encoded_num_points.max(num_encoded_values);

            let (position_min, position_max) =
                self.position_bounds_for_attribute(att_id, &point_ids)?;
            let att = self
                .mesh
                .as_ref()
                .expect("mesh must be set before encoding")
                .attribute(att_id);
            attributes.push(EncodedAttributeInfo {
                source_attribute_id: att_id,
                attribute_type: att.attribute_type(),
                data_type: att.data_type(),
                num_components: att.num_components(),
                normalized: att.normalized(),
                unique_id: att.unique_id(),
                num_encoded_values,
                position_min,
                position_max,
            });
        }

        let (source_num_points, num_faces) = self
            .mesh
            .as_ref()
            .map(|mesh| (mesh.num_points(), mesh.num_faces()))
            .expect("mesh must be set before encoding");
        if self.method == 0 {
            encoded_num_points = source_num_points;
        } else {
            encoded_num_points = self.encoded_num_points_for_mesh(encoded_num_points)?;
        }

        self.active_corner_table = None;
        self.active_data_to_corner_map = None;
        self.active_vertex_to_data_map = None;
        self.encoded_mesh_info = Some(EncodedMeshInfo {
            encoding_method: self.method,
            num_encoded_faces: num_faces,
            num_encoded_points: encoded_num_points,
            attributes,
        });
        Ok(())
    }

    fn encoded_point_ids_for_attribute(
        &mut self,
        att_id: i32,
    ) -> Result<Vec<PointIndex>, DracoError> {
        if self.method == 0 || self.use_single_connectivity {
            return Ok(self.point_ids.clone());
        }

        if let Some(data_id) = self
            .edgebreaker_attribute_connectivity
            .iter()
            .position(|connectivity| connectivity.attribute_id == att_id)
        {
            return self.prepare_active_attribute_connectivity(data_id);
        }

        Ok(self.point_ids.clone())
    }

    fn encoded_num_points_for_mesh(&mut self, base_num_points: usize) -> Result<usize, DracoError> {
        if self.method == 0 || self.use_single_connectivity {
            return Ok(base_num_points);
        }

        let mut num_points = base_num_points;
        for data_id in 0..self.edgebreaker_attribute_connectivity.len() {
            if self.edgebreaker_attribute_connectivity[data_id].no_interior_seams {
                continue;
            }
            let point_ids = self.prepare_active_attribute_connectivity(data_id)?;
            num_points = num_points.max(point_ids.len());
        }
        self.active_corner_table = None;
        self.active_data_to_corner_map = None;
        self.active_vertex_to_data_map = None;
        Ok(num_points)
    }

    fn position_bounds_for_attribute(
        &self,
        att_id: i32,
        point_ids: &[PointIndex],
    ) -> Result<PositionBounds, DracoError> {
        let mesh = self
            .mesh
            .as_ref()
            .expect("mesh must be set before encoding");
        let att = mesh.attribute(att_id);
        if att.attribute_type() != GeometryAttributeType::Position {
            return Ok((None, None));
        }
        if att.num_components() != 3 || att.data_type() != DataType::Float32 {
            return Ok((None, None));
        }

        if self.decoder_type_for_attribute(att_id) == 2 {
            let quantization_bits = self
                .options
                .get_attribute_int(att_id, "quantization_bits", -1);
            let mut q_transform = AttributeQuantizationTransform::new();
            if !q_transform.compute_parameters(att, quantization_bits) {
                return Err(DracoError::DracoError(
                    "Failed to compute position quantization parameters".to_string(),
                ));
            }

            let mut portable = PointAttribute::default();
            if !q_transform.transform_attribute(att, point_ids, &mut portable) {
                return Err(DracoError::DracoError(
                    "Failed to quantize position attribute for encoded mesh info".to_string(),
                ));
            }

            let mut dequantized = PointAttribute::new();
            dequantized.try_init(
                GeometryAttributeType::Position,
                3,
                DataType::Float32,
                false,
                portable.size(),
            )?;
            if !q_transform.inverse_transform_attribute(&portable, &mut dequantized) {
                return Err(DracoError::DracoError(
                    "Failed to dequantize position attribute for encoded mesh info".to_string(),
                ));
            }

            return Self::position_bounds_from_attribute(&dequantized, &[]);
        }

        Self::position_bounds_from_attribute(att, point_ids)
    }

    fn position_bounds_from_attribute(
        att: &PointAttribute,
        point_ids: &[PointIndex],
    ) -> Result<PositionBounds, DracoError> {
        let count = if point_ids.is_empty() {
            att.size()
        } else {
            point_ids.len()
        };
        if count == 0 {
            return Ok((None, None));
        }

        let stride = usize::try_from(att.byte_stride()).map_err(|_| {
            DracoError::DracoError("Position attribute has invalid byte stride".to_string())
        })?;
        let bytes = att.buffer().data();
        let mut min = [f32::INFINITY; 3];
        let mut max = [f32::NEG_INFINITY; 3];

        for i in 0..count {
            let point = if point_ids.is_empty() {
                PointIndex(i as u32)
            } else {
                point_ids[i]
            };
            let value_index = att.mapped_index(point);
            if value_index == INVALID_ATTRIBUTE_VALUE_INDEX {
                return Err(DracoError::DracoError(
                    "Position attribute point map contains an invalid entry".to_string(),
                ));
            }

            let value_offset = (value_index.0 as usize)
                .checked_mul(stride)
                .ok_or_else(|| {
                    DracoError::DracoError("Position attribute offset overflow".to_string())
                })?;
            for component in 0..3 {
                let offset = value_offset
                    .checked_add(component * DataType::Float32.byte_length())
                    .ok_or_else(|| {
                        DracoError::DracoError("Position attribute offset overflow".to_string())
                    })?;
                let end = offset
                    .checked_add(DataType::Float32.byte_length())
                    .ok_or_else(|| {
                        DracoError::DracoError("Position attribute offset overflow".to_string())
                    })?;
                let Some(component_bytes) = bytes.get(offset..end) else {
                    return Err(DracoError::DracoError(
                        "Position attribute buffer is shorter than metadata".to_string(),
                    ));
                };
                let value = f32::from_le_bytes([
                    component_bytes[0],
                    component_bytes[1],
                    component_bytes[2],
                    component_bytes[3],
                ]);
                min[component] = min[component].min(value);
                max[component] = max[component].max(value);
            }
        }

        Ok((
            Some(min.into_iter().map(f64::from).collect()),
            Some(max.into_iter().map(f64::from).collect()),
        ))
    }
}

impl Default for MeshEncoder {
    fn default() -> Self {
        Self::new()
    }
}