Skip to main content

voxel_framework/items/
inventory.rs

1//! Slot-based inventory resource and the [`ItemType`] trait.
2//!
3//! This module is the data layer of the item system.  It defines the
4//! [`ItemType`] trait that all item enums must implement, the [`Inventory`]
5//! resource that stores collected items, and the [`ItemPickedUp`] message
6//! emitted whenever items successfully enter the inventory.
7//!
8//! The design mirrors [`crate::voxel::VoxelType`]: item types are lightweight
9//! value types (typically unit-variant enums) stored densely in a flat slot
10//! vector.  The actual spawning, attraction, and pickup logic lives in
11//! [`crate::items::drops`]; this module is concerned only with the data model.
12
13use std::hash::Hash;
14
15use crate::voxel::{DefaultTerrainVoxel, VoxelType};
16use bevy::prelude::*;
17
18// ─── Container trait ─────────────────────────────────────────────────────────
19
20/// Neutral failure reasons for an atomic container exchange.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum ContainerExchangeError {
24    /// A positive sentinel quantity or an overflowing quantity list.
25    InvalidRequest,
26    /// The container's shape, live stacks, or totals are invalid.
27    InvalidContainer,
28    /// The container cannot supply every requested item.
29    InsufficientItems,
30    /// The post-consumption outputs exceed slot or numeric capacity.
31    CapacityExceeded,
32}
33
34/// Normalize by item equality, retaining first-occurrence order (not byte identity).
35pub(crate) fn normalize_quantities<I: ItemType>(
36    quantities: &[(I, u32)],
37) -> Result<Vec<(I, u32)>, ContainerExchangeError> {
38    let mut normalized: Vec<(I, u32)> = Vec::new();
39    for &(item, count) in quantities {
40        if count == 0 {
41            continue;
42        }
43        if item == I::default() || item.is_empty() {
44            return Err(ContainerExchangeError::InvalidRequest);
45        }
46        if let Some((_, total)) = normalized
47            .iter_mut()
48            .find(|(existing, _)| *existing == item)
49        {
50            *total = total
51                .checked_add(count)
52                .ok_or(ContainerExchangeError::InvalidRequest)?;
53        } else {
54            normalized.push((item, count));
55        }
56    }
57    Ok(normalized)
58}
59
60/// Abstraction over slot-based item storage.
61///
62/// Any type that holds items in indexed slots can implement this trait to be
63/// usable with the framework's pickup, hotbar, and crafting systems.
64///
65/// The framework provides two built-in implementors:
66/// - [`Inventory<I>`] — the standalone resource form (backward-compatible).
67/// - [`ContainerComponent<I>`] — the Bevy component form used by the new
68///   entity-based pipeline.
69pub trait Container<I: ItemType> {
70    /// Adds `count` of `item`.  Returns the number of items that could NOT be
71    /// inserted due to capacity (0 = all inserted).
72    fn add(&mut self, item: I, count: u32) -> u32;
73
74    /// Removes up to `count` of `item`.  Returns the number actually removed.
75    fn remove(&mut self, item: I, count: u32) -> u32;
76
77    /// Total number of `item` across all slots.
78    fn count_of(&self, item: I) -> u32;
79
80    /// Maximum number of distinct item stacks this container can hold.
81    fn capacity(&self) -> usize;
82
83    /// Returns `true` if every slot is occupied.
84    fn is_full(&self) -> bool;
85
86    /// Iterates over all slots, yielding `Some(&InventorySlot<I>)` for occupied
87    /// slots and `None` for empty ones.  Yields exactly `capacity()` items.
88    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>>;
89
90    /// Returns the slot at `index`, or `None` if the index is out of bounds or
91    /// the slot is empty.  Never panics.
92    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>>;
93
94    /// Optionally consume and produce a complete exchange atomically.
95    ///
96    /// `None` means unsupported; `None` and `Some(Err(_))` MUST leave the
97    /// container unchanged. `Some(Ok(()))` means every quantity was exchanged.
98    /// Normalize duplicates by equality in first-occurrence order, ignore zero
99    /// quantities, allow empty lists, and reject positive default/empty sentinels
100    /// and checked `u32` sums that overflow. Evaluate capacity after consumption.
101    /// The default keeps existing implementors compatible; legacy crafting may
102    /// partially mutate when their individual operations fail.
103    fn try_exchange_atomic(
104        &mut self,
105        _remove: &[(I, u32)],
106        _add: &[(I, u32)],
107    ) -> Option<Result<(), ContainerExchangeError>> {
108        None
109    }
110}
111
112// ─── ItemType trait ───────────────────────────────────────────────────────────
113
114/// Contract that all item types must satisfy to participate in the item pipeline.
115///
116/// Implement this trait for any `Copy + Hash + Default` enum to make it usable
117/// with [`Inventory`], [`crate::items::drops::DropTable`],
118/// [`crate::items::drops::DropsPlugin`], and
119/// [`crate::items::persistence::save_inventory`] /
120/// [`crate::items::persistence::load_inventory`].
121///
122/// The framework ships [`DefaultItem`] as a ready-made implementation.
123/// Custom implementations should designate one variant as the *empty sentinel*
124/// (returned by [`Default`]) and override [`ItemType::is_empty`] accordingly.
125///
126/// # Contract
127///
128/// * `Copy + Clone` — slots are copied freely; no heap allocation per item.
129/// * `Default` — produces the empty-sentinel value.
130/// * `PartialEq + Eq + Hash` — required for slot deduplication and hash-map
131///   lookups in [`crate::items::drops::DropTable`].
132/// * `Send + Sync + 'static` — required for use as a Bevy [`Resource`] type
133///   parameter.
134/// * [`to_byte`](ItemType::to_byte) / [`from_byte`](ItemType::from_byte) —
135///   stable single-byte encoding used by the JSON persistence layer.  Unknown
136///   bytes must round-trip to `Self::default()`.
137///
138/// # Examples
139///
140/// ```rust,no_run
141/// use voxel_framework::items::ItemType;
142///
143/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
144/// enum MyItem { #[default] Empty, Wood, Stone }
145///
146/// impl ItemType for MyItem {
147///     fn name(&self) -> &'static str {
148///         match self { MyItem::Empty => "Empty", MyItem::Wood => "Wood", MyItem::Stone => "Stone" }
149///     }
150///     fn color(&self) -> [f32; 4] {
151///         match self {
152///             MyItem::Empty => [0.0; 4],
153///             MyItem::Wood  => [0.55, 0.35, 0.20, 1.0],
154///             MyItem::Stone => [0.50, 0.50, 0.50, 1.0],
155///         }
156///     }
157///     fn to_byte(&self) -> u8   { match self { MyItem::Empty => 0, MyItem::Wood => 1, MyItem::Stone => 2 } }
158///     fn from_byte(b: u8) -> Self { match b { 1 => MyItem::Wood, 2 => MyItem::Stone, _ => MyItem::Empty } }
159///     fn is_empty(&self) -> bool { matches!(self, MyItem::Empty) }
160/// }
161/// ```
162pub trait ItemType: Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static {
163    /// Human-readable display name for this item (e.g. `"Iron Ore"`).
164    ///
165    /// Used by UI widgets such as the pickup notification overlay.
166    fn name(&self) -> &'static str;
167
168    /// Default RGBA display colour for this item, with components in `[0.0, 1.0]`.
169    ///
170    /// Used by hotbar and inventory UI as a fallback when no sprite is available.
171    fn color(&self) -> [f32; 4];
172
173    /// Encodes this item variant as a single byte for JSON persistence.
174    ///
175    /// The mapping must be stable across game versions; changing it will
176    /// corrupt existing save files.  The empty-sentinel variant should map
177    /// to `0`.
178    fn to_byte(&self) -> u8;
179
180    /// Decodes a single byte back into an item variant.
181    ///
182    /// Unknown byte values — for example from a future game version — **must**
183    /// return `Self::default()` rather than panicking so that save files from
184    /// newer versions degrade gracefully.
185    fn from_byte(b: u8) -> Self;
186
187    /// Returns `true` if this variant is the empty-slot sentinel.
188    ///
189    /// The default implementation returns `false`; override it for the variant
190    /// that represents "nothing here" (typically the `Default` variant).
191    fn is_empty(&self) -> bool {
192        false
193    }
194
195    /// Tool level provided when this item is the active hotbar selection.
196    ///
197    /// `0` = bare hands. Matched against [`crate::voxel::VoxelType::mining_level`]:
198    /// if `tool_level < voxel.mining_level()`, mining makes no progress.
199    ///
200    /// Default: `0`.
201    fn tool_level(&self) -> u8 {
202        0
203    }
204
205    /// Mining speed multiplier when this item is the active tool.
206    ///
207    /// The effective break time is divided by this value (`2.0` = twice as fast).
208    /// Default: `1.0`.
209    fn tool_speed(&self) -> f32 {
210        1.0
211    }
212}
213
214// ─── InventorySlot ────────────────────────────────────────────────────────────
215
216/// A single occupied inventory slot, holding a stack of one item type.
217///
218/// Slots are always non-empty — "no item" is represented by `None` at the
219/// [`Inventory::slots`] level rather than a zero-count `InventorySlot`.
220/// The `count` field is therefore always `>= 1` in practice; the drop systems
221/// never produce a zero-count slot.
222#[derive(Debug, Clone, PartialEq)]
223pub struct InventorySlot<I: ItemType> {
224    /// The item type stored in this slot.
225    pub item: I,
226    /// Number of items in the stack.  Always `>= 1` for a live slot.
227    pub count: u32,
228}
229
230// ─── Inventory ────────────────────────────────────────────────────────────────
231
232/// Fixed-capacity player inventory backed by a flat slot vector.
233///
234/// The inventory holds up to `capacity` stacks, each stored as
235/// `Option<`[`InventorySlot`]`<I>>`.  `None` denotes an empty slot.
236///
237/// Items of the same type are automatically stacked: [`Inventory::add`]
238/// fills existing stacks of the matching type before opening a new slot.
239/// [`Inventory::remove`] drains stacks in order and clears slots that reach
240/// zero.
241///
242/// The default capacity is 36 slots (4 rows × 9 columns), matching the
243/// standard Minecraft-style layout expected by the built-in hotbar and
244/// inventory UI widgets.
245///
246/// # Examples
247///
248/// ```rust,no_run
249/// use voxel_framework::items::{Inventory, DefaultItem};
250///
251/// let mut inv = Inventory::<DefaultItem>::new(9);
252/// inv.add(DefaultItem::IronOre, 5);
253/// assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
254/// ```
255#[derive(Resource, Debug, Clone)]
256pub struct Inventory<I: ItemType> {
257    /// The backing slot vector.  `None` at index `i` means slot `i` is empty.
258    ///
259    /// The length always equals `capacity`; slots are never removed from the
260    /// vector.
261    pub slots: Vec<Option<InventorySlot<I>>>,
262    /// Maximum number of distinct item stacks the inventory can hold.
263    ///
264    /// Set at construction time; cannot be changed after the fact without
265    /// rebuilding the inventory.
266    pub capacity: usize,
267}
268
269impl<I: ItemType> Inventory<I> {
270    /// Check publicly writable fields before transactional use or persistence.
271    pub(crate) fn validate_integrity(&self) -> Result<(), ContainerExchangeError> {
272        if self.capacity != self.slots.len() {
273            return Err(ContainerExchangeError::InvalidContainer);
274        }
275        let quantities: Vec<_> = self
276            .slots
277            .iter()
278            .flatten()
279            .map(|slot| (slot.item, slot.count))
280            .collect();
281        if quantities.iter().any(|(_, count)| *count == 0) {
282            return Err(ContainerExchangeError::InvalidContainer);
283        }
284        normalize_quantities(&quantities)
285            .map(|_| ())
286            .map_err(|_| ContainerExchangeError::InvalidContainer)
287    }
288
289    fn exchange_atomic(
290        &mut self,
291        remove: &[(I, u32)],
292        add: &[(I, u32)],
293    ) -> Result<(), ContainerExchangeError> {
294        let remove = normalize_quantities(remove)?;
295        let add = normalize_quantities(add)?;
296        self.validate_integrity()?;
297        if remove
298            .iter()
299            .any(|&(item, count)| self.count_of(item) < count)
300        {
301            return Err(ContainerExchangeError::InsufficientItems);
302        }
303        // Copy only private staging data: no extra Clone bound on item/container.
304        let mut staged = Self {
305            slots: self.slots.clone(),
306            capacity: self.capacity,
307        };
308        for (item, count) in remove {
309            if staged.remove(item, count) != count {
310                return Err(ContainerExchangeError::InsufficientItems);
311            }
312        }
313        for (item, count) in add {
314            if staged.add(item, count) != 0 {
315                return Err(ContainerExchangeError::CapacityExceeded);
316            }
317        }
318        self.slots = staged.slots;
319        Ok(())
320    }
321
322    /// Creates a new empty inventory with the given slot capacity.
323    pub fn new(capacity: usize) -> Self {
324        Self {
325            slots: vec![None; capacity],
326            capacity,
327        }
328    }
329
330    /// Adds `count` of `item` to the inventory.
331    ///
332    /// Items are stacked onto existing slots of the same type first, then into
333    /// empty slots. Returns the number of items that could **not** be added
334    /// because slot capacity or the per-item `u32` representational ceiling is
335    /// exceeded. This is not an author-configured stack limit. Invalid public
336    /// fields or positive default/empty sentinels are rejected without mutation.
337    pub fn add(&mut self, item: I, count: u32) -> u32 {
338        if count == 0 {
339            return 0;
340        }
341        if item == I::default() || item.is_empty() || self.validate_integrity().is_err() {
342            return count;
343        }
344        let accepted = count.min(u32::MAX - self.count_of(item));
345        let mut remaining = accepted;
346
347        // First pass: fill existing stacks.
348        for slot in self.slots.iter_mut().flatten() {
349            if remaining == 0 {
350                break;
351            }
352            if slot.item == item {
353                slot.count += remaining;
354                remaining = 0;
355            }
356        }
357
358        // Second pass: open new slots for leftovers.
359        if remaining > 0 {
360            for slot in self.slots.iter_mut() {
361                if remaining == 0 {
362                    break;
363                }
364                if slot.is_none() {
365                    *slot = Some(InventorySlot {
366                        item,
367                        count: remaining,
368                    });
369                    remaining = 0;
370                }
371            }
372        }
373
374        (count - accepted) + remaining
375    }
376
377    /// Removes up to `count` of `item` from the inventory.
378    ///
379    /// Returns the number of items that were actually removed (may be less than
380    /// `count` if the inventory held fewer).
381    pub fn remove(&mut self, item: I, count: u32) -> u32 {
382        let mut to_remove = count;
383        let mut removed = 0u32;
384
385        for slot in self.slots.iter_mut() {
386            if to_remove == 0 {
387                break;
388            }
389            if let Some(s) = slot {
390                if s.item == item {
391                    let take = s.count.min(to_remove);
392                    s.count -= take;
393                    to_remove -= take;
394                    removed += take;
395                    if s.count == 0 {
396                        *slot = None;
397                    }
398                }
399            }
400        }
401
402        removed
403    }
404
405    /// Returns the total number of `item`, defensively saturating for invalid
406    /// publicly modified fields rather than wrapping or panicking.
407    pub fn count_of(&self, item: I) -> u32 {
408        self.slots
409            .iter()
410            .flatten()
411            .filter(|s| s.item == item)
412            .fold(0u32, |total, slot| total.saturating_add(slot.count))
413    }
414
415    /// Returns `true` if every slot is occupied.
416    pub fn is_full(&self) -> bool {
417        self.slots.iter().all(|s| s.is_some())
418    }
419}
420
421impl<I: ItemType> Default for Inventory<I> {
422    /// Creates a default inventory with 36 slots (4 rows × 9 columns).
423    fn default() -> Self {
424        Self::new(36)
425    }
426}
427
428// ─── Container impl for Inventory ────────────────────────────────────────────
429
430impl<I: ItemType> Container<I> for Inventory<I> {
431    fn try_exchange_atomic(
432        &mut self,
433        remove: &[(I, u32)],
434        add: &[(I, u32)],
435    ) -> Option<Result<(), ContainerExchangeError>> {
436        Some(self.exchange_atomic(remove, add))
437    }
438
439    fn add(&mut self, item: I, count: u32) -> u32 {
440        Inventory::add(self, item, count)
441    }
442
443    fn remove(&mut self, item: I, count: u32) -> u32 {
444        Inventory::remove(self, item, count)
445    }
446
447    fn count_of(&self, item: I) -> u32 {
448        Inventory::count_of(self, item)
449    }
450
451    fn capacity(&self) -> usize {
452        self.capacity
453    }
454
455    fn is_full(&self) -> bool {
456        Inventory::is_full(self)
457    }
458
459    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
460        self.slots.iter().map(|s| s.as_ref())
461    }
462
463    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
464        self.slots.get(index).and_then(|s| s.as_ref())
465    }
466}
467
468// ─── ContainerComponent ───────────────────────────────────────────────────────
469
470/// Bevy [`Component`] newtype that wraps an [`Inventory<I>`] for use in the
471/// entity-based item pipeline.
472///
473/// Add this alongside [`PrimaryContainer`] on the player entity so the magnet,
474/// hotbar, and crafting systems can locate the player's inventory via ECS
475/// queries instead of a global resource.
476///
477/// # Examples
478///
479/// ```rust,no_run
480/// use bevy::prelude::*;
481/// use voxel_framework::items::{ContainerComponent, PrimaryContainer, DefaultItem};
482///
483/// fn spawn_player(mut commands: Commands) {
484///     commands.spawn((
485///         ContainerComponent::<DefaultItem>::new(36),
486///         PrimaryContainer,
487///     ));
488/// }
489/// ```
490#[derive(Component)]
491pub struct ContainerComponent<I: ItemType>(pub Inventory<I>);
492
493impl<I: ItemType> ContainerComponent<I> {
494    /// Creates a new `ContainerComponent` wrapping a fresh [`Inventory`] with
495    /// the given `capacity`.
496    pub fn new(capacity: usize) -> Self {
497        Self(Inventory::new(capacity))
498    }
499}
500
501impl<I: ItemType> Container<I> for ContainerComponent<I> {
502    fn try_exchange_atomic(
503        &mut self,
504        remove: &[(I, u32)],
505        add: &[(I, u32)],
506    ) -> Option<Result<(), ContainerExchangeError>> {
507        Container::try_exchange_atomic(&mut self.0, remove, add)
508    }
509
510    fn add(&mut self, item: I, count: u32) -> u32 {
511        self.0.add(item, count)
512    }
513
514    fn remove(&mut self, item: I, count: u32) -> u32 {
515        self.0.remove(item, count)
516    }
517
518    fn count_of(&self, item: I) -> u32 {
519        self.0.count_of(item)
520    }
521
522    fn capacity(&self) -> usize {
523        self.0.capacity
524    }
525
526    fn is_full(&self) -> bool {
527        self.0.is_full()
528    }
529
530    fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
531        self.0.slots.iter().map(|s| s.as_ref())
532    }
533
534    fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
535        self.0.slots.get(index).and_then(|s| s.as_ref())
536    }
537}
538
539// ─── PrimaryContainer marker ──────────────────────────────────────────────────
540
541/// Zero-size marker component that identifies the entity whose
542/// [`ContainerComponent`] is the player's primary backpack.
543///
544/// Exactly one entity should carry this marker at runtime.  If zero or more
545/// than one exist, the pickup and hotbar systems skip silently — no panic.
546#[derive(Component, Default)]
547pub struct PrimaryContainer;
548
549// ─── Messages ────────────────────────────────────────────────────────────────
550
551/// Message emitted when one or more items are successfully added to the inventory.
552///
553/// The magnet system in [`crate::items::drops`] writes this message after
554/// adding items to [`Inventory`].  UI systems — such as the pickup notification
555/// overlay — subscribe to this message to display transient feedback.
556///
557/// Note: this message is only written when at least one item was actually
558/// inserted (i.e. `count > 0`).  If the inventory was full the message is
559/// **not** written even though a pickup was attempted.
560#[derive(Message, Debug, Clone)]
561pub struct ItemPickedUp<I: ItemType> {
562    /// The item type that was picked up.
563    pub item: I,
564    /// Number of items that were successfully inserted.  Always `>= 1`.
565    pub count: u32,
566}
567
568// ─── DefaultItem ─────────────────────────────────────────────────────────────
569
570/// Built-in item type covering common mineral pickups.
571///
572/// `DefaultItem` is the item counterpart of [`crate::voxel::DefaultVoxel`]:
573/// it implements [`ItemType`] out of the box and is wired into the default
574/// [`crate::items::drops::DropTable`] entries provided by the framework.
575///
576/// `Empty` is the empty-slot sentinel returned by [`Default`] and by
577/// [`ItemType::from_byte`] for unknown byte values.  It should never appear
578/// as a real collectible.
579///
580/// # Examples
581///
582/// ```rust,no_run
583/// use voxel_framework::items::{DefaultItem, Inventory};
584///
585/// let mut inv = Inventory::<DefaultItem>::new(9);
586/// inv.add(DefaultItem::Crystal, 3);
587/// ```
588#[derive(
589    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
590)]
591pub enum DefaultItem {
592    /// Empty slot sentinel — not a real item; returned by [`Default`].
593    #[default]
594    Empty,
595    /// Dirt block; placeable Dirt voxel item (byte 2, matches DefaultTerrainVoxel::Dirt).
596    Dirt,
597    /// Sand block; placeable Sand voxel item (byte 4, matches DefaultTerrainVoxel::Sand).
598    Sand,
599    /// Wood log block; placeable Wood voxel item (byte 5, matches DefaultTerrainVoxel::Wood).
600    Wood,
601    /// Gravel block; placeable Gravel voxel item (byte 7, matches DefaultTerrainVoxel::Gravel).
602    Gravel,
603    /// Snow block; placeable Snow voxel item (byte 8, matches DefaultTerrainVoxel::Snow).
604    Snow,
605    /// Coal ore block; placeable CoalOre voxel item (byte 10, matches DefaultTerrainVoxel::CoalOre).
606    CoalOre,
607    /// Iron ore block; placeable IronOre voxel item (byte 11, matches DefaultTerrainVoxel::IronOre).
608    IronOre,
609    /// Cobblestone block; placeable Cobblestone voxel item (byte 12).
610    Cobblestone,
611    /// Sandstone block; placeable Sandstone voxel item (byte 13).
612    Sandstone,
613    /// Wooden planks block; placeable Planks voxel item (byte 14).
614    Planks,
615    /// Fired clay brick block; placeable Brick voxel item (byte 15).
616    Brick,
617    /// Coal lump; dropped from CoalOre voxels (byte 16).
618    Coal,
619    /// Smelted iron ingot; produced from IronOre (byte 17).
620    IronIngot,
621    /// Wood log; dropped from Wood voxels (byte 18).
622    Log,
623    /// Snowball; dropped from Snow voxels (byte 19).
624    Snowball,
625    /// Fragment of common rock; drops from Stone voxels (byte 20).
626    RockFragment,
627    /// Silicon crystal shard; drops from crystal voxels (byte 21).
628    Crystal,
629    /// Rare mineral node; drops from high-value voxels (byte 22).
630    RareMineral,
631    /// Wooden pickaxe — tool level 1, normal speed. Crafted from wood (byte 23).
632    WoodenPickaxe,
633    /// Stone pickaxe — tool level 1, 2× speed. Crafted from rock fragments (byte 24).
634    StonePickaxe,
635    /// Iron pickaxe — tool level 2, 4× speed. Crafted from iron ore (byte 25).
636    IronPickaxe,
637    /// Deprecated alias for IronOre block — maps to byte 11 on write, never returned by from_byte.
638    IronOreItem,
639}
640
641impl ItemType for DefaultItem {
642    fn name(&self) -> &'static str {
643        match self {
644            DefaultItem::Empty => "Empty",
645            DefaultItem::Dirt => "Dirt",
646            DefaultItem::Sand => "Sand",
647            DefaultItem::Wood => "Wood",
648            DefaultItem::Gravel => "Gravel",
649            DefaultItem::Snow => "Snow",
650            DefaultItem::CoalOre => "Coal Ore",
651            DefaultItem::IronOre => "Iron Ore",
652            DefaultItem::IronOreItem => "Iron Ore",
653            DefaultItem::Cobblestone => "Cobblestone",
654            DefaultItem::Sandstone => "Sandstone",
655            DefaultItem::Planks => "Planks",
656            DefaultItem::Brick => "Brick",
657            DefaultItem::Coal => "Coal",
658            DefaultItem::IronIngot => "Iron Ingot",
659            DefaultItem::Log => "Log",
660            DefaultItem::Snowball => "Snowball",
661            DefaultItem::RockFragment => "Rock Fragment",
662            DefaultItem::Crystal => "Crystal",
663            DefaultItem::RareMineral => "Rare Mineral",
664            DefaultItem::WoodenPickaxe => "Wooden Pickaxe",
665            DefaultItem::StonePickaxe => "Stone Pickaxe",
666            DefaultItem::IronPickaxe => "Iron Pickaxe",
667        }
668    }
669
670    fn color(&self) -> [f32; 4] {
671        match self {
672            DefaultItem::Empty => [0.0, 0.0, 0.0, 0.0],
673            // Block-items: delegate to the matching voxel color for visual consistency.
674            DefaultItem::Dirt
675            | DefaultItem::Sand
676            | DefaultItem::Wood
677            | DefaultItem::Gravel
678            | DefaultItem::Snow
679            | DefaultItem::CoalOre
680            | DefaultItem::IronOre
681            | DefaultItem::IronOreItem
682            | DefaultItem::Cobblestone
683            | DefaultItem::Sandstone
684            | DefaultItem::Planks
685            | DefaultItem::Brick => DefaultTerrainVoxel::from_byte(self.to_byte()).color(),
686            // Processed / dropped items — explicit colors.
687            DefaultItem::Coal => [0.15, 0.15, 0.15, 1.0],
688            DefaultItem::IronIngot => [0.75, 0.65, 0.55, 1.0],
689            DefaultItem::Log => [0.40, 0.28, 0.12, 1.0],
690            DefaultItem::Snowball => [0.92, 0.95, 1.00, 1.0],
691            DefaultItem::RockFragment => [0.35, 0.30, 0.28, 1.0],
692            DefaultItem::Crystal => [0.40, 0.50, 0.80, 1.0],
693            DefaultItem::RareMineral => [0.20, 0.85, 0.60, 1.0],
694            // Tools.
695            DefaultItem::WoodenPickaxe => [0.55, 0.35, 0.20, 1.0],
696            DefaultItem::StonePickaxe => [0.50, 0.50, 0.50, 1.0],
697            DefaultItem::IronPickaxe => [0.70, 0.75, 0.80, 1.0],
698        }
699    }
700
701    fn to_byte(&self) -> u8 {
702        match self {
703            DefaultItem::Empty => 0,
704            // Block-items: bytes match DefaultTerrainVoxel::to_byte()
705            DefaultItem::Dirt => 2,
706            DefaultItem::Sand => 4,
707            DefaultItem::Wood => 5,
708            DefaultItem::Gravel => 7,
709            DefaultItem::Snow => 8,
710            DefaultItem::CoalOre => 10,
711            DefaultItem::IronOre => 11,
712            DefaultItem::IronOreItem => 11, // deprecated alias; collapses to IronOre byte
713            DefaultItem::Cobblestone => 12,
714            DefaultItem::Sandstone => 13,
715            DefaultItem::Planks => 14,
716            DefaultItem::Brick => 15,
717            // Processed / dropped items
718            DefaultItem::Coal => 16,
719            DefaultItem::IronIngot => 17,
720            DefaultItem::Log => 18,
721            DefaultItem::Snowball => 19,
722            DefaultItem::RockFragment => 20,
723            DefaultItem::Crystal => 21,
724            DefaultItem::RareMineral => 22,
725            DefaultItem::WoodenPickaxe => 23,
726            DefaultItem::StonePickaxe => 24,
727            DefaultItem::IronPickaxe => 25,
728        }
729    }
730
731    fn from_byte(b: u8) -> Self {
732        match b {
733            // Block-items (bytes 2–15 mirror DefaultTerrainVoxel)
734            2 => DefaultItem::Dirt,
735            4 => DefaultItem::Sand,
736            5 => DefaultItem::Wood,
737            7 => DefaultItem::Gravel,
738            8 => DefaultItem::Snow,
739            10 => DefaultItem::CoalOre,
740            11 => DefaultItem::IronOre,
741            12 => DefaultItem::Cobblestone,
742            13 => DefaultItem::Sandstone,
743            14 => DefaultItem::Planks,
744            15 => DefaultItem::Brick,
745            // Processed / dropped items
746            16 => DefaultItem::Coal,
747            17 => DefaultItem::IronIngot,
748            18 => DefaultItem::Log,
749            19 => DefaultItem::Snowball,
750            20 => DefaultItem::RockFragment,
751            21 => DefaultItem::Crystal,
752            22 => DefaultItem::RareMineral,
753            23 => DefaultItem::WoodenPickaxe,
754            24 => DefaultItem::StonePickaxe,
755            25 => DefaultItem::IronPickaxe,
756            // Bytes 0, 1, 3, 6, 9 and anything else → Empty
757            _ => DefaultItem::Empty,
758        }
759    }
760
761    fn is_empty(&self) -> bool {
762        matches!(self, DefaultItem::Empty)
763    }
764
765    fn tool_level(&self) -> u8 {
766        match self {
767            DefaultItem::WoodenPickaxe => 1,
768            DefaultItem::StonePickaxe => 1,
769            DefaultItem::IronPickaxe => 2,
770            _ => 0,
771        }
772    }
773
774    fn tool_speed(&self) -> f32 {
775        match self {
776            DefaultItem::WoodenPickaxe => 1.0,
777            DefaultItem::StonePickaxe => 2.0,
778            DefaultItem::IronPickaxe => 4.0,
779            _ => 1.0,
780        }
781    }
782}
783
784// ─── Tests ───────────────────────────────────────────────────────────────────
785
786#[cfg(test)]
787mod tests {
788    use super::*;
789
790    // ── add ──────────────────────────────────────────────────────────────────
791
792    #[test]
793    fn test_inventory_add_and_count() {
794        let mut inv = Inventory::<DefaultItem>::new(9);
795        let leftover = inv.add(DefaultItem::IronOre, 5);
796        assert_eq!(leftover, 0);
797        assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
798    }
799
800    #[test]
801    fn test_inventory_add_stacks_same_type() {
802        let mut inv = Inventory::<DefaultItem>::new(9);
803        inv.add(DefaultItem::Crystal, 3);
804        inv.add(DefaultItem::Crystal, 7);
805        assert_eq!(inv.count_of(DefaultItem::Crystal), 10);
806        // Should occupy only one slot.
807        let filled = inv.slots.iter().filter(|s| s.is_some()).count();
808        assert_eq!(filled, 1);
809    }
810
811    // ── remove ───────────────────────────────────────────────────────────────
812
813    #[test]
814    fn test_inventory_remove() {
815        let mut inv = Inventory::<DefaultItem>::new(9);
816        inv.add(DefaultItem::RockFragment, 10);
817        let removed = inv.remove(DefaultItem::RockFragment, 4);
818        assert_eq!(removed, 4);
819        assert_eq!(inv.count_of(DefaultItem::RockFragment), 6);
820    }
821
822    #[test]
823    fn test_inventory_remove_more_than_held_returns_actual() {
824        let mut inv = Inventory::<DefaultItem>::new(9);
825        inv.add(DefaultItem::RareMineral, 3);
826        let removed = inv.remove(DefaultItem::RareMineral, 10);
827        assert_eq!(removed, 3);
828        assert_eq!(inv.count_of(DefaultItem::RareMineral), 0);
829    }
830
831    #[test]
832    fn test_inventory_remove_clears_slot() {
833        let mut inv = Inventory::<DefaultItem>::new(9);
834        inv.add(DefaultItem::IronOre, 2);
835        inv.remove(DefaultItem::IronOre, 2);
836        assert!(inv.slots[0].is_none());
837    }
838
839    // ── full ─────────────────────────────────────────────────────────────────
840
841    #[test]
842    fn test_inventory_full() {
843        let mut inv = Inventory::<DefaultItem>::new(2);
844        inv.add(DefaultItem::IronOre, 1);
845        inv.add(DefaultItem::Crystal, 1);
846        assert!(inv.is_full());
847
848        // Adding more should return a leftover.
849        let leftover = inv.add(DefaultItem::RockFragment, 5);
850        assert_eq!(leftover, 5);
851    }
852
853    // ── Container trait via Inventory ─────────────────────────────────────────
854
855    #[test]
856    fn container_trait_add_and_count() {
857        let mut inv = Inventory::<DefaultItem>::new(9);
858        let leftover = Container::add(&mut inv, DefaultItem::IronOre, 5);
859        assert_eq!(leftover, 0);
860        assert_eq!(Container::count_of(&inv, DefaultItem::IronOre), 5);
861    }
862
863    #[test]
864    fn container_slot_at_out_of_bounds_returns_none() {
865        let inv = Inventory::<DefaultItem>::new(9);
866        assert!(Container::slot_at(&inv, 100).is_none());
867    }
868
869    #[test]
870    fn container_iter_slots_yields_capacity_items() {
871        let inv = Inventory::<DefaultItem>::new(9);
872        assert_eq!(Container::iter_slots(&inv).count(), 9);
873    }
874
875    // ── ContainerComponent ───────────────────────────────────────────────────
876
877    #[test]
878    fn container_component_delegates_correctly() {
879        let mut cc = ContainerComponent::<DefaultItem>::new(9);
880        cc.add(DefaultItem::Crystal, 3);
881        assert_eq!(cc.count_of(DefaultItem::Crystal), 3);
882        assert_eq!(cc.0.count_of(DefaultItem::Crystal), 3);
883    }
884
885    #[test]
886    fn container_component_slot_at_oob_no_panic() {
887        let cc = ContainerComponent::<DefaultItem>::new(9);
888        assert!(cc.slot_at(100).is_none());
889    }
890
891    fn stack(item: DefaultItem, count: u32) -> Option<InventorySlot<DefaultItem>> {
892        Some(InventorySlot { item, count })
893    }
894
895    #[test]
896    fn exchange_normalizes_duplicates_and_uses_freed_capacity() {
897        let mut inv = Inventory::new(1);
898        inv.add(DefaultItem::IronOre, 4);
899        assert_eq!(
900            inv.try_exchange_atomic(
901                &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
902                &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
903            ),
904            Some(Ok(()))
905        );
906        assert_eq!(inv.slots, vec![stack(DefaultItem::Crystal, 3)]);
907        assert_eq!(inv.capacity, 1);
908    }
909
910    #[test]
911    fn exchange_failure_preserves_exact_sparse_layout() {
912        let original = Inventory {
913            capacity: 4,
914            slots: vec![
915                stack(DefaultItem::IronOre, 2),
916                None,
917                stack(DefaultItem::IronOre, 1),
918                stack(DefaultItem::Crystal, 7),
919            ],
920        };
921        let requests = [
922            (
923                vec![(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
924                vec![],
925                ContainerExchangeError::InsufficientItems,
926            ),
927            (
928                vec![(DefaultItem::IronOre, 1)],
929                vec![(DefaultItem::Wood, 1), (DefaultItem::Sand, 1)],
930                ContainerExchangeError::CapacityExceeded,
931            ),
932            (
933                vec![(DefaultItem::IronOre, 1)],
934                vec![(DefaultItem::Crystal, u32::MAX)],
935                ContainerExchangeError::CapacityExceeded,
936            ),
937            (
938                vec![(DefaultItem::IronOre, u32::MAX), (DefaultItem::IronOre, 1)],
939                vec![],
940                ContainerExchangeError::InvalidRequest,
941            ),
942            (
943                vec![],
944                vec![(DefaultItem::Crystal, u32::MAX), (DefaultItem::Crystal, 1)],
945                ContainerExchangeError::InvalidRequest,
946            ),
947            (
948                vec![(DefaultItem::Empty, 1)],
949                vec![],
950                ContainerExchangeError::InvalidRequest,
951            ),
952            (
953                vec![],
954                vec![(DefaultItem::Empty, 1)],
955                ContainerExchangeError::InvalidRequest,
956            ),
957        ];
958        for (remove, add, error) in requests {
959            let mut inv = original.clone();
960            assert_eq!(inv.try_exchange_atomic(&remove, &add), Some(Err(error)));
961            assert_eq!(inv.slots, original.slots);
962            assert_eq!(inv.capacity, original.capacity);
963        }
964    }
965
966    #[test]
967    fn exchange_same_input_outputs_and_existing_duplicate_stacks() {
968        let mut inv = Inventory {
969            capacity: 4,
970            slots: vec![
971                stack(DefaultItem::IronOre, 2),
972                None,
973                stack(DefaultItem::IronOre, 3),
974                stack(DefaultItem::Crystal, 4),
975            ],
976        };
977        assert_eq!(
978            inv.try_exchange_atomic(
979                &[(DefaultItem::IronOre, 4)],
980                &[
981                    (DefaultItem::IronOre, 2),
982                    (DefaultItem::Crystal, 1),
983                    (DefaultItem::IronOre, 3)
984                ],
985            ),
986            Some(Ok(()))
987        );
988        assert_eq!(
989            inv.slots,
990            vec![
991                None,
992                None,
993                stack(DefaultItem::IronOre, 6),
994                stack(DefaultItem::Crystal, 5)
995            ]
996        );
997    }
998
999    #[test]
1000    fn add_bounds_aggregate_headroom_and_returns_every_leftover() {
1001        let mut inv = Inventory {
1002            capacity: 3,
1003            slots: vec![
1004                stack(DefaultItem::Crystal, u32::MAX - 10),
1005                None,
1006                stack(DefaultItem::Crystal, 5),
1007            ],
1008        };
1009        assert_eq!(inv.add(DefaultItem::Crystal, 8), 3);
1010        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1011        assert_eq!(inv.slots[0], stack(DefaultItem::Crystal, u32::MAX - 5));
1012        assert_eq!(inv.slots[2], stack(DefaultItem::Crystal, 5));
1013        assert!(inv.slots[1].is_none());
1014        let before = inv.slots.clone();
1015        assert_eq!(inv.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1016        assert_eq!(inv.slots, before);
1017        let mut full = Inventory::new(1);
1018        full.add(DefaultItem::IronOre, 1);
1019        assert_eq!(full.add(DefaultItem::Crystal, u32::MAX), u32::MAX);
1020    }
1021
1022    #[test]
1023    fn malformed_sources_reject_exchange_and_add_without_mutation() {
1024        let invalid = [
1025            Inventory {
1026                capacity: 2,
1027                slots: vec![None],
1028            },
1029            Inventory {
1030                capacity: 0,
1031                slots: vec![None],
1032            },
1033            Inventory {
1034                capacity: 1,
1035                slots: vec![stack(DefaultItem::IronOre, 0)],
1036            },
1037            Inventory {
1038                capacity: 1,
1039                slots: vec![stack(DefaultItem::Empty, 1)],
1040            },
1041            Inventory {
1042                capacity: 2,
1043                slots: vec![
1044                    stack(DefaultItem::IronOre, u32::MAX),
1045                    stack(DefaultItem::IronOre, 1),
1046                ],
1047            },
1048        ];
1049        for mut inv in invalid {
1050            let before = inv.slots.clone();
1051            let capacity = inv.capacity;
1052            assert_eq!(
1053                inv.validate_integrity(),
1054                Err(ContainerExchangeError::InvalidContainer)
1055            );
1056            assert_eq!(
1057                inv.try_exchange_atomic(&[], &[]),
1058                Some(Err(ContainerExchangeError::InvalidContainer))
1059            );
1060            assert_eq!(inv.add(DefaultItem::Crystal, 5), 5);
1061            assert_eq!(inv.slots, before);
1062            assert_eq!(inv.capacity, capacity);
1063        }
1064    }
1065
1066    #[test]
1067    fn count_of_defensively_saturates_invalid_totals() {
1068        let inv = Inventory {
1069            capacity: 3,
1070            slots: vec![
1071                stack(DefaultItem::Crystal, u32::MAX),
1072                stack(DefaultItem::Crystal, u32::MAX),
1073                stack(DefaultItem::IronOre, 3),
1074            ],
1075        };
1076        assert_eq!(inv.count_of(DefaultItem::Crystal), u32::MAX);
1077        assert_eq!(inv.count_of(DefaultItem::IronOre), 3);
1078    }
1079
1080    #[test]
1081    fn empty_lists_zero_quantities_and_zero_capacity_are_valid() {
1082        let mut inv = Inventory::<DefaultItem>::new(0);
1083        assert_eq!(inv.validate_integrity(), Ok(()));
1084        assert_eq!(inv.try_exchange_atomic(&[], &[]), Some(Ok(())));
1085        assert_eq!(
1086            inv.try_exchange_atomic(&[(DefaultItem::Empty, 0)], &[(DefaultItem::Empty, 0)]),
1087            Some(Ok(()))
1088        );
1089        assert_eq!(inv.add(DefaultItem::Empty, 0), 0);
1090        assert_eq!(inv.add(DefaultItem::Empty, 1), 1);
1091        assert_eq!(inv.add(DefaultItem::Crystal, 1), 1);
1092        assert!(inv.slots.is_empty());
1093    }
1094
1095    #[test]
1096    fn normalization_uses_equality_not_serialized_bytes_and_keeps_order() {
1097        assert_eq!(
1098            DefaultItem::IronOre.to_byte(),
1099            DefaultItem::IronOreItem.to_byte()
1100        );
1101        assert_ne!(DefaultItem::IronOre, DefaultItem::IronOreItem);
1102        assert_eq!(
1103            normalize_quantities(&[
1104                (DefaultItem::Empty, 0),
1105                (DefaultItem::IronOreItem, 1),
1106                (DefaultItem::Crystal, 0),
1107                (DefaultItem::IronOre, 2),
1108                (DefaultItem::IronOreItem, 3),
1109                (DefaultItem::Crystal, 5),
1110            ]),
1111            Ok(vec![
1112                (DefaultItem::IronOreItem, 4),
1113                (DefaultItem::IronOre, 2),
1114                (DefaultItem::Crystal, 5)
1115            ])
1116        );
1117    }
1118
1119    // Deliberately no Debug/Serialize derives and no is_empty override for Default.
1120    #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
1121    enum MinimalItem {
1122        #[default]
1123        DefaultSentinel,
1124        OtherSentinel,
1125        Live,
1126    }
1127
1128    impl ItemType for MinimalItem {
1129        fn name(&self) -> &'static str {
1130            "minimal"
1131        }
1132        fn color(&self) -> [f32; 4] {
1133            [1.0; 4]
1134        }
1135        fn to_byte(&self) -> u8 {
1136            1
1137        }
1138        fn from_byte(_: u8) -> Self {
1139            Self::default()
1140        }
1141        fn is_empty(&self) -> bool {
1142            *self == Self::OtherSentinel
1143        }
1144    }
1145
1146    #[test]
1147    fn exchange_requires_no_new_item_bounds_and_rejects_both_sentinels() {
1148        let mut inv = Inventory::<MinimalItem>::new(1);
1149        assert_eq!(inv.add(MinimalItem::DefaultSentinel, 1), 1);
1150        assert_eq!(inv.add(MinimalItem::OtherSentinel, 1), 1);
1151        assert_eq!(
1152            inv.try_exchange_atomic(&[], &[(MinimalItem::Live, 1)]),
1153            Some(Ok(()))
1154        );
1155        for sentinel in [MinimalItem::DefaultSentinel, MinimalItem::OtherSentinel] {
1156            assert_eq!(
1157                inv.try_exchange_atomic(&[(sentinel, 1)], &[]),
1158                Some(Err(ContainerExchangeError::InvalidRequest))
1159            );
1160            assert_eq!(
1161                inv.try_exchange_atomic(&[], &[(sentinel, 1)]),
1162                Some(Err(ContainerExchangeError::InvalidRequest))
1163            );
1164            assert_eq!(
1165                inv.try_exchange_atomic(&[(sentinel, 0)], &[(sentinel, 0)]),
1166                Some(Ok(()))
1167            );
1168            let invalid = Inventory {
1169                capacity: 1,
1170                slots: vec![Some(InventorySlot {
1171                    item: sentinel,
1172                    count: 1,
1173                })],
1174            };
1175            assert_eq!(
1176                invalid.validate_integrity(),
1177                Err(ContainerExchangeError::InvalidContainer)
1178            );
1179        }
1180        assert_eq!(inv.count_of(MinimalItem::Live), 1);
1181    }
1182
1183    #[test]
1184    fn component_atomic_exchange_matches_inventory_success_and_failure() {
1185        let mut inv = Inventory::new(1);
1186        inv.add(DefaultItem::IronOre, 4);
1187        let mut component = ContainerComponent(inv.clone());
1188        for (remove, add) in [
1189            (
1190                vec![(DefaultItem::IronOre, 4)],
1191                vec![(DefaultItem::Crystal, 3)],
1192            ),
1193            (vec![], vec![(DefaultItem::Wood, 1)]),
1194            (vec![(DefaultItem::Crystal, 4)], vec![]),
1195            (vec![], vec![(DefaultItem::Empty, 1)]),
1196        ] {
1197            assert_eq!(
1198                component.try_exchange_atomic(&remove, &add),
1199                inv.try_exchange_atomic(&remove, &add)
1200            );
1201            assert_eq!(component.0.slots, inv.slots);
1202            assert_eq!(component.capacity(), inv.capacity);
1203        }
1204        component.0.capacity = 2;
1205        let before = component.0.slots.clone();
1206        assert_eq!(
1207            component.try_exchange_atomic(&[], &[]),
1208            Some(Err(ContainerExchangeError::InvalidContainer))
1209        );
1210        assert_eq!(component.0.slots, before);
1211    }
1212}