voxel_framework/voxel.rs
1//! Voxel type trait, the built-in [`DefaultVoxel`] palette, and runtime color lookup.
2//!
3//! ## Overview
4//!
5//! Every material in the voxel world is represented by a value type that
6//! implements [`VoxelType`]. The trait is intentionally minimal: it describes
7//! whether a voxel occupies space, what color it renders as, and how it maps
8//! to a single byte for binary persistence. Keeping the interface small lets
9//! implementors choose any internal representation — a simple enum, a newtype
10//! around a `u8`, or a richer struct.
11//!
12//! ## The `DefaultVoxel` palette
13//!
14//! [`DefaultVoxel`] is the built-in five-material palette used by the reference
15//! implementation and all bundled generators. It is the `V` parameter used by
16//! [`crate::VoxelCorePlugin`] and [`crate::VoxelPlugin`]. You can swap it for a
17//! custom type wherever the framework is generic over `V: VoxelType`.
18//!
19//! ## Serialization contract
20//!
21//! The [`VoxelType::to_byte`] / [`VoxelType::from_byte`] pair forms a stable
22//! binary serialization contract used by [`crate::chunk::persistence`]. Two
23//! invariants must hold:
24//!
25//! 1. `from_byte(v.to_byte()) == v` for every non-air voxel.
26//! 2. Unknown bytes must round-trip to [`VoxelType::air()`] — never panic.
27//!
28//! Changing the byte mapping of an existing palette breaks saved worlds.
29
30use std::collections::HashMap;
31use std::hash::Hash;
32
33use bevy::prelude::Resource;
34
35/// The interface every voxel material type must satisfy.
36///
37/// `VoxelType` is the central abstraction of the framework. It is the `V`
38/// parameter on [`crate::chunk::Chunk<V>`], [`crate::generator::GeneratorPlugin`],
39/// [`crate::mesh::MeshPlugin`], and [`crate::render::RenderPlugin`]. Any type
40/// that implements this trait can drive the full chunk pipeline.
41///
42/// Implementors must be **lightweight value types** because one instance is
43/// stored per voxel in a [`crate::chunk::Chunk`]
44/// (4 096 voxels per 16×16×16 chunk). Heap allocations inside a `VoxelType`
45/// value are strongly discouraged.
46///
47/// The required bounds (`Copy`, `Clone`, `Default`, `Send`, `Sync`,
48/// `PartialEq`, `Eq`, `Hash`, `'static`) exist because:
49/// - `Copy` / `Clone` — voxel values are read from and written to flat arrays
50/// by value without reference counting.
51/// - `Default` — used to initialize freshly allocated chunks and by [`air`].
52/// - `Send + Sync + 'static` — chunks are generated on a background thread via
53/// Bevy's `AsyncComputeTaskPool`.
54/// - `Eq + Hash` — required by [`VoxelPalette`]'s `HashMap<V, [f32; 4]>`.
55///
56/// # Examples
57///
58/// Implementing `VoxelType` for a two-material palette:
59///
60/// ```rust,no_run
61/// use voxel_framework::voxel::VoxelType;
62///
63/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
64/// pub enum MyVoxel { #[default] Air, Stone }
65///
66/// impl VoxelType for MyVoxel {
67/// fn name(&self) -> &'static str { match self { MyVoxel::Air => "Air", MyVoxel::Stone => "Stone" } }
68/// fn is_solid(&self) -> bool { !matches!(self, MyVoxel::Air) }
69/// fn color(&self) -> [f32; 4] {
70/// match self {
71/// MyVoxel::Air => [0.0, 0.0, 0.0, 0.0],
72/// MyVoxel::Stone => [0.5, 0.5, 0.5, 1.0],
73/// }
74/// }
75/// fn to_byte(&self) -> u8 { match self { MyVoxel::Air => 0, MyVoxel::Stone => 1 } }
76/// fn from_byte(b: u8) -> Self { match b { 1 => MyVoxel::Stone, _ => MyVoxel::Air } }
77/// }
78/// ```
79///
80/// # See also
81///
82/// - [`DefaultVoxel`] — built-in five-material implementation.
83/// - [`VoxelPalette`] — runtime RGBA overrides keyed by `VoxelType`.
84///
85/// [`air`]: VoxelType::air
86pub trait VoxelType:
87 Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static
88{
89 /// Human-readable name for this voxel type. Used in UI and world manifest.
90 fn name(&self) -> &'static str;
91
92 /// Returns `true` if this voxel occupies space and should produce mesh geometry.
93 ///
94 /// The meshing system skips faces between two adjacent solid voxels, so
95 /// this predicate directly controls which faces are emitted. Returning
96 /// `false` for transparent or non-solid materials (e.g. glass, water) is
97 /// valid and causes those faces to be emitted on neighbouring solid voxels.
98 ///
99 /// The default contract is: [`air()`] returns `false`, all other variants
100 /// return `true`.
101 ///
102 /// [`air()`]: VoxelType::air
103 fn is_solid(&self) -> bool;
104
105 /// Returns the RGBA color of this voxel as linear floating-point values
106 /// in the range `[0.0, 1.0]` per channel.
107 ///
108 /// The returned value is used both by [`VoxelPalette`] as the fallback
109 /// when no palette override exists, and directly by the greedy meshing
110 /// algorithm to assign per-face vertex colors.
111 ///
112 /// [`air()`] should return `[0.0, 0.0, 0.0, 0.0]` (transparent black).
113 ///
114 /// [`air()`]: VoxelType::air
115 fn color(&self) -> [f32; 4];
116
117 /// Serializes this voxel to a single byte for binary chunk persistence.
118 ///
119 /// The mapping must be **stable across releases**: changing an existing
120 /// variant's byte value breaks saved chunk data. New variants should use
121 /// previously unused byte values.
122 ///
123 /// The invariant `from_byte(v.to_byte()) == v` must hold for every valid
124 /// voxel value. [`air()`] must serialize to `0`.
125 ///
126 /// [`air()`]: VoxelType::air
127 fn to_byte(&self) -> u8;
128
129 /// Deserializes a voxel from a single byte read out of a chunk file.
130 ///
131 /// Unknown byte values (those not in the current palette) **must** map to
132 /// [`air()`] rather than panicking, so that worlds saved with a newer
133 /// palette version can still be read by an older build.
134 ///
135 /// [`air()`]: VoxelType::air
136 fn from_byte(byte: u8) -> Self;
137
138 /// Returns the hardness multiplier applied to the base mining break time.
139 ///
140 /// The effective break time is `config.break_time * voxel.hardness()`.
141 /// `0.0` prevents mining (the voxel is unbreakable).
142 ///
143 /// Default: `1.0` — inherits the global [`crate::world::mining::MiningConfig::break_time`]
144 /// unchanged.
145 fn hardness(&self) -> f32 {
146 1.0
147 }
148
149 /// Minimum tool level required to break this voxel.
150 ///
151 /// | Level | Example tool |
152 /// |-------|-------------|
153 /// | `0` | Bare hands / any tool |
154 /// | `1` | Stone pickaxe or better |
155 /// | `2` | Iron pickaxe or better |
156 /// | `3` | Diamond pickaxe |
157 ///
158 /// If the player's active tool level is below this value, mining makes
159 /// no progress (effective break time is treated as infinite).
160 ///
161 /// Default: `0` — breakable with bare hands.
162 fn mining_level(&self) -> u8 {
163 0
164 }
165
166 /// Returns the texture array layer index for this voxel on the given face.
167 ///
168 /// Face index convention (matches `FACE_DIRS` in the greedy mesher):
169 /// - `0` = +Y (top)
170 /// - `1` = -Y (bottom)
171 /// - `2` = +X
172 /// - `3` = -X
173 /// - `4` = +Z
174 /// - `5` = -Z
175 ///
176 /// The returned value selects which layer of the GPU texture array is
177 /// sampled by the `ChunkMaterial` shader. Layer indices correspond to the
178 /// order in which textures are assembled into the array by the game.
179 ///
180 /// Default: all faces use layer `0`.
181 fn texture_layer(&self, _face_index: usize) -> u32 {
182 0
183 }
184
185 /// Returns the texture array layer index for this voxel on the given face,
186 /// taking into account the block's placement state.
187 ///
188 /// `face_index` follows the same convention as [`texture_layer`]:
189 /// - `0` = +Y (top), `1` = -Y (bottom), `2` = +X, `3` = -X, `4` = +Z, `5` = -Z
190 ///
191 /// `state` is the raw byte stored in [`crate::chunk::Chunk::get_state`].
192 /// Bits 0–2 hold the placement face (see [`crate::chunk::face_to_state`]);
193 /// bits 3–7 are available for game-specific use.
194 ///
195 /// Override this method to make a block render differently depending on
196 /// which face it was placed against (e.g. a log block that shows end-grain
197 /// on the faces perpendicular to its axis).
198 ///
199 /// Default: delegates to [`texture_layer`], ignoring `state`.
200 ///
201 /// [`texture_layer`]: VoxelType::texture_layer
202 #[inline]
203 fn texture_layer_for_state(&self, face_index: usize, _state: u8) -> u32 {
204 self.texture_layer(face_index)
205 }
206
207 /// Returns the empty/air voxel for this type.
208 ///
209 /// The default implementation delegates to `Self::default()`, which is
210 /// correct as long as `Default` is derived with `#[default]` on the air
211 /// variant. Override this method only if air is not the default variant.
212 fn air() -> Self {
213 Self::default()
214 }
215
216 /// Returns the movement modifier applied to the player while standing on
217 /// this voxel type.
218 ///
219 /// The modifier scales speed, jump height, gravity, and friction
220 /// independently. All fields default to `1.0` (identity — no change).
221 /// Override for voxel types that should slow, accelerate, or alter
222 /// jump/friction behaviour.
223 fn movement_modifier(&self) -> MovementModifier {
224 MovementModifier::default()
225 }
226
227 /// Returns the opacity of this voxel (1.0 = fully opaque, 0.0 = invisible).
228 /// Used by the mesh generator to set vertex color alpha.
229 #[inline]
230 fn alpha(&self) -> f32 {
231 1.0
232 }
233}
234
235/// Per-surface movement modifiers applied by [`VoxelType::movement_modifier`].
236///
237/// Each field is a multiplier applied to the corresponding movement parameter
238/// while the player stands on the voxel. A value of `1.0` is the identity
239/// (no change). Values below `1.0` reduce; values above `1.0` amplify.
240///
241/// | Field | Applied to |
242/// |-------|-----------|
243/// | `speed_mult` | Horizontal target speed |
244/// | `jump_mult` | Jump impulse |
245/// | `gravity_mult` | Per-frame gravity accumulation |
246/// | `friction_mult`| Deceleration lerp factor (`DECEL * friction_mult`) |
247///
248/// # Convention
249/// - `friction_mult < 1.0` → slippery (less decel, e.g. Ice)
250/// - `speed_mult < 1.0` → movement slowed (e.g. Water, Snow)
251#[derive(Debug, Clone, Copy, PartialEq)]
252pub struct MovementModifier {
253 pub speed_mult: f32,
254 pub jump_mult: f32,
255 pub gravity_mult: f32,
256 pub friction_mult: f32,
257}
258
259impl Default for MovementModifier {
260 fn default() -> Self {
261 Self {
262 speed_mult: 1.0,
263 jump_mult: 1.0,
264 gravity_mult: 1.0,
265 friction_mult: 1.0,
266 }
267 }
268}
269
270/// The built-in five-material voxel palette used by all bundled systems.
271///
272/// `DefaultVoxel` is the concrete `VoxelType` implementation that the bundled
273/// plugins and generators operate on. It covers the five materials defined in
274/// the framework's reference specification and is ready to use without any
275/// additional configuration.
276///
277/// When you want a custom material set, implement [`VoxelType`] on your own
278/// enum and substitute it wherever the framework is generic over `V: VoxelType`.
279///
280/// # Byte mapping (persistence contract)
281///
282/// | Variant | `to_byte` |
283/// |---------|-----------|
284/// | `Air` | `0` |
285/// | `Rock` | `1` |
286/// | `IronOre` | `2` |
287/// | `SiliconCrystal` | `3` |
288/// | `RareMineral` | `4` |
289///
290/// Do not change these values; doing so breaks any saved chunk data.
291///
292/// # See also
293///
294/// - [`VoxelType`] — the trait this enum implements.
295/// - [`VoxelPalette`] — runtime RGBA overrides for individual variants.
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
297pub enum DefaultVoxel {
298 /// Empty space — not solid, produces no geometry.
299 ///
300 /// All voxels in a freshly allocated [`crate::chunk::Chunk`] start as
301 /// `Air`. Serializes to byte `0`.
302 #[default]
303 Air,
304 /// Common bulk rock — warm grey-brown (`#5966648`).
305 ///
306 /// The most abundant material in asteroid and terrain generators.
307 /// Linear RGBA: `[0.35, 0.30, 0.28, 1.0]`.
308 Rock,
309 /// Iron ore deposit — rusty orange.
310 ///
311 /// Appears as scattered veins inside rock masses.
312 /// Linear RGBA: `[0.55, 0.35, 0.20, 1.0]`.
313 IronOre,
314 /// Silicon crystal vein — cool blue-violet.
315 ///
316 /// Typically rarer than iron ore; used as a crafting input.
317 /// Linear RGBA: `[0.40, 0.50, 0.80, 1.0]`.
318 SiliconCrystal,
319 /// Rare mineral node — vivid teal-green.
320 ///
321 /// The rarest material; intended for high-value resource mechanics.
322 /// Linear RGBA: `[0.20, 0.85, 0.60, 1.0]`.
323 RareMineral,
324}
325
326impl VoxelType for DefaultVoxel {
327 #[inline]
328 fn name(&self) -> &'static str {
329 match self {
330 DefaultVoxel::Air => "Air",
331 DefaultVoxel::Rock => "Rock",
332 DefaultVoxel::IronOre => "Iron Ore",
333 DefaultVoxel::SiliconCrystal => "Silicon Crystal",
334 DefaultVoxel::RareMineral => "Rare Mineral",
335 }
336 }
337
338 #[inline]
339 fn is_solid(&self) -> bool {
340 !matches!(self, DefaultVoxel::Air)
341 }
342
343 #[inline]
344 fn color(&self) -> [f32; 4] {
345 match self {
346 DefaultVoxel::Air => [0.0, 0.0, 0.0, 0.0],
347 DefaultVoxel::Rock => [0.35, 0.30, 0.28, 1.0],
348 DefaultVoxel::IronOre => [0.55, 0.35, 0.20, 1.0],
349 DefaultVoxel::SiliconCrystal => [0.40, 0.50, 0.80, 1.0],
350 DefaultVoxel::RareMineral => [0.20, 0.85, 0.60, 1.0],
351 }
352 }
353
354 #[inline]
355 fn to_byte(&self) -> u8 {
356 match self {
357 DefaultVoxel::Air => 0,
358 DefaultVoxel::Rock => 1,
359 DefaultVoxel::IronOre => 2,
360 DefaultVoxel::SiliconCrystal => 3,
361 DefaultVoxel::RareMineral => 4,
362 }
363 }
364
365 #[inline]
366 fn from_byte(byte: u8) -> Self {
367 match byte {
368 0 => DefaultVoxel::Air,
369 1 => DefaultVoxel::Rock,
370 2 => DefaultVoxel::IronOre,
371 3 => DefaultVoxel::SiliconCrystal,
372 4 => DefaultVoxel::RareMineral,
373 _ => DefaultVoxel::Air,
374 }
375 }
376
377 #[inline]
378 fn hardness(&self) -> f32 {
379 match self {
380 DefaultVoxel::Air => 0.0,
381 DefaultVoxel::Rock => 3.0,
382 DefaultVoxel::IronOre => 4.0,
383 DefaultVoxel::SiliconCrystal => 2.5,
384 DefaultVoxel::RareMineral => 5.0,
385 }
386 }
387
388 #[inline]
389 fn mining_level(&self) -> u8 {
390 match self {
391 DefaultVoxel::Air => 0,
392 DefaultVoxel::Rock => 1,
393 DefaultVoxel::IronOre => 2,
394 DefaultVoxel::SiliconCrystal => 1,
395 DefaultVoxel::RareMineral => 2,
396 }
397 }
398
399 /// Returns the texture array layer index for this voxel.
400 ///
401 /// Layers align with the loading order in `basic_world`:
402 /// - `0` = Air placeholder (grey)
403 /// - `1` = Rock (stone.png)
404 /// - `2` = IronOre (iron_ore.png)
405 /// - `3` = SiliconCrystal (amethyst_block.png)
406 /// - `4` = RareMineral (emerald_ore.png)
407 #[inline]
408 fn texture_layer(&self, _face_index: usize) -> u32 {
409 match self {
410 DefaultVoxel::Air => 0,
411 DefaultVoxel::Rock => 1,
412 DefaultVoxel::IronOre => 2,
413 DefaultVoxel::SiliconCrystal => 3,
414 DefaultVoxel::RareMineral => 4,
415 }
416 }
417}
418
419/// Built-in terrain voxel palette for Minetest/Minecraft-style worlds.
420///
421/// `DefaultTerrainVoxel` is a ten-material palette tuned for procedural
422/// heightmap terrain. Use it with [`crate::generator::terrain::TerrainGenerator`]
423/// and [`crate::VoxelPlugin::<DefaultTerrainVoxel>::new()`].
424///
425/// # Byte mapping (persistence contract)
426///
427/// | Variant | `to_byte` |
428/// |---------|-----------|
429/// | `Air` | `0` |
430/// | `Grass` | `1` |
431/// | `Dirt` | `2` |
432/// | `Stone` | `3` |
433/// | `Sand` | `4` |
434/// | `Wood` | `5` |
435/// | `Leaves` | `6` |
436/// | `Gravel` | `7` |
437/// | `Snow` | `8` |
438/// | `Water` | `9` |
439/// | `CoalOre` | `10` |
440/// | `IronOre` | `11` |
441/// | `Cobblestone` | `12` |
442/// | `Sandstone` | `13` |
443/// | `Planks` | `14` |
444/// | `Brick` | `15` |
445///
446/// Do not change these values; doing so breaks any saved chunk data.
447#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
448pub enum DefaultTerrainVoxel {
449 /// Empty space — not solid, produces no geometry.
450 #[default]
451 Air,
452 /// Grass-covered topsoil — vivid green.
453 ///
454 /// Top layer of terrain surface. Linear RGBA: `[0.30, 0.60, 0.20, 1.0]`.
455 Grass,
456 /// Dirt layer — warm brown.
457 ///
458 /// Found just below the grass layer. Linear RGBA: `[0.50, 0.35, 0.20, 1.0]`.
459 Dirt,
460 /// Stone — cool grey.
461 ///
462 /// Bulk underground material. Linear RGBA: `[0.50, 0.50, 0.50, 1.0]`.
463 Stone,
464 /// Sand — pale yellow.
465 ///
466 /// Replaces grass/dirt at very low elevations (beaches). Linear RGBA: `[0.85, 0.80, 0.50, 1.0]`.
467 Sand,
468 /// Tree trunk wood — brown.
469 ///
470 /// Used for procedurally generated tree trunks. Linear RGBA: `[0.45, 0.30, 0.18, 1.0]`.
471 Wood,
472 /// Tree foliage — green.
473 ///
474 /// Used for procedurally generated tree crowns. Linear RGBA: `[0.20, 0.55, 0.15, 1.0]`.
475 Leaves,
476 /// Gravel — mid grey.
477 ///
478 /// Loose stone aggregate. Linear RGBA: `[0.55, 0.52, 0.50, 1.0]`.
479 Gravel,
480 /// Snow — near-white.
481 ///
482 /// Surface cover at high elevations. Linear RGBA: `[0.92, 0.95, 0.98, 1.0]`.
483 Snow,
484 /// Water — blue, non-solid.
485 ///
486 /// Fills low-elevation air voxels up to the configured water level.
487 /// Not solid — adjacent solid faces are still meshed. Linear RGBA: `[0.15, 0.40, 0.75, 1.0]`.
488 Water,
489 /// Coal ore — black speckled stone.
490 ///
491 /// Common underground fuel ore. Linear RGBA: `[0.30, 0.30, 0.30, 1.0]`.
492 CoalOre,
493 /// Iron ore — rusty brown stone.
494 ///
495 /// Iron-bearing rock formation. Linear RGBA: `[0.60, 0.45, 0.35, 1.0]`.
496 IronOre,
497 /// Cobblestone — rough gray stone.
498 ///
499 /// Processed stone aggregate. Linear RGBA: `[0.40, 0.40, 0.40, 1.0]`.
500 Cobblestone,
501 /// Sandstone — beige compacted stone.
502 ///
503 /// Compressed sand layers. Linear RGBA: `[0.80, 0.72, 0.45, 1.0]`.
504 Sandstone,
505 /// Planks — warm tan wood.
506 ///
507 /// Processed wood boards. Linear RGBA: `[0.65, 0.48, 0.28, 1.0]`.
508 Planks,
509 /// Brick — deep red fired clay.
510 ///
511 /// Kiln-fired clay building block. Linear RGBA: `[0.65, 0.28, 0.20, 1.0]`.
512 Brick,
513}
514
515impl VoxelType for DefaultTerrainVoxel {
516 #[inline]
517 fn name(&self) -> &'static str {
518 match self {
519 DefaultTerrainVoxel::Air => "Air",
520 DefaultTerrainVoxel::Grass => "Grass",
521 DefaultTerrainVoxel::Dirt => "Dirt",
522 DefaultTerrainVoxel::Stone => "Stone",
523 DefaultTerrainVoxel::Sand => "Sand",
524 DefaultTerrainVoxel::Wood => "Wood",
525 DefaultTerrainVoxel::Leaves => "Leaves",
526 DefaultTerrainVoxel::Gravel => "Gravel",
527 DefaultTerrainVoxel::Snow => "Snow",
528 DefaultTerrainVoxel::Water => "Water",
529 DefaultTerrainVoxel::CoalOre => "Coal Ore",
530 DefaultTerrainVoxel::IronOre => "Iron Ore",
531 DefaultTerrainVoxel::Cobblestone => "Cobblestone",
532 DefaultTerrainVoxel::Sandstone => "Sandstone",
533 DefaultTerrainVoxel::Planks => "Planks",
534 DefaultTerrainVoxel::Brick => "Brick",
535 }
536 }
537
538 #[inline]
539 fn is_solid(&self) -> bool {
540 !matches!(self, DefaultTerrainVoxel::Air | DefaultTerrainVoxel::Water)
541 }
542
543 #[inline]
544 fn color(&self) -> [f32; 4] {
545 match self {
546 DefaultTerrainVoxel::Air => [0.0, 0.0, 0.0, 0.0],
547 DefaultTerrainVoxel::Grass => [0.30, 0.60, 0.20, 1.0],
548 DefaultTerrainVoxel::Dirt => [0.50, 0.35, 0.20, 1.0],
549 DefaultTerrainVoxel::Stone => [0.50, 0.50, 0.50, 1.0],
550 DefaultTerrainVoxel::Sand => [0.85, 0.80, 0.50, 1.0],
551 DefaultTerrainVoxel::Wood => [0.45, 0.30, 0.18, 1.0],
552 DefaultTerrainVoxel::Leaves => [0.20, 0.55, 0.15, 1.0],
553 DefaultTerrainVoxel::Gravel => [0.55, 0.52, 0.50, 1.0],
554 DefaultTerrainVoxel::Snow => [0.92, 0.95, 0.98, 1.0],
555 DefaultTerrainVoxel::Water => [0.15, 0.40, 0.75, 0.7],
556 DefaultTerrainVoxel::CoalOre => [0.30, 0.30, 0.30, 1.0],
557 DefaultTerrainVoxel::IronOre => [0.60, 0.45, 0.35, 1.0],
558 DefaultTerrainVoxel::Cobblestone => [0.40, 0.40, 0.40, 1.0],
559 DefaultTerrainVoxel::Sandstone => [0.80, 0.72, 0.45, 1.0],
560 DefaultTerrainVoxel::Planks => [0.65, 0.48, 0.28, 1.0],
561 DefaultTerrainVoxel::Brick => [0.65, 0.28, 0.20, 1.0],
562 }
563 }
564
565 #[inline]
566 fn to_byte(&self) -> u8 {
567 match self {
568 DefaultTerrainVoxel::Air => 0,
569 DefaultTerrainVoxel::Grass => 1,
570 DefaultTerrainVoxel::Dirt => 2,
571 DefaultTerrainVoxel::Stone => 3,
572 DefaultTerrainVoxel::Sand => 4,
573 DefaultTerrainVoxel::Wood => 5,
574 DefaultTerrainVoxel::Leaves => 6,
575 DefaultTerrainVoxel::Gravel => 7,
576 DefaultTerrainVoxel::Snow => 8,
577 DefaultTerrainVoxel::Water => 9,
578 DefaultTerrainVoxel::CoalOre => 10,
579 DefaultTerrainVoxel::IronOre => 11,
580 DefaultTerrainVoxel::Cobblestone => 12,
581 DefaultTerrainVoxel::Sandstone => 13,
582 DefaultTerrainVoxel::Planks => 14,
583 DefaultTerrainVoxel::Brick => 15,
584 }
585 }
586
587 #[inline]
588 fn from_byte(byte: u8) -> Self {
589 match byte {
590 1 => DefaultTerrainVoxel::Grass,
591 2 => DefaultTerrainVoxel::Dirt,
592 3 => DefaultTerrainVoxel::Stone,
593 4 => DefaultTerrainVoxel::Sand,
594 5 => DefaultTerrainVoxel::Wood,
595 6 => DefaultTerrainVoxel::Leaves,
596 7 => DefaultTerrainVoxel::Gravel,
597 8 => DefaultTerrainVoxel::Snow,
598 9 => DefaultTerrainVoxel::Water,
599 10 => DefaultTerrainVoxel::CoalOre,
600 11 => DefaultTerrainVoxel::IronOre,
601 12 => DefaultTerrainVoxel::Cobblestone,
602 13 => DefaultTerrainVoxel::Sandstone,
603 14 => DefaultTerrainVoxel::Planks,
604 15 => DefaultTerrainVoxel::Brick,
605 _ => DefaultTerrainVoxel::Air,
606 }
607 }
608
609 #[inline]
610 fn hardness(&self) -> f32 {
611 match self {
612 DefaultTerrainVoxel::Air => 0.0, // unbreakable
613 DefaultTerrainVoxel::Grass => 0.5,
614 DefaultTerrainVoxel::Dirt => 0.5,
615 DefaultTerrainVoxel::Stone => 3.0,
616 DefaultTerrainVoxel::Sand => 0.5,
617 DefaultTerrainVoxel::Wood => 1.5,
618 DefaultTerrainVoxel::Leaves => 0.3,
619 DefaultTerrainVoxel::Gravel => 0.75,
620 DefaultTerrainVoxel::Snow => 0.3,
621 DefaultTerrainVoxel::Water => 0.0, // unbreakable
622 DefaultTerrainVoxel::CoalOre => 3.0,
623 DefaultTerrainVoxel::IronOre => 4.0,
624 DefaultTerrainVoxel::Cobblestone => 2.5,
625 DefaultTerrainVoxel::Sandstone => 1.5,
626 DefaultTerrainVoxel::Planks => 1.0,
627 DefaultTerrainVoxel::Brick => 2.0,
628 }
629 }
630
631 #[inline]
632 fn mining_level(&self) -> u8 {
633 match self {
634 DefaultTerrainVoxel::Stone => 1,
635 DefaultTerrainVoxel::Gravel => 1,
636 DefaultTerrainVoxel::CoalOre => 1,
637 DefaultTerrainVoxel::IronOre => 2,
638 DefaultTerrainVoxel::Cobblestone => 1,
639 DefaultTerrainVoxel::Sandstone => 1,
640 DefaultTerrainVoxel::Brick => 1,
641 _ => 0,
642 }
643 }
644
645 #[inline]
646 fn texture_layer(&self, _face_index: usize) -> u32 {
647 match self {
648 DefaultTerrainVoxel::Air => 0,
649 DefaultTerrainVoxel::Grass => 1,
650 DefaultTerrainVoxel::Dirt => 2,
651 DefaultTerrainVoxel::Stone => 3,
652 DefaultTerrainVoxel::Sand => 4,
653 DefaultTerrainVoxel::Wood => 5,
654 DefaultTerrainVoxel::Leaves => 6,
655 DefaultTerrainVoxel::Gravel => 7,
656 DefaultTerrainVoxel::Snow => 8,
657 DefaultTerrainVoxel::Water => 9,
658 DefaultTerrainVoxel::CoalOre => 10,
659 DefaultTerrainVoxel::IronOre => 11,
660 DefaultTerrainVoxel::Cobblestone => 12,
661 DefaultTerrainVoxel::Sandstone => 13,
662 DefaultTerrainVoxel::Planks => 14,
663 DefaultTerrainVoxel::Brick => 15,
664 }
665 }
666
667 #[inline]
668 fn movement_modifier(&self) -> MovementModifier {
669 match self {
670 DefaultTerrainVoxel::Water => MovementModifier {
671 speed_mult: 0.4,
672 jump_mult: 0.5,
673 gravity_mult: 1.0,
674 friction_mult: 1.0,
675 },
676 DefaultTerrainVoxel::Snow => MovementModifier {
677 speed_mult: 0.7,
678 ..MovementModifier::default()
679 },
680 _ => MovementModifier::default(),
681 }
682 }
683
684 #[inline]
685 fn alpha(&self) -> f32 {
686 match self {
687 Self::Water => 0.7,
688 _ => 1.0,
689 }
690 }
691}
692
693/// A Bevy [`Resource`] that maps voxel types to runtime RGBA color overrides.
694///
695/// `VoxelPalette` lets you override the colors returned by
696/// [`VoxelType::color`] without changing the `VoxelType` implementation. This
697/// is useful when colors come from a data file or when you want to support
698/// texture packs / themes at runtime.
699///
700/// The palette is inserted into the Bevy world at startup and cloned into
701/// async mesh generation tasks, so it must be `Clone`. When no override is
702/// registered for a voxel, [`color_of`] falls back to `VoxelType::color`.
703///
704/// # Example
705///
706/// ```rust,no_run
707/// use std::collections::HashMap;
708/// use voxel_framework::voxel::{DefaultVoxel, VoxelPalette};
709///
710/// let mut colors = HashMap::new();
711/// // Override Rock to a brighter shade for testing.
712/// colors.insert(DefaultVoxel::Rock, [0.6, 0.6, 0.6, 1.0]);
713/// let palette = VoxelPalette::new(colors);
714///
715/// // Unknown voxels fall back to their own color() impl.
716/// let iron_color = palette.color_of(&DefaultVoxel::IronOre);
717/// assert_eq!(iron_color, [0.55, 0.35, 0.20, 1.0]);
718/// ```
719///
720/// # See also
721///
722/// - [`VoxelType::color`] — the per-variant color fallback.
723///
724/// [`color_of`]: VoxelPalette::color_of
725#[derive(Resource, Clone, Debug)]
726pub struct VoxelPalette<V: VoxelType> {
727 colors: HashMap<V, [f32; 4]>,
728}
729
730impl<V: VoxelType> VoxelPalette<V> {
731 /// Creates a new palette from a pre-built map of voxel types to RGBA colors.
732 ///
733 /// Only the variants present in `colors` are overridden; all others
734 /// continue to use their [`VoxelType::color`] value.
735 pub fn new(colors: HashMap<V, [f32; 4]>) -> Self {
736 Self { colors }
737 }
738
739 /// Returns the RGBA color for `voxel`.
740 ///
741 /// Checks the override map first. If no entry is present, falls back to
742 /// `voxel.color()`. The returned array is in linear floating-point RGBA
743 /// with each channel in `[0.0, 1.0]`.
744 #[inline]
745 pub fn color_of(&self, voxel: &V) -> [f32; 4] {
746 self.colors
747 .get(voxel)
748 .copied()
749 .unwrap_or_else(|| voxel.color())
750 }
751}
752
753impl<V: VoxelType> Default for VoxelPalette<V> {
754 fn default() -> Self {
755 Self {
756 colors: HashMap::new(),
757 }
758 }
759}
760
761#[cfg(test)]
762mod tests {
763 use super::*;
764
765 #[test]
766 fn default_voxel_hardness_overrides() {
767 assert_eq!(DefaultVoxel::Air.hardness(), 0.0);
768 assert_eq!(DefaultVoxel::Rock.hardness(), 3.0);
769 assert_eq!(DefaultVoxel::IronOre.hardness(), 4.0);
770 assert_eq!(DefaultVoxel::SiliconCrystal.hardness(), 2.5);
771 assert_eq!(DefaultVoxel::RareMineral.hardness(), 5.0);
772 }
773
774 #[test]
775 fn default_voxel_mining_level_overrides() {
776 assert_eq!(DefaultVoxel::Air.mining_level(), 0);
777 assert_eq!(DefaultVoxel::Rock.mining_level(), 1);
778 assert_eq!(DefaultVoxel::IronOre.mining_level(), 2);
779 assert_eq!(DefaultVoxel::SiliconCrystal.mining_level(), 1);
780 assert_eq!(DefaultVoxel::RareMineral.mining_level(), 2);
781 }
782
783 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
784 enum MinimalVoxel {
785 #[default]
786 Air,
787 Solid,
788 }
789
790 impl VoxelType for MinimalVoxel {
791 fn name(&self) -> &'static str {
792 match self {
793 MinimalVoxel::Air => "Air",
794 MinimalVoxel::Solid => "Solid",
795 }
796 }
797 fn is_solid(&self) -> bool {
798 matches!(self, MinimalVoxel::Solid)
799 }
800 fn color(&self) -> [f32; 4] {
801 [0.0, 0.0, 0.0, 1.0]
802 }
803 fn to_byte(&self) -> u8 {
804 match self {
805 MinimalVoxel::Air => 0,
806 MinimalVoxel::Solid => 1,
807 }
808 }
809 fn from_byte(byte: u8) -> Self {
810 match byte {
811 1 => MinimalVoxel::Solid,
812 _ => MinimalVoxel::Air,
813 }
814 }
815 }
816
817 #[test]
818 fn voxel_type_trait_defaults() {
819 assert_eq!(MinimalVoxel::Solid.hardness(), 1.0);
820 assert_eq!(MinimalVoxel::Solid.mining_level(), 0);
821 assert_eq!(MinimalVoxel::Air.hardness(), 1.0);
822 assert_eq!(MinimalVoxel::Air.mining_level(), 0);
823 }
824}