Skip to main content

voxel_framework/mesh/
mod.rs

1//! Greedy mesh generation for voxel chunks with LOD and neighbor-aware seam culling.
2//!
3//! # Greedy meshing
4//!
5//! Naive voxel renderers emit one quad per visible face, producing O(n³) geometry
6//! even for flat surfaces. Greedy meshing collapses adjacent coplanar faces of the
7//! same voxel type into a single merged quad, reducing geometry by an order of
8//! magnitude for typical terrain.  The algorithm processes each of the six cardinal
9//! directions independently: for every slice perpendicular to the current axis it
10//! builds a 2-D visibility mask, then scans the mask left-to-right / top-to-bottom
11//! extending each run into the largest rectangle of identical voxels before emitting
12//! a single quad and clearing the merged region.
13//!
14//! # Entry points
15//!
16//! Two public meshing functions are provided:
17//!
18//! - [`generate_chunk_mesh`] — standalone meshing. Border faces that exit the
19//!   chunk boundary are always emitted as visible, which leaves gaps between
20//!   adjacent loaded chunks until they are meshed independently.
21//! - [`generate_chunk_mesh_with_neighbors`] — seam-free meshing. Border faces are
22//!   checked against the corresponding face of each adjacent chunk via
23//!   [`ChunkNeighbors`]. A face is culled when the neighboring voxel is solid,
24//!   eliminating single-voxel cracks at chunk boundaries.
25//!
26//! Prefer [`generate_chunk_mesh_with_neighbors`] for in-world rendering.
27//! Use [`generate_chunk_mesh`] for isolated previews or when neighbor data is
28//! unavailable.
29//!
30//! # Level of detail (LOD)
31//!
32//! The `step` parameter controls the LOD resolution.  A step of `1` samples every
33//! voxel at full detail.  A step of `2` groups each `2×2×2` block into a single
34//! super-voxel (half resolution), halving triangle counts for distant chunks.
35//! [`lod::compute_lod`] maps viewer distance to a level; [`lod::lod_to_step`]
36//! converts a level to the step value to pass here.
37//!
38//! | LOD level | Step | Distance threshold     |
39//! |-----------|------|------------------------|
40//! | `0`       | `1`  | < 200 world units      |
41//! | `1`       | `2`  | ≥ 200 world units      |
42//!
43//! [`lod::compute_lod_with_hysteresis`] adds a ±5-unit hysteresis band around the
44//! threshold to prevent rapid LOD oscillation as the viewer moves along the boundary.
45//!
46//! # Output mesh attributes
47//!
48//! Every mesh produced by this module contains:
49//!
50//! | Attribute               | Type          | Description                        |
51//! |-------------------------|---------------|------------------------------------|
52//! | `ATTRIBUTE_POSITION`    | `Float32x3`   | Vertex positions in chunk-local space |
53//! | `ATTRIBUTE_NORMAL`      | `Float32x3`   | Face normals (one of six unit axes) |
54//! | `ATTRIBUTE_UV_0`        | `Float32x2`   | UVs scaled by voxel count for tiling |
55//! | `ATTRIBUTE_COLOR`       | `Float32x4`   | Per-vertex color from [`VoxelType::color`] |
56//! | Indices                 | `U32`         | Triangle list with CCW winding      |
57//!
58//! [`MeshPlugin<V>`] wires the mesh generation, LOD update, and chunk despawn
59//! systems into a Bevy app.
60
61mod greedy;
62pub mod lod;
63mod neighbor;
64pub mod systems;
65
66pub use greedy::{ATTRIBUTE_TEXTURE_LAYER, generate_chunk_mesh};
67pub use neighbor::generate_chunk_mesh_with_neighbors;
68pub use systems::{
69    PendingNeighborRemesh, chunk_despawn_system, chunk_mesh_system, flush_neighbor_remesh_system,
70    lod_update_system,
71};
72
73use bevy::prelude::*;
74
75use crate::chunk::CHUNK_SIZE;
76use crate::generator::GeneratorSystems;
77use crate::voxel::VoxelType;
78
79// ─── MeshPlugin ───────────────────────────────────────────────────────────────
80
81/// Bevy [`Plugin`] that registers the mesh generation, LOD update, and chunk
82/// despawn systems for a specific voxel type `V`.
83///
84/// Add this plugin after [`crate::world::WorldPlugin`] and
85/// [`crate::generator::GeneratorPlugin`].  It registers three systems in the
86/// [`Update`] schedule:
87///
88/// - [`lod_update_system`] — recomputes LOD levels every frame and emits
89///   [`crate::world::ChunkModified`] when a level changes.
90/// - [`chunk_mesh_system`] — runs after [`crate::generator::GeneratorSystems`];
91///   responds to [`crate::world::ChunkModified`] by (re)building chunk meshes.
92/// - [`chunk_despawn_system`] — responds to [`crate::world::ChunkUnloadRequest`]
93///   by optionally saving to disk and despawning the entity.
94///
95/// # Examples
96///
97/// ```rust,no_run
98/// use bevy::prelude::*;
99/// use voxel_framework::{VoxelPlugin, generator::GeneratorPlugin, mesh::MeshPlugin, voxel::DefaultVoxel};
100///
101/// App::new()
102///     .add_plugins(DefaultPlugins)
103///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
104///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
105///     .add_plugins(MeshPlugin::<DefaultVoxel>::new())
106///     .run();
107/// ```
108pub struct MeshPlugin<V: VoxelType> {
109    _marker: std::marker::PhantomData<V>,
110}
111
112impl<V: VoxelType> MeshPlugin<V> {
113    /// Creates a new [`MeshPlugin`] for voxel type `V`.
114    pub fn new() -> Self {
115        Self {
116            _marker: std::marker::PhantomData,
117        }
118    }
119}
120
121impl<V: VoxelType> Default for MeshPlugin<V> {
122    fn default() -> Self {
123        Self::new()
124    }
125}
126
127impl<V: VoxelType> Plugin for MeshPlugin<V> {
128    fn build(&self, app: &mut App) {
129        app.init_resource::<systems::PendingNeighborRemesh>();
130        app.add_systems(
131            Update,
132            (
133                systems::lod_update_system::<V>,
134                systems::chunk_mesh_system::<V>.after(GeneratorSystems),
135                systems::flush_neighbor_remesh_system.after(systems::chunk_mesh_system::<V>),
136                systems::chunk_despawn_system::<V>,
137            ),
138        );
139    }
140}
141
142/// Border voxel data from the six cardinal neighbors of a chunk, used for
143/// seam-free meshing with [`generate_chunk_mesh_with_neighbors`].
144///
145/// Each slot holds a flat `CHUNK_SIZE × CHUNK_SIZE` array containing the
146/// outermost face of the adjacent chunk that abuts the current chunk on that
147/// side.  The array is obtained from `Chunk::border_slice` on the neighbor.
148///
149/// The face index convention matches `FACE_DIRS`:
150///
151/// | Index | Direction | Neighbor face stored          |
152/// |-------|-----------|-------------------------------|
153/// | `0`   | `+Y`      | bottom face of the chunk above |
154/// | `1`   | `-Y`      | top face of the chunk below    |
155/// | `2`   | `+X`      | left face of the chunk to the right |
156/// | `3`   | `-X`      | right face of the chunk to the left |
157/// | `4`   | `+Z`      | back face of the chunk in front |
158/// | `5`   | `-Z`      | front face of the chunk behind  |
159///
160/// A slot set to `None` means the neighbor is not loaded; the border face is
161/// then treated as open air and the face is emitted unconditionally.
162pub struct ChunkNeighbors<V: VoxelType> {
163    /// Six border face slices in `[+Y, -Y, +X, -X, +Z, -Z]` order.
164    ///
165    /// Each `Some` entry is a `CHUNK_SIZE * CHUNK_SIZE` flat array packed in
166    /// the same order as `Chunk::border_slice` for that face index.
167    pub faces: [Option<[V; CHUNK_SIZE * CHUNK_SIZE]>; 6],
168}
169
170impl<V: VoxelType> Default for ChunkNeighbors<V> {
171    fn default() -> Self {
172        Self {
173            faces: [None, None, None, None, None, None],
174        }
175    }
176}