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