voxel_framework/chunk/mod.rs
1//! Chunk data model, coordinate utilities, and persistence for the voxel world.
2//!
3//! ## Overview
4//!
5//! This module defines the core data structures that represent a piece of the
6//! voxel world at rest. The runtime lifecycle (request, generate, mesh, render)
7//! lives in [`crate::world`], [`crate::generator`], and [`crate::mesh`]. This
8//! module is purely about *what a chunk is* and *where it lives in space*.
9//!
10//! ## The `Chunk<V>` data model
11//!
12//! A [`Chunk<V>`] is a 16×16×16 block of voxels stored in a single,
13//! heap-allocated flat array of length [`CHUNK_VOLUME`] (4 096 elements).
14//! Voxels are indexed in X-major order:
15//!
16//! ```text
17//! flat_index = x * CHUNK_SIZE² + y * CHUNK_SIZE + z
18//! ```
19//!
20//! This layout keeps a full Z-row of voxels contiguous in memory, which is
21//! cache-friendly for the greedy meshing algorithm's inner loop. The array is
22//! wrapped in a `Box` to keep the chunk's stack footprint to a single pointer
23//! regardless of voxel size.
24//!
25//! Because [`Chunk<V>`] derives [`bevy::prelude::Component`], it can be
26//! attached directly to a Bevy entity, making it queryable alongside
27//! [`ChunkCoordComp`] and [`ChunkLod`] without any indirection.
28//!
29//! ## Coordinate systems
30//!
31//! The framework uses three distinct coordinate spaces:
32//!
33//! | Space | Type | Unit |
34//! |-------|------|------|
35//! | **World space** | `Vec3` | One unit = one voxel = [`VOXEL_SIZE`] meters |
36//! | **Chunk space** | [`ChunkCoord`] (`IVec3`) | One unit = `CHUNK_SIZE` world units |
37//! | **Local space** | `(usize, usize, usize)` | Voxel index within a chunk, each in `[0, CHUNK_SIZE)` |
38//!
39//! ### Conversion helpers
40//!
41//! | Function | Input → Output |
42//! |----------|----------------|
43//! | [`world_to_chunk_coord`] | `Vec3` → [`ChunkCoord`] |
44//! | [`world_to_local_coord`] | `Vec3` → `(x, y, z)` local |
45//! | [`chunk_origin`] | [`ChunkCoord`] → `Vec3` (min corner) |
46//! | [`chunk_center`] | [`ChunkCoord`] → `Vec3` (center) |
47//!
48//! All conversions use Euclidean division, so negative world coordinates map
49//! correctly to negative chunk coordinates without off-by-one errors.
50//!
51//! ## Constants
52//!
53//! | Constant | Value | Meaning |
54//! |----------|-------|---------|
55//! | [`CHUNK_SIZE`] | `16` | Voxels per axis |
56//! | [`CHUNK_VOLUME`] | `4 096` | Total voxels per chunk |
57//! | [`VOXEL_SIZE`] | `1.0` | World-space size of one voxel |
58//!
59//! ## Persistence
60//!
61//! Raw chunk data can be written to and read from disk via the
62//! [`persistence`] sub-module, which serializes each voxel with
63//! [`crate::voxel::VoxelType::to_byte`] / [`crate::voxel::VoxelType::from_byte`].
64
65pub mod persistence;
66mod storage;
67
68pub use storage::{Chunk, face_to_state};
69
70use bevy::prelude::*;
71
72/// Number of voxels along each axis of a chunk.
73///
74/// A chunk is a cube with `CHUNK_SIZE` voxels per edge. The value `16` is
75/// chosen to balance memory footprint (4 096 voxels per chunk), generation
76/// granularity, and cache locality during meshing. Increasing this value
77/// reduces chunk boundary overhead but raises per-chunk allocation size and
78/// generation latency.
79pub const CHUNK_SIZE: usize = 16;
80
81/// Total number of voxels in a single chunk (`CHUNK_SIZE³ = 4 096`).
82///
83/// This is the length of the flat array inside every [`Chunk<V>`].
84/// At one byte per voxel (the minimum for `DefaultVoxel`), a fully populated
85/// chunk occupies 4 KiB of heap memory before any component overhead.
86pub const CHUNK_VOLUME: usize = CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE;
87
88/// World-space size of a single voxel, in Bevy world units.
89///
90/// Currently `1.0`, meaning one voxel corresponds to one world unit. All
91/// coordinate conversion functions in this module factor `VOXEL_SIZE` in so
92/// that changing this constant is sufficient to rescale the entire world.
93pub const VOXEL_SIZE: f32 = 1.0;
94
95/// Integer coordinate identifying a chunk in the world grid.
96///
97/// `ChunkCoord` is a type alias for [`bevy::math::IVec3`]. Each component
98/// is a signed integer where one unit equals `CHUNK_SIZE * VOXEL_SIZE`
99/// world-space units. The minimum corner of the chunk in world space is:
100///
101/// ```text
102/// chunk_origin = coord.as_vec3() * (CHUNK_SIZE as f32 * VOXEL_SIZE)
103/// ```
104///
105/// Chunk `(0, 0, 0)` covers world positions `[0, 16)³`.
106/// Chunk `(-1, 0, 0)` covers world positions `[-16, 0)` on the X axis.
107///
108/// Use [`world_to_chunk_coord`] to convert a world-space position to the
109/// chunk that contains it, and [`chunk_origin`] / [`chunk_center`] to go
110/// back the other way.
111pub type ChunkCoord = IVec3;
112
113/// Bevy [`Component`] that tags a chunk entity with its [`ChunkCoord`].
114///
115/// Every chunk entity receives this component when generation completes.
116/// Having the coordinate on the entity lets systems query
117/// `&ChunkCoordComp` directly — without going through
118/// [`crate::world::ChunkManager`] — and avoids the lock contention that
119/// would arise if all per-chunk logic had to look up coordinates in the
120/// manager's `HashMap`.
121///
122/// The inner [`IVec3`] is the same value as the corresponding entry in
123/// [`crate::world::ChunkManager`] and can be passed to any function
124/// expecting a [`ChunkCoord`].
125#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Hash)]
126pub struct ChunkCoordComp(pub IVec3);
127
128/// Bevy [`Component`] that stores the current Level of Detail for a chunk entity.
129///
130/// The LOD level controls the voxel sampling step used during greedy mesh
131/// generation — a higher step skips more voxels, producing a lower-resolution
132/// mesh that is cheaper to render.
133///
134/// | `ChunkLod` | Distance from viewer | Sampling step | Effective resolution |
135/// |------------|---------------------|---------------|----------------------|
136/// | `0` | < 200 units | 1 (every voxel) | Full 16³ |
137/// | `1` | >= 200 units | 2 (every 2nd) | Effective 8³ |
138///
139/// The value is updated every frame by `lod_update_system` based on the
140/// distance between the chunk center and [`crate::world::systems::ViewerPosition`].
141/// When the level changes, a [`crate::world::ChunkModified`] event is emitted
142/// so that [`crate::mesh::MeshPlugin`] regenerates the geometry at the new
143/// detail level on the next frame.
144///
145/// `Default` produces `ChunkLod(0)` (full detail).
146#[derive(Component, Debug, Clone, Copy, PartialEq, Eq, Default)]
147pub struct ChunkLod(pub u8);
148
149impl ChunkCoordComp {
150 /// Returns the underlying `IVec3` coordinate.
151 #[inline]
152 pub fn coord(&self) -> IVec3 {
153 self.0
154 }
155}
156
157// ─── Coordinate utilities ─────────────────────────────────────────────────────
158
159/// Converts a world-space position to the [`ChunkCoord`] of the chunk that contains it.
160///
161/// Each chunk spans `CHUNK_SIZE * VOXEL_SIZE` (`16.0`) world units per axis.
162/// Euclidean division is used so that negative positions round toward negative
163/// infinity and map to the correct chunk rather than toward zero.
164///
165/// # Examples
166///
167/// ```rust,no_run
168/// use bevy::math::Vec3;
169/// use voxel_framework::chunk::world_to_chunk_coord;
170///
171/// // Origin is in chunk (0, 0, 0).
172/// assert_eq!(world_to_chunk_coord(Vec3::ZERO), bevy::math::IVec3::ZERO);
173///
174/// // Position (16.0, 0.0, 0.0) is the first voxel of chunk (1, 0, 0).
175/// assert_eq!(world_to_chunk_coord(Vec3::new(16.0, 0.0, 0.0)).x, 1);
176///
177/// // Negative positions map to negative chunks.
178/// assert_eq!(world_to_chunk_coord(Vec3::new(-1.0, 0.0, 0.0)).x, -1);
179/// ```
180pub fn world_to_chunk_coord(world_pos: Vec3) -> ChunkCoord {
181 let size = CHUNK_SIZE as f32 * VOXEL_SIZE;
182 IVec3::new(
183 world_pos.x.div_euclid(size) as i32,
184 world_pos.y.div_euclid(size) as i32,
185 world_pos.z.div_euclid(size) as i32,
186 )
187}
188
189/// Converts a world-space position to the local voxel coordinate within its chunk.
190///
191/// Returns `(x, y, z)` where each component is in `[0, CHUNK_SIZE)`.
192/// The result can be passed directly to [`Chunk::get`] or [`Chunk::set`].
193///
194/// Use [`world_to_chunk_coord`] to find which chunk the position belongs to,
195/// then this function to get the offset within that chunk.
196///
197/// # Examples
198///
199/// ```rust,no_run
200/// use bevy::math::Vec3;
201/// use voxel_framework::chunk::world_to_local_coord;
202///
203/// // Position (0.5, 0.5, 0.5) → local voxel (0, 0, 0).
204/// assert_eq!(world_to_local_coord(Vec3::splat(0.5)), (0, 0, 0));
205///
206/// // Position (15.5, 0.0, 0.0) is in local voxel (15, 0, 0).
207/// assert_eq!(world_to_local_coord(Vec3::new(15.5, 0.0, 0.0)).0, 15);
208/// ```
209pub fn world_to_local_coord(world_pos: Vec3) -> (usize, usize, usize) {
210 let size = CHUNK_SIZE as f32 * VOXEL_SIZE;
211 let local = Vec3::new(
212 world_pos.x.rem_euclid(size),
213 world_pos.y.rem_euclid(size),
214 world_pos.z.rem_euclid(size),
215 );
216 (
217 (local.x / VOXEL_SIZE) as usize,
218 (local.y / VOXEL_SIZE) as usize,
219 (local.z / VOXEL_SIZE) as usize,
220 )
221}
222
223/// Returns the world-space position of the minimum corner (origin) of a chunk.
224///
225/// The origin is the corner with the smallest X, Y, and Z values. It equals
226/// `coord.as_vec3() * (CHUNK_SIZE as f32 * VOXEL_SIZE)`.
227pub fn chunk_origin(coord: ChunkCoord) -> Vec3 {
228 coord.as_vec3() * (CHUNK_SIZE as f32 * VOXEL_SIZE)
229}
230
231/// Returns the world-space position of the center of a chunk.
232///
233/// Equivalent to `chunk_origin(coord) + Vec3::splat(CHUNK_SIZE as f32 * VOXEL_SIZE * 0.5)`.
234/// Used by the LOD and occlusion systems to measure the distance from a chunk
235/// to the viewer or camera.
236pub fn chunk_center(coord: ChunkCoord) -> Vec3 {
237 chunk_origin(coord) + Vec3::splat(CHUNK_SIZE as f32 * VOXEL_SIZE * 0.5)
238}
239
240// ─── Tests ────────────────────────────────────────────────────────────────────
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn world_to_chunk_coord_at_origin() {
248 assert_eq!(world_to_chunk_coord(Vec3::ZERO), IVec3::new(0, 0, 0));
249 }
250
251 #[test]
252 fn world_to_chunk_coord_one_chunk_over() {
253 // CHUNK_SIZE = 16, VOXEL_SIZE = 1.0 → chunk boundary at 16.0
254 assert_eq!(
255 world_to_chunk_coord(Vec3::new(16.0, 0.0, 0.0)),
256 IVec3::new(1, 0, 0)
257 );
258 }
259
260 #[test]
261 fn world_to_local_coord_at_origin() {
262 assert_eq!(world_to_local_coord(Vec3::new(0.5, 0.5, 0.5)), (0, 0, 0));
263 }
264
265 #[test]
266 fn world_to_local_coord_second_chunk() {
267 // 16.5 is 0.5 into the second chunk → local x = 0
268 assert_eq!(world_to_local_coord(Vec3::new(16.5, 0.0, 0.0)), (0, 0, 0));
269 }
270}