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` | 0 to 1 across each merged quad (no tiling) |
55//! | `ATTRIBUTE_COLOR` | `Float32x4` | [`VoxelType::color`] in linear RGB, darkened by baked ambient occlusion |
56//! | [`ATTRIBUTE_TEXTURE_LAYER`] | `Uint32` | [`VoxelType::texture_layer_for_state`] of the face |
57//! | [`ATTRIBUTE_FACE_EXPOSED`] | `Float32` | `1.0` on faces uncovered by an edit ([`crate::chunk::Chunk::exposed_faces`]), else `0.0` |
58//! | Indices | `U32` | Triangle list with CCW winding |
59//!
60//! # Terrain materials
61//!
62//! [`generate_chunk_material_meshes`] returns one mesh per
63//! [`VoxelType::material`]. [`chunk_mesh_system`] uses it to draw the faces of
64//! every material registered in
65//! [`TerrainMaterials`](crate::render::TerrainMaterials) with a child entity of
66//! the chunk; all other faces stay in the chunk's own mesh.
67//!
68//! [`MeshPlugin<V>`] wires the mesh generation, LOD update, and chunk despawn
69//! systems into a Bevy app.
70
71mod greedy;
72pub mod lod;
73mod neighbor;
74pub mod systems;
75
76pub use greedy::{ATTRIBUTE_FACE_EXPOSED, ATTRIBUTE_TEXTURE_LAYER, generate_chunk_mesh};
77pub use neighbor::{
78 generate_chunk_material_meshes, generate_chunk_material_meshes_with_config,
79 generate_chunk_mesh_with_neighbors,
80};
81pub use systems::{
82 ChunkMeshBudget, PendingChunkMeshes, PendingNeighborRemesh, chunk_despawn_system,
83 chunk_mesh_system, flush_neighbor_remesh_system, lod_update_system, mesh_config_changed_system,
84 terrain_materials_changed_system,
85};
86
87use bevy::prelude::*;
88
89use crate::chunk::CHUNK_SIZE;
90use crate::generator::GeneratorSystems;
91use crate::voxel::VoxelType;
92
93/// System set containing the chunk meshing systems that
94/// [`MeshPlugin`] adds: [`chunk_mesh_system`] and
95/// [`flush_neighbor_remesh_system`].
96///
97/// Order your own systems `.after(MeshSystems)` to observe the state left by
98/// this frame's meshing, such as [`PendingChunkMeshes`].
99#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
100pub struct MeshSystems;
101
102// ─── MeshPlugin ───────────────────────────────────────────────────────────────
103
104/// Bevy [`Plugin`] that registers the mesh generation, LOD update, and chunk
105/// despawn systems for a specific voxel type `V`.
106///
107/// Add this plugin after [`crate::world::WorldPlugin`] and
108/// [`crate::generator::GeneratorPlugin`]. It registers three systems in the
109/// [`Update`] schedule:
110///
111/// - [`lod_update_system`] — recomputes LOD levels every frame and emits
112/// [`crate::world::ChunkModified`] when a level changes.
113/// - [`ChunkMeshBudget`] and [`PendingChunkMeshes`] resources: the per-frame
114/// bound on meshing and the queue of chunks waiting for it.
115/// - [`chunk_mesh_system`] — runs after [`crate::generator::GeneratorSystems`];
116/// responds to [`crate::world::ChunkModified`] by (re)building chunk meshes.
117/// - [`chunk_despawn_system`] — responds to [`crate::world::ChunkUnloadRequest`]
118/// by saving the chunk if it has unsaved changes and despawning the entity.
119///
120/// # Examples
121///
122/// ```rust,no_run
123/// use bevy::prelude::*;
124/// use voxel_framework::{VoxelPlugin, generator::GeneratorPlugin, mesh::MeshPlugin, voxel::DefaultVoxel};
125///
126/// App::new()
127/// .add_plugins(DefaultPlugins)
128/// .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
129/// .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
130/// .add_plugins(MeshPlugin::<DefaultVoxel>::new())
131/// .run();
132/// ```
133pub struct MeshPlugin<V: VoxelType> {
134 _marker: std::marker::PhantomData<V>,
135}
136
137impl<V: VoxelType> MeshPlugin<V> {
138 /// Creates a new [`MeshPlugin`] for voxel type `V`.
139 pub fn new() -> Self {
140 Self {
141 _marker: std::marker::PhantomData,
142 }
143 }
144}
145
146impl<V: VoxelType> Default for MeshPlugin<V> {
147 fn default() -> Self {
148 Self::new()
149 }
150}
151
152impl<V: VoxelType> Plugin for MeshPlugin<V> {
153 fn build(&self, app: &mut App) {
154 app.init_resource::<systems::PendingNeighborRemesh>();
155 app.init_resource::<systems::PendingChunkMeshes>();
156 app.init_resource::<systems::ChunkMeshBudget>();
157 app.init_resource::<MeshConfig>();
158 app.add_systems(
159 Update,
160 (
161 systems::lod_update_system::<V>,
162 systems::terrain_materials_changed_system.before(systems::chunk_mesh_system::<V>),
163 systems::mesh_config_changed_system.before(systems::chunk_mesh_system::<V>),
164 systems::chunk_mesh_system::<V>
165 .after(GeneratorSystems)
166 .in_set(MeshSystems),
167 systems::flush_neighbor_remesh_system
168 .after(systems::chunk_mesh_system::<V>)
169 .in_set(MeshSystems),
170 systems::chunk_despawn_system::<V>,
171 ),
172 );
173 }
174}
175
176/// Options of the chunk mesher.
177///
178/// [`MeshPlugin`] initializes it with the defaults, which draw sharp cubes as
179/// before. Changing it while the game runs rebuilds the meshes of the loaded
180/// chunks.
181///
182/// # Edge chamfer
183///
184/// `edge_chamfer: Some(width)` cuts every convex edge between two exposed
185/// faces with a flat facet. `width` is the part of each face that is cut, as a
186/// fraction of the voxel; it is clamped to `0.5` and a value that is zero,
187/// negative or not finite turns the chamfer off.
188///
189/// - It is a visual effect of the mesh only. Collision, raycasts, mining and
190/// saved chunks do not change.
191/// - Only solid, opaque voxels are chamfered, and only where nothing is drawn
192/// in front of either face. Voxels surrounded by others and flat seams
193/// between neighbors stay untouched and still merge into large quads.
194/// - A chamfer facet has its own normal, halfway between the two faces, so it
195/// shades as a facet. Its vertices take the color, baked ambient occlusion
196/// and texture layer of the face they border.
197/// - Only LOD 0 (step 1) is chamfered; LOD 1 meshes stay sharp.
198/// - Cost: each chamfered side of a quad adds 4 vertices, each convex corner
199/// 4 more and each chamfer that ends against another voxel 3 more. A lone
200/// voxel goes from 24 to 216 vertices; a large flat surface gains only its
201/// outline. A quad can also merge a little less, because each of its sides
202/// has to be chamfered along its whole length or not at all.
203/// - Across a chunk border the chamfer needs the neighbor's voxels. Where the
204/// mesher cannot know them (chunks that only share an edge or a corner) it
205/// closes the chamfer with a small cap, which may be hidden inside the
206/// terrain.
207#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
208pub struct MeshConfig {
209 /// Width of the chamfer on convex edges, as a fraction of the voxel.
210 /// `None` (the default) keeps sharp edges.
211 pub edge_chamfer: Option<f32>,
212}
213
214impl MeshConfig {
215 /// The chamfer width in world units, or `None` when chamfers are off.
216 pub(crate) fn chamfer_width(&self) -> Option<f32> {
217 self.edge_chamfer
218 .filter(|width| width.is_finite() && *width > 0.0)
219 .map(|width| width.min(0.5) * crate::chunk::VOXEL_SIZE)
220 }
221}
222
223/// Border voxel data from the six cardinal neighbors of a chunk, used for
224/// seam-free meshing with [`generate_chunk_mesh_with_neighbors`].
225///
226/// Each slot holds a flat `CHUNK_SIZE × CHUNK_SIZE` array containing the
227/// outermost face of the adjacent chunk that abuts the current chunk on that
228/// side. The array is obtained from `Chunk::border_slice` on the neighbor.
229///
230/// The face index convention matches `FACE_DIRS`:
231///
232/// | Index | Direction | Neighbor face stored |
233/// |-------|-----------|-------------------------------|
234/// | `0` | `+Y` | bottom face of the chunk above |
235/// | `1` | `-Y` | top face of the chunk below |
236/// | `2` | `+X` | left face of the chunk to the right |
237/// | `3` | `-X` | right face of the chunk to the left |
238/// | `4` | `+Z` | back face of the chunk in front |
239/// | `5` | `-Z` | front face of the chunk behind |
240///
241/// A slot set to `None` means the neighbor is not loaded; the border face is
242/// then treated as open air and the face is emitted unconditionally.
243pub struct ChunkNeighbors<V: VoxelType> {
244 /// Six border face slices in `[+Y, -Y, +X, -X, +Z, -Z]` order.
245 ///
246 /// Each `Some` entry is a `CHUNK_SIZE * CHUNK_SIZE` flat array packed in
247 /// the same order as `Chunk::border_slice` for that face index.
248 pub faces: [Option<[V; CHUNK_SIZE * CHUNK_SIZE]>; 6],
249}
250
251impl<V: VoxelType> Default for ChunkNeighbors<V> {
252 fn default() -> Self {
253 Self {
254 faces: [None, None, None, None, None, None],
255 }
256 }
257}
258
259/// A voxel palette with two terrain materials, for the mesh tests.
260#[cfg(test)]
261pub(crate) mod test_voxel {
262 use crate::voxel::{TerrainMaterialId, VoxelType};
263
264 /// The material of [`TwoMaterialVoxel::Glass`].
265 pub(crate) const GLASS: TerrainMaterialId = TerrainMaterialId(7);
266
267 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
268 pub(crate) enum TwoMaterialVoxel {
269 #[default]
270 Air,
271 Stone,
272 Glass,
273 }
274
275 impl VoxelType for TwoMaterialVoxel {
276 fn name(&self) -> &'static str {
277 match self {
278 Self::Air => "air",
279 Self::Stone => "stone",
280 Self::Glass => "glass",
281 }
282 }
283
284 fn is_solid(&self) -> bool {
285 !matches!(self, Self::Air)
286 }
287
288 fn color(&self) -> [f32; 4] {
289 match self {
290 Self::Air => [0.0; 4],
291 Self::Stone => [0.5, 0.5, 0.5, 1.0],
292 Self::Glass => [0.6, 0.8, 1.0, 1.0],
293 }
294 }
295
296 fn to_byte(&self) -> u8 {
297 *self as u8
298 }
299
300 fn from_byte(byte: u8) -> Self {
301 match byte {
302 1 => Self::Stone,
303 2 => Self::Glass,
304 _ => Self::Air,
305 }
306 }
307
308 fn material(&self) -> TerrainMaterialId {
309 match self {
310 Self::Glass => GLASS,
311 _ => TerrainMaterialId::DEFAULT,
312 }
313 }
314 }
315}