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/// Mapping from voxel byte IDs to item drop definitions.
44///
45/// Each entry associates a voxel byte value (the `u8` returned by
46/// [`crate::voxel::VoxelType::to_byte`]) with an item type and a drop-count
47/// range `[min, max]`. When a matching voxel is broken, `spawn_drops_system`
48/// queries this table and selects a count within the range using a
49/// deterministic LCG seeded from the voxel's world position. If `min == max`
50/// the count is always fixed.
51///
52/// [`DropTable`] is initialized empty; register entries before the first
53/// [`crate::world::VoxelBroken`] message is processed. It is available as a
54/// Bevy [`Resource`] after [`DropsPlugin`] is added.
55///
56/// # Examples
57///
58/// ```rust,no_run
59/// use voxel_framework::items::{DropTable, DefaultItem};
60///
61/// let mut table = DropTable::<DefaultItem>::new();
62/// // Voxel byte 1 drops 1–3 rock fragments.
63/// table.register(1, DefaultItem::RockFragment, 1, 3);
64/// // Voxel byte 2 always drops exactly 1 iron ore.
65/// table.register(2, DefaultItem::IronOre, 1, 1);
66/// ```
67#[derive(Resource, Debug, Clone)]
68pub struct DropTable<I: ItemType> {
69 /// Internal map: `voxel_byte` → `(item, count_min, count_max)`.
70 entries: HashMap<u8, (I, u32, u32)>,
71}
72
73impl<I: ItemType> DropTable<I> {
74 /// Creates an empty drop table.
75 pub fn new() -> Self {
76 Self {
77 entries: HashMap::new(),
78 }
79 }
80
81 /// Registers a drop for the given voxel byte.
82 ///
83 /// When a voxel with `voxel_byte` is broken, between `min` and `max` items
84 /// (inclusive) of `item` will be dropped. If `min == max` the count is
85 /// always fixed.
86 pub fn register(&mut self, voxel_byte: u8, item: I, min: u32, max: u32) {
87 self.entries.insert(voxel_byte, (item, min, max));
88 }
89
90 /// Iterates over all explicitly registered drop entries.
91 ///
92 /// Yields `(voxel_byte, item, min_count, max_count)` for each registration.
93 /// Identity-fallback entries (not explicitly registered) are not included.
94 pub fn iter_entries(&self) -> impl Iterator<Item = (u8, I, u32, u32)> + '_ {
95 self.entries
96 .iter()
97 .map(|(&voxel_byte, &(item, min, max))| (voxel_byte, item, min, max))
98 }
99
100 /// Returns the drop for `voxel_byte`, using `seed` for deterministic count
101 /// selection within `[min, max]`.
102 ///
103 /// Explicit registrations always win. If no entry is registered for
104 /// `voxel_byte`, falls back to the identity mapping: `I::from_byte(voxel_byte)`
105 /// with count 1. If the resulting item is the empty sentinel (i.e.
106 /// `item.to_byte() == 0`), returns `None` — meaning no drop.
107 pub fn get_drop(&self, voxel_byte: u8, seed: u64) -> Option<(I, u32)> {
108 if let Some(&(item, min, max)) = self.entries.get(&voxel_byte) {
109 let count = if min == max {
110 min
111 } else {
112 let range = (max - min + 1) as u64;
113 min + (seed
114 .wrapping_mul(6364136223846793005)
115 .wrapping_add(1442695040888963407)
116 % range) as u32
117 };
118 return Some((item, count));
119 }
120
121 // Identity fallback: try mapping the voxel byte directly to an item.
122 let item = I::from_byte(voxel_byte);
123 if item.to_byte() != 0 {
124 Some((item, 1))
125 } else {
126 None
127 }
128 }
129}
130
131impl<I: ItemType> Default for DropTable<I> {
132 fn default() -> Self {
133 Self::new()
134 }
135}
136
137// ─── MagnetConfig ─────────────────────────────────────────────────────────────
138
139/// Configuration for the magnetic item-attraction system.
140///
141/// This resource is inserted by [`DropsPlugin`] with [`Default`] values and
142/// can be overwritten after plugin registration to tune pickup feel.
143///
144/// # Examples
145///
146/// ```rust,no_run
147/// use bevy::prelude::*;
148/// use voxel_framework::items::MagnetConfig;
149///
150/// fn setup(mut config: ResMut<MagnetConfig>) {
151/// config.radius = 8.0;
152/// config.force = 16.0;
153/// }
154/// ```
155#[derive(Resource, Debug, Clone)]
156pub struct MagnetConfig {
157 /// Distance (in world units) within which [`DroppedItem`] entities are
158 /// attracted toward the [`ItemCollector`].
159 ///
160 /// Items outside this radius are neither attracted nor collected.
161 /// Default: `4.0`.
162 pub radius: f32,
163 /// Acceleration magnitude applied toward the collector each second
164 /// (world units/sec²).
165 ///
166 /// Higher values make items snap to the player faster. Default: `8.0`.
167 pub force: f32,
168}
169
170impl Default for MagnetConfig {
171 fn default() -> Self {
172 Self {
173 radius: 4.0,
174 force: 8.0,
175 }
176 }
177}
178
179// ─── Components ───────────────────────────────────────────────────────────────
180
181/// Component on a world entity representing an uncollected item drop.
182///
183/// `DroppedItem` entities are spawned by `spawn_drops_system` in response to
184/// [`crate::world::VoxelBroken`] messages and despawned by `magnet_system`
185/// when either collected or expired.
186///
187/// The entity has no [`Transform`] by default — `spawn_drops_system` creates
188/// the component without one. Attaching a [`Transform`] enables spatial
189/// magnet logic; entities without one are skipped by the attraction phase but
190/// will still expire via `lifetime`.
191///
192/// # Lifecycle
193///
194/// 1. Spawned with `velocity` set to `(0, 2, 0)` (small upward bounce).
195/// 2. Attracted toward the [`ItemCollector`] once within [`MagnetConfig::radius`].
196/// 3. Collected (and despawned) when within 0.5 world units of the collector.
197/// 4. Despawned after `lifetime` seconds regardless of collection.
198#[derive(Component, Debug, Clone)]
199pub struct DroppedItem<I: ItemType> {
200 /// The item type carried by this drop entity.
201 pub item: I,
202 /// Number of items in this drop stack. Always `>= 1`.
203 pub count: u32,
204 /// Current velocity in world space (units/sec).
205 ///
206 /// Updated by the magnet system each frame; game code can modify this to
207 /// apply custom physics (e.g. gravity or bounce).
208 pub velocity: Vec3,
209 /// Seconds remaining before the entity is automatically despawned.
210 ///
211 /// Decremented each frame. Default: `60.0`.
212 pub lifetime: f32,
213}
214
215/// Tag component marking the entity that attracts and collects nearby [`DroppedItem`] entities.
216///
217/// Add this component to the player entity after spawning it. Only one
218/// collector entity is supported; `magnet_system` uses
219/// [`bevy::ecs::query::QuerySingleError`] and silently skips collection if
220/// zero or more than one entity carries this tag.
221///
222/// # Examples
223///
224/// ```rust,no_run
225/// use bevy::prelude::*;
226/// use voxel_framework::items::ItemCollector;
227///
228/// fn spawn_player(mut commands: Commands) {
229/// commands.spawn((Transform::default(), ItemCollector));
230/// }
231/// ```
232#[derive(Component, Default)]
233pub struct ItemCollector;
234
235// ─── Systems ─────────────────────────────────────────────────────────────────
236
237/// Reads [`VoxelBroken`] messages and spawns [`DroppedItem`] entities using
238/// [`DropTable`].
239fn spawn_drops_system<I: ItemType>(
240 mut broken_reader: MessageReader<VoxelBroken>,
241 drop_table: Res<DropTable<I>>,
242 mut commands: Commands,
243) {
244 for event in broken_reader.read() {
245 // Use world position bits as a deterministic seed.
246 let seed = {
247 let x = event.world_pos.x.to_bits() as u64;
248 let y = event.world_pos.y.to_bits() as u64;
249 let z = event.world_pos.z.to_bits() as u64;
250 x.wrapping_mul(1000003)
251 .wrapping_add(y.wrapping_mul(1000033))
252 .wrapping_add(z)
253 };
254
255 // Derive voxel byte from chunk + local coords for the lookup.
256 // The VoxelBroken event doesn't carry the byte directly, so we
257 // derive a pseudo-byte from the local coord to index the drop table.
258 // In real game code users should extend VoxelBroken or pass voxel_byte
259 // separately; here we look up all registered entries and use the seed.
260 let voxel_byte = derive_voxel_byte(event);
261 if let Some((item, count)) = drop_table.get_drop(voxel_byte, seed) {
262 commands.spawn(DroppedItem {
263 item,
264 count,
265 velocity: Vec3::new(0.0, 2.0, 0.0),
266 lifetime: 60.0,
267 });
268 }
269 }
270}
271
272/// Derives a voxel byte from a [`VoxelBroken`] event.
273///
274/// `VoxelBroken` does not store the original voxel byte. This helper encodes
275/// the local voxel coordinate into a stable byte so the drop table can be
276/// indexed. Game code that needs exact voxel-type drops should store the byte
277/// in `VoxelBroken` or pass it separately.
278fn derive_voxel_byte(event: &VoxelBroken) -> u8 {
279 let (x, y, z) = event.local;
280 // Simple hash of local coordinates, stable per voxel position.
281 ((x as u32)
282 .wrapping_mul(73856093)
283 .wrapping_add((y as u32).wrapping_mul(19349663))
284 .wrapping_add((z as u32).wrapping_mul(83492791))
285 & 0xFF) as u8
286}
287
288/// Applies magnet force toward [`ItemCollector`] and picks up items within
289/// pickup range, adding them to the [`ContainerComponent`] on the
290/// [`PrimaryContainer`] entity and emitting [`ItemPickedUp`].
291fn magnet_system<I: ItemType>(
292 time: Res<Time>,
293 config: Res<MagnetConfig>,
294 collector_query: Query<&Transform, With<ItemCollector>>,
295 mut item_query: Query<(Entity, &mut DroppedItem<I>, Option<&Transform>)>,
296 mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
297 mut pickup_writer: MessageWriter<ItemPickedUp<I>>,
298 mut commands: Commands,
299) {
300 let Ok(collector_transform) = collector_query.single() else {
301 return;
302 };
303 let collector_pos = collector_transform.translation;
304 let dt = time.delta_secs();
305
306 for (entity, mut dropped, transform_opt) in item_query.iter_mut() {
307 // Tick lifetime.
308 dropped.lifetime -= dt;
309 if dropped.lifetime <= 0.0 {
310 commands.entity(entity).despawn();
311 continue;
312 }
313
314 // If entity has no transform we can't do spatial logic — skip.
315 let Some(transform) = transform_opt else {
316 continue;
317 };
318
319 let item_pos = transform.translation;
320 let diff = collector_pos - item_pos;
321 let dist = diff.length();
322
323 if dist < 0.5 {
324 // Close enough — pick up via PrimaryContainer entity.
325 let Ok(mut container) = container_query.single_mut() else {
326 continue;
327 };
328 let added = dropped.count - container.0.add(dropped.item, dropped.count);
329 if added > 0 {
330 pickup_writer.write(ItemPickedUp {
331 item: dropped.item,
332 count: added,
333 });
334 }
335 commands.entity(entity).despawn();
336 } else if dist < config.radius {
337 // Apply attraction force.
338 let dir = diff / dist;
339 dropped.velocity += dir * config.force * dt;
340 }
341 }
342}
343
344// ─── DropsPlugin ─────────────────────────────────────────────────────────────
345
346/// Plugin that wires up the full item-drop pipeline for item type `I`.
347///
348/// Registering this plugin inserts the following resources (with defaults) and
349/// systems into the Bevy [`App`]:
350///
351/// | Resource | Purpose |
352/// |---|---|
353/// | [`DropTable<I>`] | Empty table; populate it in a `Startup` system |
354/// | [`MagnetConfig`] | Tunable attraction radius and force |
355/// | [`crate::items::inventory::Inventory<I>`] | Player's item storage |
356///
357/// It also registers the [`crate::items::inventory::ItemPickedUp<I>`] message
358/// type and adds `spawn_drops_system` and `magnet_system` to the `Update`
359/// schedule.
360///
361/// **This plugin is NOT included in [`crate::VoxelPlugin`]** — because it is
362/// generic over `I: `[`ItemType`], it must be added separately by game code.
363/// Add it alongside [`crate::generator::GeneratorPlugin`]:
364///
365/// ```rust,no_run
366/// use bevy::prelude::*;
367/// use voxel_framework::items::{DefaultItem, DropsPlugin};
368///
369/// App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
370/// ```
371pub struct DropsPlugin<I: ItemType> {
372 _marker: PhantomData<I>,
373}
374
375impl<I: ItemType> DropsPlugin<I> {
376 /// Creates a new `DropsPlugin`.
377 pub fn new() -> Self {
378 Self {
379 _marker: PhantomData,
380 }
381 }
382}
383
384impl<I: ItemType> Default for DropsPlugin<I> {
385 fn default() -> Self {
386 Self::new()
387 }
388}
389
390impl<I: ItemType> Plugin for DropsPlugin<I> {
391 fn build(&self, app: &mut App) {
392 app.init_resource::<DropTable<I>>();
393 app.init_resource::<MagnetConfig>();
394 app.add_message::<ItemPickedUp<I>>();
395 app.add_systems(Update, spawn_drops_system::<I>);
396 app.add_systems(Update, magnet_system::<I>);
397 }
398}
399
400// ─── Tests ───────────────────────────────────────────────────────────────────
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use crate::items::DefaultItem;
406
407 #[test]
408 fn test_drop_table_get_drop() {
409 let mut table = DropTable::<DefaultItem>::new();
410 table.register(1, DefaultItem::RockFragment, 1, 3);
411
412 // With seed 0: deterministic count should be in [1, 3].
413 let result = table.get_drop(1, 0);
414 assert!(result.is_some());
415 let (item, count) = result.unwrap();
416 assert_eq!(item, DefaultItem::RockFragment);
417 assert!((1..=3).contains(&count));
418 }
419
420 #[test]
421 fn test_drop_table_no_entry_returns_none() {
422 let table = DropTable::<DefaultItem>::new();
423 assert!(table.get_drop(99, 42).is_none());
424 }
425
426 #[test]
427 fn test_drop_table_fixed_count() {
428 let mut table = DropTable::<DefaultItem>::new();
429 table.register(2, DefaultItem::IronOre, 5, 5);
430 let (_, count) = table.get_drop(2, 12345).unwrap();
431 assert_eq!(count, 5);
432 }
433
434 #[test]
435 fn test_drop_table_identity_fallback_with_other_entries() {
436 let mut table = DropTable::<DefaultItem>::new();
437 table.register(2, DefaultItem::Dirt, 1, 1);
438 let (item, count) = table.get_drop(11, 0).unwrap();
439 assert_eq!(item, DefaultItem::IronOre);
440 assert_eq!(count, 1);
441 }
442}