voxel-framework 0.13.1

A reusable voxel engine framework built on Bevy
Documentation
//! Greedy mesh generation for voxel chunks with LOD and neighbor-aware seam culling.
//!
//! # Greedy meshing
//!
//! Naive voxel renderers emit one quad per visible face, producing O(n³) geometry
//! even for flat surfaces. Greedy meshing collapses adjacent coplanar faces of the
//! same voxel type into a single merged quad, reducing geometry by an order of
//! magnitude for typical terrain.  The algorithm processes each of the six cardinal
//! directions independently: for every slice perpendicular to the current axis it
//! builds a 2-D visibility mask, then scans the mask left-to-right / top-to-bottom
//! extending each run into the largest rectangle of identical voxels before emitting
//! a single quad and clearing the merged region.
//!
//! # Entry points
//!
//! Two public meshing functions are provided:
//!
//! - [`generate_chunk_mesh`] — standalone meshing. Border faces that exit the
//!   chunk boundary are always emitted as visible, which leaves gaps between
//!   adjacent loaded chunks until they are meshed independently.
//! - [`generate_chunk_mesh_with_neighbors`] — seam-free meshing. Border faces are
//!   checked against the corresponding face of each adjacent chunk via
//!   [`ChunkNeighbors`]. A face is culled when the neighboring voxel is solid,
//!   eliminating single-voxel cracks at chunk boundaries.
//!
//! Prefer [`generate_chunk_mesh_with_neighbors`] for in-world rendering.
//! Use [`generate_chunk_mesh`] for isolated previews or when neighbor data is
//! unavailable.
//!
//! # Level of detail (LOD)
//!
//! The `step` parameter controls the LOD resolution.  A step of `1` samples every
//! voxel at full detail.  A step of `2` groups each `2×2×2` block into a single
//! super-voxel (half resolution), halving triangle counts for distant chunks.
//! [`lod::compute_lod`] maps viewer distance to a level; [`lod::lod_to_step`]
//! converts a level to the step value to pass here.
//!
//! | LOD level | Step | Distance threshold     |
//! |-----------|------|------------------------|
//! | `0`       | `1`  | < 200 world units      |
//! | `1`       | `2`  | ≥ 200 world units      |
//!
//! [`lod::compute_lod_with_hysteresis`] adds a ±5-unit hysteresis band around the
//! threshold to prevent rapid LOD oscillation as the viewer moves along the boundary.
//!
//! # Output mesh attributes
//!
//! Every mesh produced by this module contains:
//!
//! | Attribute               | Type          | Description                        |
//! |-------------------------|---------------|------------------------------------|
//! | `ATTRIBUTE_POSITION`    | `Float32x3`   | Vertex positions in chunk-local space |
//! | `ATTRIBUTE_NORMAL`      | `Float32x3`   | Face normals (one of six unit axes) |
//! | `ATTRIBUTE_UV_0`        | `Float32x2`   | 0 to 1 across each merged quad (no tiling) |
//! | `ATTRIBUTE_COLOR`       | `Float32x4`   | [`VoxelType::color`] in linear RGB, darkened by baked ambient occlusion |
//! | [`ATTRIBUTE_TEXTURE_LAYER`] | `Uint32`  | [`VoxelType::texture_layer_for_state`] of the face |
//! | [`ATTRIBUTE_FACE_EXPOSED`] | `Float32`  | `1.0` on faces uncovered by an edit ([`crate::chunk::Chunk::exposed_faces`]), else `0.0` |
//! | Indices                 | `U32`         | Triangle list with CCW winding      |
//!
//! # Terrain materials
//!
//! [`generate_chunk_material_meshes`] returns one mesh per
//! [`VoxelType::material`]. [`chunk_mesh_system`] uses it to draw the faces of
//! every material registered in
//! [`TerrainMaterials`](crate::render::TerrainMaterials) with a child entity of
//! the chunk; all other faces stay in the chunk's own mesh.
//!
//! [`MeshPlugin<V>`] wires the mesh generation, LOD update, and chunk despawn
//! systems into a Bevy app.

mod greedy;
pub mod lod;
mod neighbor;
pub mod systems;

pub use greedy::{ATTRIBUTE_FACE_EXPOSED, ATTRIBUTE_TEXTURE_LAYER, generate_chunk_mesh};
pub use neighbor::{
    generate_chunk_material_meshes, generate_chunk_material_meshes_with_config,
    generate_chunk_mesh_with_neighbors,
};
pub use systems::{
    ChunkMeshBudget, PendingChunkMeshes, PendingNeighborRemesh, chunk_despawn_system,
    chunk_mesh_system, flush_neighbor_remesh_system, lod_update_system, mesh_config_changed_system,
    terrain_materials_changed_system,
};

use bevy::prelude::*;

use crate::chunk::CHUNK_SIZE;
use crate::generator::GeneratorSystems;
use crate::voxel::VoxelType;

/// System set containing the chunk meshing systems that
/// [`MeshPlugin`] adds: [`chunk_mesh_system`] and
/// [`flush_neighbor_remesh_system`].
///
/// Order your own systems `.after(MeshSystems)` to observe the state left by
/// this frame's meshing, such as [`PendingChunkMeshes`].
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub struct MeshSystems;

// ─── MeshPlugin ───────────────────────────────────────────────────────────────

/// Bevy [`Plugin`] that registers the mesh generation, LOD update, and chunk
/// despawn systems for a specific voxel type `V`.
///
/// Add this plugin after [`crate::world::WorldPlugin`] and
/// [`crate::generator::GeneratorPlugin`].  It registers three systems in the
/// [`Update`] schedule:
///
/// - [`lod_update_system`] — recomputes LOD levels every frame and emits
///   [`crate::world::ChunkModified`] when a level changes.
/// - [`ChunkMeshBudget`] and [`PendingChunkMeshes`] resources: the per-frame
///   bound on meshing and the queue of chunks waiting for it.
/// - [`chunk_mesh_system`] — runs after [`crate::generator::GeneratorSystems`];
///   responds to [`crate::world::ChunkModified`] by (re)building chunk meshes.
/// - [`chunk_despawn_system`] — responds to [`crate::world::ChunkUnloadRequest`]
///   by saving the chunk if it has unsaved changes and despawning the entity.
///
/// # Examples
///
/// ```rust,no_run
/// use bevy::prelude::*;
/// use voxel_framework::{VoxelPlugin, generator::GeneratorPlugin, mesh::MeshPlugin, voxel::DefaultVoxel};
///
/// App::new()
///     .add_plugins(DefaultPlugins)
///     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
///     .add_plugins(MeshPlugin::<DefaultVoxel>::new())
///     .run();
/// ```
pub struct MeshPlugin<V: VoxelType> {
    _marker: std::marker::PhantomData<V>,
}

impl<V: VoxelType> MeshPlugin<V> {
    /// Creates a new [`MeshPlugin`] for voxel type `V`.
    pub fn new() -> Self {
        Self {
            _marker: std::marker::PhantomData,
        }
    }
}

impl<V: VoxelType> Default for MeshPlugin<V> {
    fn default() -> Self {
        Self::new()
    }
}

impl<V: VoxelType> Plugin for MeshPlugin<V> {
    fn build(&self, app: &mut App) {
        app.init_resource::<systems::PendingNeighborRemesh>();
        app.init_resource::<systems::PendingChunkMeshes>();
        app.init_resource::<systems::ChunkMeshBudget>();
        app.init_resource::<MeshConfig>();
        app.add_systems(
            Update,
            (
                systems::lod_update_system::<V>,
                systems::terrain_materials_changed_system.before(systems::chunk_mesh_system::<V>),
                systems::mesh_config_changed_system.before(systems::chunk_mesh_system::<V>),
                systems::chunk_mesh_system::<V>
                    .after(GeneratorSystems)
                    .in_set(MeshSystems),
                systems::flush_neighbor_remesh_system
                    .after(systems::chunk_mesh_system::<V>)
                    .in_set(MeshSystems),
                systems::chunk_despawn_system::<V>,
            ),
        );
    }
}

/// Options of the chunk mesher.
///
/// [`MeshPlugin`] initializes it with the defaults, which draw sharp cubes as
/// before. Changing it while the game runs rebuilds the meshes of the loaded
/// chunks.
///
/// # Edge chamfer
///
/// `edge_chamfer: Some(width)` cuts every convex edge between two exposed
/// faces with a flat facet. `width` is the part of each face that is cut, as a
/// fraction of the voxel; it is clamped to `0.5` and a value that is zero,
/// negative or not finite turns the chamfer off.
///
/// - It is a visual effect of the mesh only. Collision, raycasts, mining and
///   saved chunks do not change.
/// - Only solid, opaque voxels are chamfered, and only where nothing is drawn
///   in front of either face. Voxels surrounded by others and flat seams
///   between neighbors stay untouched and still merge into large quads.
/// - A chamfer facet has its own normal, halfway between the two faces, so it
///   shades as a facet. Its vertices take the color, baked ambient occlusion
///   and texture layer of the face they border.
/// - Only LOD 0 (step 1) is chamfered; LOD 1 meshes stay sharp.
/// - Cost: each chamfered side of a quad adds 4 vertices, each convex corner
///   4 more and each chamfer that ends against another voxel 3 more. A lone
///   voxel goes from 24 to 216 vertices; a large flat surface gains only its
///   outline. A quad can also merge a little less, because each of its sides
///   has to be chamfered along its whole length or not at all.
/// - Across a chunk border the chamfer needs the neighbor's voxels. Where the
///   mesher cannot know them (chunks that only share an edge or a corner) it
///   closes the chamfer with a small cap, which may be hidden inside the
///   terrain.
#[derive(Resource, Debug, Clone, Copy, PartialEq, Default)]
pub struct MeshConfig {
    /// Width of the chamfer on convex edges, as a fraction of the voxel.
    /// `None` (the default) keeps sharp edges.
    pub edge_chamfer: Option<f32>,
}

impl MeshConfig {
    /// The chamfer width in world units, or `None` when chamfers are off.
    pub(crate) fn chamfer_width(&self) -> Option<f32> {
        self.edge_chamfer
            .filter(|width| width.is_finite() && *width > 0.0)
            .map(|width| width.min(0.5) * crate::chunk::VOXEL_SIZE)
    }
}

/// Border voxel data from the six cardinal neighbors of a chunk, used for
/// seam-free meshing with [`generate_chunk_mesh_with_neighbors`].
///
/// Each slot holds a flat `CHUNK_SIZE × CHUNK_SIZE` array containing the
/// outermost face of the adjacent chunk that abuts the current chunk on that
/// side.  The array is obtained from `Chunk::border_slice` on the neighbor.
///
/// The face index convention matches `FACE_DIRS`:
///
/// | Index | Direction | Neighbor face stored          |
/// |-------|-----------|-------------------------------|
/// | `0`   | `+Y`      | bottom face of the chunk above |
/// | `1`   | `-Y`      | top face of the chunk below    |
/// | `2`   | `+X`      | left face of the chunk to the right |
/// | `3`   | `-X`      | right face of the chunk to the left |
/// | `4`   | `+Z`      | back face of the chunk in front |
/// | `5`   | `-Z`      | front face of the chunk behind  |
///
/// A slot set to `None` means the neighbor is not loaded; the border face is
/// then treated as open air and the face is emitted unconditionally.
pub struct ChunkNeighbors<V: VoxelType> {
    /// Six border face slices in `[+Y, -Y, +X, -X, +Z, -Z]` order.
    ///
    /// Each `Some` entry is a `CHUNK_SIZE * CHUNK_SIZE` flat array packed in
    /// the same order as `Chunk::border_slice` for that face index.
    pub faces: [Option<[V; CHUNK_SIZE * CHUNK_SIZE]>; 6],
}

impl<V: VoxelType> Default for ChunkNeighbors<V> {
    fn default() -> Self {
        Self {
            faces: [None, None, None, None, None, None],
        }
    }
}

/// A voxel palette with two terrain materials, for the mesh tests.
#[cfg(test)]
pub(crate) mod test_voxel {
    use crate::voxel::{TerrainMaterialId, VoxelType};

    /// The material of [`TwoMaterialVoxel::Glass`].
    pub(crate) const GLASS: TerrainMaterialId = TerrainMaterialId(7);

    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
    pub(crate) enum TwoMaterialVoxel {
        #[default]
        Air,
        Stone,
        Glass,
    }

    impl VoxelType for TwoMaterialVoxel {
        fn name(&self) -> &'static str {
            match self {
                Self::Air => "air",
                Self::Stone => "stone",
                Self::Glass => "glass",
            }
        }

        fn is_solid(&self) -> bool {
            !matches!(self, Self::Air)
        }

        fn color(&self) -> [f32; 4] {
            match self {
                Self::Air => [0.0; 4],
                Self::Stone => [0.5, 0.5, 0.5, 1.0],
                Self::Glass => [0.6, 0.8, 1.0, 1.0],
            }
        }

        fn to_byte(&self) -> u8 {
            *self as u8
        }

        fn from_byte(byte: u8) -> Self {
            match byte {
                1 => Self::Stone,
                2 => Self::Glass,
                _ => Self::Air,
            }
        }

        fn material(&self) -> TerrainMaterialId {
            match self {
                Self::Glass => GLASS,
                _ => TerrainMaterialId::DEFAULT,
            }
        }
    }
}