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`] only for accepted items, and
15//!    retains the unaccepted remainder. It despawns the entity only when empty.
16//!    A full inventory leaves the drop available and emits no pickup message.
17//! 4. **Expire** — items that are never collected despawn automatically after
18//!    their [`DroppedItem::lifetime`] reaches zero (default 60 seconds).
19//!
20//! # Plugin registration
21//!
22//! [`DropsPlugin`] is intentionally **not** bundled inside
23//! [`crate::VoxelPlugin`] because it is generic over `I: `[`ItemType`].
24//! Add it explicitly in game code, alongside
25//! [`crate::generator::GeneratorPlugin`]:
26//!
27//! ```rust,no_run
28//! use bevy::prelude::*;
29//! use voxel_framework::items::{DefaultItem, DropsPlugin};
30//!
31//! App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
32//! ```
33
34use std::collections::HashMap;
35use std::marker::PhantomData;
36
37use bevy::prelude::*;
38
39use crate::world::VoxelBroken;
40
41use super::inventory::{ContainerComponent, ItemPickedUp, ItemType, PrimaryContainer};
42
43// ─── DropTable ────────────────────────────────────────────────────────────────
44
45/// One runtime drop entry for a voxel byte.
46///
47/// This is the runtime counterpart of
48/// [`crate::content::BlockDropDefinition`]. It is intentionally keyed by voxel
49/// byte because [`DropsPlugin`] reacts to [`crate::world::VoxelBroken`] events,
50/// and those events carry the destroyed voxel byte.
51#[derive(Debug, Clone, Copy, PartialEq)]
52pub struct DropTableEntry<I: ItemType> {
53    /// Item produced by this entry.
54    pub item: I,
55    /// Minimum count, inclusive.
56    pub min_count: u32,
57    /// Maximum count, inclusive.
58    pub max_count: u32,
59    /// Probability in `0.0..=1.0`.
60    pub chance: f32,
61}
62
63impl<I: ItemType> DropTableEntry<I> {
64    /// Creates a guaranteed drop entry.
65    pub fn new(item: I, min_count: u32, max_count: u32) -> Self {
66        Self::with_chance(item, min_count, max_count, 1.0)
67    }
68
69    /// Creates a drop entry with an explicit probability.
70    pub fn with_chance(item: I, min_count: u32, max_count: u32, chance: f32) -> Self {
71        Self {
72            item,
73            min_count: min_count.min(max_count),
74            max_count: min_count.max(max_count),
75            chance: chance.clamp(0.0, 1.0),
76        }
77    }
78}
79
80/// Mapping from voxel byte IDs to item drop definitions.
81///
82/// Each entry associates a voxel byte value (the `u8` returned by
83/// [`crate::voxel::VoxelType::to_byte`]) with an item type and a drop-count
84/// range `[min, max]`. Runtime entries may also carry a chance, and a voxel may
85/// have multiple entries. When a matching voxel is broken,
86/// `spawn_drops_system` queries this table and selects counts/chance outcomes
87/// using deterministic pseudo-random values seeded from the voxel's world
88/// position. If `min == max` the count is always fixed.
89///
90/// [`DropTable`] is initialized empty; register entries before the first
91/// [`crate::world::VoxelBroken`] message is processed.  It is available as a
92/// Bevy [`Resource`] after [`DropsPlugin`] is added.
93///
94/// # Examples
95///
96/// ```rust,no_run
97/// use voxel_framework::items::{DropTable, DefaultItem};
98///
99/// let mut table = DropTable::<DefaultItem>::new();
100/// // Voxel byte 1 drops 1–3 rock fragments.
101/// table.register(1, DefaultItem::RockFragment, 1, 3);
102/// // Voxel byte 2 always drops exactly 1 iron ore.
103/// table.register(2, DefaultItem::IronOre, 1, 1);
104/// // Voxel byte 3 can produce multiple runtime entries.
105/// table.add_entry(3, voxel_framework::items::DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
106/// table.add_entry(3, voxel_framework::items::DropTableEntry::with_chance(DefaultItem::Coal, 1, 2, 0.25));
107/// ```
108#[derive(Resource, Debug, Clone)]
109pub struct DropTable<I: ItemType> {
110    /// Internal map: `voxel_byte` → runtime drop entries.
111    entries: HashMap<u8, Vec<DropTableEntry<I>>>,
112}
113
114impl<I: ItemType> DropTable<I> {
115    /// Creates an empty drop table.
116    pub fn new() -> Self {
117        Self {
118            entries: HashMap::new(),
119        }
120    }
121
122    /// Registers a drop for the given voxel byte.
123    ///
124    /// When a voxel with `voxel_byte` is broken, between `min` and `max` items
125    /// (inclusive) of `item` will be dropped. If `min == max` the count is
126    /// always fixed.
127    ///
128    /// This replaces any previous runtime entries for the voxel byte, preserving
129    /// the historical one-entry behavior of [`DropTable::register`]. Use
130    /// [`DropTable::add_entry`] when a voxel should produce multiple drops.
131    pub fn register(&mut self, voxel_byte: u8, item: I, min: u32, max: u32) {
132        self.replace_entries(voxel_byte, [DropTableEntry::new(item, min, max)]);
133    }
134
135    /// Registers a single probabilistic drop for the given voxel byte.
136    ///
137    /// Like [`DropTable::register`], this replaces any previous entries for the
138    /// voxel byte.
139    pub fn register_with_chance(
140        &mut self,
141        voxel_byte: u8,
142        item: I,
143        min: u32,
144        max: u32,
145        chance: f32,
146    ) {
147        self.replace_entries(
148            voxel_byte,
149            [DropTableEntry::with_chance(item, min, max, chance)],
150        );
151    }
152
153    /// Appends one runtime entry without removing existing entries for the same
154    /// voxel byte.
155    pub fn add_entry(&mut self, voxel_byte: u8, entry: DropTableEntry<I>) {
156        self.entries.entry(voxel_byte).or_default().push(entry);
157    }
158
159    /// Replaces all runtime entries for one voxel byte.
160    pub fn replace_entries(
161        &mut self,
162        voxel_byte: u8,
163        entries: impl IntoIterator<Item = DropTableEntry<I>>,
164    ) {
165        self.entries
166            .insert(voxel_byte, entries.into_iter().collect());
167    }
168
169    /// Iterates over all explicitly registered drop entries.
170    ///
171    /// Yields `(voxel_byte, item, min_count, max_count)` for each registration.
172    /// Identity-fallback entries (not explicitly registered) are not included.
173    pub fn iter_entries(&self) -> impl Iterator<Item = (u8, I, u32, u32)> + '_ {
174        self.iter_drop_entries()
175            .map(|(voxel_byte, entry)| (voxel_byte, entry.item, entry.min_count, entry.max_count))
176    }
177
178    /// Iterates over all explicitly registered runtime drop entries, including
179    /// chance metadata.
180    pub fn iter_drop_entries(&self) -> impl Iterator<Item = (u8, &DropTableEntry<I>)> + '_ {
181        self.entries
182            .iter()
183            .flat_map(|(&voxel_byte, entries)| entries.iter().map(move |entry| (voxel_byte, entry)))
184    }
185
186    /// Returns the drop for `voxel_byte`, using `seed` for deterministic count
187    /// selection within `[min, max]`.
188    ///
189    /// Explicit registrations always win. If no entry is registered for
190    /// `voxel_byte`, falls back to the identity mapping: `I::from_byte(voxel_byte)`
191    /// with count 1. If the resulting item is the empty sentinel (i.e.
192    /// `item.to_byte() == 0`), returns `None` — meaning no drop.
193    pub fn get_drop(&self, voxel_byte: u8, seed: u64) -> Option<(I, u32)> {
194        self.get_drops(voxel_byte, seed).into_iter().next()
195    }
196
197    /// Returns all drops produced for `voxel_byte` with deterministic chance
198    /// rolls and count selection.
199    pub fn get_drops(&self, voxel_byte: u8, seed: u64) -> Vec<(I, u32)> {
200        if let Some(entries) = self.entries.get(&voxel_byte) {
201            return entries
202                .iter()
203                .enumerate()
204                .filter_map(|(index, entry)| entry.roll(seed, index as u64))
205                .collect();
206        }
207
208        // Identity fallback: try mapping the voxel byte directly to an item.
209        let item = I::from_byte(voxel_byte);
210        if !item.is_empty() {
211            vec![(item, 1)]
212        } else {
213            Vec::new()
214        }
215    }
216}
217
218impl<I: ItemType> DropTableEntry<I> {
219    fn roll(&self, seed: u64, salt: u64) -> Option<(I, u32)> {
220        if self.item.is_empty() || self.max_count == 0 || self.chance <= 0.0 {
221            return None;
222        }
223
224        let chance_roll = unit_interval(seed, salt);
225        if chance_roll > self.chance {
226            return None;
227        }
228
229        let count = if self.min_count == self.max_count {
230            self.min_count
231        } else {
232            let range = (self.max_count - self.min_count + 1) as u64;
233            self.min_count + (lcg(seed, salt.wrapping_add(1)) % range) as u32
234        };
235
236        (count > 0).then_some((self.item, count))
237    }
238}
239
240fn lcg(seed: u64, salt: u64) -> u64 {
241    seed.wrapping_add(salt.wrapping_mul(0x9E37_79B9_7F4A_7C15))
242        .wrapping_mul(6364136223846793005)
243        .wrapping_add(1442695040888963407)
244}
245
246fn unit_interval(seed: u64, salt: u64) -> f32 {
247    let value = lcg(seed, salt) >> 40;
248    value as f32 / ((1u64 << 24) - 1) as f32
249}
250
251impl<I: ItemType> Default for DropTable<I> {
252    fn default() -> Self {
253        Self::new()
254    }
255}
256
257// ─── MagnetConfig ─────────────────────────────────────────────────────────────
258
259/// Configuration for the magnetic item-attraction system.
260///
261/// This resource is inserted by [`DropsPlugin`] with [`Default`] values and
262/// can be overwritten after plugin registration to tune pickup feel.
263///
264/// # Examples
265///
266/// ```rust,no_run
267/// use bevy::prelude::*;
268/// use voxel_framework::items::MagnetConfig;
269///
270/// fn setup(mut config: ResMut<MagnetConfig>) {
271///     config.radius = 8.0;
272///     config.force  = 16.0;
273/// }
274/// ```
275#[derive(Resource, Debug, Clone)]
276pub struct MagnetConfig {
277    /// Distance (in world units) within which [`DroppedItem`] entities are
278    /// attracted toward the [`ItemCollector`].
279    ///
280    /// Items outside this radius are neither attracted nor collected.
281    /// Default: `4.0`.
282    pub radius: f32,
283    /// Acceleration magnitude applied toward the collector each second
284    /// (world units/sec²).
285    ///
286    /// Higher values make items snap to the player faster.  Default: `8.0`.
287    pub force: f32,
288}
289
290impl Default for MagnetConfig {
291    fn default() -> Self {
292        Self {
293            radius: 4.0,
294            force: 8.0,
295        }
296    }
297}
298
299// ─── Components ───────────────────────────────────────────────────────────────
300
301/// Component on a world entity representing an uncollected item drop.
302///
303/// `DroppedItem` entities are spawned by `spawn_drops_system` in response to
304/// [`crate::world::VoxelBroken`] messages and despawned by `magnet_system`
305/// when either collected or expired.
306///
307/// The plugin spawns each drop with a [`Transform`] at the broken voxel's
308/// world-space center, ready for spatial magnet logic. Manually spawned drops
309/// must also provide a [`Transform`] to participate in spatial attraction.
310///
311/// # Lifecycle
312///
313/// 1. Spawned with `velocity` set to `(0, 2, 0)` (small upward bounce).
314/// 2. Attracted toward the [`ItemCollector`] once within [`MagnetConfig::radius`].
315/// 3. Collected when within 0.5 world units of the collector. A full inventory
316///    that accepts no items leaves the drop available until pickup or expiry.
317///    Partial pickups leave the unaccepted remainder in the world.
318/// 4. Despawned after `lifetime` seconds regardless of collection.
319#[derive(Component, Debug, Clone)]
320pub struct DroppedItem<I: ItemType> {
321    /// The item type carried by this drop entity.
322    pub item: I,
323    /// Number of items in this drop stack.  Always `>= 1`.
324    pub count: u32,
325    /// Current velocity in world space (units/sec).
326    ///
327    /// The magnet system accelerates drops inside the attraction radius and
328    /// advances their position by velocity times elapsed time while a collector
329    /// is available. Outside the radius, existing velocity is preserved.
330    /// Game code can modify velocity for custom gravity or bounce; it should
331    /// not integrate the same movement a second time.
332    pub velocity: Vec3,
333    /// Seconds remaining before the entity is automatically despawned.
334    ///
335    /// Decremented each frame.  Default: `60.0`.
336    pub lifetime: f32,
337}
338
339/// Tag component marking the entity that attracts and collects nearby [`DroppedItem`] entities.
340///
341/// Add this component to the player entity after spawning it.  Only one
342/// collector entity is supported; `magnet_system` uses
343/// [`bevy::ecs::query::QuerySingleError`] and silently skips collection if
344/// zero or more than one entity carries this tag.
345///
346/// # Examples
347///
348/// ```rust,no_run
349/// use bevy::prelude::*;
350/// use voxel_framework::items::ItemCollector;
351///
352/// fn spawn_player(mut commands: Commands) {
353///     commands.spawn((Transform::default(), ItemCollector));
354/// }
355/// ```
356#[derive(Component, Default)]
357pub struct ItemCollector;
358
359// ─── Systems ─────────────────────────────────────────────────────────────────
360
361/// Reads [`VoxelBroken`] messages and spawns [`DroppedItem`] entities using
362/// [`DropTable`].
363fn spawn_drops_system<I: ItemType>(
364    mut broken_reader: MessageReader<VoxelBroken>,
365    drop_table: Res<DropTable<I>>,
366    mut commands: Commands,
367) {
368    for event in broken_reader.read() {
369        // Use world position bits as a deterministic seed.
370        let seed = {
371            let x = event.world_pos.x.to_bits() as u64;
372            let y = event.world_pos.y.to_bits() as u64;
373            let z = event.world_pos.z.to_bits() as u64;
374            x.wrapping_mul(1000003)
375                .wrapping_add(y.wrapping_mul(1000033))
376                .wrapping_add(z)
377        };
378
379        for (item, count) in drop_table.get_drops(event.voxel_byte, seed) {
380            commands.spawn((
381                DroppedItem {
382                    item,
383                    count,
384                    velocity: Vec3::new(0.0, 2.0, 0.0),
385                    lifetime: 60.0,
386                },
387                Transform::from_translation(event.world_pos),
388            ));
389        }
390    }
391}
392
393/// Applies magnet force toward [`ItemCollector`] and picks up items within
394/// pickup range, adding them to the [`ContainerComponent`] on the
395/// [`PrimaryContainer`] entity and emitting [`ItemPickedUp`].
396fn magnet_system<I: ItemType>(
397    time: Res<Time>,
398    config: Res<MagnetConfig>,
399    collector_query: Query<&Transform, (With<ItemCollector>, Without<DroppedItem<I>>)>,
400    mut item_query: Query<(Entity, &mut DroppedItem<I>, Option<&mut Transform>)>,
401    mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
402    mut pickup_writer: MessageWriter<ItemPickedUp<I>>,
403    mut commands: Commands,
404) {
405    let collector_pos = collector_query
406        .single()
407        .ok()
408        .map(|transform| transform.translation);
409    let dt = time.delta_secs();
410
411    for (entity, mut dropped, transform_opt) in item_query.iter_mut() {
412        // Tick lifetime.
413        dropped.lifetime -= dt;
414        if dropped.lifetime <= 0.0 {
415            commands.entity(entity).despawn();
416            continue;
417        }
418
419        // Expiration is independent of the single-collector spatial contract.
420        let Some(collector_pos) = collector_pos else {
421            continue;
422        };
423
424        // If entity has no transform we can't do spatial logic — skip.
425        let Some(mut transform) = transform_opt else {
426            continue;
427        };
428
429        let item_pos = transform.translation;
430        let diff = collector_pos - item_pos;
431        let dist = diff.length();
432
433        if dist < 0.5 {
434            // Close enough — pick up via PrimaryContainer entity.
435            let Ok(mut container) = container_query.single_mut() else {
436                continue;
437            };
438            let added = dropped.count - container.0.add(dropped.item, dropped.count);
439            if added == 0 {
440                continue;
441            }
442            dropped.count -= added;
443            pickup_writer.write(ItemPickedUp {
444                item: dropped.item,
445                count: added,
446            });
447            if dropped.count == 0 {
448                commands.entity(entity).despawn();
449            }
450            continue;
451        } else if dist < config.radius {
452            // Apply attraction force.
453            let dir = diff / dist;
454            dropped.velocity += dir * config.force * dt;
455        }
456        transform.translation += dropped.velocity * dt;
457    }
458}
459
460// ─── DropsPlugin ─────────────────────────────────────────────────────────────
461
462/// Plugin that wires up the full item-drop pipeline for item type `I`.
463///
464/// Registering this plugin inserts the following resources (with defaults) and
465/// systems into the Bevy [`App`]:
466///
467/// | Resource | Purpose |
468/// |---|---|
469/// | [`DropTable<I>`] | Empty table; populate it in a `Startup` system |
470/// | [`MagnetConfig`] | Tunable attraction radius and force |
471/// | [`crate::items::inventory::Inventory<I>`] | Player's item storage |
472///
473/// It also registers the [`crate::items::inventory::ItemPickedUp<I>`] message
474/// type and adds `spawn_drops_system` and `magnet_system` to the `Update`
475/// schedule.
476///
477/// **This plugin is NOT included in [`crate::VoxelPlugin`]** — because it is
478/// generic over `I: `[`ItemType`], it must be added separately by game code.
479/// Add it alongside [`crate::generator::GeneratorPlugin`]:
480///
481/// ```rust,no_run
482/// use bevy::prelude::*;
483/// use voxel_framework::items::{DefaultItem, DropsPlugin};
484///
485/// App::new().add_plugins(DropsPlugin::<DefaultItem>::new());
486/// ```
487pub struct DropsPlugin<I: ItemType> {
488    _marker: PhantomData<I>,
489}
490
491impl<I: ItemType> DropsPlugin<I> {
492    /// Creates a new `DropsPlugin`.
493    pub fn new() -> Self {
494        Self {
495            _marker: PhantomData,
496        }
497    }
498}
499
500impl<I: ItemType> Default for DropsPlugin<I> {
501    fn default() -> Self {
502        Self::new()
503    }
504}
505
506impl<I: ItemType> Plugin for DropsPlugin<I> {
507    fn build(&self, app: &mut App) {
508        app.init_resource::<DropTable<I>>();
509        app.init_resource::<MagnetConfig>();
510        app.add_message::<ItemPickedUp<I>>();
511        app.add_systems(Update, spawn_drops_system::<I>);
512        app.add_systems(Update, magnet_system::<I>);
513    }
514}
515
516// ─── Tests ───────────────────────────────────────────────────────────────────
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    use crate::items::DefaultItem;
522
523    #[test]
524    fn drops_expire_without_a_unique_collector_or_transform() {
525        for collectors in [0, 2] {
526            let mut app = App::new();
527            app.init_resource::<Time>()
528                .add_message::<VoxelBroken>()
529                .add_plugins(DropsPlugin::<DefaultItem>::new());
530            for _ in 0..collectors {
531                app.world_mut().spawn((ItemCollector, Transform::default()));
532            }
533            let mut entities = Vec::new();
534            for positioned in [false, true] {
535                let mut entity = app.world_mut().spawn(DroppedItem {
536                    item: DefaultItem::RockFragment,
537                    count: 3,
538                    velocity: Vec3::ZERO,
539                    lifetime: 0.2,
540                });
541                if positioned {
542                    entity.insert(Transform::default());
543                }
544                entities.push(entity.id());
545            }
546            app.world_mut()
547                .resource_mut::<Time>()
548                .advance_by(std::time::Duration::from_millis(100));
549            app.update();
550            for &entity in &entities {
551                let drop = app.world().get::<DroppedItem<DefaultItem>>(entity).unwrap();
552                assert!((drop.lifetime - 0.1).abs() < 0.0001);
553                assert_eq!(drop.count, 3);
554            }
555            app.update();
556            for entity in entities {
557                assert!(app.world().get_entity(entity).is_err());
558            }
559            assert!(
560                app.world()
561                    .resource::<Messages<ItemPickedUp<DefaultItem>>>()
562                    .is_empty()
563            );
564        }
565    }
566
567    #[test]
568    fn broken_voxel_spawns_one_mapped_drop_at_world_position() {
569        let mut app = App::new();
570        app.init_resource::<Time>()
571            .add_message::<VoxelBroken>()
572            .add_plugins(DropsPlugin::<DefaultItem>::new());
573        app.world_mut()
574            .resource_mut::<DropTable<DefaultItem>>()
575            .register(1, DefaultItem::RockFragment, 1, 1);
576        let position = Vec3::new(18.5, -12.5, 36.5);
577        app.world_mut().write_message(VoxelBroken {
578            chunk_coord: IVec3::new(1, -1, 2),
579            local: (2, 3, 4),
580            world_pos: position,
581            voxel_byte: 1,
582        });
583
584        app.update();
585
586        let world = app.world_mut();
587        let mut query = world.query::<(&DroppedItem<DefaultItem>, Option<&Transform>)>();
588        let drops: Vec<_> = query.iter(world).collect();
589        assert_eq!(drops.len(), 1);
590        assert_eq!(drops[0].0.item, DefaultItem::RockFragment);
591        assert_eq!(drops[0].0.count, 1);
592        assert_eq!(
593            drops[0]
594                .1
595                .expect("spawned drop must have a world position")
596                .translation,
597            position
598        );
599    }
600
601    #[test]
602    fn nearby_drop_moves_and_is_collected_once_without_attracting_distant_drop() {
603        let mut app = App::new();
604        app.init_resource::<Time>()
605            .add_message::<VoxelBroken>()
606            .add_plugins(DropsPlugin::<DefaultItem>::new());
607        let player = app
608            .world_mut()
609            .spawn((
610                Transform::default(),
611                ItemCollector,
612                PrimaryContainer,
613                ContainerComponent::<DefaultItem>::new(9),
614            ))
615            .id();
616        let spawn_drop = |world: &mut World, position| {
617            world
618                .spawn((
619                    DroppedItem {
620                        item: DefaultItem::RockFragment,
621                        count: 1,
622                        velocity: Vec3::ZERO,
623                        lifetime: 60.0,
624                    },
625                    Transform::from_translation(position),
626                ))
627                .id()
628        };
629        let nearby = spawn_drop(app.world_mut(), Vec3::new(2.0, 0.0, 0.0));
630        let distant_position = Vec3::new(8.0, 0.0, 0.0);
631        let distant = spawn_drop(app.world_mut(), distant_position);
632        app.world_mut()
633            .resource_mut::<Time>()
634            .advance_by(std::time::Duration::from_millis(100));
635
636        app.update();
637        assert!(
638            app.world()
639                .get::<Transform>(nearby)
640                .unwrap()
641                .translation
642                .length()
643                < 2.0,
644            "nearby drop must move toward the collector"
645        );
646
647        let mut pickups = Vec::new();
648        for _ in 0..30 {
649            app.world_mut()
650                .resource_mut::<Time>()
651                .advance_by(std::time::Duration::from_millis(100));
652            app.update();
653            pickups.extend(
654                app.world_mut()
655                    .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
656                    .drain(),
657            );
658        }
659        assert!(app.world().get_entity(nearby).is_err());
660        assert_eq!(
661            app.world()
662                .get::<ContainerComponent<DefaultItem>>(player)
663                .unwrap()
664                .0
665                .count_of(DefaultItem::RockFragment),
666            1
667        );
668        assert_eq!(pickups.len(), 1);
669        assert_eq!(pickups[0].item, DefaultItem::RockFragment);
670        assert_eq!(pickups[0].count, 1);
671        assert_eq!(
672            app.world().get::<Transform>(distant).unwrap().translation,
673            distant_position
674        );
675        assert_eq!(
676            app.world()
677                .get::<DroppedItem<DefaultItem>>(distant)
678                .unwrap()
679                .velocity,
680            Vec3::ZERO
681        );
682    }
683
684    #[test]
685    fn partial_pickup_retains_remainder_until_inventory_has_room() {
686        let mut app = App::new();
687        app.init_resource::<Time>()
688            .add_message::<VoxelBroken>()
689            .add_plugins(DropsPlugin::<DefaultItem>::new());
690        let item = DefaultItem::RockFragment;
691        let mut container = ContainerComponent::<DefaultItem>::new(1);
692        // Published inventories use u32 aggregate quantities: leave room for one.
693        assert_eq!(container.0.add(item, u32::MAX - 1), 0);
694        let player = app
695            .world_mut()
696            .spawn((
697                Transform::default(),
698                ItemCollector,
699                PrimaryContainer,
700                container,
701            ))
702            .id();
703        let drop = app
704            .world_mut()
705            .spawn((
706                DroppedItem {
707                    item,
708                    count: 3,
709                    velocity: Vec3::ZERO,
710                    lifetime: 60.0,
711                },
712                Transform::from_xyz(0.25, 0.0, 0.0),
713            ))
714            .id();
715
716        let mut total_picked_up = 0;
717        for (expected_pickup, expected_remainder) in [(1, 2), (0, 2), (2, 0), (0, 0), (0, 0)] {
718            if expected_pickup == 2 {
719                assert_eq!(
720                    app.world_mut()
721                        .get_mut::<ContainerComponent<DefaultItem>>(player)
722                        .unwrap()
723                        .0
724                        .remove(item, 2),
725                    2
726                );
727            }
728            app.world_mut()
729                .resource_mut::<Time>()
730                .advance_by(std::time::Duration::from_millis(100));
731            app.update();
732            assert_eq!(
733                app.world()
734                    .get::<ContainerComponent<DefaultItem>>(player)
735                    .unwrap()
736                    .0
737                    .count_of(item),
738                u32::MAX
739            );
740            if expected_remainder == 0 {
741                assert!(app.world().get_entity(drop).is_err());
742            } else {
743                let retained = app
744                    .world()
745                    .get::<DroppedItem<DefaultItem>>(drop)
746                    .expect("partial pickup must preserve the remainder");
747                assert_eq!(retained.item, item);
748                assert_eq!(retained.count, expected_remainder);
749            }
750            let pickups: Vec<_> = app
751                .world_mut()
752                .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
753                .drain()
754                .collect();
755            if expected_pickup == 0 {
756                assert!(pickups.is_empty());
757            } else {
758                assert_eq!(pickups.len(), 1);
759                assert_eq!(pickups[0].item, item);
760                assert_eq!(pickups[0].count, expected_pickup);
761                total_picked_up += pickups[0].count;
762            }
763            assert_eq!(
764                total_picked_up + expected_remainder,
765                3,
766                "no units lost or duplicated"
767            );
768        }
769        assert_eq!(total_picked_up, 3);
770    }
771
772    #[test]
773    fn full_inventory_retains_drop_without_reporting_pickup() {
774        let mut app = App::new();
775        app.init_resource::<Time>()
776            .add_message::<VoxelBroken>()
777            .add_plugins(DropsPlugin::<DefaultItem>::new());
778        let mut container = ContainerComponent::<DefaultItem>::new(1);
779        assert_eq!(container.0.add(DefaultItem::IronOre, 1), 0);
780        let player = app
781            .world_mut()
782            .spawn((
783                Transform::default(),
784                ItemCollector,
785                PrimaryContainer,
786                container,
787            ))
788            .id();
789        let drop = app
790            .world_mut()
791            .spawn((
792                DroppedItem {
793                    item: DefaultItem::RockFragment,
794                    count: 3,
795                    velocity: Vec3::ZERO,
796                    lifetime: 60.0,
797                },
798                Transform::from_xyz(0.25, 0.0, 0.0),
799            ))
800            .id();
801
802        for _ in 0..3 {
803            app.world_mut()
804                .resource_mut::<Time>()
805                .advance_by(std::time::Duration::from_millis(100));
806            app.update();
807            let retained = app
808                .world()
809                .get::<DroppedItem<DefaultItem>>(drop)
810                .expect("full inventory must retain the unaccepted drop");
811            assert_eq!(retained.item, DefaultItem::RockFragment);
812            assert_eq!(retained.count, 3);
813            let inventory = &app
814                .world()
815                .get::<ContainerComponent<DefaultItem>>(player)
816                .unwrap()
817                .0;
818            assert_eq!(inventory.count_of(DefaultItem::IronOre), 1);
819            assert_eq!(inventory.count_of(DefaultItem::RockFragment), 0);
820            assert_eq!(
821                app.world_mut()
822                    .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
823                    .drain()
824                    .count(),
825                0
826            );
827        }
828
829        assert_eq!(
830            app.world_mut()
831                .get_mut::<ContainerComponent<DefaultItem>>(player)
832                .unwrap()
833                .0
834                .remove(DefaultItem::IronOre, 1),
835            1
836        );
837        for expected_messages in [1, 0, 0] {
838            app.world_mut()
839                .resource_mut::<Time>()
840                .advance_by(std::time::Duration::from_millis(100));
841            app.update();
842            assert!(app.world().get_entity(drop).is_err());
843            let inventory = &app
844                .world()
845                .get::<ContainerComponent<DefaultItem>>(player)
846                .unwrap()
847                .0;
848            assert_eq!(inventory.count_of(DefaultItem::RockFragment), 3);
849            assert_eq!(inventory.count_of(DefaultItem::IronOre), 0);
850            let pickups: Vec<_> = app
851                .world_mut()
852                .resource_mut::<Messages<ItemPickedUp<DefaultItem>>>()
853                .drain()
854                .collect();
855            assert_eq!(pickups.len(), expected_messages);
856            if let Some(pickup) = pickups.first() {
857                assert_eq!(pickup.item, DefaultItem::RockFragment);
858                assert_eq!(pickup.count, 3);
859            }
860        }
861    }
862
863    #[test]
864    fn test_drop_table_get_drop() {
865        let mut table = DropTable::<DefaultItem>::new();
866        table.register(1, DefaultItem::RockFragment, 1, 3);
867
868        // With seed 0: deterministic count should be in [1, 3].
869        let result = table.get_drop(1, 0);
870        assert!(result.is_some());
871        let (item, count) = result.unwrap();
872        assert_eq!(item, DefaultItem::RockFragment);
873        assert!((1..=3).contains(&count));
874    }
875
876    #[test]
877    fn test_drop_table_no_entry_returns_none() {
878        let table = DropTable::<DefaultItem>::new();
879        assert!(table.get_drop(99, 42).is_none());
880    }
881
882    #[test]
883    fn test_drop_table_fixed_count() {
884        let mut table = DropTable::<DefaultItem>::new();
885        table.register(2, DefaultItem::IronOre, 5, 5);
886        let (_, count) = table.get_drop(2, 12345).unwrap();
887        assert_eq!(count, 5);
888    }
889
890    #[test]
891    fn test_drop_table_identity_fallback_with_other_entries() {
892        let mut table = DropTable::<DefaultItem>::new();
893        table.register(2, DefaultItem::Dirt, 1, 1);
894        let (item, count) = table.get_drop(11, 0).unwrap();
895        assert_eq!(item, DefaultItem::IronOre);
896        assert_eq!(count, 1);
897    }
898
899    #[test]
900    fn drop_table_supports_multiple_runtime_entries() {
901        let mut table = DropTable::<DefaultItem>::new();
902        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
903        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 2, 2));
904
905        let drops = table.get_drops(3, 123);
906        assert_eq!(drops.len(), 2);
907        assert_eq!(drops[0], (DefaultItem::Cobblestone, 1));
908        assert_eq!(drops[1], (DefaultItem::Coal, 2));
909    }
910
911    #[test]
912    fn register_preserves_single_entry_replacement_behavior() {
913        let mut table = DropTable::<DefaultItem>::new();
914        table.add_entry(3, DropTableEntry::new(DefaultItem::Cobblestone, 1, 1));
915        table.add_entry(3, DropTableEntry::new(DefaultItem::Coal, 1, 1));
916
917        table.register(3, DefaultItem::IronOre, 1, 1);
918
919        let drops = table.get_drops(3, 0);
920        assert_eq!(drops, vec![(DefaultItem::IronOre, 1)]);
921    }
922
923    #[test]
924    fn drop_table_entry_chance_can_disable_a_drop() {
925        let mut table = DropTable::<DefaultItem>::new();
926        table.add_entry(
927            3,
928            DropTableEntry::with_chance(DefaultItem::Cobblestone, 1, 1, 0.0),
929        );
930        table.add_entry(3, DropTableEntry::with_chance(DefaultItem::Coal, 1, 1, 1.0));
931
932        let drops = table.get_drops(3, 0);
933        assert_eq!(drops, vec![(DefaultItem::Coal, 1)]);
934    }
935
936    #[test]
937    fn iter_drop_entries_includes_chance_metadata() {
938        let mut table = DropTable::<DefaultItem>::new();
939        table.register_with_chance(3, DefaultItem::Cobblestone, 1, 2, 0.25);
940
941        let entries: Vec<_> = table.iter_drop_entries().collect();
942        assert_eq!(entries.len(), 1);
943        assert_eq!(entries[0].0, 3);
944        assert_eq!(entries[0].1.item, DefaultItem::Cobblestone);
945        assert_eq!(entries[0].1.min_count, 1);
946        assert_eq!(entries[0].1.max_count, 2);
947        assert_eq!(entries[0].1.chance, 0.25);
948    }
949}