Skip to main content

voxel_framework/items/
drops.rs

1//! Drop table, world-entity lifecycle, and magnet pickup systems.
2//!
3//! When a voxel is destroyed the mining subsystem emits a
4//! [`crate::world::VoxelBroken`] message.  This module listens to that message
5//! and drives the full item-drop pipeline:
6//!
7//! 1. **Spawn** — `spawn_drops_system` consults [`DropTable`] and spawns a
8//!    [`DroppedItem`] entity at the broken voxel's world position.
9//! 2. **Attract** — `magnet_system` applies a configurable acceleration toward
10//!    any entity tagged with [`ItemCollector`] once the item is within
11//!    [`MagnetConfig::radius`] world units.
12//! 3. **Collect** — when the item reaches within 0.5 units of the collector,
13//!    `magnet_system` calls [`crate::items::inventory::Inventory::add`], emits
14//!    [`crate::items::inventory::ItemPickedUp`], and despawns the entity.
15//! 4. **Expire** — items that are never collected despawn automatically after
16//!    their [`DroppedItem::lifetime`] reaches zero (default 60 seconds).
17//!
18//! # Plugin registration
19//!
20//! [`DropsPlugin`] is intentionally **not** bundled inside
21//! [`crate::VoxelPlugin`] because it is generic over `I: `[`ItemType`].
22//! Add it explicitly in game code, alongside
23//! [`crate::generator::GeneratorPlugin`]:
24//!
25//! ```rust,no_run
26//! use bevy::prelude::*;
27//! use voxel_framework::items::{DefaultItem, DropsPlugin};
28//!
29//! App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
30//! ```
31
32use std::collections::HashMap;
33use std::marker::PhantomData;
34
35use bevy::prelude::*;
36
37use crate::world::VoxelBroken;
38
39use super::inventory::{ContainerComponent, ItemPickedUp, ItemType, PrimaryContainer};
40
41// ─── DropTable ────────────────────────────────────────────────────────────────
42
43/// One runtime drop entry for a voxel byte.
44///
45/// This is the runtime counterpart of
46/// [`crate::content::BlockDropDefinition`]. It is intentionally keyed by voxel
47/// byte because [`DropsPlugin`] reacts to [`crate::world::VoxelBroken`] events,
48/// and those events carry the destroyed voxel byte.
49#[derive(Debug, Clone, Copy, PartialEq)]
50pub struct DropTableEntry<I: ItemType> {
51    /// Item produced by this entry.
52    pub item: I,
53    /// Minimum count, inclusive.
54    pub min_count: u32,
55    /// Maximum count, inclusive.
56    pub max_count: u32,
57    /// Probability in `0.0..=1.0`.
58    pub chance: f32,
59}
60
61impl<I: ItemType> DropTableEntry<I> {
62    /// Creates a guaranteed drop entry.
63    pub fn new(item: I, min_count: u32, max_count: u32) -> Self {
64        Self::with_chance(item, min_count, max_count, 1.0)
65    }
66
67    /// Creates a drop entry with an explicit probability.
68    pub fn with_chance(item: I, min_count: u32, max_count: u32, chance: f32) -> Self {
69        Self {
70            item,
71            min_count: min_count.min(max_count),
72            max_count: min_count.max(max_count),
73            chance: chance.clamp(0.0, 1.0),
74        }
75    }
76}
77
78/// Mapping from voxel byte IDs to item drop definitions.
79///
80/// Each entry associates a voxel byte value (the `u8` returned by
81/// [`crate::voxel::VoxelType::to_byte`]) with an item type and a drop-count
82/// range `[min, max]`. Runtime entries may also carry a chance, and a voxel may
83/// have multiple entries. When a matching voxel is broken,
84/// `spawn_drops_system` queries this table and selects counts/chance outcomes
85/// using deterministic pseudo-random values seeded from the voxel's world
86/// position. If `min == max` the count is always fixed.
87///
88/// [`DropTable`] is initialized empty; register entries before the first
89/// [`crate::world::VoxelBroken`] message is processed.  It is available as a
90/// Bevy [`Resource`] after [`DropsPlugin`] is added.
91///
92/// # Examples
93///
94/// ```rust,no_run
95/// use voxel_framework::items::{DropTable, DefaultItem};
96///
97/// let mut table = DropTable::<DefaultItem>::new();
98/// // Voxel byte 1 drops 1–3 rock fragments.
99/// table.register(1, DefaultItem::RockFragment, 1, 3);
100/// // Voxel byte 2 always drops exactly 1 iron ore.
101/// table.register(2, DefaultItem::IronOre, 1, 1);
102/// // Voxel byte 3 can produce multiple runtime entries.
103/// table.add_entry(3, voxel_framework::items::DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
104/// table.add_entry(3, voxel_framework::items::DropTableEntry::with_chance(DefaultItem::Coal, 1, 2, 0.25));
105/// ```
106#[derive(Resource, Debug, Clone)]
107pub struct DropTable<I: ItemType> {
108    /// Internal map: `voxel_byte` → runtime drop entries.
109    entries: HashMap<u8, Vec<DropTableEntry<I>>>,
110}
111
112impl<I: ItemType> DropTable<I> {
113    /// Creates an empty drop table.
114    pub fn new() -> Self {
115        Self {
116            entries: HashMap::new(),
117        }
118    }
119
120    /// Registers a drop for the given voxel byte.
121    ///
122    /// When a voxel with `voxel_byte` is broken, between `min` and `max` items
123    /// (inclusive) of `item` will be dropped. If `min == max` the count is
124    /// always fixed.
125    ///
126    /// This replaces any previous runtime entries for the voxel byte, preserving
127    /// the historical one-entry behavior of [`DropTable::register`]. Use
128    /// [`DropTable::add_entry`] when a voxel should produce multiple drops.
129    pub fn register(&mut self, voxel_byte: u8, item: I, min: u32, max: u32) {
130        self.replace_entries(voxel_byte, [DropTableEntry::new(item, min, max)]);
131    }
132
133    /// Registers a single probabilistic drop for the given voxel byte.
134    ///
135    /// Like [`DropTable::register`], this replaces any previous entries for the
136    /// voxel byte.
137    pub fn register_with_chance(
138        &mut self,
139        voxel_byte: u8,
140        item: I,
141        min: u32,
142        max: u32,
143        chance: f32,
144    ) {
145        self.replace_entries(
146            voxel_byte,
147            [DropTableEntry::with_chance(item, min, max, chance)],
148        );
149    }
150
151    /// Appends one runtime entry without removing existing entries for the same
152    /// voxel byte.
153    pub fn add_entry(&mut self, voxel_byte: u8, entry: DropTableEntry<I>) {
154        self.entries.entry(voxel_byte).or_default().push(entry);
155    }
156
157    /// Replaces all runtime entries for one voxel byte.
158    pub fn replace_entries(
159        &mut self,
160        voxel_byte: u8,
161        entries: impl IntoIterator<Item = DropTableEntry<I>>,
162    ) {
163        self.entries
164            .insert(voxel_byte, entries.into_iter().collect());
165    }
166
167    /// Iterates over all explicitly registered drop entries.
168    ///
169    /// Yields `(voxel_byte, item, min_count, max_count)` for each registration.
170    /// Identity-fallback entries (not explicitly registered) are not included.
171    pub fn iter_entries(&self) -> impl Iterator<Item = (u8, I, u32, u32)> + '_ {
172        self.iter_drop_entries()
173            .map(|(voxel_byte, entry)| (voxel_byte, entry.item, entry.min_count, entry.max_count))
174    }
175
176    /// Iterates over all explicitly registered runtime drop entries, including
177    /// chance metadata.
178    pub fn iter_drop_entries(&self) -> impl Iterator<Item = (u8, &DropTableEntry<I>)> + '_ {
179        self.entries
180            .iter()
181            .flat_map(|(&voxel_byte, entries)| entries.iter().map(move |entry| (voxel_byte, entry)))
182    }
183
184    /// Returns the drop for `voxel_byte`, using `seed` for deterministic count
185    /// selection within `[min, max]`.
186    ///
187    /// Explicit registrations always win. If no entry is registered for
188    /// `voxel_byte`, falls back to the identity mapping: `I::from_byte(voxel_byte)`
189    /// with count 1. If the resulting item is the empty sentinel (i.e.
190    /// `item.to_byte() == 0`), returns `None` — meaning no drop.
191    pub fn get_drop(&self, voxel_byte: u8, seed: u64) -> Option<(I, u32)> {
192        self.get_drops(voxel_byte, seed).into_iter().next()
193    }
194
195    /// Returns all drops produced for `voxel_byte` with deterministic chance
196    /// rolls and count selection.
197    pub fn get_drops(&self, voxel_byte: u8, seed: u64) -> Vec<(I, u32)> {
198        if let Some(entries) = self.entries.get(&voxel_byte) {
199            return entries
200                .iter()
201                .enumerate()
202                .filter_map(|(index, entry)| entry.roll(seed, index as u64))
203                .collect();
204        }
205
206        // Identity fallback: try mapping the voxel byte directly to an item.
207        let item = I::from_byte(voxel_byte);
208        if !item.is_empty() {
209            vec![(item, 1)]
210        } else {
211            Vec::new()
212        }
213    }
214}
215
216impl<I: ItemType> DropTableEntry<I> {
217    fn roll(&self, seed: u64, salt: u64) -> Option<(I, u32)> {
218        if self.item.is_empty() || self.max_count == 0 || self.chance <= 0.0 {
219            return None;
220        }
221
222        let chance_roll = unit_interval(seed, salt);
223        if chance_roll > self.chance {
224            return None;
225        }
226
227        let count = if self.min_count == self.max_count {
228            self.min_count
229        } else {
230            let range = (self.max_count - self.min_count + 1) as u64;
231            self.min_count + (lcg(seed, salt.wrapping_add(1)) % range) as u32
232        };
233
234        (count > 0).then_some((self.item, count))
235    }
236}
237
238fn lcg(seed: u64, salt: u64) -> u64 {
239    seed.wrapping_add(salt.wrapping_mul(0x9E37_79B9_7F4A_7C15))
240        .wrapping_mul(6364136223846793005)
241        .wrapping_add(1442695040888963407)
242}
243
244fn unit_interval(seed: u64, salt: u64) -> f32 {
245    let value = lcg(seed, salt) >> 40;
246    value as f32 / ((1u64 << 24) - 1) as f32
247}
248
249impl<I: ItemType> Default for DropTable<I> {
250    fn default() -> Self {
251        Self::new()
252    }
253}
254
255// ─── MagnetConfig ─────────────────────────────────────────────────────────────
256
257/// Configuration for the magnetic item-attraction system.
258///
259/// This resource is inserted by [`DropsPlugin`] with [`Default`] values and
260/// can be overwritten after plugin registration to tune pickup feel.
261///
262/// # Examples
263///
264/// ```rust,no_run
265/// use bevy::prelude::*;
266/// use voxel_framework::items::MagnetConfig;
267///
268/// fn setup(mut config: ResMut<MagnetConfig>) {
269///     config.radius = 8.0;
270///     config.force  = 16.0;
271/// }
272/// ```
273#[derive(Resource, Debug, Clone)]
274pub struct MagnetConfig {
275    /// Distance (in world units) within which [`DroppedItem`] entities are
276    /// attracted toward the [`ItemCollector`].
277    ///
278    /// Items outside this radius are neither attracted nor collected.
279    /// Default: `4.0`.
280    pub radius: f32,
281    /// Acceleration magnitude applied toward the collector each second
282    /// (world units/sec²).
283    ///
284    /// Higher values make items snap to the player faster.  Default: `8.0`.
285    pub force: f32,
286}
287
288impl Default for MagnetConfig {
289    fn default() -> Self {
290        Self {
291            radius: 4.0,
292            force: 8.0,
293        }
294    }
295}
296
297// ─── Components ───────────────────────────────────────────────────────────────
298
299/// Component on a world entity representing an uncollected item drop.
300///
301/// `DroppedItem` entities are spawned by `spawn_drops_system` in response to
302/// [`crate::world::VoxelBroken`] messages and despawned by `magnet_system`
303/// when either collected or expired.
304///
305/// The entity has no [`Transform`] by default — `spawn_drops_system` creates
306/// the component without one.  Attaching a [`Transform`] enables spatial
307/// magnet logic; entities without one are skipped by the attraction phase but
308/// will still expire via `lifetime`.
309///
310/// # Lifecycle
311///
312/// 1. Spawned with `velocity` set to `(0, 2, 0)` (small upward bounce).
313/// 2. Attracted toward the [`ItemCollector`] once within [`MagnetConfig::radius`].
314/// 3. Collected (and despawned) when within 0.5 world units of the collector.
315/// 4. Despawned after `lifetime` seconds regardless of collection.
316#[derive(Component, Debug, Clone)]
317pub struct DroppedItem<I: ItemType> {
318    /// The item type carried by this drop entity.
319    pub item: I,
320    /// Number of items in this drop stack.  Always `>= 1`.
321    pub count: u32,
322    /// Current velocity in world space (units/sec).
323    ///
324    /// Updated by the magnet system each frame; game code can modify this to
325    /// apply custom physics (e.g. gravity or bounce).
326    pub velocity: Vec3,
327    /// Seconds remaining before the entity is automatically despawned.
328    ///
329    /// Decremented each frame.  Default: `60.0`.
330    pub lifetime: f32,
331}
332
333/// Tag component marking the entity that attracts and collects nearby [`DroppedItem`] entities.
334///
335/// Add this component to the player entity after spawning it.  Only one
336/// collector entity is supported; `magnet_system` uses
337/// [`bevy::ecs::query::QuerySingleError`] and silently skips collection if
338/// zero or more than one entity carries this tag.
339///
340/// # Examples
341///
342/// ```rust,no_run
343/// use bevy::prelude::*;
344/// use voxel_framework::items::ItemCollector;
345///
346/// fn spawn_player(mut commands: Commands) {
347///     commands.spawn((Transform::default(), ItemCollector));
348/// }
349/// ```
350#[derive(Component, Default)]
351pub struct ItemCollector;
352
353// ─── Systems ─────────────────────────────────────────────────────────────────
354
355/// Reads [`VoxelBroken`] messages and spawns [`DroppedItem`] entities using
356/// [`DropTable`].
357fn spawn_drops_system<I: ItemType>(
358    mut broken_reader: MessageReader<VoxelBroken>,
359    drop_table: Res<DropTable<I>>,
360    mut commands: Commands,
361) {
362    for event in broken_reader.read() {
363        // Use world position bits as a deterministic seed.
364        let seed = {
365            let x = event.world_pos.x.to_bits() as u64;
366            let y = event.world_pos.y.to_bits() as u64;
367            let z = event.world_pos.z.to_bits() as u64;
368            x.wrapping_mul(1000003)
369                .wrapping_add(y.wrapping_mul(1000033))
370                .wrapping_add(z)
371        };
372
373        for (item, count) in drop_table.get_drops(event.voxel_byte, seed) {
374            commands.spawn(DroppedItem {
375                item,
376                count,
377                velocity: Vec3::new(0.0, 2.0, 0.0),
378                lifetime: 60.0,
379            });
380        }
381    }
382}
383
384/// Applies magnet force toward [`ItemCollector`] and picks up items within
385/// pickup range, adding them to the [`ContainerComponent`] on the
386/// [`PrimaryContainer`] entity and emitting [`ItemPickedUp`].
387fn magnet_system<I: ItemType>(
388    time: Res<Time>,
389    config: Res<MagnetConfig>,
390    collector_query: Query<&Transform, With<ItemCollector>>,
391    mut item_query: Query<(Entity, &mut DroppedItem<I>, Option<&Transform>)>,
392    mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
393    mut pickup_writer: MessageWriter<ItemPickedUp<I>>,
394    mut commands: Commands,
395) {
396    let Ok(collector_transform) = collector_query.single() else {
397        return;
398    };
399    let collector_pos = collector_transform.translation;
400    let dt = time.delta_secs();
401
402    for (entity, mut dropped, transform_opt) in item_query.iter_mut() {
403        // Tick lifetime.
404        dropped.lifetime -= dt;
405        if dropped.lifetime <= 0.0 {
406            commands.entity(entity).despawn();
407            continue;
408        }
409
410        // If entity has no transform we can't do spatial logic — skip.
411        let Some(transform) = transform_opt else {
412            continue;
413        };
414
415        let item_pos = transform.translation;
416        let diff = collector_pos - item_pos;
417        let dist = diff.length();
418
419        if dist < 0.5 {
420            // Close enough — pick up via PrimaryContainer entity.
421            let Ok(mut container) = container_query.single_mut() else {
422                continue;
423            };
424            let added = dropped.count - container.0.add(dropped.item, dropped.count);
425            if added > 0 {
426                pickup_writer.write(ItemPickedUp {
427                    item: dropped.item,
428                    count: added,
429                });
430            }
431            commands.entity(entity).despawn();
432        } else if dist < config.radius {
433            // Apply attraction force.
434            let dir = diff / dist;
435            dropped.velocity += dir * config.force * dt;
436        }
437    }
438}
439
440// ─── DropsPlugin ─────────────────────────────────────────────────────────────
441
442/// Plugin that wires up the full item-drop pipeline for item type `I`.
443///
444/// Registering this plugin inserts the following resources (with defaults) and
445/// systems into the Bevy [`App`]:
446///
447/// | Resource | Purpose |
448/// |---|---|
449/// | [`DropTable<I>`] | Empty table; populate it in a `Startup` system |
450/// | [`MagnetConfig`] | Tunable attraction radius and force |
451/// | [`crate::items::inventory::Inventory<I>`] | Player's item storage |
452///
453/// It also registers the [`crate::items::inventory::ItemPickedUp<I>`] message
454/// type and adds `spawn_drops_system` and `magnet_system` to the `Update`
455/// schedule.
456///
457/// **This plugin is NOT included in [`crate::VoxelPlugin`]** — because it is
458/// generic over `I: `[`ItemType`], it must be added separately by game code.
459/// Add it alongside [`crate::generator::GeneratorPlugin`]:
460///
461/// ```rust,no_run
462/// use bevy::prelude::*;
463/// use voxel_framework::items::{DefaultItem, DropsPlugin};
464///
465/// App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
466/// ```
467pub struct DropsPlugin<I: ItemType> {
468    _marker: PhantomData<I>,
469}
470
471impl<I: ItemType> DropsPlugin<I> {
472    /// Creates a new `DropsPlugin`.
473    pub fn new() -> Self {
474        Self {
475            _marker: PhantomData,
476        }
477    }
478}
479
480impl<I: ItemType> Default for DropsPlugin<I> {
481    fn default() -> Self {
482        Self::new()
483    }
484}
485
486impl<I: ItemType> Plugin for DropsPlugin<I> {
487    fn build(&self, app: &mut App) {
488        app.init_resource::<DropTable<I>>();
489        app.init_resource::<MagnetConfig>();
490        app.add_message::<ItemPickedUp<I>>();
491        app.add_systems(Update, spawn_drops_system::<I>);
492        app.add_systems(Update, magnet_system::<I>);
493    }
494}
495
496// ─── Tests ───────────────────────────────────────────────────────────────────
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use crate::items::DefaultItem;
502
503    #[test]
504    fn test_drop_table_get_drop() {
505        let mut table = DropTable::<DefaultItem>::new();
506        table.register(1, DefaultItem::RockFragment, 1, 3);
507
508        // With seed 0: deterministic count should be in [1, 3].
509        let result = table.get_drop(1, 0);
510        assert!(result.is_some());
511        let (item, count) = result.unwrap();
512        assert_eq!(item, DefaultItem::RockFragment);
513        assert!((1..=3).contains(&count));
514    }
515
516    #[test]
517    fn test_drop_table_no_entry_returns_none() {
518        let table = DropTable::<DefaultItem>::new();
519        assert!(table.get_drop(99, 42).is_none());
520    }
521
522    #[test]
523    fn test_drop_table_fixed_count() {
524        let mut table = DropTable::<DefaultItem>::new();
525        table.register(2, DefaultItem::IronOre, 5, 5);
526        let (_, count) = table.get_drop(2, 12345).unwrap();
527        assert_eq!(count, 5);
528    }
529
530    #[test]
531    fn test_drop_table_identity_fallback_with_other_entries() {
532        let mut table = DropTable::<DefaultItem>::new();
533        table.register(2, DefaultItem::Dirt, 1, 1);
534        let (item, count) = table.get_drop(11, 0).unwrap();
535        assert_eq!(item, DefaultItem::IronOre);
536        assert_eq!(count, 1);
537    }
538
539    #[test]
540    fn drop_table_supports_multiple_runtime_entries() {
541        let mut table = DropTable::<DefaultItem>::new();
542        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
543        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 2, 2));
544
545        let drops = table.get_drops(3, 123);
546        assert_eq!(drops.len(), 2);
547        assert_eq!(drops[0], (DefaultItem::Cobblestone, 1));
548        assert_eq!(drops[1], (DefaultItem::Coal, 2));
549    }
550
551    #[test]
552    fn register_preserves_single_entry_replacement_behavior() {
553        let mut table = DropTable::<DefaultItem>::new();
554        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
555        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 1, 1));
556
557        table.register(3, DefaultItem::IronOre, 1, 1);
558
559        let drops = table.get_drops(3, 0);
560        assert_eq!(drops, vec![(DefaultItem::IronOre, 1)]);
561    }
562
563    #[test]
564    fn drop_table_entry_chance_can_disable_a_drop() {
565        let mut table = DropTable::<DefaultItem>::new();
566        table.add_entry(
567            3,
568            DropTableEntry::with_chance(DefaultItem::Cobblestone, 1, 1, 0.0),
569        );
570        table.add_entry(3, DropTableEntry::with_chance(DefaultItem::Coal, 1, 1, 1.0));
571
572        let drops = table.get_drops(3, 0);
573        assert_eq!(drops, vec![(DefaultItem::Coal, 1)]);
574    }
575
576    #[test]
577    fn iter_drop_entries_includes_chance_metadata() {
578        let mut table = DropTable::<DefaultItem>::new();
579        table.register_with_chance(3, DefaultItem::Cobblestone, 1, 2, 0.25);
580
581        let entries: Vec<_> = table.iter_drop_entries().collect();
582        assert_eq!(entries.len(), 1);
583        assert_eq!(entries[0].0, 3);
584        assert_eq!(entries[0].1.item, DefaultItem::Cobblestone);
585        assert_eq!(entries[0].1.min_count, 1);
586        assert_eq!(entries[0].1.max_count, 2);
587        assert_eq!(entries[0].1.chance, 0.25);
588    }
589}