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`], [`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;
136pub mod content;
137#[cfg(feature = "crafting")]
138pub mod crafting;
139pub mod effects;
140pub mod fragments;
141pub mod generator;
142#[cfg(feature = "items")]
143pub mod items;
144pub mod mesh;
145#[cfg(feature = "mobs")]
146pub mod mobs;
147pub mod noise;
148pub mod player;
149pub mod plugin_category;
150pub mod prelude;
151pub mod profile;
152pub mod render;
153pub mod settings;
154pub mod skybox;
155pub mod stats;
156pub mod ui;
157pub mod voxel;
158pub mod world;
159
160use bevy::prelude::*;
161
162use audio::SfxPlugin;
163use fragments::FragmentPlugin;
164#[cfg(feature = "items")]
165use items::hotbar::HotbarPlugin;
166use mesh::MeshPlugin;
167use render::RenderPlugin;
168use skybox::SkyboxPlugin;
169use ui::UiPlugin;
170use voxel::DefaultVoxel;
171use voxel::VoxelType;
172use world::loading::LoadingPlugin;
173use world::mining::MiningPlugin;
174use world::occlusion::OcclusionPlugin;
175use world::placement::PlacementPlugin;
176use world::{WorldConfigPlugin, WorldPlugin};
177
178/// Convenience bundle for the historical core voxel runtime.
179///
180/// `VoxelCorePlugin<V>` wires up the legacy core bundle — world streaming,
181/// chunk lifecycle, meshing, PBR rendering, neighbor-solid occlusion, mining,
182/// placement, and loading state — without the bundled presentation defaults
183/// from [`VoxelPlugin`].
184///
185/// In the plugin catalog taxonomy this type is a [`plugin_category::ConveniencePlugin`]:
186/// it composes stricter Engine and Gameplay plugins for compatibility and quick
187/// starts. New architecture should describe those individual plugins by their
188/// primary categories rather than treating this bundle as the whole model.
189///
190/// The generic parameter `V` selects the voxel type used by the rendering,
191/// meshing, and occlusion systems. Defaults to [`DefaultVoxel`] for backwards
192/// compatibility: `VoxelCorePlugin::default()` and
193/// `VoxelCorePlugin::<DefaultVoxel>::new()` are equivalent.
194///
195/// # Included systems
196///
197/// | Plugin | Responsibility |
198/// |--------|----------------|
199/// | [`WorldPlugin`] | [`world::ChunkManager`], [`world::systems::ViewerPosition`], chunk lifecycle events, and streaming |
200/// | [`WorldConfigPlugin`] | Inserts the [`world::WorldConfig`] resource |
201/// | `RenderPlugin<V>` | Shared chunk PBR material and entity spawn |
202/// | `MeshPlugin<V>` | Greedy mesh generation and chunk despawn |
203/// | `OcclusionPlugin<V>` | Neighbor-solid chunk occlusion |
204/// | [`world::mining::MiningPlugin`] | Gameplay primitive for voxel removal |
205/// | [`world::placement::PlacementPlugin`] | Gameplay primitive for voxel placement |
206/// | [`world::loading::LoadingPlugin`] | World loading state machine |
207///
208/// # Not included (opt-in)
209///
210/// - [`generator::GeneratorPlugin`] — requires the caller to supply a
211/// [`generator::GeneratorResource`].
212/// - [`FragmentPlugin`], [`SkyboxPlugin`], [`SfxPlugin`], [`HotbarPlugin`],
213/// [`UiPlugin`] — presentation/gameplay defaults included by [`VoxelPlugin`].
214///
215/// # Example
216///
217/// ```rust,no_run
218/// use bevy::prelude::*;
219/// use voxel_framework::{VoxelCorePlugin, generator::{GeneratorPlugin, GeneratorResource}};
220/// use voxel_framework::generator::asteroid::{AsteroidConfig, AsteroidGenerator};
221/// use voxel_framework::voxel::DefaultVoxel;
222/// use std::sync::Arc;
223///
224/// App::new()
225/// .add_plugins(DefaultPlugins)
226/// .add_plugins(VoxelCorePlugin::<DefaultVoxel>::new())
227/// .add_plugins(GeneratorPlugin::<DefaultVoxel>::new())
228/// .insert_resource(GeneratorResource::<DefaultVoxel> {
229/// generator: Arc::new(AsteroidGenerator::new(AsteroidConfig::default())),
230/// })
231/// .run();
232/// ```
233///
234/// # See also
235///
236/// - [`VoxelPlugin`] — broader quick-start convenience bundle.
237pub struct VoxelCorePlugin<V: VoxelType = DefaultVoxel> {
238 _m: std::marker::PhantomData<V>,
239}
240
241impl<V: VoxelType> VoxelCorePlugin<V> {
242 /// Creates a new [`VoxelCorePlugin`] for voxel type `V`.
243 pub fn new() -> Self {
244 Self {
245 _m: std::marker::PhantomData,
246 }
247 }
248}
249
250impl<V: VoxelType> Default for VoxelCorePlugin<V> {
251 fn default() -> Self {
252 Self::new()
253 }
254}
255
256impl<V: VoxelType> Plugin for VoxelCorePlugin<V> {
257 fn build(&self, app: &mut App) {
258 app.add_plugins(WorldPlugin);
259 app.add_plugins(WorldConfigPlugin);
260 app.add_plugins(RenderPlugin::<V>::new());
261 app.add_plugins(MeshPlugin::<V>::new());
262 app.add_plugins(OcclusionPlugin::<V>::new());
263 app.add_plugins(MiningPlugin);
264 app.add_plugins(PlacementPlugin);
265 app.add_plugins(LoadingPlugin);
266 }
267}
268
269/// Quick-start convenience bundle for demos and prototypes.
270///
271/// `VoxelPlugin<V>` composes [`VoxelCorePlugin<V>`] with selected presentation
272/// and gameplay defaults. It is useful for examples, demos, and early
273/// prototyping, but it is not the architectural definition of the full
274/// framework. Production games should treat it as a convenience bundle and
275/// switch to explicit catalog plugins when they need finer control.
276///
277/// The generic parameter `V` selects the voxel type. Defaults to
278/// [`DefaultVoxel`] — `VoxelPlugin::default()` produces an asteroid-palette
279/// world, `VoxelPlugin::<DefaultTerrainVoxel>::new()` produces a terrain world.
280///
281/// # Included beyond [`VoxelCorePlugin`]
282///
283/// | Plugin | Responsibility |
284/// |--------|----------------|
285/// | [`FragmentPlugin`] | Floating voxel debris entities ejected on mining |
286/// | [`SkyboxPlugin`] | Procedural starfield and skybox rendering |
287/// | [`SfxPlugin`] | Positional audio effects for mining and placement |
288/// | [`HotbarPlugin`] | Player hotbar, item switching, and held-item state |
289/// | [`UiPlugin`] | Crosshair, loading screen, and HUD overlays |
290///
291/// # Generator not included
292///
293/// [`generator::GeneratorPlugin`] is intentionally excluded because it requires
294/// the caller to supply a concrete [`generator::GeneratorResource`]. Always add
295/// it separately:
296///
297/// ```rust,no_run
298/// use bevy::prelude::*;
299/// use voxel_framework::{VoxelPlugin, generator::{GeneratorPlugin, GeneratorResource}};
300/// use voxel_framework::generator::terrain::{TerrainConfig, TerrainGenerator};
301/// use voxel_framework::voxel::DefaultTerrainVoxel;
302/// use std::sync::Arc;
303///
304/// App::new()
305/// .add_plugins(DefaultPlugins)
306/// .add_plugins(VoxelPlugin::<DefaultTerrainVoxel>::new())
307/// .add_plugins(GeneratorPlugin::<DefaultTerrainVoxel>::new())
308/// .insert_resource(GeneratorResource::<DefaultTerrainVoxel> {
309/// generator: Arc::new(TerrainGenerator::new(TerrainConfig::default())),
310/// })
311/// .run();
312/// ```
313///
314/// # See also
315///
316/// - [`VoxelCorePlugin`] — narrower compatibility/convenience bundle.
317/// - [`prelude`] — commonly used re-exports for convenience imports.
318pub struct VoxelPlugin<V: VoxelType = DefaultVoxel> {
319 _m: std::marker::PhantomData<V>,
320}
321
322impl<V: VoxelType> VoxelPlugin<V> {
323 /// Creates a new [`VoxelPlugin`] for voxel type `V`.
324 pub fn new() -> Self {
325 Self {
326 _m: std::marker::PhantomData,
327 }
328 }
329}
330
331impl<V: VoxelType> Default for VoxelPlugin<V> {
332 fn default() -> Self {
333 Self::new()
334 }
335}
336
337impl<V: VoxelType> Plugin for VoxelPlugin<V> {
338 fn build(&self, app: &mut App) {
339 app.add_plugins(VoxelCorePlugin::<V>::new());
340 app.add_plugins(FragmentPlugin);
341 app.add_plugins(SkyboxPlugin);
342 app.add_plugins(SfxPlugin);
343 #[cfg(feature = "items")]
344 app.add_plugins(HotbarPlugin);
345 app.add_plugins(UiPlugin);
346 }
347}