Skip to main content

Chunk

Struct Chunk 

Source
pub struct Chunk<V: VoxelType> {
    pub states: Box<[u8; 4096]>,
    /* private fields */
}
Expand description

A 16×16×16 block of voxels — the fundamental unit of world storage.

Chunk<V> is a Bevy Component that holds all voxel data for one 16-voxel-per-axis region of the world. It is generic over any type implementing VoxelType, so it works with crate::voxel::DefaultVoxel out of the box and with custom palettes without any changes to the framework.

§Memory layout

Voxels are stored in a single heap-allocated array of length CHUNK_VOLUME (4 096), indexed in X-major order:

flat_index = x * CHUNK_SIZE² + y * CHUNK_SIZE + z

This means a full row of Z-adjacent voxels is contiguous in memory — the layout the greedy meshing algorithm iterates most frequently. The array is wrapped in a Box to keep the struct’s stack size to a single pointer (8 bytes) regardless of V’s size.

§Block states

Each voxel has a companion u8 state byte stored in a parallel states array. The state byte is set automatically by the placement system to record which face the block was placed against (bits 0-2, see face_to_state):

BitsMeaning
0–2Placement face (0=+X, 1=−X, 2=+Y, 3=−Y, 4=+Z, 5=−Z, 6=unknown)
3–7Reserved for game-specific use

Games may read and write state bytes freely via Chunk::get_state / Chunk::set_state for door open/close flags, liquid level, growth stage, or any other per-voxel metadata.

§Coordinate bounds

Every method that takes (x, y, z) expects each coordinate in [0, CHUNK_SIZE) (i.e. 0..16). Out-of-bounds access panics in debug builds via debug_assert inside Chunk::get_index. In release builds, out-of-bounds indices silently alias other voxels — callers must ensure correct inputs.

Use crate::chunk::world_to_local_coord to convert a world-space position to a valid (x, y, z) triple before calling get or set.

§See also

Fields§

§states: Box<[u8; 4096]>

Per-voxel state bytes — parallel array to voxels.

Bits 0–2 encode the placement face; bits 3–7 are reserved for games. All states are initialised to 0 (face = +X, conventional default).

Implementations§

Source§

impl<V: VoxelType> Chunk<V>

Source

pub fn new() -> Self

Creates a new chunk with every voxel initialized to VoxelType::air and every state byte set to 0.

Allocates two CHUNK_VOLUME-element arrays on the heap.

Source

pub fn get_index(x: usize, y: usize, z: usize) -> usize

Computes the flat array index for the voxel at local coordinate (x, y, z).

The formula is x * CHUNK_SIZE² + y * CHUNK_SIZE + z, giving X-major (row-major with X as the outermost dimension) storage order.

Prefer calling Chunk::get or Chunk::set directly; this method is public for use by the meshing and persistence systems that need to iterate the flat array efficiently.

§Panics

Panics in debug builds if any coordinate is >= CHUNK_SIZE. In release builds, the assertion is omitted for performance.

Source

pub fn get(&self, x: usize, y: usize, z: usize) -> V

Returns a copy of the voxel at local coordinate (x, y, z).

Each coordinate must be in [0, CHUNK_SIZE). The value is returned by copy because VoxelType requires Copy.

§Panics

Panics in debug builds if any coordinate is out of bounds (see Chunk::get_index).

Source

pub fn set(&mut self, x: usize, y: usize, z: usize, voxel: V)

Overwrites the voxel at local coordinate (x, y, z) with voxel.

Each coordinate must be in [0, CHUNK_SIZE). Use VoxelType::air to clear a voxel back to empty.

After calling this method on an already-spawned chunk entity, emit a crate::world::ChunkModified event so that the mesh system regenerates the chunk’s geometry.

§Panics

Panics in debug builds if any coordinate is out of bounds (see Chunk::get_index).

Source

pub fn get_state(&self, x: usize, y: usize, z: usize) -> u8

Returns the state byte for the voxel at local coordinate (x, y, z).

Bits 0–2 hold the placement face (see face_to_state); bits 3–7 are available for game-specific use. Returns 0 for voxels that have never been explicitly placed (e.g. generator-filled voxels).

§Panics

Panics in debug builds if any coordinate is out of bounds.

Source

pub fn set_state(&mut self, x: usize, y: usize, z: usize, state: u8)

Overwrites the state byte for the voxel at local coordinate (x, y, z).

Games may set bits 3–7 freely. Bits 0–2 are normally written by the placement system via face_to_state.

§Panics

Panics in debug builds if any coordinate is out of bounds.

Source

pub fn is_solid_at(&self, x: usize, y: usize, z: usize) -> bool

Returns true if the voxel at local coordinate (x, y, z) is solid.

Equivalent to self.get(x, y, z).is_solid(). Used by the meshing and occlusion systems to test individual voxels without materializing the full voxel value.

§Panics

Panics in debug builds if any coordinate is out of bounds.

Source

pub fn is_fully_solid(&self) -> bool

Returns true if every voxel in the chunk is solid.

A fully solid chunk is opaque from all six faces and requires no interior face geometry. The occlusion system uses this to skip mesh generation for completely buried chunks.

Runs in O(CHUNK_VOLUME) time by scanning the flat array.

Source

pub fn is_empty(&self) -> bool

Returns true if every voxel in the chunk is air (non-solid).

An empty chunk produces no geometry. The streaming system uses this to avoid spawning mesh entities for chunks that contain only air, such as the open space above a terrain surface or inside a cave ceiling.

Runs in O(CHUNK_VOLUME) time by scanning the flat array.

Source

pub fn border_slice(&self, face: usize) -> [V; 256]

Extracts a 16x16 border slice for one of the six chunk faces.

The returned array contains the voxels on the outermost layer in the direction indicated by face:

FaceDirectionFixed axis value
0+Yy = 15
1-Yy = 0
2+Xx = 15
3-Xx = 0
4+Zz = 15
5-Zz = 0

The slice is packed in row-major order for the two varying axes.

§Panics

Panics if face >= 6.

Trait Implementations§

Source§

impl<V: Clone + VoxelType> Clone for Chunk<V>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<V: VoxelType> Component for Chunk<V>
where Self: Send + Sync + 'static,

Source§

const STORAGE_TYPE: StorageType = ::bevy::ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Self>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_replace() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_replace ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

impl<V: Debug + VoxelType> Debug for Chunk<V>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<V: VoxelType> Default for Chunk<V>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<V> Forget for Chunk<V>

§

impl<V> Freeze for Chunk<V>

§

impl<V> Move for Chunk<V>

§

impl<V> RefUnwindSafe for Chunk<V>

§

impl<V> Send for Chunk<V>
where Box<[V; 4096]>: Send,

§

impl<V> Sync for Chunk<V>
where Box<[V; 4096]>: Sync,

§

impl<V> Unpin for Chunk<V>

§

impl<V> UnsafeUnpin for Chunk<V>

§

impl<V> UnwindSafe for Chunk<V>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Return a iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of this value.
Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more