voxel-framework 0.13.1

A reusable voxel engine framework built on Bevy
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
//! Neighbor-aware greedy meshing with cross-chunk border culling.
//!
//! The standalone mesher in [`super::greedy`] always emits border faces as
//! visible, which produces single-voxel cracks between adjacent loaded chunks.
//! This module plugs a custom `face_visible` callback into [`super::greedy::build_mesh`]
//! that consults [`super::ChunkNeighbors`] for voxels that cross chunk boundaries.
//!
//! # Culling strategy
//!
//! For each candidate face the callback checks whether the neighbor cell falls
//! inside or outside the current chunk:
//!
//! - **Interior** — the neighbor is within bounds; the standard solid-check
//!   (`!super_voxel.is_solid()`) is used, identical to the standalone mesher.
//! - **Border** — the neighbor is outside bounds; the corresponding slot in
//!   [`super::ChunkNeighbors::faces`] is consulted.  If the slot is `None`
//!   (neighbor not loaded), the face is treated as visible.  If the slot is
//!   `Some`, the voxel at the matching `(u, v)` position in the border slice
//!   is checked; the face is culled when that voxel is solid.
//!
//! This approach requires no changes to the greedy merge loop itself — only
//! the face-visibility predicate changes, making it zero-cost for interior faces.

use bevy::mesh::Mesh;

use crate::chunk::{CHUNK_SIZE, Chunk};
use crate::voxel::{TerrainMaterialId, VoxelType};

use super::greedy::{Chamfer, FaceDir, build_material_meshes, build_mesh, super_voxel};
use super::{ChunkNeighbors, MeshConfig};

/// Generates a seam-free [`Mesh`] for a chunk by culling border faces against
/// adjacent chunk data supplied in `neighbors`.
///
/// This is the preferred meshing entry point for in-world rendering.  It
/// produces the same greedy-merged geometry as [`super::generate_chunk_mesh`]
/// but eliminates single-voxel gaps at chunk boundaries by consulting
/// [`ChunkNeighbors`] before emitting any border face.
///
/// # Parameters
///
/// - `chunk` — The [`Chunk<V>`] to mesh.
/// - `neighbors` — Border voxel data for the six adjacent chunks.  Slots set
///   to `None` are treated as open air; the corresponding border faces are
///   always emitted.  Build this from [`Chunk::border_slice`] on each loaded
///   neighbor or use [`ChunkNeighbors::default`] to treat all borders as air.
/// - `step` — LOD step size.  `1` = full detail; `2` = half detail.  Use
///   [`super::lod::lod_to_step`] to derive this from a LOD level.
///
/// # Returns
///
/// See [`super::generate_chunk_mesh`] for the full attribute list.  The mesh
/// is otherwise identical; only face culling at chunk borders differs.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::{
///     chunk::Chunk,
///     mesh::{ChunkNeighbors, generate_chunk_mesh_with_neighbors},
///     voxel::DefaultVoxel,
/// };
///
/// let chunk = Chunk::<DefaultVoxel>::new();
/// // All neighbors absent — borders treated as open air.
/// let neighbors = ChunkNeighbors::<DefaultVoxel>::default();
/// let mesh = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);
/// ```
pub fn generate_chunk_mesh_with_neighbors<V: VoxelType>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    step: usize,
) -> Mesh {
    crate::profile_span!("voxel::mesh::neighbor");
    let face_visible =
        |chunk: &Chunk<V>, x: usize, y: usize, z: usize, face: &FaceDir, step: usize| -> bool {
            is_face_visible(chunk, neighbors, x, y, z, face, step)
        };
    build_mesh(chunk, step, &face_visible)
}

/// Generates one mesh per terrain material for a chunk, with neighbor-aware
/// border culling.
///
/// Works like [`generate_chunk_mesh_with_neighbors`], but the faces of each
/// [`VoxelType::material`] go into a mesh of their own. Only materials with at
/// least one visible face are returned, sorted by id. Together the meshes hold
/// exactly the quads of the single mesh.
///
/// # Example
///
/// ```
/// use voxel_framework::{
///     chunk::Chunk,
///     mesh::{ChunkNeighbors, generate_chunk_material_meshes},
///     voxel::{DefaultVoxel, TerrainMaterialId},
/// };
///
/// let mut chunk = Chunk::<DefaultVoxel>::new();
/// chunk.set(1, 1, 1, DefaultVoxel::Rock);
/// let neighbors = ChunkNeighbors::<DefaultVoxel>::default();
/// let meshes = generate_chunk_material_meshes(&chunk, &neighbors, 1);
/// // `DefaultVoxel` keeps every voxel on the default material.
/// assert_eq!(meshes.len(), 1);
/// assert_eq!(meshes[0].0, TerrainMaterialId::DEFAULT);
/// ```
pub fn generate_chunk_material_meshes<V: VoxelType>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    step: usize,
) -> Vec<(TerrainMaterialId, Mesh)> {
    generate_chunk_material_meshes_with_config(chunk, neighbors, step, &MeshConfig::default())
}

/// [`generate_chunk_material_meshes`] with a [`MeshConfig`], which can turn on
/// chamfered edges.
///
/// # Example
///
/// ```
/// use voxel_framework::{
///     chunk::Chunk,
///     mesh::{ChunkNeighbors, MeshConfig, generate_chunk_material_meshes_with_config},
///     voxel::DefaultVoxel,
/// };
///
/// let mut chunk = Chunk::<DefaultVoxel>::new();
/// chunk.set(1, 1, 1, DefaultVoxel::Rock);
/// let neighbors = ChunkNeighbors::<DefaultVoxel>::default();
/// let config = MeshConfig {
///     edge_chamfer: Some(0.15),
/// };
/// let meshes = generate_chunk_material_meshes_with_config(&chunk, &neighbors, 1, &config);
/// // A lone voxel has twelve chamfered edges, so more than six quads.
/// assert!(meshes[0].1.count_vertices() > 24);
/// ```
pub fn generate_chunk_material_meshes_with_config<V: VoxelType>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    step: usize,
    config: &MeshConfig,
) -> Vec<(TerrainMaterialId, Mesh)> {
    generate_chunk_material_meshes_with(chunk, neighbors, step, config, &|voxel: V| {
        voxel.material()
    })
}

/// [`generate_chunk_material_meshes`] with the routing of voxels to materials
/// chosen by the caller.
pub(crate) fn generate_chunk_material_meshes_with<V: VoxelType, K: Copy + Ord>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    step: usize,
    config: &MeshConfig,
    material_of: &dyn Fn(V) -> K,
) -> Vec<(K, Mesh)> {
    crate::profile_span!("voxel::mesh::neighbor");
    let face_visible =
        |chunk: &Chunk<V>, x: usize, y: usize, z: usize, face: &FaceDir, step: usize| -> bool {
            is_face_visible(chunk, neighbors, x, y, z, face, step)
        };
    let sample = |coords: [i32; 3]| sample_voxel(chunk, neighbors, coords);
    let chamfer = config.chamfer_width().map(|width| Chamfer {
        width,
        sample: &sample,
    });
    build_material_meshes(chunk, step, &face_visible, chamfer.as_ref(), material_of)
}

/// The voxel at chunk-local `coords`, which may lie one voxel outside the
/// chunk on one axis (then it is read from the neighbor's border, or is air
/// when that neighbor is not loaded). `None` for any other position: the
/// mesher has no data for chunks that only share an edge or a corner.
fn sample_voxel<V: VoxelType>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    coords: [i32; 3],
) -> Option<V> {
    let size = CHUNK_SIZE as i32;
    let mut outside = None;
    for (axis, &coord) in coords.iter().enumerate() {
        if coord < 0 || coord >= size {
            if outside.is_some() || coord < -1 || coord > size {
                return None;
            }
            outside = Some((axis, coord >= size));
        }
    }
    let [x, y, z] = coords.map(|coord| coord.clamp(0, size - 1) as usize);
    let Some((axis, positive)) = outside else {
        return Some(chunk.get(x, y, z));
    };
    // Face indices and border packing as in `Chunk::border_slice`.
    let (face_index, slice_index) = match axis {
        1 => (if positive { 0 } else { 1 }, x * CHUNK_SIZE + z),
        0 => (if positive { 2 } else { 3 }, y * CHUNK_SIZE + z),
        _ => (if positive { 4 } else { 5 }, x * CHUNK_SIZE + y),
    };
    Some(match &neighbors.faces[face_index] {
        Some(slice) => slice[slice_index],
        None => V::air(),
    })
}

/// Determines whether a face is visible, checking neighbor data at borders.
///
/// For interior voxels, this is equivalent to `!neighbor_voxel.is_solid()`.
/// For border voxels, the neighbor border slice is consulted.
#[inline]
fn is_face_visible<V: VoxelType>(
    chunk: &Chunk<V>,
    neighbors: &ChunkNeighbors<V>,
    x: usize,
    y: usize,
    z: usize,
    face: &FaceDir,
    step: usize,
) -> bool {
    let coords = [x, y, z];
    let axis = face.axis;

    // Check if the neighbor in this direction falls outside the chunk.
    let neighbor_on_axis = if face.positive {
        coords[axis].wrapping_add(step)
    } else {
        coords[axis].wrapping_sub(step)
    };

    if neighbor_on_axis < CHUNK_SIZE {
        // Neighbor is within the chunk — check directly.
        // A neighbor occludes only when it is solid AND fully opaque (alpha >= 1.0),
        // consistent with the build_mask condition (color()[3] > 0.0).
        let mut nc = [x, y, z];
        nc[axis] = neighbor_on_axis;
        let sv = super_voxel(chunk, nc[0], nc[1], nc[2], step);
        return !sv.is_solid() || sv.color()[3] < 1.0;
    }

    // Neighbor is outside the chunk — consult the border slice.
    let face_index = face_dir_to_index(face);
    match &neighbors.faces[face_index] {
        None => true, // No neighbor data — treat as air.
        Some(slice) => {
            // At step > 1 (LOD 1/2) the current super-voxel covers a step×step
            // region on the neighbor's border face.  Check ALL step×step neighbor
            // voxels — the face is visible if ANY of them is non-solid or
            // transparent (i.e. cull only when the entire region is fully solid).
            //
            // Checking only the corner voxel (u_coord, v_coord) caused incorrect
            // face culling when the corner was solid but other voxels in the region
            // were air, producing transparent holes at LOD 1+ chunk boundaries.
            let u_coord = coords[face.u_axis];
            let v_coord = coords[face.v_axis];

            for du in 0..step {
                for dv in 0..step {
                    let u = u_coord + du;
                    let v = v_coord + dv;
                    if u >= CHUNK_SIZE || v >= CHUNK_SIZE {
                        return true; // out of bounds → treat as air → face visible
                    }
                    let slice_index = border_slice_index(face_index, u, v);
                    let neighbor = slice[slice_index];
                    if !neighbor.is_solid() || neighbor.color()[3] < 1.0 {
                        return true; // any gap in the step×step region → face visible
                    }
                }
            }
            false // entire step×step region is solid and opaque → cull
        }
    }
}

/// Maps a `FaceDir` to its conventional face index (0..6).
#[inline]
fn face_dir_to_index(face: &FaceDir) -> usize {
    // FACE_DIRS[0] = +Y, [1] = -Y, [2] = +X, [3] = -X, [4] = +Z, [5] = -Z
    match (face.axis, face.positive) {
        (1, true) => 0,  // +Y
        (1, false) => 1, // -Y
        (0, true) => 2,  // +X
        (0, false) => 3, // -X
        (2, true) => 4,  // +Z
        (2, false) => 5, // -Z
        _ => unreachable!(),
    }
}

/// Computes the index into a `border_slice` array for a given face and
/// local (u, v) coordinates.
///
/// The packing matches `Chunk::border_slice`:
/// - Face 0 (+Y): `x * CHUNK_SIZE + z`
/// - Face 1 (-Y): `x * CHUNK_SIZE + z`
/// - Face 2 (+X): `y * CHUNK_SIZE + z`
/// - Face 3 (-X): `y * CHUNK_SIZE + z`
/// - Face 4 (+Z): `x * CHUNK_SIZE + y`
/// - Face 5 (-Z): `x * CHUNK_SIZE + y`
///
/// The `u_coord` and `v_coord` here are in the FaceDir's tangent-axis space.
#[inline]
fn border_slice_index(face_index: usize, u_coord: usize, v_coord: usize) -> usize {
    // FaceDir tangent axes vs border_slice packing:
    //   Face 0/1 (+Y/-Y): u=X(0), v=Z(2) -> border_slice packs [x * CS + z] -> u * CS + v
    //   Face 2/3 (+X/-X): u=Z(2), v=Y(1) -> border_slice packs [y * CS + z] -> v * CS + u
    //   Face 4/5 (+Z/-Z): u=X(0), v=Y(1) -> border_slice packs [x * CS + y] -> u * CS + v
    match face_index {
        0 | 1 => u_coord * CHUNK_SIZE + v_coord,
        2 | 3 => v_coord * CHUNK_SIZE + u_coord,
        4 | 5 => u_coord * CHUNK_SIZE + v_coord,
        _ => unreachable!(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::voxel::DefaultVoxel;

    const MAX: usize = CHUNK_SIZE - 1;

    /// For each face index `[+Y, -Y, +X, -X, +Z, -Z]`: the opposite face, the
    /// border cell in this chunk, and the touching cell in the neighbor chunk.
    /// Coordinates are deliberately asymmetric (3 vs 7) so a swapped (u, v)
    /// lookup in the border slice would be caught.
    fn face_cases() -> [(usize, usize, (usize, usize, usize), (usize, usize, usize)); 6] {
        [
            (0, 1, (3, MAX, 7), (3, 0, 7)),
            (1, 0, (3, 0, 7), (3, MAX, 7)),
            (2, 3, (MAX, 3, 7), (0, 3, 7)),
            (3, 2, (0, 3, 7), (MAX, 3, 7)),
            (4, 5, (3, 7, MAX), (3, 7, 0)),
            (5, 4, (3, 7, 0), (3, 7, MAX)),
        ]
    }

    fn single(cell: (usize, usize, usize)) -> Chunk<DefaultVoxel> {
        let mut chunk = Chunk::new();
        chunk.set(cell.0, cell.1, cell.2, DefaultVoxel::Rock);
        chunk
    }

    fn mesh_vertices(
        chunk: &Chunk<DefaultVoxel>,
        face: usize,
        slice_src: &Chunk<DefaultVoxel>,
        opposite: usize,
    ) -> usize {
        let mut neighbors = ChunkNeighbors::<DefaultVoxel>::default();
        neighbors.faces[face] = Some(slice_src.border_slice(opposite));
        generate_chunk_mesh_with_neighbors(chunk, &neighbors, 1).count_vertices()
    }

    #[test]
    fn solid_neighbor_culls_the_touching_face_on_every_side() {
        for (face, opposite, cell, touching) in face_cases() {
            let vertices = mesh_vertices(&single(cell), face, &single(touching), opposite);
            assert_eq!(
                vertices, 20,
                "face {face}: one of six quads (4 vertices) should be culled"
            );
        }
    }

    #[test]
    fn neighbor_solid_at_a_different_cell_does_not_cull() {
        for (face, opposite, cell, touching) in face_cases() {
            // Swap the two in-plane coordinates of the neighbor cell.
            let swapped = match face {
                0 | 1 => (touching.2, touching.1, touching.0),
                2 | 3 => (touching.0, touching.2, touching.1),
                _ => (touching.1, touching.0, touching.2),
            };
            let vertices = mesh_vertices(&single(cell), face, &single(swapped), opposite);
            assert_eq!(
                vertices, 24,
                "face {face}: misaligned neighbor must not cull"
            );
        }
    }

    #[test]
    fn missing_or_empty_neighbor_keeps_all_faces() {
        let chunk = single((0, 0, 0));
        let none = ChunkNeighbors::<DefaultVoxel>::default();
        assert_eq!(
            generate_chunk_mesh_with_neighbors(&chunk, &none, 1).count_vertices(),
            24
        );

        let empty = Chunk::<DefaultVoxel>::new();
        assert_eq!(mesh_vertices(&chunk, 3, &empty, 2), 24);
    }

    use crate::mesh::test_voxel::{GLASS, TwoMaterialVoxel};

    fn quad_count(mesh: &Mesh) -> usize {
        mesh.count_vertices() / 4
    }

    #[test]
    fn faces_are_split_into_one_mesh_per_material() {
        let mut chunk = Chunk::<TwoMaterialVoxel>::new();
        chunk.set(2, 2, 2, TwoMaterialVoxel::Stone);
        chunk.set(8, 8, 8, TwoMaterialVoxel::Glass);
        chunk.set(12, 8, 8, TwoMaterialVoxel::Glass);
        let neighbors = ChunkNeighbors::default();

        let meshes = generate_chunk_material_meshes(&chunk, &neighbors, 1);

        let ids: Vec<_> = meshes.iter().map(|(id, _)| *id).collect();
        assert_eq!(ids, vec![TerrainMaterialId::DEFAULT, GLASS]);
        assert_eq!(quad_count(&meshes[0].1), 6);
        assert_eq!(quad_count(&meshes[1].1), 12);
    }

    #[test]
    fn material_meshes_hold_the_same_quads_as_the_single_mesh() {
        let mut chunk = Chunk::<TwoMaterialVoxel>::new();
        for x in 0..6 {
            for z in 0..6 {
                let voxel = if (x + z) % 3 == 0 {
                    TwoMaterialVoxel::Glass
                } else {
                    TwoMaterialVoxel::Stone
                };
                chunk.set(x, 4, z, voxel);
            }
        }
        let neighbors = ChunkNeighbors::default();

        for step in [1, 2] {
            let single = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, step);
            let split = generate_chunk_material_meshes(&chunk, &neighbors, step);
            let total: usize = split.iter().map(|(_, mesh)| quad_count(mesh)).sum();
            assert_eq!(total, quad_count(&single), "step {step}");
        }
    }

    #[test]
    fn a_material_without_visible_faces_has_no_mesh() {
        let mut chunk = Chunk::<TwoMaterialVoxel>::new();
        chunk.set(3, 3, 3, TwoMaterialVoxel::Glass);
        let neighbors = ChunkNeighbors::default();

        let meshes = generate_chunk_material_meshes(&chunk, &neighbors, 1);

        assert_eq!(meshes.len(), 1);
        assert_eq!(meshes[0].0, GLASS);
    }

    #[test]
    fn empty_chunk_has_no_material_meshes() {
        let chunk = Chunk::<TwoMaterialVoxel>::new();
        let neighbors = ChunkNeighbors::default();
        assert!(generate_chunk_material_meshes(&chunk, &neighbors, 1).is_empty());
    }

    #[test]
    fn caller_routing_can_send_every_voxel_to_one_material() {
        let mut chunk = Chunk::<TwoMaterialVoxel>::new();
        chunk.set(2, 2, 2, TwoMaterialVoxel::Stone);
        chunk.set(8, 8, 8, TwoMaterialVoxel::Glass);
        let neighbors = ChunkNeighbors::default();

        let meshes = generate_chunk_material_meshes_with(
            &chunk,
            &neighbors,
            1,
            &MeshConfig::default(),
            &|_| TerrainMaterialId::DEFAULT,
        );

        assert_eq!(meshes.len(), 1);
        assert_eq!(quad_count(&meshes[0].1), 12);
    }

    // ── Edge chamfer ─────────────────────────────────────────────────────

    use bevy::mesh::{Indices, VertexAttributeValues};
    use bevy::prelude::Vec3;

    const CHAMFER: MeshConfig = MeshConfig {
        edge_chamfer: Some(0.2),
    };

    fn chamfered(chunk: &Chunk<DefaultVoxel>, neighbors: &ChunkNeighbors<DefaultVoxel>) -> Mesh {
        let mut meshes = generate_chunk_material_meshes_with_config(chunk, neighbors, 1, &CHAMFER);
        assert_eq!(meshes.len(), 1);
        meshes.remove(0).1
    }

    /// The triangles of a mesh as corner positions plus the vertex normal of
    /// the first corner.
    fn triangles(mesh: &Mesh) -> Vec<([Vec3; 3], Vec3)> {
        let Some(VertexAttributeValues::Float32x3(positions)) =
            mesh.attribute(Mesh::ATTRIBUTE_POSITION)
        else {
            panic!("positions");
        };
        let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("normals");
        };
        let Some(Indices::U32(indices)) = mesh.indices() else {
            panic!("indices");
        };
        indices
            .chunks(3)
            .map(|tri| {
                let corner = |i: u32| Vec3::from_array(positions[i as usize]);
                (
                    [corner(tri[0]), corner(tri[1]), corner(tri[2])],
                    Vec3::from_array(normals[tri[0] as usize]),
                )
            })
            .collect()
    }

    /// Checks that the mesh is a closed surface seen from outside: every
    /// triangle faces along its vertex normal, and the area vectors add up to
    /// zero, which a missing or flipped triangle would break. Returns the
    /// enclosed volume.
    fn assert_closed(mesh: &Mesh) -> f32 {
        // Summed in f64: a large mesh adds thousands of terms, and the
        // smallest real defect (half a cap) is only 0.01.
        let mut area = bevy::math::DVec3::ZERO;
        let mut volume = 0.0f64;
        for ([a, b, c], normal) in triangles(mesh) {
            let cross = (b - a).cross(c - a);
            assert!(
                cross.length() == 0.0 || cross.normalize().dot(normal) > 0.99,
                "triangle {a} {b} {c} does not face along its normal {normal}"
            );
            assert!((normal.length() - 1.0).abs() < 1e-4, "unit normal");
            let (a, b, c) = (a.as_dvec3(), b.as_dvec3(), c.as_dvec3());
            area += (b - a).cross(c - a) * 0.5;
            volume += a.dot(b.cross(c)) / 6.0;
        }
        assert!(area.length() < 1e-3, "open surface: area vector sum {area}");
        volume as f32
    }

    #[test]
    fn no_chamfer_by_default() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        let neighbors = ChunkNeighbors::default();

        let off = generate_chunk_material_meshes_with_config(
            &chunk,
            &neighbors,
            1,
            &MeshConfig::default(),
        );
        assert_eq!(off[0].1.count_vertices(), 24);
        for width in [0.0, -0.3, f32::NAN] {
            let config = MeshConfig {
                edge_chamfer: Some(width),
            };
            let mesh = generate_chunk_material_meshes_with_config(&chunk, &neighbors, 1, &config);
            assert_eq!(mesh[0].1.count_vertices(), 24, "width {width}");
        }
    }

    #[test]
    fn lone_voxel_is_chamfered_on_every_edge_and_stays_closed() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        // Per face: the face, four strips and four corner pieces.
        assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
        let volume = assert_closed(&mesh);
        // Twelve edges lose a wedge of at most 0.2 * 0.2 / 2 each.
        assert!(
            volume < 1.0 && volume > 1.0 - 12.0 * 0.02,
            "volume {volume}"
        );
        // Nothing sticks out of the voxel.
        for ([a, b, c], _) in triangles(&mesh) {
            for p in [a, b, c] {
                assert!(p.min_element() >= 5.0 - 1e-5 && p.max_element() <= 6.0 + 1e-5);
            }
        }
    }

    #[test]
    fn flat_seams_between_voxels_stay_merged() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 2..10 {
            for z in 2..10 {
                chunk.set(x, 4, z, DefaultVoxel::Rock);
            }
        }
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        // An 8x1x8 slab is still six faces with chamfers on the outline only.
        assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
        let volume = assert_closed(&mesh);
        // The outline loses 2 * 4 * 8 wedges of 0.02 per unit and a little more.
        assert!(
            volume < 64.0 - 1.2 && volume > 64.0 - 1.5,
            "volume {volume}"
        );
    }

    #[test]
    fn chamfer_ending_against_another_voxel_is_capped() {
        // Stairs: the top edges of the low step end against the high step.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(4, 4, 4, DefaultVoxel::Rock);
        chunk.set(5, 4, 4, DefaultVoxel::Rock);
        chunk.set(5, 5, 4, DefaultVoxel::Rock);
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        let volume = assert_closed(&mesh);
        assert!(volume < 3.0 && volume > 2.5, "volume {volume}");
    }

    #[test]
    fn irregular_shapes_stay_closed() {
        // A deterministic blob with overhangs, holes and diagonal contacts.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        let mut count = 0;
        for x in 1..15usize {
            for y in 1..15usize {
                for z in 1..15usize {
                    let hash = (x * 73_856_093) ^ (y * 19_349_663) ^ (z * 83_492_791);
                    if hash % 5 < 2 {
                        let voxel = if hash % 7 == 0 {
                            DefaultVoxel::IronOre
                        } else {
                            DefaultVoxel::Rock
                        };
                        chunk.set(x, y, z, voxel);
                        count += 1;
                    }
                }
            }
        }
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        let volume = assert_closed(&mesh);
        assert!(volume < count as f32 && volume > count as f32 * 0.7);
    }

    #[test]
    fn chamfer_reaches_the_chunk_border_and_stays_closed() {
        // A full chunk: every edge of the cube lies on the chunk border.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    chunk.set(x, y, z, DefaultVoxel::Rock);
                }
            }
        }
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        assert_eq!(mesh.count_vertices(), 6 * (4 + 4 * 4 + 4 * 4));
        assert_closed(&mesh);
    }

    #[test]
    fn edge_against_a_solid_neighbor_chunk_is_not_chamfered() {
        // A slab on the chunk floor, continued by a solid chunk below: its
        // bottom edges are not convex.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 0, 5, DefaultVoxel::Rock);
        let mut neighbors = ChunkNeighbors::default();
        neighbors.faces[1] = Some([DefaultVoxel::Rock; CHUNK_SIZE * CHUNK_SIZE]);
        let mesh = chamfered(&chunk, &neighbors);

        // Five faces. The top has four chamfered sides and four corners; each
        // side has three chamfered sides and two corners, and its two vertical
        // chamfers end on the floor, where each face caps its half.
        assert_eq!(
            mesh.count_vertices(),
            (4 + 4 * 4 + 4 * 4) + 4 * (4 + 3 * 4 + 2 * 4 + 2 * 3)
        );
        // No vertex below the top of the neighbor chunk, and none cut there.
        for ([a, b, c], _) in triangles(&mesh) {
            for p in [a, b, c] {
                assert!(p.y >= 0.0);
            }
        }
    }

    #[test]
    fn coarse_lod_is_not_chamfered() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(4, 4, 4, DefaultVoxel::Rock);
        let neighbors = ChunkNeighbors::default();

        let sharp = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 2);
        let with_config =
            generate_chunk_material_meshes_with_config(&chunk, &neighbors, 2, &CHAMFER);

        assert_eq!(with_config[0].1.count_vertices(), sharp.count_vertices());
    }

    #[test]
    fn chamfer_keeps_material_meshes_separate_and_closed_together() {
        let mut chunk = Chunk::<TwoMaterialVoxel>::new();
        chunk.set(4, 4, 4, TwoMaterialVoxel::Stone);
        chunk.set(5, 4, 4, TwoMaterialVoxel::Glass);
        let neighbors = ChunkNeighbors::default();

        let meshes = generate_chunk_material_meshes_with_config(&chunk, &neighbors, 1, &CHAMFER);

        assert_eq!(meshes.len(), 2);
        // Each half is open where it touches the other; together they close.
        let mut area = Vec3::ZERO;
        for (_, mesh) in &meshes {
            for ([a, b, c], _) in triangles(mesh) {
                area += (b - a).cross(c - a) * 0.5;
            }
        }
        assert!(area.length() < 1e-3, "area vector sum {area}");
    }

    // ── Exposed faces ────────────────────────────────────────────────────

    use crate::mesh::ATTRIBUTE_FACE_EXPOSED;

    /// (normal, exposed flag) of every vertex.
    fn exposed_by_vertex(mesh: &Mesh) -> Vec<([f32; 3], f32)> {
        let Some(VertexAttributeValues::Float32x3(normals)) =
            mesh.attribute(Mesh::ATTRIBUTE_NORMAL)
        else {
            panic!("normals");
        };
        let Some(VertexAttributeValues::Float32(exposed)) = mesh.attribute(ATTRIBUTE_FACE_EXPOSED)
        else {
            panic!("exposed attribute");
        };
        assert_eq!(normals.len(), exposed.len());
        normals
            .iter()
            .copied()
            .zip(exposed.iter().copied())
            .collect()
    }

    #[test]
    fn every_vertex_reports_no_exposed_face_by_default() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        let mesh = generate_chunk_mesh_with_neighbors(&chunk, &ChunkNeighbors::default(), 1);

        let vertices = exposed_by_vertex(&mesh);
        assert_eq!(vertices.len(), 24);
        assert!(vertices.iter().all(|(_, exposed)| *exposed == 0.0));
    }

    #[test]
    fn only_the_recorded_face_is_reported_as_exposed() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        // Face 2 is +X.
        chunk.set_exposed_faces(5, 5, 5, 1 << 2);
        let mesh = generate_chunk_mesh_with_neighbors(&chunk, &ChunkNeighbors::default(), 1);

        for (normal, exposed) in exposed_by_vertex(&mesh) {
            let expected = if normal == [1.0, 0.0, 0.0] { 1.0 } else { 0.0 };
            assert_eq!(exposed, expected, "normal {normal:?}");
        }
    }

    #[test]
    fn exposed_and_original_faces_do_not_merge() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 2..6 {
            chunk.set(x, 5, 5, DefaultVoxel::Rock);
        }
        let neighbors = ChunkNeighbors::default();
        let merged = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);
        assert_eq!(merged.count_vertices(), 24);

        // The top (+Y, face 0) of one voxel in the middle is fresh.
        chunk.set_exposed_faces(3, 5, 5, 1 << 0);
        let split = generate_chunk_mesh_with_neighbors(&chunk, &neighbors, 1);

        // The top is now three quads: before, the fresh voxel, after.
        assert_eq!(split.count_vertices(), 24 + 8);
        let fresh = exposed_by_vertex(&split)
            .iter()
            .filter(|(_, exposed)| *exposed == 1.0)
            .count();
        assert_eq!(fresh, 4);
    }

    #[test]
    fn chamfer_vertices_carry_the_flag_of_their_face() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(5, 5, 5, DefaultVoxel::Rock);
        chunk.set_exposed_faces(5, 5, 5, 1 << 0);
        let mesh = chamfered(&chunk, &ChunkNeighbors::default());

        // The top face, its four strips and its four corner pieces.
        let fresh = exposed_by_vertex(&mesh)
            .iter()
            .filter(|(_, exposed)| *exposed == 1.0)
            .count();
        assert_eq!(fresh, 4 + 4 * 4 + 4 * 4);
        assert_closed(&mesh);
    }
}