voxel-framework 0.10.0

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
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
//! Core greedy meshing algorithm for voxel chunks.
//!
//! # Algorithm
//!
//! Greedy meshing eliminates redundant geometry by merging adjacent coplanar
//! faces of identical voxel type into a single large quad.  The implementation
//! follows the classic Mikola Lysenko approach adapted for a cubic grid:
//!
//! 1. **Iterate over face directions** — the six cardinal axes (`±X`, `±Y`,
//!    `±Z`) are processed independently via [`FACE_DIRS`].
//! 2. **Build a 2-D mask** per slice — for each depth `d` along the face's
//!    primary axis, a `size × size` mask records `Some(voxel)` when the
//!    super-voxel at that cell is solid *and* its outward face is visible
//!    (i.e., the neighbor cell is air).  The `face_visible` callback is
//!    injected so the neighbor-aware variant can plug in its own logic without
//!    duplicating the merge loop.
//! 3. **Greedy merge** — the mask is scanned row by row.  For each non-empty
//!    cell the algorithm extends a rectangle as wide as possible in `u`, then
//!    as tall as possible in `v`, while every cell in the rectangle matches the
//!    same voxel type.  The merged region is cleared in the mask and a single
//!    quad is emitted.
//!
//! # LOD super-voxels
//!
//! The `step` parameter coarsens the grid: each super-voxel covers a
//! `step × step × step` region.  [`super_voxel`] picks the first solid voxel
//! within the region, so a coarser LOD level collapses fine detail but retains
//! the presence of solid material.  This is a "representative sample" strategy
//! chosen for its O(step³) simplicity and acceptable visual quality at distance.

use bevy::asset::RenderAssetUsages;
use bevy::mesh::{Indices, Mesh, MeshVertexAttribute, PrimitiveTopology, VertexFormat};

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

/// Custom mesh vertex attribute carrying the texture array layer index.
///
/// Each vertex stores a `u32` that selects which layer of the GPU texture
/// array the `ChunkMaterial` shader samples when rendering that vertex.
/// The value comes from [`crate::voxel::VoxelType::texture_layer`].
pub const ATTRIBUTE_TEXTURE_LAYER: MeshVertexAttribute =
    MeshVertexAttribute::new("Vertex_TextureLayer", 988540919, VertexFormat::Uint32);

/// Face direction descriptor used by the greedy mesher.
///
/// Each of the 6 faces has a primary axis, a sign (positive or negative),
/// and two tangent axes (u and v) that span the 2D slice plane.
pub(crate) struct FaceDir {
    /// Primary axis index: 0=X, 1=Y, 2=Z.
    pub axis: usize,
    /// `true` for positive direction (+X, +Y, +Z).
    pub positive: bool,
    /// First tangent axis index.
    pub u_axis: usize,
    /// Second tangent axis index.
    pub v_axis: usize,
    /// Face normal as `[f32; 3]`.
    normal: [f32; 3],
}

/// The six cardinal face directions in project convention order.
pub(crate) const FACE_DIRS: [FaceDir; 6] = [
    // Face 0: +Y (top) — axis=Y(1), u=X(0), v=Z(2)
    FaceDir {
        axis: 1,
        positive: true,
        u_axis: 0,
        v_axis: 2,
        normal: [0.0, 1.0, 0.0],
    },
    // Face 1: -Y (bottom) — axis=Y(1), u=X(0), v=Z(2)
    FaceDir {
        axis: 1,
        positive: false,
        u_axis: 0,
        v_axis: 2,
        normal: [0.0, -1.0, 0.0],
    },
    // Face 2: +X (right) — axis=X(0), u=Z(2), v=Y(1)
    FaceDir {
        axis: 0,
        positive: true,
        u_axis: 2,
        v_axis: 1,
        normal: [1.0, 0.0, 0.0],
    },
    // Face 3: -X (left) — axis=X(0), u=Z(2), v=Y(1)
    FaceDir {
        axis: 0,
        positive: false,
        u_axis: 2,
        v_axis: 1,
        normal: [-1.0, 0.0, 0.0],
    },
    // Face 4: +Z (front) — axis=Z(2), u=X(0), v=Y(1)
    FaceDir {
        axis: 2,
        positive: true,
        u_axis: 0,
        v_axis: 1,
        normal: [0.0, 0.0, 1.0],
    },
    // Face 5: -Z (back) — axis=Z(2), u=X(0), v=Y(1)
    FaceDir {
        axis: 2,
        positive: false,
        u_axis: 0,
        v_axis: 1,
        normal: [0.0, 0.0, -1.0],
    },
];

/// Returns the representative voxel for a `step × step × step` region rooted
/// at `(sx, sy, sz)`.
///
/// Iterates over the region in XYZ order and returns the first solid voxel
/// found.  If the entire region is air or out of bounds, returns [`VoxelType::air`].
///
/// This "first-visible-wins" strategy returns the first voxel with non-zero
/// alpha (solid OR non-solid but colored, e.g. water).  Solid voxels are still
/// preferred over transparent-but-colored ones when both exist in the region.
#[inline]
pub(crate) fn super_voxel<V: VoxelType>(
    chunk: &Chunk<V>,
    sx: usize,
    sy: usize,
    sz: usize,
    step: usize,
) -> V {
    let mut first_visible = V::air();
    for dx in 0..step {
        for dy in 0..step {
            for dz in 0..step {
                let x = sx + dx;
                let y = sy + dy;
                let z = sz + dz;
                if x < CHUNK_SIZE && y < CHUNK_SIZE && z < CHUNK_SIZE {
                    let v = chunk.get(x, y, z);
                    if v.is_solid() {
                        return v; // solid wins immediately
                    }
                    if first_visible.color()[3] == 0.0 && v.color()[3] > 0.0 {
                        first_visible = v; // remember first non-air non-solid (e.g. water)
                    }
                }
            }
        }
    }
    first_visible
}

/// Generates a [`Mesh`] for a single chunk using greedy meshing.
///
/// This is the standalone variant: border faces that exit the chunk boundary
/// are always emitted as visible.  When adjacent chunks are loaded and their
/// data is available, prefer [`super::generate_chunk_mesh_with_neighbors`] to
/// avoid single-voxel gaps at chunk seams.
///
/// # Parameters
///
/// - `chunk` — The [`Chunk<V>`] to mesh.
/// - `step` — LOD step size.  `1` produces one voxel per grid cell (full
///   detail, LOD 0).  `2` groups each `2×2×2` block into a single super-voxel
///   (half detail, LOD 1).  Use [`super::lod::lod_to_step`] to convert a LOD
///   level to this value.
///
/// # Returns
///
/// A Bevy [`Mesh`] with [`bevy::mesh::PrimitiveTopology::TriangleList`]
/// topology.  The mesh contains the following vertex attributes:
///
/// - `ATTRIBUTE_POSITION` (`Float32x3`) — positions in chunk-local space.
/// - `ATTRIBUTE_NORMAL` (`Float32x3`) — outward face normals.
/// - `ATTRIBUTE_UV_0` (`Float32x2`) — UVs scaled by the merged quad size in
///   voxels, suitable for tiling textures.
/// - `ATTRIBUTE_COLOR` (`Float32x4`) — per-vertex color from [`VoxelType::color`].
/// - `U32` index buffer — CCW triangle winding in Bevy's right-hand coordinate system.
///
/// An all-air chunk produces a mesh with zero vertices and no index buffer entries.
///
/// # Examples
///
/// ```rust,no_run
/// use voxel_framework::{chunk::Chunk, mesh::generate_chunk_mesh, voxel::DefaultVoxel};
///
/// let mut chunk = Chunk::<DefaultVoxel>::new();
/// // ... fill chunk with voxel data ...
/// let mesh = generate_chunk_mesh(&chunk, 1); // full detail
/// let mesh_lod1 = generate_chunk_mesh(&chunk, 2); // half detail
/// ```
pub fn generate_chunk_mesh<V: VoxelType>(chunk: &Chunk<V>, step: usize) -> Mesh {
    crate::profile_span!("voxel::mesh::greedy");
    build_mesh(chunk, step, &default_face_visible::<V>)
}

/// The default face-visibility test: a face is visible if the neighbor in
/// the given direction does not fully occlude it.
///
/// A neighbor occludes a face only when it is both solid (`is_solid()`) **and**
/// fully opaque (`color()[3] >= 1.0`).  This matches the condition used in
/// [`build_mask`] — a voxel generates geometry when `color()[3] > 0.0` —
/// ensuring consistency: a neighbor that would itself generate no geometry
/// (alpha = 0) should never hide the current face.
///
/// At chunk borders, the neighbor is always treated as air (face visible).
#[inline]
fn default_face_visible<V: VoxelType>(
    chunk: &Chunk<V>,
    x: usize,
    y: usize,
    z: usize,
    face: &FaceDir,
    step: usize,
) -> bool {
    let (nx, ny, nz) = neighbor_coords(x, y, z, face, step);
    if nx >= CHUNK_SIZE || ny >= CHUNK_SIZE || nz >= CHUNK_SIZE {
        // Outside chunk bounds — treat as air (face visible).
        return true;
    }
    let neighbor = super_voxel(chunk, nx, ny, nz, step);
    !neighbor.is_solid() || neighbor.color()[3] < 1.0
}

/// Computes the neighbor coordinates in the direction of `face`, offset by `step`.
///
/// Uses wrapping arithmetic so that underflow (e.g., `0 - 1`) wraps to
/// `usize::MAX`, which is always `>= CHUNK_SIZE` and detected as out-of-bounds.
#[inline]
fn neighbor_coords(
    x: usize,
    y: usize,
    z: usize,
    face: &FaceDir,
    step: usize,
) -> (usize, usize, usize) {
    let mut result = [x, y, z];
    if face.positive {
        result[face.axis] = result[face.axis].wrapping_add(step);
    } else {
        result[face.axis] = result[face.axis].wrapping_sub(step);
    }
    (result[0], result[1], result[2])
}

/// Core greedy mesh builder. The `face_visible` callback determines whether
/// a particular face should be emitted, allowing neighbor-aware variants to
/// plug in their own logic.
#[allow(clippy::type_complexity)]
pub(crate) fn build_mesh<V: VoxelType>(
    chunk: &Chunk<V>,
    step: usize,
    face_visible: &dyn Fn(&Chunk<V>, usize, usize, usize, &FaceDir, usize) -> bool,
) -> Mesh {
    let size = CHUNK_SIZE / step;
    let mut positions: Vec<[f32; 3]> = Vec::new();
    let mut normals: Vec<[f32; 3]> = Vec::new();
    let mut uvs: Vec<[f32; 2]> = Vec::new();
    let mut colors: Vec<[f32; 4]> = Vec::new();
    let mut texture_layers: Vec<u32> = Vec::new();
    let mut indices: Vec<u32> = Vec::new();

    // Temporary mask buffer, reused across slices.
    // Each cell stores `Some((voxel, state))` when the face is visible, or
    // `None` when it should be skipped.  Two cells are only merged when both
    // the voxel type AND the state byte match, ensuring that blocks placed
    // against different faces (which may use different textures) are never
    // incorrectly merged into a single quad.
    let mut mask: Vec<Option<(V, u8)>> = vec![None; size * size];

    for (face_index, face) in FACE_DIRS.iter().enumerate() {
        for d in 0..size {
            // Build the 2D mask for this slice.
            build_mask(chunk, face, d, step, size, &mut mask, face_visible);

            // Greedy merge the mask into quads.
            greedy_merge(
                chunk,
                &mut mask,
                size,
                face,
                face_index,
                d,
                step,
                &mut positions,
                &mut normals,
                &mut uvs,
                &mut colors,
                &mut texture_layers,
                &mut indices,
            );
        }
    }

    Mesh::new(
        PrimitiveTopology::TriangleList,
        RenderAssetUsages::default(),
    )
    .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
    .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
    .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
    .with_inserted_attribute(Mesh::ATTRIBUTE_COLOR, colors)
    .with_inserted_attribute(ATTRIBUTE_TEXTURE_LAYER, texture_layers)
    .with_inserted_indices(Indices::U32(indices))
}

/// Builds the 2D visibility mask for a single slice.
///
/// For each cell `(u, v)` in the slice plane, the mask contains
/// `Some((voxel, state))` if the super-voxel is solid and its face in the
/// current direction is visible (neighbor is air), or `None` otherwise.
/// The state byte is used by the greedy merge step to prevent cells with
/// different states from being merged into the same quad.
#[allow(clippy::type_complexity)]
#[inline]
fn build_mask<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    d: usize,
    step: usize,
    size: usize,
    mask: &mut [Option<(V, u8)>],
    face_visible: &dyn Fn(&Chunk<V>, usize, usize, usize, &FaceDir, usize) -> bool,
) {
    for v in 0..size {
        for u in 0..size {
            // Convert (d, u, v) in slice space to (x, y, z) in chunk space.
            let (x, y, z) = slice_to_chunk(face, d * step, u * step, v * step);
            let voxel = super_voxel(chunk, x, y, z, step);
            // Render solid voxels AND non-solid voxels that have visible color
            // (e.g. water: alpha > 0 but is_solid = false).  Air (alpha = 0)
            // is always skipped.
            let has_color = voxel.color()[3] > 0.0;
            if has_color && face_visible(chunk, x, y, z, face, step) {
                let state = chunk.get_state(x, y, z);
                mask[v * size + u] = Some((voxel, state));
            } else {
                mask[v * size + u] = None;
            }
        }
    }
}

/// Converts slice-space coordinates `(d, u, v)` to chunk-space `(x, y, z)`.
#[inline]
fn slice_to_chunk(face: &FaceDir, d: usize, u: usize, v: usize) -> (usize, usize, usize) {
    let mut coords = [0usize; 3];
    coords[face.axis] = d;
    coords[face.u_axis] = u;
    coords[face.v_axis] = v;
    (coords[0], coords[1], coords[2])
}

/// Greedy-merges the mask and emits quads into the output buffers.
///
/// Two cells are merged only when both the voxel type AND the state byte are
/// identical.  This ensures that blocks placed against different faces — which
/// may map to different texture layers via
/// [`crate::voxel::VoxelType::texture_layer_for_state`] — are never collapsed
/// into a single quad that would display the wrong texture on part of it.
#[allow(clippy::too_many_arguments)] // All args are distinct output buffers; splitting would add indirection.
fn greedy_merge<V: VoxelType>(
    chunk: &Chunk<V>,
    mask: &mut [Option<(V, u8)>],
    size: usize,
    face: &FaceDir,
    face_index: usize,
    d: usize,
    step: usize,
    positions: &mut Vec<[f32; 3]>,
    normals: &mut Vec<[f32; 3]>,
    uvs: &mut Vec<[f32; 2]>,
    colors: &mut Vec<[f32; 4]>,
    texture_layers: &mut Vec<u32>,
    indices: &mut Vec<u32>,
) {
    for v in 0..size {
        let mut u = 0;
        while u < size {
            let (voxel, state) = match mask[v * size + u] {
                Some(entry) => entry,
                None => {
                    u += 1;
                    continue;
                }
            };

            // Find width: extend in u while same voxel type AND same state.
            let mut width = 1;
            while u + width < size && mask[v * size + u + width] == Some((voxel, state)) {
                width += 1;
            }

            // Find height: extend in v while entire row of width matches.
            let mut height = 1;
            'outer: while v + height < size {
                for du in 0..width {
                    if mask[(v + height) * size + u + du] != Some((voxel, state)) {
                        break 'outer;
                    }
                }
                height += 1;
            }

            // Clear the merged region in the mask.
            for dv in 0..height {
                for du in 0..width {
                    mask[(v + dv) * size + u + du] = None;
                }
            }

            // Emit the quad.
            emit_quad(
                chunk,
                face,
                face_index,
                d,
                u,
                v,
                width,
                height,
                step,
                voxel,
                state,
                positions,
                normals,
                uvs,
                colors,
                texture_layers,
                indices,
            );

            u += width;
        }
    }
}

/// Returns `true` if the voxel at `coords` (indexed by axis) is solid.
///
/// Any coordinate outside `[0, CHUNK_SIZE)` is treated as air (not solid),
/// using wrapping arithmetic so that `usize` underflow is detected as
/// out-of-bounds.
#[inline]
fn ao_neighbor_solid<V: VoxelType>(chunk: &Chunk<V>, coords: [usize; 3]) -> bool {
    if coords[0] >= CHUNK_SIZE || coords[1] >= CHUNK_SIZE || coords[2] >= CHUNK_SIZE {
        return false;
    }
    chunk.get(coords[0], coords[1], coords[2]).is_solid()
}

/// Computes the ambient occlusion factor for a single vertex corner.
///
/// Queries the two edge neighbors (`side1`, `side2`) and the diagonal
/// corner neighbor around the vertex in the tangent plane at the face
/// surface.  The classic voxel AO formula maps 0–3 occluders to the range
/// `[1.0, 0.4]`:
///
/// | Occluders | AO factor |
/// |-----------|-----------|
/// | 0         | 1.0       |
/// | 1         | 0.8       |
/// | 2         | 0.6       |
/// | 3         | 0.4       |
///
/// When both side neighbors are solid the corner is always fully occluded
/// (`0.4`) regardless of the actual corner voxel, matching standard voxel
/// AO behavior.
#[inline]
fn compute_ao(side1: bool, side2: bool, corner: bool) -> f32 {
    match side1 as u8 + side2 as u8 + corner as u8 {
        0 => 1.0,
        1 => 0.8,
        2 => 0.6,
        _ => 0.4,
    }
}

/// Computes the AO factor for one vertex of a quad.
///
/// `d_voxel` is the voxel-space coordinate along the face's primary axis
/// where the AO neighbors live (just beyond the face surface).
/// `cu_voxel` and `cv_voxel` are the corner's integer voxel coordinates
/// in the u and v tangent axes respectively.
///
/// The three neighbors are sampled using wrapping arithmetic; any sample
/// that falls outside `[0, CHUNK_SIZE)` on any axis is treated as air.
#[inline]
fn vertex_ao<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    d_voxel: usize,
    cu_voxel: usize,
    cv_voxel: usize,
) -> f32 {
    // Side1: one step back along u (wrapping_sub so underflow → usize::MAX → out-of-bounds).
    let mut s1 = [0usize; 3];
    s1[face.axis] = d_voxel;
    s1[face.u_axis] = cu_voxel.wrapping_sub(1);
    s1[face.v_axis] = cv_voxel;
    let side1 = ao_neighbor_solid(chunk, s1);

    // Side2: one step back along v.
    let mut s2 = [0usize; 3];
    s2[face.axis] = d_voxel;
    s2[face.u_axis] = cu_voxel;
    s2[face.v_axis] = cv_voxel.wrapping_sub(1);
    let side2 = ao_neighbor_solid(chunk, s2);

    // Corner: one step back along both u and v.
    let mut sc = [0usize; 3];
    sc[face.axis] = d_voxel;
    sc[face.u_axis] = cu_voxel.wrapping_sub(1);
    sc[face.v_axis] = cv_voxel.wrapping_sub(1);
    let corner = ao_neighbor_solid(chunk, sc);

    compute_ao(side1, side2, corner)
}

/// Emits a single quad (4 vertices, 6 indices) for a merged rectangle.
///
/// Per-vertex ambient occlusion is computed by sampling the three voxels
/// surrounding each corner in the tangent plane at the face surface.  The AO
/// factor darkens the vertex color's RGB channels while leaving alpha intact.
/// The quad's triangulation is flipped when needed to avoid the AO anisotropy
/// seam artifact described in Mikola Lysenko's original voxel AO paper.
#[allow(clippy::too_many_arguments)] // All args are distinct mesh output buffers; a wrapper struct adds no clarity.
#[inline]
fn emit_quad<V: VoxelType>(
    chunk: &Chunk<V>,
    face: &FaceDir,
    face_index: usize,
    d: usize,
    u: usize,
    v: usize,
    width: usize,
    height: usize,
    step: usize,
    voxel: V,
    state: u8,
    positions: &mut Vec<[f32; 3]>,
    normals: &mut Vec<[f32; 3]>,
    uvs: &mut Vec<[f32; 2]>,
    colors: &mut Vec<[f32; 4]>,
    texture_layers: &mut Vec<u32>,
    indices: &mut Vec<u32>,
) {
    let s = step as f32 * VOXEL_SIZE;

    // The slice position along the primary axis.
    // For positive faces, the quad sits at (d + 1) * step (the far side of the voxel).
    // For negative faces, the quad sits at d * step (the near side).
    let d_pos = if face.positive {
        (d as f32 + 1.0) * s
    } else {
        d as f32 * s
    };

    // The voxel-space depth coordinate for AO sampling.
    // For a positive face, the visible surface is the +face.axis side of voxel d*step,
    // so the AO neighbors live at (d+1)*step (the first layer beyond the surface).
    // For a negative face, the surface is the -face.axis side of voxel d*step,
    // so AO neighbors live at d*step - 1 (wrapping; out-of-bounds → treated as air).
    let ao_depth: usize = if face.positive {
        (d + 1) * step
    } else {
        d * step.wrapping_sub(1) // wrapping so step=0 case yields usize::MAX → out-of-bounds
    };
    // Clamp out-of-bounds depth to a sentinel that ao_neighbor_solid will reject.
    let ao_depth = if !face.positive && d == 0 {
        usize::MAX // underflow → out-of-bounds → all AO neighbors treated as air
    } else {
        ao_depth
    };

    let u_start = u as f32 * s;
    let v_start = v as f32 * s;
    let u_end = (u + width) as f32 * s;
    let v_end = (v + height) as f32 * s;

    // Voxel-space integer coords for each of the 4 corners (in u, v axes).
    // AO is sampled in the tangent plane at the face surface:
    //   v0: (u,       v)        → AO looks at (u-1, d_ao, v-1), etc.
    //   v1: (u+width, v)        → AO looks at (u+width-1, d_ao, v-1), etc.
    //   v2: (u+width, v+height) → AO looks at (u+width-1, d_ao, v+height-1), etc.
    //   v3: (u,       v+height) → AO looks at (u-1, d_ao, v+height-1), etc.
    //
    // The vertex_ao helper uses wrapping_sub so corner (u,v)=(0,0) correctly
    // treats the missing neighbors as air without a bounds check.
    let ao_v0 = vertex_ao(chunk, face, ao_depth, u * step, v * step);
    let ao_v1 = vertex_ao(chunk, face, ao_depth, (u + width) * step, v * step);
    let ao_v2 = vertex_ao(
        chunk,
        face,
        ao_depth,
        (u + width) * step,
        (v + height) * step,
    );
    let ao_v3 = vertex_ao(chunk, face, ao_depth, u * step, (v + height) * step);

    // Build the 4 corner positions in chunk-local space.
    // Corners in (u, v) order: (u_start, v_start), (u_end, v_start), (u_end, v_end), (u_start, v_end)
    let corners = [
        (u_start, v_start, ao_v0),
        (u_end, v_start, ao_v1),
        (u_end, v_end, ao_v2),
        (u_start, v_end, ao_v3),
    ];

    let base_idx = positions.len() as u32;
    // VoxelType::color() returns sRGB values (as humans define them).
    // The ChunkMaterial shader treats ATTRIBUTE_COLOR as linear RGB (used for AO),
    // so we convert here. The shader multiplies texture color by vertex color to
    // apply the baked AO.
    let srgb = voxel.color();
    let to_linear = |c: f32| -> f32 {
        if c <= 0.04045 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    let base_color = [
        to_linear(srgb[0]),
        to_linear(srgb[1]),
        to_linear(srgb[2]),
        srgb[3],
    ];

    // Texture layer for this face — same for all 4 vertices.
    // Uses texture_layer_for_state so that voxels with different placement
    // states can map to different texture layers (e.g. a log showing end-grain
    // on its top/bottom faces).  The default implementation ignores state and
    // delegates to texture_layer, so existing code is unaffected.
    let layer = voxel.texture_layer_for_state(face_index, state);

    for &(cu, cv, ao) in &corners {
        let mut pos = [0.0f32; 3];
        pos[face.axis] = d_pos;
        pos[face.u_axis] = cu;
        pos[face.v_axis] = cv;
        positions.push(pos);
        normals.push(face.normal);
        // Multiply linear RGB by the AO factor; alpha is left unchanged.
        // When ChunkMaterial is active the RGB carries the AO value (1.0 = no
        // occlusion, 0.4 = fully occluded). The shader multiplies the sampled
        // texture color by this value to apply AO.
        colors.push([
            base_color[0] * ao,
            base_color[1] * ao,
            base_color[2] * ao,
            base_color[3],
        ]);
        texture_layers.push(layer);
    }

    // UVs fixed to 0→1 per quad so the texture is displayed once per face
    // regardless of the merged quad size.  Tiling is intentionally disabled —
    // the texture array layers already contain the correct per-voxel texture.
    uvs.push([0.0, 0.0]);
    uvs.push([1.0, 0.0]);
    uvs.push([1.0, 1.0]);
    uvs.push([0.0, 1.0]);

    // Two triangles with CCW winding when viewed from the normal direction.
    // Bevy uses a right-hand coordinate system with CCW front faces.
    //
    // Cross-product analysis per face:
    //   axis=0 (+X/-X) and axis=1 (+Y/-Y): positive faces need (0,2,1),(0,3,2)
    //   and negative faces need (0,1,2),(0,2,3).
    //
    //   axis=2 (+Z/-Z): the u=X, v=Y tangent frame is left-handed relative to
    //   +Z, so the winding must be inverted — positive Z needs (0,1,2),(0,2,3)
    //   and negative Z needs (0,2,1),(0,3,2).
    //
    // A single XOR captures this: flip when (positive XOR axis==2) is false,
    // i.e. use the "CCW" branch when face.positive != (face.axis == 2).
    //
    // Additionally, flip the triangulation when ao_v0 + ao_v2 < ao_v1 + ao_v3.
    // This avoids the AO anisotropy seam artifact (Mikola Lysenko's fix).
    //
    // IMPORTANT: the flip must switch the DIAGONAL used to split the quad, NOT
    // the winding direction.  Inverting the winding would reverse the face
    // normal and cause Bevy's back-face culling to discard the triangle —
    // producing transparent holes.  Each case below independently maintains
    // correct CCW / CW winding while using the other diagonal (v1-v3 instead
    // of the default v0-v2) when `ao_flip` is true.
    //
    // Quad vertex layout (u increases right, v increases up):
    //   v3 --- v2
    //   |       |
    //   v0 --- v1
    //
    // Default diagonal v0-v2: triangles (v0,v2,v1) + (v0,v3,v2)  [CCW]
    //                                or (v0,v1,v2) + (v0,v2,v3)  [CW]
    // Alt diagonal    v1-v3: triangles (v0,v3,v1) + (v1,v3,v2)  [CCW]
    //                                or (v0,v1,v3) + (v1,v2,v3)  [CW]
    let ao_flip = ao_v0 + ao_v2 < ao_v1 + ao_v3;
    let ccw = face.positive != (face.axis == 2);
    match (ccw, ao_flip) {
        (true, false) => {
            // Default diagonal, CCW winding.
            indices.push(base_idx);
            indices.push(base_idx + 2);
            indices.push(base_idx + 1);
            indices.push(base_idx);
            indices.push(base_idx + 3);
            indices.push(base_idx + 2);
        }
        (true, true) => {
            // Alt diagonal (v1-v3), CCW winding — avoids AO seam.
            indices.push(base_idx);
            indices.push(base_idx + 3);
            indices.push(base_idx + 1);
            indices.push(base_idx + 1);
            indices.push(base_idx + 3);
            indices.push(base_idx + 2);
        }
        (false, false) => {
            // Default diagonal, CW winding.
            indices.push(base_idx);
            indices.push(base_idx + 1);
            indices.push(base_idx + 2);
            indices.push(base_idx);
            indices.push(base_idx + 2);
            indices.push(base_idx + 3);
        }
        (false, true) => {
            // Alt diagonal (v1-v3), CW winding — avoids AO seam.
            indices.push(base_idx);
            indices.push(base_idx + 1);
            indices.push(base_idx + 3);
            indices.push(base_idx + 1);
            indices.push(base_idx + 2);
            indices.push(base_idx + 3);
        }
    }
}

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

    /// Helper to extract vertex count from a mesh.
    fn vertex_count(mesh: &Mesh) -> usize {
        match mesh.attribute(Mesh::ATTRIBUTE_POSITION).expect("positions") {
            VertexAttributeValues::Float32x3(v) => v.len(),
            _ => panic!("unexpected attribute type"),
        }
    }

    /// Helper to extract index count from a mesh.
    fn index_count(mesh: &Mesh) -> usize {
        match mesh.indices().expect("indices") {
            Indices::U32(idx) => idx.len(),
            _ => panic!("expected U32 indices"),
        }
    }

    #[test]
    fn empty_chunk_produces_empty_mesh() {
        let chunk = Chunk::<DefaultVoxel>::new();
        let mesh = generate_chunk_mesh(&chunk, 1);
        assert_eq!(
            vertex_count(&mesh),
            0,
            "empty chunk should produce 0 vertices"
        );
    }

    #[test]
    fn fully_solid_chunk_produces_six_quads() {
        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 = generate_chunk_mesh(&chunk, 1);

        assert_eq!(
            vertex_count(&mesh),
            24,
            "fully solid chunk should have 24 vertices (4 per face x 6 faces)"
        );
        assert_eq!(
            index_count(&mesh),
            36,
            "fully solid chunk should have 36 indices (6 per face x 6 faces)"
        );
    }

    #[test]
    fn single_voxel_produces_six_faces() {
        let mut chunk = Chunk::<DefaultVoxel>::new();
        chunk.set(0, 0, 0, DefaultVoxel::Rock);
        let mesh = generate_chunk_mesh(&chunk, 1);

        assert_eq!(
            vertex_count(&mesh),
            24,
            "single voxel should have 24 vertices (4 per face x 6 faces)"
        );
        assert_eq!(
            index_count(&mesh),
            36,
            "single voxel should have 36 indices (6 per face x 6 faces)"
        );
    }

    #[test]
    fn lod_mesh_has_fewer_vertices() {
        // Create a chunk with a checkerboard pattern of two different voxel
        // types. At LOD 0, the greedy mesher cannot merge across different
        // types, producing many quads. At LOD 1, each 2x2x2 super-voxel
        // collapses to a single type, enabling much more merging.
        let mut chunk = Chunk::<DefaultVoxel>::new();
        for x in 0..CHUNK_SIZE {
            for y in 0..CHUNK_SIZE {
                for z in 0..CHUNK_SIZE {
                    if (x + y + z) % 2 == 0 {
                        chunk.set(x, y, z, DefaultVoxel::Rock);
                    } else {
                        chunk.set(x, y, z, DefaultVoxel::IronOre);
                    }
                }
            }
        }

        let mesh_lod0 = generate_chunk_mesh(&chunk, 1);
        let mesh_lod1 = generate_chunk_mesh(&chunk, 2);

        let count_lod0 = vertex_count(&mesh_lod0);
        let count_lod1 = vertex_count(&mesh_lod1);

        assert!(
            count_lod1 < count_lod0,
            "LOD 1 ({count_lod1} verts) should have fewer vertices than LOD 0 ({count_lod0} verts)"
        );
    }
}