Skip to main content

voxel_framework/
lib.rs

1//! # voxel-framework
2//!
3//! A reusable voxel engine library built on [Bevy](https://bevyengine.org/),
4//! providing all the infrastructure needed to build voxel-based games and
5//! simulations: chunk storage, procedural generation, greedy meshing, world
6//! streaming, PBR rendering, and player interaction.
7//!
8//! ## Overview
9//!
10//! The framework is built around three core abstractions:
11//!
12//! - **[`voxel::VoxelType`]** — a trait that every voxel palette must implement.
13//!   It describes whether a voxel is solid, what color it renders as, and how
14//!   it serializes to and from a single byte for persistence. The built-in
15//!   [`voxel::DefaultVoxel`] palette covers five material types (Air, Rock,
16//!   IronOre, SiliconCrystal, RareMineral) and is ready to use out of the box.
17//!
18//! - **[`chunk::Chunk<V>`]** — the fundamental storage unit. A 16×16×16 flat
19//!   array of voxels stored on the heap. All generation, meshing, and I/O
20//!   operate on chunks identified by a [`chunk::ChunkCoord`] (an `IVec3`
21//!   where one unit equals `CHUNK_SIZE` world-space units).
22//!
23//! - **[`generator::ChunkGenerator`]** — an async-safe trait implemented by
24//!   procedural generators. Generators run on a Bevy `AsyncComputeTaskPool`
25//!   thread and produce fully populated [`chunk::Chunk<V>`] values, which are
26//!   then handed back to the main world for meshing and insertion.
27//!
28//! ## Plugin Catalog Architecture
29//!
30//! `voxel-framework` exposes a flat catalog of Bevy plugins grouped by
31//! responsibility. Game crates compose the plugins they need instead of
32//! depending on a hidden monolithic game plugin:
33//!
34//! | Category | Purpose | Examples |
35//! |----------|---------|----------|
36//! | Engine | Foundation for streamable/renderable voxel worlds | [`world::WorldPlugin`], [`mesh::MeshPlugin`], [`render::RenderPlugin`] |
37//! | World Data | Chunk sources, generation, persistence, lifecycle data | [`generator::GeneratorPlugin`], [`world::PersistencePlugin`] |
38//! | Gameplay | Reusable rules and interactions | [`content::VoxelContentPlugin`], [`stats::VoxelStatsPlugin`], [`effects::VoxelEffectsPlugin`], [`world::mining::MiningPlugin`], [`world::placement::PlacementPlugin`], [`player::PlayerPlugin`] |
39//! | Default Implementation | Replaceable UI/audio/visual defaults | [`ui::UiPlugin`], [`ui::VoxelHudPlugin`], [`skybox::SkyboxPlugin`], [`audio::DefaultAudioPlugin`] |
40//! | Convenience | Compatibility bundles, input adapters, recipes, prototyping helpers | [`VoxelCorePlugin`], [`VoxelPlugin`] |
41//!
42//! These categories are also represented by marker traits in
43//! [`plugin_category`]. They are documentation and API classification tools;
44//! Bevy composition still uses the normal [`Plugin`] trait.
45//!
46//! [`VoxelCorePlugin`] and [`VoxelPlugin`] remain available as convenience
47//! bundles for compatibility and quick starts, but they are not the primary
48//! architecture. New domain behavior should normally be modeled as an explicit
49//! Engine, World Data, Gameplay, or Default Implementation plugin.
50//!
51//! With `items`, `items::DropVisualPlugin<I>` supplies optional item-colored drop
52//! cubes alongside `items::DropsPlugin<I>` gameplay. See `docs/drops.md` and the
53//! graphical `drops` example. Both plugins remain explicit consumer choices.
54//! With `items`, `ui::HotbarContentPlugin<I>` and `ui::ItemIconPalette<I>` add
55//! explicit material-colored icons, quantities, and selected names to the
56//! existing hotbar. See `docs/hotbar.md` and the native `hotbar_icons` example.
57//!
58//! [`generator::GeneratorPlugin`] is always **opt-in** because it is generic
59//! over `V: VoxelType` and requires the caller to supply a
60//! [`generator::GeneratorResource`] holding a concrete generator. Add it
61//! separately after either a bundle or explicit engine plugins.
62//!
63//! [`ui::VoxelHudPlugin`] is also explicit and remains outside [`ui::UiPlugin`]
64//! and the convenience bundles. Authors register domain-neutral presentation
65//! definitions, publish screen-ready values, and may schedule same-frame
66//! publishers in [`ui::HudSystemSet::Publish`]. The retained renderer preserves
67//! element identity and safely hides unresolved or unavailable asset inputs.
68//!
69//! ## The Chunk Pipeline
70//!
71//! The full data flow from viewer movement to rendered geometry:
72//!
73//! ```text
74//! ViewerPosition update
75//!        │
76//!        ▼
77//! WorldPlugin — streaming system
78//!   Computes which chunks are within the configured render distance.
79//!   Emits ChunkRequested events for chunks not yet loaded.
80//!        │
81//!        ▼
82//! GeneratorPlugin — async generation (AsyncComputeTaskPool)
83//!   Spawns a task per requested chunk. Each task calls
84//!   ChunkGenerator::generate(coord) → Chunk<V>.
85//!   When the task completes, inserts the Chunk<V> component and emits
86//!   ChunkModified so downstream systems are notified.
87//!        │
88//!        ▼
89//! MeshPlugin — greedy mesh generation
90//!   Reacts to ChunkModified. Iterates the chunk with a configurable LOD
91//!   step, runs the greedy meshing algorithm, and uploads a Bevy Mesh asset.
92//!        │
93//!        ▼
94//! RenderPlugin — PBR material + entity spawn
95//!   Attaches a shared chunk PBR material and a MeshBundle to the chunk
96//!   entity so Bevy's renderer picks it up on the next frame.
97//!        │
98//!        ▼
99//! OcclusionPlugin — neighbor-solid occlusion
100//!   Reacts to ChunkModified and hides chunks whose six face-adjacent
101//!   neighbours are all loaded and fully solid.
102//! ```
103//!
104//! ## Quick Start
105//!
106//! A minimal working world using the built-in asteroid generator:
107//!
108//! ```rust,no_run
109//! use bevy::prelude::*;
110//! use voxel_framework::{
111//!     VoxelPlugin,
112//!     generator::{GeneratorPlugin, GeneratorResource},
113//!     generator::asteroid::{AsteroidConfig, AsteroidGenerator},
114//!     voxel::DefaultVoxel,
115//! };
116//! use std::sync::Arc;
117//!
118//! App::new()
119//!     .add_plugins(DefaultPlugins)
120//!     .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
121//!     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
122//!     .insert_resource(GeneratorResource::<DefaultVoxel> {
123//!         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
124//!     })
125//!     .run();
126//! ```
127//!
128//! Use explicit catalog plugins instead of [`VoxelPlugin`] when you want full
129//! control over engine, world data, gameplay, and presentation defaults.
130//!
131//! ## Extending the Framework
132//!
133//! To use a custom voxel palette, implement [`voxel::VoxelType`] on your own type and
134//! substitute it wherever the framework is generic over `V: VoxelType`:
135//!
136//! - [`generator::GeneratorPlugin::<YourVoxel>::new()`][`generator::GeneratorPlugin`]
137//! - [`mesh::MeshPlugin::<YourVoxel>::new()`][`mesh::MeshPlugin`]
138//! - [`render::RenderPlugin::<YourVoxel>::new()`][`render::RenderPlugin`]
139//!
140//! To drive generation, implement [`generator::ChunkGenerator`] and wrap it in
141//! a [`generator::GeneratorResource`].
142//!
143//! See [`prelude`] for the most commonly used re-exports.
144
145#![deny(rustdoc::broken_intra_doc_links)]
146
147pub mod audio;
148pub mod automation;
149pub mod chunk;
150pub mod content;
151#[cfg(feature = "crafting")]
152pub mod crafting;
153pub mod effects;
154pub mod fragments;
155pub mod generator;
156#[cfg(feature = "items")]
157pub mod items;
158pub mod lighting;
159pub mod mesh;
160#[cfg(feature = "mobs")]
161pub mod mobs;
162pub mod noise;
163pub mod particles;
164pub mod player;
165pub mod plugin_category;
166pub mod prelude;
167pub mod profile;
168pub mod render;
169pub mod settings;
170pub mod skybox;
171pub mod stats;
172pub mod ui;
173pub mod voxel;
174pub mod world;
175
176#[cfg(test)]
177pub(crate) mod test_support;
178
179use bevy::prelude::*;
180
181use audio::SfxPlugin;
182use fragments::FragmentPlugin;
183#[cfg(feature = "items")]
184use items::hotbar::HotbarPlugin;
185use mesh::MeshPlugin;
186use render::RenderPlugin;
187use skybox::SkyboxPlugin;
188use ui::UiPlugin;
189use voxel::DefaultVoxel;
190use voxel::VoxelType;
191use world::loading::LoadingPlugin;
192use world::mining::MiningPlugin;
193use world::occlusion::OcclusionPlugin;
194use world::placement::PlacementPlugin;
195use world::{WorldConfigPlugin, WorldPlugin};
196
197/// Convenience bundle for the historical core voxel runtime.
198///
199/// `VoxelCorePlugin<V>` wires up the legacy core bundle — world streaming,
200/// chunk lifecycle, meshing, PBR rendering, neighbor-solid occlusion, mining,
201/// placement, and loading state — without the bundled presentation defaults
202/// from [`VoxelPlugin`].
203///
204/// In the plugin catalog taxonomy this type is a [`plugin_category::ConveniencePlugin`]:
205/// it composes stricter Engine and Gameplay plugins for compatibility and quick
206/// starts. New architecture should describe those individual plugins by their
207/// primary categories rather than treating this bundle as the whole model.
208///
209/// The generic parameter `V` selects the voxel type used by the rendering,
210/// meshing, and occlusion systems. Defaults to [`DefaultVoxel`] for backwards
211/// compatibility: `VoxelCorePlugin::default()` and
212/// `VoxelCorePlugin::<DefaultVoxel>::new()` are equivalent.
213///
214/// # Included systems
215///
216/// | Plugin | Responsibility |
217/// |--------|----------------|
218/// | [`WorldPlugin`] | [`world::ChunkManager`], [`world::systems::ViewerPosition`], chunk lifecycle events, and streaming |
219/// | [`WorldConfigPlugin`] | Inserts the [`world::WorldConfig`] resource |
220/// | `RenderPlugin<V>` | Shared chunk PBR material and entity spawn |
221/// | `MeshPlugin<V>` | Greedy mesh generation and chunk despawn |
222/// | `OcclusionPlugin<V>` | Neighbor-solid chunk occlusion |
223/// | [`world::mining::MiningPlugin`] | Gameplay primitive for voxel removal |
224/// | [`world::placement::PlacementPlugin`] | Gameplay primitive for voxel placement |
225/// | [`world::loading::LoadingPlugin`] | World loading state machine |
226///
227/// # Not included (opt-in)
228///
229/// - [`generator::GeneratorPlugin`] — requires the caller to supply a
230///   [`generator::GeneratorResource`].
231#[cfg_attr(
232    feature = "items",
233    doc = "- [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], [`HotbarPlugin`], and [`UiPlugin`] — presentation/gameplay defaults included by [`VoxelPlugin`]."
234)]
235#[cfg_attr(
236    not(feature = "items"),
237    doc = "- [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], and [`UiPlugin`] — presentation defaults included by [`VoxelPlugin`]. `HotbarPlugin` additionally requires the `items` feature."
238)]
239///
240/// # Example
241///
242/// ```rust,no_run
243/// use bevy::prelude::*;
244/// use voxel_framework::{VoxelCorePlugin, generator::{GeneratorPlugin, GeneratorResource}};
245/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
246/// use voxel_framework::voxel::DefaultVoxel;
247/// use std::sync::Arc;
248///
249/// App::new()
250///     .add_plugins(DefaultPlugins)
251///     .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
252///     .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
253///     .insert_resource(GeneratorResource::<DefaultVoxel> {
254///         generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
255///     })
256///     .run();
257/// ```
258///
259/// # See also
260///
261/// - [`VoxelPlugin`] — broader quick-start convenience bundle.
262pub struct VoxelCorePlugin<V: VoxelType = DefaultVoxel> {
263    _m: std::marker::PhantomData<V>,
264}
265
266impl<V: VoxelType> VoxelCorePlugin<V> {
267    /// Creates a new [`VoxelCorePlugin`] for voxel type `V`.
268    pub fn new() -> Self {
269        Self {
270            _m: std::marker::PhantomData,
271        }
272    }
273}
274
275impl<V: VoxelType> Default for VoxelCorePlugin<V> {
276    fn default() -> Self {
277        Self::new()
278    }
279}
280
281impl<V: VoxelType> Plugin for VoxelCorePlugin<V> {
282    fn build(&self, app: &mut App) {
283        app.add_plugins(WorldPlugin);
284        app.add_plugins(WorldConfigPlugin);
285        app.add_plugins(RenderPlugin::<V>::new());
286        app.add_plugins(MeshPlugin::<V>::new());
287        app.add_plugins(OcclusionPlugin::<V>::new());
288        app.add_plugins(MiningPlugin);
289        app.add_plugins(PlacementPlugin);
290        app.add_plugins(LoadingPlugin);
291    }
292}
293
294/// Quick-start convenience bundle for demos and prototypes.
295///
296/// `VoxelPlugin<V>` composes [`VoxelCorePlugin<V>`] with selected presentation
297/// and gameplay defaults. It is useful for examples, demos, and early
298/// prototyping, but it is not the architectural definition of the full
299/// framework. Production games should treat it as a convenience bundle and
300/// switch to explicit catalog plugins when they need finer control.
301///
302/// The generic parameter `V` selects the voxel type. Defaults to
303/// [`DefaultVoxel`] — `VoxelPlugin::default()` produces an asteroid-palette
304/// world, `VoxelPlugin::<DefaultTerrainVoxel>::new()` produces a terrain world.
305///
306/// # Included beyond [`VoxelCorePlugin`]
307///
308/// | Plugin | Responsibility |
309/// |--------|----------------|
310/// | [`FragmentPlugin`] | Floating voxel debris entities ejected on mining |
311/// | [`SkyboxPlugin`] | Procedural starfield and skybox rendering |
312/// | [`SfxPlugin`] | Positional audio effects for mining and placement |
313#[cfg_attr(
314    feature = "items",
315    doc = "| [`HotbarPlugin`] | Player hotbar, item switching, and held-item state |"
316)]
317#[cfg_attr(
318    not(feature = "items"),
319    doc = "| `HotbarPlugin` *(feature `items`)* | Player hotbar, item switching, and held-item state |"
320)]
321/// | [`UiPlugin`] | Crosshair, loading screen, and HUD overlays |
322///
323/// # Generator not included
324///
325/// [`generator::GeneratorPlugin`] is intentionally excluded because it requires
326/// the caller to supply a concrete [`generator::GeneratorResource`]. Always add
327/// it separately:
328///
329/// ```rust,no_run
330/// use bevy::prelude::*;
331/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
332/// use voxel_framework::generator::terrain::{TerrainConfig, TerrainGenerator};
333/// use voxel_framework::voxel::DefaultTerrainVoxel;
334/// use std::sync::Arc;
335///
336/// App::new()
337///     .add_plugins(DefaultPlugins)
338///     .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
339///     .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
340///     .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
341///         generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
342///     })
343///     .run();
344/// ```
345///
346/// # See also
347///
348/// - [`VoxelCorePlugin`] — narrower compatibility/convenience bundle.
349/// - [`prelude`] — commonly used re-exports for convenience imports.
350pub struct VoxelPlugin<V: VoxelType = DefaultVoxel> {
351    _m: std::marker::PhantomData<V>,
352}
353
354impl<V: VoxelType> VoxelPlugin<V> {
355    /// Creates a new [`VoxelPlugin`] for voxel type `V`.
356    pub fn new() -> Self {
357        Self {
358            _m: std::marker::PhantomData,
359        }
360    }
361}
362
363impl<V: VoxelType> Default for VoxelPlugin<V> {
364    fn default() -> Self {
365        Self::new()
366    }
367}
368
369impl<V: VoxelType> Plugin for VoxelPlugin<V> {
370    fn build(&self, app: &mut App) {
371        app.add_plugins(VoxelCorePlugin::<V>::new());
372        app.add_plugins(FragmentPlugin);
373        app.add_plugins(SkyboxPlugin);
374        app.add_plugins(SfxPlugin);
375        #[cfg(feature = "items")]
376        app.add_plugins(HotbarPlugin);
377        app.add_plugins(UiPlugin);
378    }
379}