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 | [`world::mining::MiningPlugin`], [`world::placement::PlacementPlugin`], [`player::PlayerPlugin`] |
39//! | Default Implementation | Replaceable UI/audio/visual defaults | [`ui::UiPlugin`], [`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//! [`generator::GeneratorPlugin`] is always **opt-in** because it is generic
52//! over `V: VoxelType` and requires the caller to supply a
53//! [`generator::GeneratorResource`] holding a concrete generator. Add it
54//! separately after either a bundle or explicit engine plugins.
55//!
56//! ## The Chunk Pipeline
57//!
58//! The full data flow from viewer movement to rendered geometry:
59//!
60//! ```text
61//! ViewerPosition update
62//! │
63//! ▼
64//! WorldPlugin — streaming system
65//! Computes which chunks are within the configured render distance.
66//! Emits ChunkRequested events for chunks not yet loaded.
67//! │
68//! ▼
69//! GeneratorPlugin — async generation (AsyncComputeTaskPool)
70//! Spawns a task per requested chunk. Each task calls
71//! ChunkGenerator::generate(coord) → Chunk<V>.
72//! When the task completes, inserts the Chunk<V> component and emits
73//! ChunkModified so downstream systems are notified.
74//! │
75//! ▼
76//! MeshPlugin — greedy mesh generation
77//! Reacts to ChunkModified. Iterates the chunk with a configurable LOD
78//! step, runs the greedy meshing algorithm, and uploads a Bevy Mesh asset.
79//! │
80//! ▼
81//! RenderPlugin — PBR material + entity spawn
82//! Attaches a shared chunk PBR material and a MeshBundle to the chunk
83//! entity so Bevy's renderer picks it up on the next frame.
84//! │
85//! ▼
86//! OcclusionPlugin — neighbor-solid occlusion
87//! Reacts to ChunkModified and hides chunks whose six face-adjacent
88//! neighbours are all loaded and fully solid.
89//! ```
90//!
91//! ## Quick Start
92//!
93//! A minimal working world using the built-in asteroid generator:
94//!
95//! ```rust,no_run
96//! use bevy::prelude::*;
97//! use voxel_framework::{
98//! VoxelPlugin,
99//! generator::{GeneratorPlugin, GeneratorResource},
100//! generator::asteroid::{AsteroidConfig, AsteroidGenerator},
101//! voxel::DefaultVoxel,
102//! };
103//! use std::sync::Arc;
104//!
105//! App::new()
106//! .add_plugins(DefaultPlugins)
107//! .add_plugins(VoxelPlugin::<DefaultVoxel>::new())
108//! .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
109//! .insert_resource(GeneratorResource::<DefaultVoxel> {
110//! generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
111//! })
112//! .run();
113//! ```
114//!
115//! Use explicit catalog plugins instead of [`VoxelPlugin`] when you want full
116//! control over engine, world data, gameplay, and presentation defaults.
117//!
118//! ## Extending the Framework
119//!
120//! To use a custom voxel palette, implement [`voxel::VoxelType`] on your own type and
121//! substitute it wherever the framework is generic over `V: VoxelType`:
122//!
123//! - [`generator::GeneratorPlugin::<YourVoxel>::new()`][`generator::GeneratorPlugin`]
124//! - [`mesh::MeshPlugin::<YourVoxel>::new()`][`mesh::MeshPlugin`]
125//! - [`render::RenderPlugin::<YourVoxel>::new()`][`render::RenderPlugin`]
126//!
127//! To drive generation, implement [`generator::ChunkGenerator`] and wrap it in
128//! a [`generator::GeneratorResource`].
129//!
130//! See [`prelude`] for the most commonly used re-exports.
131
132#![deny(rustdoc::broken_intra_doc_links)]
133
134pub mod audio;
135pub mod chunk;
136#[cfg(feature = "crafting")]
137pub mod crafting;
138pub mod fragments;
139pub mod generator;
140#[cfg(feature = "items")]
141pub mod items;
142pub mod mesh;
143#[cfg(feature = "mobs")]
144pub mod mobs;
145pub mod noise;
146pub mod player;
147pub mod plugin_category;
148pub mod prelude;
149pub mod profile;
150pub mod render;
151pub mod settings;
152pub mod skybox;
153pub mod ui;
154pub mod voxel;
155pub mod world;
156
157use bevy::prelude::*;
158
159use audio::SfxPlugin;
160use fragments::FragmentPlugin;
161#[cfg(feature = "items")]
162use items::hotbar::HotbarPlugin;
163use mesh::MeshPlugin;
164use render::RenderPlugin;
165use skybox::SkyboxPlugin;
166use ui::UiPlugin;
167use voxel::DefaultVoxel;
168use voxel::VoxelType;
169use world::loading::LoadingPlugin;
170use world::mining::MiningPlugin;
171use world::occlusion::OcclusionPlugin;
172use world::placement::PlacementPlugin;
173use world::{WorldConfigPlugin, WorldPlugin};
174
175/// Convenience bundle for the historical core voxel runtime.
176///
177/// `VoxelCorePlugin<V>` wires up the legacy core bundle — world streaming,
178/// chunk lifecycle, meshing, PBR rendering, neighbor-solid occlusion, mining,
179/// placement, and loading state — without the bundled presentation defaults
180/// from [`VoxelPlugin`].
181///
182/// In the plugin catalog taxonomy this type is a [`plugin_category::ConveniencePlugin`]:
183/// it composes stricter Engine and Gameplay plugins for compatibility and quick
184/// starts. New architecture should describe those individual plugins by their
185/// primary categories rather than treating this bundle as the whole model.
186///
187/// The generic parameter `V` selects the voxel type used by the rendering,
188/// meshing, and occlusion systems. Defaults to [`DefaultVoxel`] for backwards
189/// compatibility: `VoxelCorePlugin::default()` and
190/// `VoxelCorePlugin::<DefaultVoxel>::new()` are equivalent.
191///
192/// # Included systems
193///
194/// | Plugin | Responsibility |
195/// |--------|----------------|
196/// | [`WorldPlugin`] | [`world::ChunkManager`], [`world::systems::ViewerPosition`], chunk lifecycle events, and streaming |
197/// | [`WorldConfigPlugin`] | Inserts the [`world::WorldConfig`] resource |
198/// | `RenderPlugin<V>` | Shared chunk PBR material and entity spawn |
199/// | `MeshPlugin<V>` | Greedy mesh generation and chunk despawn |
200/// | `OcclusionPlugin<V>` | Neighbor-solid chunk occlusion |
201/// | [`world::mining::MiningPlugin`] | Gameplay primitive for voxel removal |
202/// | [`world::placement::PlacementPlugin`] | Gameplay primitive for voxel placement |
203/// | [`world::loading::LoadingPlugin`] | World loading state machine |
204///
205/// # Not included (opt-in)
206///
207/// - [`generator::GeneratorPlugin`] — requires the caller to supply a
208/// [`generator::GeneratorResource`].
209/// - [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], [`HotbarPlugin`],
210/// [`UiPlugin`] — presentation/gameplay defaults included by [`VoxelPlugin`].
211///
212/// # Example
213///
214/// ```rust,no_run
215/// use bevy::prelude::*;
216/// use voxel_framework::{VoxelCorePlugin, generator::{GeneratorPlugin, GeneratorResource}};
217/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
218/// use voxel_framework::voxel::DefaultVoxel;
219/// use std::sync::Arc;
220///
221/// App::new()
222/// .add_plugins(DefaultPlugins)
223/// .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
224/// .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
225/// .insert_resource(GeneratorResource::<DefaultVoxel> {
226/// generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
227/// })
228/// .run();
229/// ```
230///
231/// # See also
232///
233/// - [`VoxelPlugin`] — broader quick-start convenience bundle.
234pub struct VoxelCorePlugin<V: VoxelType = DefaultVoxel> {
235 _m: std::marker::PhantomData<V>,
236}
237
238impl<V: VoxelType> VoxelCorePlugin<V> {
239 /// Creates a new [`VoxelCorePlugin`] for voxel type `V`.
240 pub fn new() -> Self {
241 Self {
242 _m: std::marker::PhantomData,
243 }
244 }
245}
246
247impl<V: VoxelType> Default for VoxelCorePlugin<V> {
248 fn default() -> Self {
249 Self::new()
250 }
251}
252
253impl<V: VoxelType> Plugin for VoxelCorePlugin<V> {
254 fn build(&self, app: &mut App) {
255 app.add_plugins(WorldPlugin);
256 app.add_plugins(WorldConfigPlugin);
257 app.add_plugins(RenderPlugin::<V>::new());
258 app.add_plugins(MeshPlugin::<V>::new());
259 app.add_plugins(OcclusionPlugin::<V>::new());
260 app.add_plugins(MiningPlugin);
261 app.add_plugins(PlacementPlugin);
262 app.add_plugins(LoadingPlugin);
263 }
264}
265
266/// Quick-start convenience bundle for demos and prototypes.
267///
268/// `VoxelPlugin<V>` composes [`VoxelCorePlugin<V>`] with selected presentation
269/// and gameplay defaults. It is useful for examples, demos, and early
270/// prototyping, but it is not the architectural definition of the full
271/// framework. Production games should treat it as a convenience bundle and
272/// switch to explicit catalog plugins when they need finer control.
273///
274/// The generic parameter `V` selects the voxel type. Defaults to
275/// [`DefaultVoxel`] — `VoxelPlugin::default()` produces an asteroid-palette
276/// world, `VoxelPlugin::<DefaultTerrainVoxel>::new()` produces a terrain world.
277///
278/// # Included beyond [`VoxelCorePlugin`]
279///
280/// | Plugin | Responsibility |
281/// |--------|----------------|
282/// | [`FragmentPlugin`] | Floating voxel debris entities ejected on mining |
283/// | [`SkyboxPlugin`] | Procedural starfield and skybox rendering |
284/// | [`SfxPlugin`] | Positional audio effects for mining and placement |
285/// | [`HotbarPlugin`] | Player hotbar, item switching, and held-item state |
286/// | [`UiPlugin`] | Crosshair, loading screen, and HUD overlays |
287///
288/// # Generator not included
289///
290/// [`generator::GeneratorPlugin`] is intentionally excluded because it requires
291/// the caller to supply a concrete [`generator::GeneratorResource`]. Always add
292/// it separately:
293///
294/// ```rust,no_run
295/// use bevy::prelude::*;
296/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
297/// use voxel_framework::generator::terrain::{TerrainConfig, TerrainGenerator};
298/// use voxel_framework::voxel::DefaultTerrainVoxel;
299/// use std::sync::Arc;
300///
301/// App::new()
302/// .add_plugins(DefaultPlugins)
303/// .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
304/// .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
305/// .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
306/// generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
307/// })
308/// .run();
309/// ```
310///
311/// # See also
312///
313/// - [`VoxelCorePlugin`] — narrower compatibility/convenience bundle.
314/// - [`prelude`] — commonly used re-exports for convenience imports.
315pub struct VoxelPlugin<V: VoxelType = DefaultVoxel> {
316 _m: std::marker::PhantomData<V>,
317}
318
319impl<V: VoxelType> VoxelPlugin<V> {
320 /// Creates a new [`VoxelPlugin`] for voxel type `V`.
321 pub fn new() -> Self {
322 Self {
323 _m: std::marker::PhantomData,
324 }
325 }
326}
327
328impl<V: VoxelType> Default for VoxelPlugin<V> {
329 fn default() -> Self {
330 Self::new()
331 }
332}
333
334impl<V: VoxelType> Plugin for VoxelPlugin<V> {
335 fn build(&self, app: &mut App) {
336 app.add_plugins(VoxelCorePlugin::<V>::new());
337 app.add_plugins(FragmentPlugin);
338 app.add_plugins(SkyboxPlugin);
339 app.add_plugins(SfxPlugin);
340 #[cfg(feature = "items")]
341 app.add_plugins(HotbarPlugin);
342 app.add_plugins(UiPlugin);
343 }
344}