voxel-framework 0.13.2

A reusable voxel engine framework built on Bevy
Documentation
//! Recording which voxel faces were uncovered by edits.
//!
//! A generated chunk has no exposed faces. When an edit removes a voxel, the
//! faces of its neighbors that it was covering are recorded as exposed in
//! [`Chunk::exposed_faces`]. The mesher reports the record per face in
//! [`ATTRIBUTE_FACE_EXPOSED`](crate::mesh::ATTRIBUTE_FACE_EXPOSED), so a
//! terrain material can draw mined surfaces differently from the original
//! surface. The framework only keeps the record; what a fresh face looks
//! like is the game's.

use bevy::prelude::*;

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

use super::{ChunkManager, ChunkModified};

/// The six face directions in face-index order: `0` = +Y, `1` = -Y, `2` = +X,
/// `3` = -X, `4` = +Z, `5` = -Z. The opposite of face `i` is `i ^ 1`.
const FACE_OFFSETS: [IVec3; 6] = [
    IVec3::Y,
    IVec3::NEG_Y,
    IVec3::X,
    IVec3::NEG_X,
    IVec3::Z,
    IVec3::NEG_Z,
];

/// Whether a voxel draws anything, as the mesher decides it.
fn is_drawn<V: VoxelType>(voxel: V) -> bool {
    voxel.color()[3] > 0.0
}

/// Updates the exposed-face record after the voxel at `local` in
/// `chunk_coord` changed from `old` to `new`. Call it after writing the voxel.
///
/// - The edited voxel starts with no exposed faces: the record describes the
///   voxel that was there.
/// - **Removal** (`old` was drawn, `new` is not): every drawn neighbor gets
///   the face that looked at the removed voxel marked as exposed.
/// - **Fill** (`new` is drawn): the neighbors' faces that look at it are
///   covered again and leave the record. The faces of a placed voxel are not
///   exposed faces.
///
/// Neighbors in other loaded chunks are updated too, and a [`ChunkModified`]
/// is written for each chunk other than `chunk_coord` whose record changed,
/// so its mesh is rebuilt. Neighbors in chunks that are not loaded are
/// skipped. A chunk whose record changes becomes dirty and is saved like any
/// edited chunk.
///
/// [`set_voxel_at`](super::set_voxel_at), [`tick_mining`](super::tick_mining),
/// the mining input adapter and [`try_place_voxel`](super::try_place_voxel)
/// call this. A game that edits chunks with [`Chunk::set`] directly calls it
/// itself, or leaves the record alone on purpose.
pub fn record_voxel_edit<V: VoxelType>(
    chunk_coord: IVec3,
    local: (usize, usize, usize),
    old: V,
    new: V,
    manager: &ChunkManager,
    chunks: &mut Query<&mut Chunk<V>>,
    modified: &mut MessageWriter<ChunkModified>,
) {
    if old == new {
        return;
    }
    let size = CHUNK_SIZE as i32;
    if let Some(mut chunk) = manager
        .get_entity(chunk_coord)
        .and_then(|entity| chunks.get_mut(entity).ok())
        && chunk.exposed_faces(local.0, local.1, local.2) != 0
    {
        chunk.set_exposed_faces(local.0, local.1, local.2, 0);
    }

    let removed = is_drawn(old) && !is_drawn(new);
    let filled = is_drawn(new);
    if !removed && !filled {
        return;
    }

    let world_voxel =
        chunk_coord * size + IVec3::new(local.0 as i32, local.1 as i32, local.2 as i32);
    for (face, offset) in FACE_OFFSETS.iter().enumerate() {
        let neighbor = world_voxel + *offset;
        let neighbor_chunk = neighbor.div_euclid(IVec3::splat(size));
        let (x, y, z) = (
            neighbor.x.rem_euclid(size) as usize,
            neighbor.y.rem_euclid(size) as usize,
            neighbor.z.rem_euclid(size) as usize,
        );
        let Some(mut chunk) = manager
            .get_entity(neighbor_chunk)
            .and_then(|entity| chunks.get_mut(entity).ok())
        else {
            continue;
        };
        // The neighbor's face that looks back at the edited voxel.
        let bit = 1u8 << (face ^ 1);
        let before = chunk.exposed_faces(x, y, z);
        let after = if removed && is_drawn(chunk.get(x, y, z)) {
            before | bit
        } else {
            before & !bit
        };
        if after != before {
            chunk.set_exposed_faces(x, y, z, after);
            if neighbor_chunk != chunk_coord {
                modified.write(ChunkModified(neighbor_chunk));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::world_with_chunks;
    use crate::voxel::DefaultVoxel;
    use crate::world::{get_voxel_at, set_voxel_at};
    use bevy::ecs::message::Messages;
    use bevy::ecs::system::SystemState;

    const ROCK: DefaultVoxel = DefaultVoxel::Rock;
    const AIR: DefaultVoxel = DefaultVoxel::Air;

    /// Face bits by direction, as documented on `Chunk::exposed_faces`.
    const UP: u8 = 1 << 0;
    const DOWN: u8 = 1 << 1;
    const EAST: u8 = 1 << 2;
    const WEST: u8 = 1 << 3;

    /// Two chunks side by side across x = 0. The left one is full of rock up
    /// to y = 4, the right one too: a flat "generated" floor five voxels deep.
    fn floor_world() -> World {
        let floor = || {
            let mut chunk = Chunk::<DefaultVoxel>::new();
            for x in 0..CHUNK_SIZE {
                for y in 0..5 {
                    for z in 0..CHUNK_SIZE {
                        chunk.set(x, y, z, ROCK);
                    }
                }
            }
            chunk.mark_clean();
            chunk
        };
        let mut world =
            world_with_chunks([(IVec3::new(-1, 0, 0), floor()), (IVec3::ZERO, floor())]);
        world.init_resource::<Messages<ChunkModified>>();
        world
    }

    fn set(world: &mut World, voxel_pos: IVec3, voxel: DefaultVoxel) {
        let mut state: SystemState<(
            Res<ChunkManager>,
            Query<&mut Chunk<DefaultVoxel>>,
            MessageWriter<ChunkModified>,
        )> = SystemState::new(world);
        let (manager, mut chunks, mut writer) = state.get_mut(world);
        let center = voxel_pos.as_vec3() + Vec3::splat(0.5);
        assert!(set_voxel_at(
            center,
            voxel,
            &manager,
            &mut chunks,
            &mut writer
        ));
        state.apply(world);
    }

    fn exposed(world: &mut World, voxel_pos: IVec3) -> u8 {
        let size = CHUNK_SIZE as i32;
        let coord = voxel_pos.div_euclid(IVec3::splat(size));
        let local = voxel_pos.rem_euclid(IVec3::splat(size)).as_usizevec3();
        let entity = world.resource::<ChunkManager>().get_entity(coord).unwrap();
        world
            .get::<Chunk<DefaultVoxel>>(entity)
            .unwrap()
            .exposed_faces(local.x, local.y, local.z)
    }

    fn chunk_at(world: &World, coord: IVec3) -> &Chunk<DefaultVoxel> {
        let entity = world.resource::<ChunkManager>().get_entity(coord).unwrap();
        world.get::<Chunk<DefaultVoxel>>(entity).unwrap()
    }

    fn modified(world: &World) -> Vec<IVec3> {
        world
            .resource::<Messages<ChunkModified>>()
            .iter_current_update_messages()
            .map(|message| message.0)
            .collect()
    }

    #[test]
    fn generated_terrain_has_no_exposed_faces() {
        let world = floor_world();
        assert!(!chunk_at(&world, IVec3::ZERO).has_exposed_faces());
        assert!(!chunk_at(&world, IVec3::new(-1, 0, 0)).has_exposed_faces());
    }

    #[test]
    fn removing_a_voxel_exposes_the_faces_that_looked_at_it() {
        let mut world = floor_world();
        let dug = IVec3::new(5, 4, 5);

        set(&mut world, dug, AIR);

        // Below and beside the hole: the face towards the hole is fresh.
        assert_eq!(exposed(&mut world, dug + IVec3::NEG_Y), UP);
        assert_eq!(exposed(&mut world, dug + IVec3::X), WEST);
        assert_eq!(exposed(&mut world, dug + IVec3::NEG_X), EAST);
        // Air above the hole draws nothing and records nothing.
        assert_eq!(exposed(&mut world, dug + IVec3::Y), 0);
        // The surface around it is still the original one.
        assert_eq!(exposed(&mut world, IVec3::new(9, 4, 9)), 0);
        assert!(chunk_at(&world, IVec3::ZERO).is_dirty());
    }

    #[test]
    fn digging_deeper_keeps_earlier_faces_and_adds_new_ones() {
        let mut world = floor_world();
        set(&mut world, IVec3::new(5, 4, 5), AIR);
        set(&mut world, IVec3::new(5, 3, 5), AIR);

        // The voxel beside the first hole keeps its fresh face; the one
        // beside the second hole gets one; the bottom of the shaft gets one.
        assert_eq!(exposed(&mut world, IVec3::new(6, 4, 5)), WEST);
        assert_eq!(exposed(&mut world, IVec3::new(6, 3, 5)), WEST);
        assert_eq!(exposed(&mut world, IVec3::new(5, 2, 5)), UP);
    }

    #[test]
    fn removed_voxel_loses_its_own_record() {
        let mut world = floor_world();
        set(&mut world, IVec3::new(5, 4, 5), AIR);
        assert_eq!(exposed(&mut world, IVec3::new(5, 3, 5)), UP);

        set(&mut world, IVec3::new(5, 3, 5), AIR);

        assert_eq!(exposed(&mut world, IVec3::new(5, 3, 5)), 0);
    }

    #[test]
    fn filling_the_hole_covers_the_faces_again() {
        let mut world = floor_world();
        let dug = IVec3::new(5, 4, 5);
        set(&mut world, dug, AIR);

        set(&mut world, dug, DefaultVoxel::IronOre);

        assert_eq!(exposed(&mut world, dug + IVec3::NEG_Y), 0);
        assert_eq!(exposed(&mut world, dug + IVec3::X), 0);
        // A placed voxel has no exposed faces of its own.
        assert_eq!(exposed(&mut world, dug), 0);
        assert!(!chunk_at(&world, IVec3::ZERO).has_exposed_faces());
    }

    #[test]
    fn placing_a_voxel_on_the_surface_records_nothing() {
        let mut world = floor_world();

        set(&mut world, IVec3::new(5, 5, 5), ROCK);

        assert!(!chunk_at(&world, IVec3::ZERO).has_exposed_faces());
    }

    #[test]
    fn replacing_a_voxel_with_another_records_nothing() {
        let mut world = floor_world();

        set(&mut world, IVec3::new(5, 4, 5), DefaultVoxel::IronOre);

        assert!(!chunk_at(&world, IVec3::ZERO).has_exposed_faces());
    }

    #[test]
    fn removal_at_a_chunk_border_marks_and_remeshes_the_neighbor_chunk() {
        let mut world = floor_world();
        let left = IVec3::new(-1, 0, 0);

        // The first voxel of the right chunk, next to the left chunk.
        set(&mut world, IVec3::new(0, 4, 5), AIR);

        assert_eq!(exposed(&mut world, IVec3::new(-1, 4, 5)), EAST);
        assert!(chunk_at(&world, left).is_dirty());
        assert!(modified(&world).contains(&left));
    }

    #[test]
    fn unloaded_neighbor_chunk_is_skipped() {
        let mut world = floor_world();

        // The last voxel of the right chunk; there is no chunk at x = 1.
        set(&mut world, IVec3::new(15, 4, 5), AIR);

        assert_eq!(exposed(&mut world, IVec3::new(14, 4, 5)), EAST);
        assert_eq!(modified(&world), vec![IVec3::ZERO]);
    }

    #[test]
    fn floor_under_a_removed_voxel_at_the_bottom_of_the_world_is_fine() {
        let mut world = floor_world();

        set(&mut world, IVec3::new(5, 0, 5), AIR);

        // Buried voxel removed: its neighbors' faces are recorded even though
        // nothing sees them yet.
        assert_eq!(exposed(&mut world, IVec3::new(5, 1, 5)), DOWN);
        let mut state: SystemState<(Res<ChunkManager>, Query<&Chunk<DefaultVoxel>>)> =
            SystemState::new(&mut world);
        let (manager, chunks) = state.get(&world);
        assert_eq!(
            get_voxel_at(Vec3::new(5.5, 0.5, 5.5), &manager, &chunks),
            Some(AIR)
        );
    }
}