draco-core 2.3.2

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
// Test uses array indexing patterns that mirror C++ test structure for clarity.
// needless_range_loop: for i in 0..n { arr[i] } makes index-based operations explicit
#![allow(clippy::needless_range_loop)]

use draco_core::decoder_buffer::DecoderBuffer;
use draco_core::draco_types::DataType;
use draco_core::encoder_buffer::EncoderBuffer;
use draco_core::encoder_options::EncoderOptions;
use draco_core::geometry_attribute::{GeometryAttributeType, PointAttribute};
use draco_core::geometry_indices::FaceIndex;
use draco_core::mesh::Mesh;
use draco_core::mesh_decoder::MeshDecoder;
use draco_core::mesh_encoder::MeshEncoder;
use draco_core::point_cloud::PointCloud;
use draco_core::point_cloud_decoder::PointCloudDecoder;
use draco_core::point_cloud_encoder::PointCloudEncoder;
use draco_core::version::{DEFAULT_MESH_VERSION, DEFAULT_POINT_CLOUD_VERSION};
#[cfg(feature = "legacy_bitstream_encode")]
use draco_core::DracoError;

/// The oldest point-cloud bitstream this crate still writes when asked for it
/// explicitly. It is no longer any method's default -- upstream writes 2.3 for
/// every point cloud -- so this test names it rather than importing a constant.
const LEGACY_POINT_CLOUD_VERSION: (u8, u8) = (1, 3);

fn create_test_pc() -> PointCloud {
    let mut pc = PointCloud::new();
    let mut pos_att = PointAttribute::new();
    let num_points = 3;
    pos_att.init(
        GeometryAttributeType::Position,
        3,
        DataType::Float32,
        false,
        num_points,
    );
    let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
    let buffer = pos_att.buffer_mut();
    for i in 0..9 {
        buffer.write(i * 4, &positions[i].to_le_bytes());
    }
    pc.add_attribute(pos_att);
    pc
}

fn create_test_mesh() -> Mesh {
    let mut mesh = Mesh::new();
    let mut pos_att = PointAttribute::new();
    let num_points = 3;
    pos_att.init(
        GeometryAttributeType::Position,
        3,
        DataType::Float32,
        false,
        num_points,
    );
    let positions: [f32; 9] = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
    let buffer = pos_att.buffer_mut();
    for i in 0..9 {
        buffer.write(i * 4, &positions[i].to_le_bytes());
    }
    mesh.add_attribute(pos_att);
    mesh.set_num_faces(1);
    mesh.set_face(FaceIndex(0), [0u32.into(), 1u32.into(), 2u32.into()]);
    mesh
}

#[test]
fn test_mesh_roundtrip_v1_3() {
    let mesh = create_test_mesh();
    let mut encoder = MeshEncoder::new();
    encoder.set_mesh(mesh);

    let mut options = EncoderOptions::new();
    // Use legacy v1.3 header for testing sequential encoding with legacy version.
    // We do NOT set quantization_bits here: the Rust encoder never writes the old
    // v < 2.0 quantization-params-before-symbols layout, so round-tripping
    // quantized attributes at v1.3 is not supported (matches current C++ behavior).
    options.set_version(1, 3);
    options.set_encoding_method(0); // Sequential

    let mut enc_buffer = EncoderBuffer::new();
    assert!(encoder.encode(&options, &mut enc_buffer).is_ok());

    let mut dec_buffer = DecoderBuffer::new(enc_buffer.data());
    let mut decoded_mesh = Mesh::new();
    let mut decoder = MeshDecoder::new();
    assert!(decoder.decode(&mut dec_buffer, &mut decoded_mesh).is_ok());

    assert_eq!(decoded_mesh.num_points(), 3);
    assert_eq!(decoded_mesh.num_faces(), 1);
}

#[test]
fn test_mesh_roundtrip_v2_2() {
    let mesh = create_test_mesh();
    let mut encoder = MeshEncoder::new();
    encoder.set_mesh(mesh);

    let mut options = EncoderOptions::new();
    options.set_version(DEFAULT_MESH_VERSION.0, DEFAULT_MESH_VERSION.1);
    options.set_encoding_method(1); // Edgebreaker
    options.set_attribute_int(0, "quantization_bits", 14);

    let mut enc_buffer = EncoderBuffer::new();
    assert!(encoder.encode(&options, &mut enc_buffer).is_ok());

    let mut dec_buffer = DecoderBuffer::new(enc_buffer.data());
    let mut decoded_mesh = Mesh::new();
    let mut decoder = MeshDecoder::new();
    assert!(decoder.decode(&mut dec_buffer, &mut decoded_mesh).is_ok());

    assert_eq!(decoded_mesh.num_points(), 3);
    assert_eq!(decoded_mesh.num_faces(), 1);
}

/// The decoded positions, sorted, so a comparison does not depend on the point
/// order — the KD-tree coder reorders points by construction.
fn sorted_positions(pc: &PointCloud) -> Vec<[i32; 3]> {
    let att = pc.attribute(pc.named_attribute_id(GeometryAttributeType::Position));
    let stride = att.byte_stride() as usize;
    let mut out = Vec::with_capacity(att.size());
    for i in 0..att.size() {
        let mut position = [0i32; 3];
        for (k, component) in position.iter_mut().enumerate() {
            let mut bytes = [0u8; 4];
            att.buffer().read(i * stride + k * 4, &mut bytes);
            // 14-bit quantization over a unit range leaves an error near 6e-5;
            // rounding to 1e-3 keeps the comparison exact-valued while staying
            // far above it.
            *component = (f32::from_le_bytes(bytes) * 1000.0).round() as i32;
        }
        out.push(position);
    }
    out.sort_unstable();
    out
}

/// Every point cloud version this crate claims must return the geometry it was
/// given, not merely the right number of points.
///
/// These three tests used to assert `num_points == 3` and nothing else, which a
/// stream whose quantization parameters land in the wrong place survives
/// unchanged — the count is written in the header, well before anything that
/// could go wrong with the values.
fn assert_point_cloud_round_trips(major: u8, minor: u8, method: i32) {
    let pc = create_test_pc();
    let expected = sorted_positions(&pc);

    let mut encoder = PointCloudEncoder::new();
    encoder.set_point_cloud(pc);

    let mut options = EncoderOptions::new();
    options.set_version(major, minor);
    options.set_encoding_method(method);
    options.set_attribute_int(0, "quantization_bits", 14);

    let mut enc_buffer = EncoderBuffer::new();
    encoder
        .encode(&options, &mut enc_buffer)
        .unwrap_or_else(|e| panic!("v{major}.{minor} method {method} encode: {e:?}"));

    let mut dec_buffer = DecoderBuffer::new(enc_buffer.data());
    let mut decoded_pc = PointCloud::new();
    PointCloudDecoder::new()
        .decode(&mut dec_buffer, &mut decoded_pc)
        .unwrap_or_else(|e| panic!("v{major}.{minor} method {method} decode: {e:?}"));

    assert_eq!(
        decoded_pc.num_points(),
        3,
        "v{major}.{minor} method {method}: point count"
    );
    assert_eq!(
        sorted_positions(&decoded_pc),
        expected,
        "v{major}.{minor} method {method}: positions"
    );
}

#[test]
fn test_point_cloud_roundtrip_v1_3() {
    assert_point_cloud_round_trips(
        LEGACY_POINT_CLOUD_VERSION.0,
        LEGACY_POINT_CLOUD_VERSION.1,
        0,
    );
}

#[test]
fn test_point_cloud_roundtrip_v2_3() {
    assert_point_cloud_round_trips(
        DEFAULT_POINT_CLOUD_VERSION.0,
        DEFAULT_POINT_CLOUD_VERSION.1,
        1, // KD-tree
    );
}

/// The sequential point-cloud coder at its own newest claimed version, which
/// neither of the two tests above reached: 1.3 exercises sequential and 2.3
/// exercised the KD-tree.
#[test]
fn a_sequential_point_cloud_round_trips_at_2_3() {
    assert_point_cloud_round_trips(
        DEFAULT_POINT_CLOUD_VERSION.0,
        DEFAULT_POINT_CLOUD_VERSION.1,
        0,
    );
}

/// A claimed version must survive the index-width boundary it straddles.
///
/// Sequential connectivity picks its index width from the point count: u8 below
/// 256, u16 below 65536, then varints — but the decoder only reads varints from
/// 2.2, so at 1.3 the encoder wrote varints the decoder read as u32. The stream
/// decoded without error and with the right face count, and the faces were
/// different ones. Counts are exactly what a test must not stop at here.
#[test]
#[cfg(feature = "legacy_bitstream_encode")]
fn a_sequential_mesh_at_1_3_survives_the_varint_index_boundary() {
    use draco_core::geometry_indices::FaceIndex;

    // 257 x 257 = 66,049 points, just past the 65,536 boundary.
    let mesh = grid_mesh(257);
    assert!(
        mesh.num_points() > 65536,
        "the boundary is the point of this"
    );

    let mut options = EncoderOptions::new();
    options.set_version(1, 3);
    options.set_encoding_method(0);

    let mut encoder = MeshEncoder::new();
    encoder.set_mesh(mesh.clone());
    let mut buffer = EncoderBuffer::new();
    encoder.encode(&options, &mut buffer).expect("1.3 encode");

    let mut decoded = Mesh::new();
    MeshDecoder::new()
        .decode(&mut DecoderBuffer::new(buffer.data()), &mut decoded)
        .expect("1.3 decode");

    assert_eq!(decoded.num_faces(), mesh.num_faces(), "face count");
    for face_id in 0..mesh.num_faces() {
        let index = FaceIndex(face_id as u32);
        assert_eq!(
            decoded.face(index),
            mesh.face(index),
            "face {face_id} differs, so the index width disagreed"
        );
    }
}

/// Every EdgeBreaker traversal round-trips at every claimed pre-2.2 version.
///
/// The traversal is not a caller-visible option -- it follows from the speed and
/// the face count -- so a version request that works on a 2048-face mesh has to
/// work on a 162-face one, which takes a different path. The standard traversal
/// wrote its connectivity block in a buffer pinned to 2.2, so every case here
/// failed to decode at "start start-face bit decoding" until that buffer took
/// the target version like the valence branch beside it.
#[test]
#[cfg(feature = "legacy_bitstream_encode")]
fn every_edgebreaker_traversal_round_trips_at_every_claimed_version() {
    use draco_core::mesh_edgebreaker_encoder::{
        select_edgebreaker_traversal, EdgebreakerTraversal,
    };

    // 2048 faces, over the 1000-face floor below which no speed selects valence.
    let large = grid_mesh(33);
    // 162 faces, under it: the traversal is standard at every speed.
    let tiny = grid_mesh(10);

    let encode = |mesh: &Mesh, speed: i32, major: u8, minor: u8| {
        let mut options = EncoderOptions::new();
        options.set_version(major, minor);
        options.set_encoding_method(1); // EdgeBreaker
        options.set_global_int("encoding_speed", speed);
        options.set_global_int("decoding_speed", speed);
        let mut encoder = MeshEncoder::new();
        encoder.set_mesh(mesh.clone());
        let mut buffer = EncoderBuffer::new();
        encoder.encode(&options, &mut buffer).map(|()| buffer)
    };

    for (major, minor) in [(2u8, 2u8), (2, 1), (2, 0), (1, 2), (1, 1)] {
        for (mesh, speed, expected) in [
            (&large, 5, EdgebreakerTraversal::Standard),
            (&large, 0, EdgebreakerTraversal::Valence),
            (&tiny, 5, EdgebreakerTraversal::Standard),
            (&tiny, 0, EdgebreakerTraversal::Standard),
        ] {
            // Named so a failure says which traversal broke, not just which
            // speed: the mapping from speed to traversal is the thing that
            // makes this matrix worth running.
            assert_eq!(
                select_edgebreaker_traversal(speed as usize, mesh.num_faces(), false),
                expected,
                "{} faces at speed {speed}",
                mesh.num_faces()
            );
            let label = format!("v{major}.{minor}, {expected:?}, {} faces", mesh.num_faces());
            let buffer = encode(mesh, speed, major, minor)
                .unwrap_or_else(|e| panic!("{label}: encode: {e:?}"));
            let mut decoded = Mesh::new();
            MeshDecoder::new()
                .decode(&mut DecoderBuffer::new(buffer.data()), &mut decoded)
                .unwrap_or_else(|e| panic!("{label}: decode: {e:?}"));
            assert_eq!(decoded.num_faces(), mesh.num_faces(), "{label}: face count");
            // Not face by face: EdgeBreaker reorders vertices, so the geometry
            // is what survives, not the index buffer.
            assert_eq!(
                sorted_mesh_positions(&decoded),
                sorted_mesh_positions(mesh),
                "{label}: positions"
            );
        }
    }
}

/// A mesh with topology splits round-trips at every claimed version.
///
/// The split section changes shape three times across the table, and the
/// neighbouring traversal matrix reaches none of them, because a grid is a disc
/// and a disc produces no split events at all:
///
/// - below 1.2 an event is two absolute `u32` ids and a byte for the edge, with
///   no bit-coded section after them at all;
/// - from 1.2 it is a delta/varint pair per event and then the edge selectors
///   packed two bits each;
/// - from 2.2 the selector is one bit, and from 2.0 the event count is a varint
///   rather than a fixed `u32`.
///
/// The encoder only ever wrote the second and third forms, so a 1.1 stream
/// carried events the decoder read as absolute `u32`s -- silently, because the
/// count parses the same either way. Falsified by removing the `< 0x0102` arm
/// from `encode_split_data`: the 1.1 cases then fail, and every one of them
/// passes on a grid, which is what 1.1's previous round-trip test stood on.
#[test]
#[cfg(feature = "legacy_bitstream_encode")]
fn a_mesh_with_topology_splits_round_trips_at_every_claimed_version() {
    for (major, minor) in [(2u8, 2u8), (2, 1), (2, 0), (1, 2), (1, 1)] {
        // Both sides of the 1000-face floor, so the standard and valence
        // traversals each write their own connectivity block ahead of the same
        // event section.
        // The predictive traversal writes the same event section and is only
        // legal below 2.0, so it joins the matrix where it is allowed.
        for (n, speed, predictive) in [
            (10usize, 5i32, false),
            (33, 5, false),
            (33, 0, false),
            (33, 0, true),
        ] {
            if predictive && major >= 2 {
                continue;
            }
            let mesh = annulus_mesh(n);
            let mut options = EncoderOptions::new();
            options.set_version(major, minor);
            options.set_encoding_method(1); // EdgeBreaker
            options.set_global_int("encoding_speed", speed);
            options.set_global_int("decoding_speed", speed);
            if predictive {
                options.set_global_int("force_predictive_traversal", 1);
            }
            let traversal = if predictive { ", predictive" } else { "" };
            let label = format!("v{major}.{minor}, {n}x{n} at speed {speed}{traversal}");
            let decoded =
                round_trip(&mesh, &options).unwrap_or_else(|error| panic!("{label}: {error:?}"));
            assert_eq!(decoded.num_faces(), mesh.num_faces(), "{label}: face count");
            assert_eq!(
                sorted_mesh_positions(&decoded),
                sorted_mesh_positions(&mesh),
                "{label}: positions"
            );
        }
    }
}

/// Every attribute coding round-trips at every claimed version, values and all.
///
/// The version table alone cannot reach these: they depend on the attribute's
/// encoder, so one version request takes a different layout per attribute. Each
/// row below produced a stream this crate's own decoder rejected, and each has
/// its own cause -- inline quantization parameters below 2.0, and three
/// prediction schemes whose rANS size prefix is a u32 below 2.2 because
/// `RAnsBitEncoder` reads the width off the buffer it is handed and each of them
/// handed it a fresh, version-less one.
///
/// Compared against the 2.2 round-trip rather than the input mesh: quantization
/// is lossy, so the input is not what any version returns.
#[test]
#[cfg(feature = "legacy_bitstream_encode")]
fn every_attribute_coding_round_trips_at_every_claimed_version() {
    // A quantized non-normal attribute, whose parameters go inline below 2.0
    // and trailing at 2.0 and above.
    let quantized_position = |major, minor, method, speed| {
        let mut options = EncoderOptions::new();
        options.set_version(major, minor);
        options.set_encoding_method(method);
        options.set_global_int("encoding_speed", speed);
        options.set_global_int("decoding_speed", speed);
        options.set_attribute_int(0, "quantization_bits", 12);
        options
    };
    let mesh = grid_mesh(33);
    let reference = sorted_mesh_positions(
        &round_trip(&mesh, &quantized_position(2, 2, 1, 0)).expect("2.2 quantized"),
    );
    for (major, minor, method, speed) in [(2u8, 0u8, 1i32, 0i32), (1, 2, 1, 0), (1, 3, 0, 5)] {
        let decoded = round_trip(&mesh, &quantized_position(major, minor, method, speed))
            .unwrap_or_else(|e| panic!("v{major}.{minor} quantized: {e:?}"));
        assert_eq!(
            sorted_mesh_positions(&decoded),
            reference,
            "v{major}.{minor}: quantized positions"
        );
    }

    // A quantized normal takes the octahedron transform, which has its own
    // inline block one version boundary earlier.
    let mut normal_options = EncoderOptions::new();
    normal_options.set_version(1, 2);
    normal_options.set_encoding_method(1);
    normal_options.set_global_int("encoding_speed", 0);
    normal_options.set_global_int("decoding_speed", 0);
    normal_options.set_attribute_int(1, "quantization_bits", 10);
    round_trip(&grid_mesh_with_normals(33), &normal_options).expect("v1.2 quantized normal");

    // The three prediction schemes that carry a rANS stream of their own.
    // Scheme 5 is here because it was not in the original list: it broke the
    // same way and nothing tested it, which is what a refusal would have
    // shipped.
    for scheme in [3i32, 5, 6] {
        // Each scheme predicts one attribute kind, and forcing it onto another
        // is refused by `validate_prediction_schemes`.
        let mesh = if scheme == 6 {
            grid_mesh_with_normals(33)
        } else {
            grid_mesh_with_texcoords(33)
        };
        let scheme_options = |major, minor| {
            let mut options = EncoderOptions::new();
            options.set_version(major, minor);
            options.set_encoding_method(1);
            options.set_global_int("encoding_speed", 0);
            options.set_global_int("decoding_speed", 0);
            options.set_attribute_int(1, "prediction_scheme", scheme);
            options.set_attribute_int(1, "quantization_bits", 10);
            options
        };

        let reference = sorted_mesh_positions(
            &round_trip(&mesh, &scheme_options(2, 2))
                .unwrap_or_else(|e| panic!("scheme {scheme} at 2.2: {e:?}")),
        );
        for (major, minor) in [(2u8, 1u8), (2, 0), (1, 2)] {
            let decoded = round_trip(&mesh, &scheme_options(major, minor))
                .unwrap_or_else(|e| panic!("scheme {scheme} at {major}.{minor}: {e:?}"));
            assert_eq!(
                sorted_mesh_positions(&decoded),
                reference,
                "scheme {scheme} at {major}.{minor}: positions"
            );
        }
    }
}

/// Decoded positions sorted by bit pattern, so a comparison does not depend on
/// the vertex order the traversal produced.
#[cfg(feature = "legacy_bitstream_encode")]
fn sorted_mesh_positions(mesh: &Mesh) -> Vec<[u32; 3]> {
    let attribute = mesh.attribute(mesh.named_attribute_id(GeometryAttributeType::Position));
    let stride = attribute.byte_stride() as usize;
    let mut out = Vec::with_capacity(attribute.size());
    for i in 0..attribute.size() {
        let mut position = [0u32; 3];
        for (k, component) in position.iter_mut().enumerate() {
            let mut bytes = [0u8; 4];
            attribute.buffer().read(i * stride + k * 4, &mut bytes);
            *component = u32::from_le_bytes(bytes);
        }
        out.push(position);
    }
    out.sort_unstable();
    out
}

/// The decoded texture coordinates, sorted, as raw bit patterns.
///
/// Sorted because the traversal is free to number entries its own way; raw
/// because these are compared against another round trip's output rather than
/// against a value anyone computed, so a bit-for-bit match is the claim.
#[cfg(feature = "legacy_bitstream_encode")]
fn sorted_mesh_texcoords(mesh: &Mesh) -> Vec<[u32; 2]> {
    let attribute = mesh.attribute(mesh.named_attribute_id(GeometryAttributeType::TexCoord));
    let stride = attribute.byte_stride() as usize;
    let mut out = Vec::with_capacity(attribute.size());
    for i in 0..attribute.size() {
        let mut uv = [0u32; 2];
        for (k, component) in uv.iter_mut().enumerate() {
            let mut bytes = [0u8; 4];
            attribute.buffer().read(i * stride + k * 4, &mut bytes);
            *component = u32::from_le_bytes(bytes);
        }
        out.push(uv);
    }
    out.sort_unstable();
    out
}

/// Which half of a round trip failed. Both payloads exist for the panic
/// message; nothing matches on them, now that every claimed combination is
/// expected to succeed.
#[cfg(feature = "legacy_bitstream_encode")]
#[derive(Debug)]
enum RoundTripError {
    Encode(#[allow(dead_code)] DracoError),
    Decode(#[allow(dead_code)] DracoError),
}

/// Encode then decode, reporting which half failed.
#[cfg(feature = "legacy_bitstream_encode")]
fn round_trip(mesh: &Mesh, options: &EncoderOptions) -> Result<Mesh, RoundTripError> {
    let mut encoder = MeshEncoder::new();
    encoder.set_mesh(mesh.clone());
    let mut buffer = EncoderBuffer::new();
    encoder
        .encode(options, &mut buffer)
        .map_err(RoundTripError::Encode)?;
    let mut decoded = Mesh::new();
    MeshDecoder::new()
        .decode(&mut DecoderBuffer::new(buffer.data()), &mut decoded)
        .map_err(RoundTripError::Decode)?;
    Ok(decoded)
}

/// A grid whose texture coordinates part along the middle column.
///
/// The seam is what makes an attribute's connectivity differ from the mesh's:
/// two points share one position value and carry different UVs, so the corners
/// on either side of that column belong to one position vertex and two
/// attribute vertices. [`grid_mesh_with_texcoords`] cannot produce that -- one
/// UV per point leaves nothing to split -- and the encoder writes a seam bit
/// per edge only when there is a split to describe.
#[cfg(feature = "legacy_bitstream_encode")]
fn grid_mesh_with_uv_seam(n: usize) -> Mesh {
    use draco_core::geometry_indices::{AttributeValueIndex, PointIndex};

    let seam_column = n / 2;
    // One point per grid vertex, plus a second for every vertex on the seam
    // column: same position value, its own texture coordinate.
    let num_points = n * n + n;
    let point_of = |x: usize, y: usize, right_side: bool| -> u32 {
        if right_side && x == seam_column {
            (n * n + y) as u32
        } else {
            (y * n + x) as u32
        }
    };

    let mut mesh = Mesh::new();
    mesh.set_num_points(num_points);

    let mut position = PointAttribute::new();
    position.init(
        GeometryAttributeType::Position,
        3,
        DataType::Float32,
        false,
        n * n,
    );
    for y in 0..n {
        for x in 0..n {
            let offset = (y * n + x) * 12;
            position
                .buffer_mut()
                .write(offset, &(x as f32).to_le_bytes());
            position
                .buffer_mut()
                .write(offset + 4, &(y as f32).to_le_bytes());
            position
                .buffer_mut()
                .write(offset + 8, &(((x + y) % 5) as f32).to_le_bytes());
        }
    }
    position.set_explicit_mapping(num_points);
    for y in 0..n {
        for x in 0..n {
            position.set_point_map_entry(
                PointIndex((y * n + x) as u32),
                AttributeValueIndex((y * n + x) as u32),
            );
        }
        // The duplicate resolves to the same position value as the original.
        position.set_point_map_entry(
            PointIndex((n * n + y) as u32),
            AttributeValueIndex((y * n + seam_column) as u32),
        );
    }
    mesh.add_attribute(position);

    let mut uv = PointAttribute::new();
    uv.init(
        GeometryAttributeType::TexCoord,
        2,
        DataType::Float32,
        false,
        num_points,
    );
    for y in 0..n {
        for x in 0..n {
            let offset = (y * n + x) * 8;
            uv.buffer_mut()
                .write(offset, &(x as f32 / n as f32).to_le_bytes());
            uv.buffer_mut()
                .write(offset + 4, &(y as f32 / n as f32).to_le_bytes());
        }
        // The far side of the seam restarts the u axis, which is what a real
        // unwrap does and what makes the edge a seam rather than a duplicate.
        let offset = (n * n + y) * 8;
        uv.buffer_mut().write(offset, &0.0f32.to_le_bytes());
        uv.buffer_mut()
            .write(offset + 4, &(y as f32 / n as f32).to_le_bytes());
    }
    mesh.add_attribute(uv);

    mesh.set_num_faces((n - 1) * (n - 1) * 2);
    let mut face_id = 0;
    for y in 0..n - 1 {
        for x in 0..n - 1 {
            let right_side = x >= seam_column;
            let p0 = point_of(x, y, right_side);
            let p1 = point_of(x + 1, y, right_side);
            let p2 = point_of(x, y + 1, right_side);
            let p3 = point_of(x + 1, y + 1, right_side);
            mesh.set_face_from_indices(face_id, [p0, p1, p2]);
            face_id += 1;
            mesh.set_face_from_indices(face_id, [p1, p3, p2]);
            face_id += 1;
        }
    }
    mesh
}

/// [`grid_mesh`] plus a tex coordinate per point.
#[cfg(feature = "legacy_bitstream_encode")]
fn grid_mesh_with_texcoords(n: usize) -> Mesh {
    let mut mesh = grid_mesh(n);
    let num_points = n * n;
    let mut uv = PointAttribute::new();
    uv.init(
        GeometryAttributeType::TexCoord,
        2,
        DataType::Float32,
        false,
        num_points,
    );
    for y in 0..n {
        for x in 0..n {
            let offset = (y * n + x) * 8;
            uv.buffer_mut()
                .write(offset, &(x as f32 / n as f32).to_le_bytes());
            uv.buffer_mut()
                .write(offset + 4, &(y as f32 / n as f32).to_le_bytes());
        }
    }
    mesh.add_attribute(uv);
    mesh
}

/// [`grid_mesh`] plus a unit normal per point.
#[cfg(feature = "legacy_bitstream_encode")]
fn grid_mesh_with_normals(n: usize) -> Mesh {
    let mut mesh = grid_mesh(n);
    let num_points = n * n;
    let mut normal = PointAttribute::new();
    normal.init(
        GeometryAttributeType::Normal,
        3,
        DataType::Float32,
        false,
        num_points,
    );
    for i in 0..num_points {
        for (k, component) in [0.0f32, 0.0, 1.0].iter().enumerate() {
            normal
                .buffer_mut()
                .write(i * 12 + k * 4, &component.to_le_bytes());
        }
    }
    mesh.add_attribute(normal);
    mesh
}

/// [`grid_mesh`] with the middle cell removed, so the surface is a ring.
///
/// A grid is a disc, and EdgeBreaker walks a disc without ever meeting itself:
/// it emits no topology-split events at all, whatever its size. Put a hole in
/// the middle and the traversal has to come back around to a boundary it has
/// already seen, which is what a split event records. That is the whole reason
/// this mesh exists -- a test of the split layout on a grid tests nothing.
#[cfg(feature = "legacy_bitstream_encode")]
fn annulus_mesh(n: usize) -> Mesh {
    // Three holes rather than one, so the events are written back to back:
    // below 1.2 nothing separates them, while 1.2 puts a bit-coded section
    // after the last one. A single event cannot tell those apart.
    let holes = [(n / 4, n / 4), (n / 2, n / 2), (3 * n / 4 - 1, n / 4)];

    let mut mesh = Mesh::new();
    mesh.set_num_points(n * n);
    mesh.add_attribute(grid_mesh(n).attribute(0).clone());

    let mut faces = Vec::new();
    for y in 0..n - 1 {
        for x in 0..n - 1 {
            if holes.contains(&(x, y)) {
                continue;
            }
            let p0 = (y * n + x) as u32;
            let p1 = (y * n + x + 1) as u32;
            let p2 = ((y + 1) * n + x) as u32;
            let p3 = ((y + 1) * n + x + 1) as u32;
            faces.push([p0, p1, p2]);
            faces.push([p1, p3, p2]);
        }
    }

    mesh.set_num_faces(faces.len());
    for (id, face) in faces.into_iter().enumerate() {
        mesh.set_face_from_indices(id, face);
    }
    mesh
}

/// A square grid of `n` by `n` points with two triangles per cell.
#[cfg(feature = "legacy_bitstream_encode")]
fn grid_mesh(n: usize) -> Mesh {
    use draco_core::draco_types::DataType;
    use draco_core::geometry_attribute::{GeometryAttributeType, PointAttribute};

    let mut mesh = Mesh::new();
    let num_points = n * n;
    let mut position = PointAttribute::new();
    position.init(
        GeometryAttributeType::Position,
        3,
        DataType::Float32,
        false,
        num_points,
    );
    for y in 0..n {
        for x in 0..n {
            let offset = (y * n + x) * 12;
            position
                .buffer_mut()
                .write(offset, &(x as f32).to_le_bytes());
            position
                .buffer_mut()
                .write(offset + 4, &(y as f32).to_le_bytes());
            position
                .buffer_mut()
                .write(offset + 8, &(((x + y) % 5) as f32).to_le_bytes());
        }
    }
    mesh.set_num_points(num_points);
    mesh.add_attribute(position);

    mesh.set_num_faces((n - 1) * (n - 1) * 2);
    let mut face_id = 0;
    for y in 0..n - 1 {
        for x in 0..n - 1 {
            let p0 = (y * n + x) as u32;
            let p1 = (y * n + x + 1) as u32;
            let p2 = ((y + 1) * n + x) as u32;
            let p3 = ((y + 1) * n + x + 1) as u32;
            mesh.set_face_from_indices(face_id, [p0, p1, p2]);
            face_id += 1;
            mesh.set_face_from_indices(face_id, [p1, p3, p2]);
            face_id += 1;
        }
    }
    mesh
}

/// A second attribute, with its own seams and its own prediction, round-trips
/// at every claimed version.
///
/// The matrices above vary version against traversal, size and topology, and
/// leave the attribute layout trivial: one position, one value per point, no
/// seams. Every rule that changes shape between versions on the *attribute*
/// side is therefore reached at one version only, and two of them were wrong
/// for years below 2.1 without a test noticing:
///
/// - the seam bits, which carry both sides of an interior edge below 2.1 and
///   one side from 2.1;
/// - the prediction parent, which is the portable integer position from 2.0
///   and was the dequantized one below it, so the two halves predicted from
///   different numbers.
///
/// Both were found by the `encode_drc` campaign rather than here. This is the
/// row that would have found them: a texture coordinate with an interior seam,
/// quantized, predicted, over the same version list.
#[test]
#[cfg(feature = "legacy_bitstream_encode")]
fn a_seamed_predicted_texcoord_round_trips_at_every_claimed_version() {
    let mesh = grid_mesh_with_uv_seam(9);

    let options_for = |major: u8, minor: u8, speed: i32, uv_scheme: i32| {
        let mut options = EncoderOptions::new();
        options.set_version(major, minor);
        options.set_encoding_method(1);
        options.set_global_int("encoding_speed", speed);
        options.set_global_int("decoding_speed", speed);
        options.set_attribute_int(0, "quantization_bits", 12);
        options.set_attribute_int(1, "quantization_bits", 12);
        if uv_scheme >= 0 {
            options.set_attribute_int(1, "prediction_scheme", uv_scheme);
        }
        options
    };

    // Quantization is lossy, so the input mesh is not what any version returns;
    // the newest version's own answer is the reference the older ones have to
    // reproduce.
    for (speed, uv_scheme) in [(5i32, -1i32), (0, -1), (5, 5), (0, 5)] {
        let reference = round_trip(&mesh, &options_for(2, 2, speed, uv_scheme))
            .unwrap_or_else(|e| panic!("v2.2 speed {speed} scheme {uv_scheme}: {e:?}"));
        let reference_positions = sorted_mesh_positions(&reference);
        let reference_texcoords = sorted_mesh_texcoords(&reference);

        for (major, minor) in [(2u8, 1u8), (2, 0), (1, 2), (1, 1)] {
            let decoded = round_trip(&mesh, &options_for(major, minor, speed, uv_scheme))
                .unwrap_or_else(|e| {
                    panic!("v{major}.{minor} speed {speed} scheme {uv_scheme}: {e:?}")
                });
            assert_eq!(
                decoded.num_faces(),
                reference.num_faces(),
                "v{major}.{minor} speed {speed} scheme {uv_scheme}: face count"
            );
            assert_eq!(
                sorted_mesh_positions(&decoded),
                reference_positions,
                "v{major}.{minor} speed {speed} scheme {uv_scheme}: positions"
            );
            assert_eq!(
                decoded.num_attributes(),
                2,
                "v{major}.{minor}: the texture coordinate survives"
            );
            // The values, not just their presence: a prediction that reads the
            // wrong parent still produces a coordinate for every entry, and
            // only their numbers say it read the wrong one.
            assert_eq!(
                sorted_mesh_texcoords(&decoded),
                reference_texcoords,
                "v{major}.{minor} speed {speed} scheme {uv_scheme}: texture coordinates"
            );
        }
    }
}