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/// Abstraction over slot-based item storage.
21///
22/// Any type that holds items in indexed slots can implement this trait to be
23/// usable with the framework's pickup, hotbar, and crafting systems.
24///
25/// The framework provides two built-in implementors:
26/// - [`Inventory<I>`] — the standalone resource form (backward-compatible).
27/// - [`ContainerComponent<I>`] — the Bevy component form used by the new
28/// entity-based pipeline.
29pub trait Container<I: ItemType> {
30 /// Adds `count` of `item`. Returns the number of items that could NOT be
31 /// inserted due to capacity (0 = all inserted).
32 fn add(&mut self, item: I, count: u32) -> u32;
33
34 /// Removes up to `count` of `item`. Returns the number actually removed.
35 fn remove(&mut self, item: I, count: u32) -> u32;
36
37 /// Total number of `item` across all slots.
38 fn count_of(&self, item: I) -> u32;
39
40 /// Maximum number of distinct item stacks this container can hold.
41 fn capacity(&self) -> usize;
42
43 /// Returns `true` if every slot is occupied.
44 fn is_full(&self) -> bool;
45
46 /// Iterates over all slots, yielding `Some(&InventorySlot<I>)` for occupied
47 /// slots and `None` for empty ones. Yields exactly `capacity()` items.
48 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>>;
49
50 /// Returns the slot at `index`, or `None` if the index is out of bounds or
51 /// the slot is empty. Never panics.
52 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>>;
53}
54
55// ─── ItemType trait ───────────────────────────────────────────────────────────
56
57/// Contract that all item types must satisfy to participate in the item pipeline.
58///
59/// Implement this trait for any `Copy + Hash + Default` enum to make it usable
60/// with [`Inventory`], [`crate::items::drops::DropTable`],
61/// [`crate::items::drops::DropsPlugin`], and
62/// [`crate::items::persistence::save_inventory`] /
63/// [`crate::items::persistence::load_inventory`].
64///
65/// The framework ships [`DefaultItem`] as a ready-made implementation.
66/// Custom implementations should designate one variant as the *empty sentinel*
67/// (returned by [`Default`]) and override [`ItemType::is_empty`] accordingly.
68///
69/// # Contract
70///
71/// * `Copy + Clone` — slots are copied freely; no heap allocation per item.
72/// * `Default` — produces the empty-sentinel value.
73/// * `PartialEq + Eq + Hash` — required for slot deduplication and hash-map
74/// lookups in [`crate::items::drops::DropTable`].
75/// * `Send + Sync + 'static` — required for use as a Bevy [`Resource`] type
76/// parameter.
77/// * [`to_byte`](ItemType::to_byte) / [`from_byte`](ItemType::from_byte) —
78/// stable single-byte encoding used by the JSON persistence layer. Unknown
79/// bytes must round-trip to `Self::default()`.
80///
81/// # Examples
82///
83/// ```rust,no_run
84/// use voxel_framework::items::ItemType;
85///
86/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
87/// enum MyItem { #[default] Empty, Wood, Stone }
88///
89/// impl ItemType for MyItem {
90/// fn name(&self) -> &'static str {
91/// match self { MyItem::Empty => "Empty", MyItem::Wood => "Wood", MyItem::Stone => "Stone" }
92/// }
93/// fn color(&self) -> [f32; 4] {
94/// match self {
95/// MyItem::Empty => [0.0; 4],
96/// MyItem::Wood => [0.55, 0.35, 0.20, 1.0],
97/// MyItem::Stone => [0.50, 0.50, 0.50, 1.0],
98/// }
99/// }
100/// fn to_byte(&self) -> u8 { match self { MyItem::Empty => 0, MyItem::Wood => 1, MyItem::Stone => 2 } }
101/// fn from_byte(b: u8) -> Self { match b { 1 => MyItem::Wood, 2 => MyItem::Stone, _ => MyItem::Empty } }
102/// fn is_empty(&self) -> bool { matches!(self, MyItem::Empty) }
103/// }
104/// ```
105pub trait ItemType: Copy + Clone + Default + Send + Sync + PartialEq + Eq + Hash + 'static {
106 /// Human-readable display name for this item (e.g. `"Iron Ore"`).
107 ///
108 /// Used by UI widgets such as the pickup notification overlay.
109 fn name(&self) -> &'static str;
110
111 /// Default RGBA display colour for this item, with components in `[0.0, 1.0]`.
112 ///
113 /// Used by hotbar and inventory UI as a fallback when no sprite is available.
114 fn color(&self) -> [f32; 4];
115
116 /// Encodes this item variant as a single byte for JSON persistence.
117 ///
118 /// The mapping must be stable across game versions; changing it will
119 /// corrupt existing save files. The empty-sentinel variant should map
120 /// to `0`.
121 fn to_byte(&self) -> u8;
122
123 /// Decodes a single byte back into an item variant.
124 ///
125 /// Unknown byte values — for example from a future game version — **must**
126 /// return `Self::default()` rather than panicking so that save files from
127 /// newer versions degrade gracefully.
128 fn from_byte(b: u8) -> Self;
129
130 /// Returns `true` if this variant is the empty-slot sentinel.
131 ///
132 /// The default implementation returns `false`; override it for the variant
133 /// that represents "nothing here" (typically the `Default` variant).
134 fn is_empty(&self) -> bool {
135 false
136 }
137
138 /// Tool level provided when this item is the active hotbar selection.
139 ///
140 /// `0` = bare hands. Matched against [`crate::voxel::VoxelType::mining_level`]:
141 /// if `tool_level < voxel.mining_level()`, mining makes no progress.
142 ///
143 /// Default: `0`.
144 fn tool_level(&self) -> u8 {
145 0
146 }
147
148 /// Mining speed multiplier when this item is the active tool.
149 ///
150 /// The effective break time is divided by this value (`2.0` = twice as fast).
151 /// Default: `1.0`.
152 fn tool_speed(&self) -> f32 {
153 1.0
154 }
155}
156
157// ─── InventorySlot ────────────────────────────────────────────────────────────
158
159/// A single occupied inventory slot, holding a stack of one item type.
160///
161/// Slots are always non-empty — "no item" is represented by `None` at the
162/// [`Inventory::slots`] level rather than a zero-count `InventorySlot`.
163/// The `count` field is therefore always `>= 1` in practice; the drop systems
164/// never produce a zero-count slot.
165#[derive(Debug, Clone, PartialEq)]
166pub struct InventorySlot<I: ItemType> {
167 /// The item type stored in this slot.
168 pub item: I,
169 /// Number of items in the stack. Always `>= 1` for a live slot.
170 pub count: u32,
171}
172
173// ─── Inventory ────────────────────────────────────────────────────────────────
174
175/// Fixed-capacity player inventory backed by a flat slot vector.
176///
177/// The inventory holds up to `capacity` stacks, each stored as
178/// `Option<`[`InventorySlot`]`<I>>`. `None` denotes an empty slot.
179///
180/// Items of the same type are automatically stacked: [`Inventory::add`]
181/// fills existing stacks of the matching type before opening a new slot.
182/// [`Inventory::remove`] drains stacks in order and clears slots that reach
183/// zero.
184///
185/// The default capacity is 36 slots (4 rows × 9 columns), matching the
186/// standard Minecraft-style layout expected by the built-in hotbar and
187/// inventory UI widgets.
188///
189/// # Examples
190///
191/// ```rust,no_run
192/// use voxel_framework::items::{Inventory, DefaultItem};
193///
194/// let mut inv = Inventory::<DefaultItem>::new(9);
195/// inv.add(DefaultItem::IronOre, 5);
196/// assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
197/// ```
198#[derive(Resource, Debug, Clone)]
199pub struct Inventory<I: ItemType> {
200 /// The backing slot vector. `None` at index `i` means slot `i` is empty.
201 ///
202 /// The length always equals `capacity`; slots are never removed from the
203 /// vector.
204 pub slots: Vec<Option<InventorySlot<I>>>,
205 /// Maximum number of distinct item stacks the inventory can hold.
206 ///
207 /// Set at construction time; cannot be changed after the fact without
208 /// rebuilding the inventory.
209 pub capacity: usize,
210}
211
212impl<I: ItemType> Inventory<I> {
213 /// Creates a new empty inventory with the given slot capacity.
214 pub fn new(capacity: usize) -> Self {
215 Self {
216 slots: vec![None; capacity],
217 capacity,
218 }
219 }
220
221 /// Adds `count` of `item` to the inventory.
222 ///
223 /// Items are stacked onto existing slots of the same type first, then into
224 /// empty slots. Returns the number of items that could **not** be added
225 /// because the inventory is full.
226 pub fn add(&mut self, item: I, count: u32) -> u32 {
227 let mut remaining = count;
228
229 // First pass: fill existing stacks.
230 for slot in self.slots.iter_mut().flatten() {
231 if remaining == 0 {
232 break;
233 }
234 if slot.item == item {
235 slot.count += remaining;
236 remaining = 0;
237 }
238 }
239
240 // Second pass: open new slots for leftovers.
241 if remaining > 0 {
242 for slot in self.slots.iter_mut() {
243 if remaining == 0 {
244 break;
245 }
246 if slot.is_none() {
247 *slot = Some(InventorySlot {
248 item,
249 count: remaining,
250 });
251 remaining = 0;
252 }
253 }
254 }
255
256 remaining
257 }
258
259 /// Removes up to `count` of `item` from the inventory.
260 ///
261 /// Returns the number of items that were actually removed (may be less than
262 /// `count` if the inventory held fewer).
263 pub fn remove(&mut self, item: I, count: u32) -> u32 {
264 let mut to_remove = count;
265 let mut removed = 0u32;
266
267 for slot in self.slots.iter_mut() {
268 if to_remove == 0 {
269 break;
270 }
271 if let Some(s) = slot {
272 if s.item == item {
273 let take = s.count.min(to_remove);
274 s.count -= take;
275 to_remove -= take;
276 removed += take;
277 if s.count == 0 {
278 *slot = None;
279 }
280 }
281 }
282 }
283
284 removed
285 }
286
287 /// Returns the total number of `item` across all slots.
288 pub fn count_of(&self, item: I) -> u32 {
289 self.slots
290 .iter()
291 .flatten()
292 .filter(|s| s.item == item)
293 .map(|s| s.count)
294 .sum()
295 }
296
297 /// Returns `true` if every slot is occupied.
298 pub fn is_full(&self) -> bool {
299 self.slots.iter().all(|s| s.is_some())
300 }
301}
302
303impl<I: ItemType> Default for Inventory<I> {
304 /// Creates a default inventory with 36 slots (4 rows × 9 columns).
305 fn default() -> Self {
306 Self::new(36)
307 }
308}
309
310// ─── Container impl for Inventory ────────────────────────────────────────────
311
312impl<I: ItemType> Container<I> for Inventory<I> {
313 fn add(&mut self, item: I, count: u32) -> u32 {
314 Inventory::add(self, item, count)
315 }
316
317 fn remove(&mut self, item: I, count: u32) -> u32 {
318 Inventory::remove(self, item, count)
319 }
320
321 fn count_of(&self, item: I) -> u32 {
322 Inventory::count_of(self, item)
323 }
324
325 fn capacity(&self) -> usize {
326 self.capacity
327 }
328
329 fn is_full(&self) -> bool {
330 Inventory::is_full(self)
331 }
332
333 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
334 self.slots.iter().map(|s| s.as_ref())
335 }
336
337 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
338 self.slots.get(index).and_then(|s| s.as_ref())
339 }
340}
341
342// ─── ContainerComponent ───────────────────────────────────────────────────────
343
344/// Bevy [`Component`] newtype that wraps an [`Inventory<I>`] for use in the
345/// entity-based item pipeline.
346///
347/// Add this alongside [`PrimaryContainer`] on the player entity so the magnet,
348/// hotbar, and crafting systems can locate the player's inventory via ECS
349/// queries instead of a global resource.
350///
351/// # Examples
352///
353/// ```rust,no_run
354/// use bevy::prelude::*;
355/// use voxel_framework::items::{ContainerComponent, PrimaryContainer, DefaultItem};
356///
357/// fn spawn_player(mut commands: Commands) {
358/// commands.spawn((
359/// ContainerComponent::<DefaultItem>::new(36),
360/// PrimaryContainer,
361/// ));
362/// }
363/// ```
364#[derive(Component)]
365pub struct ContainerComponent<I: ItemType>(pub Inventory<I>);
366
367impl<I: ItemType> ContainerComponent<I> {
368 /// Creates a new `ContainerComponent` wrapping a fresh [`Inventory`] with
369 /// the given `capacity`.
370 pub fn new(capacity: usize) -> Self {
371 Self(Inventory::new(capacity))
372 }
373}
374
375impl<I: ItemType> Container<I> for ContainerComponent<I> {
376 fn add(&mut self, item: I, count: u32) -> u32 {
377 self.0.add(item, count)
378 }
379
380 fn remove(&mut self, item: I, count: u32) -> u32 {
381 self.0.remove(item, count)
382 }
383
384 fn count_of(&self, item: I) -> u32 {
385 self.0.count_of(item)
386 }
387
388 fn capacity(&self) -> usize {
389 self.0.capacity
390 }
391
392 fn is_full(&self) -> bool {
393 self.0.is_full()
394 }
395
396 fn iter_slots(&self) -> impl Iterator<Item = Option<&InventorySlot<I>>> {
397 self.0.slots.iter().map(|s| s.as_ref())
398 }
399
400 fn slot_at(&self, index: usize) -> Option<&InventorySlot<I>> {
401 self.0.slots.get(index).and_then(|s| s.as_ref())
402 }
403}
404
405// ─── PrimaryContainer marker ──────────────────────────────────────────────────
406
407/// Zero-size marker component that identifies the entity whose
408/// [`ContainerComponent`] is the player's primary backpack.
409///
410/// Exactly one entity should carry this marker at runtime. If zero or more
411/// than one exist, the pickup and hotbar systems skip silently — no panic.
412#[derive(Component, Default)]
413pub struct PrimaryContainer;
414
415// ─── Messages ────────────────────────────────────────────────────────────────
416
417/// Message emitted when one or more items are successfully added to the inventory.
418///
419/// The magnet system in [`crate::items::drops`] writes this message after
420/// adding items to [`Inventory`]. UI systems — such as the pickup notification
421/// overlay — subscribe to this message to display transient feedback.
422///
423/// Note: this message is only written when at least one item was actually
424/// inserted (i.e. `count > 0`). If the inventory was full the message is
425/// **not** written even though a pickup was attempted.
426#[derive(Message, Debug, Clone)]
427pub struct ItemPickedUp<I: ItemType> {
428 /// The item type that was picked up.
429 pub item: I,
430 /// Number of items that were successfully inserted. Always `>= 1`.
431 pub count: u32,
432}
433
434// ─── DefaultItem ─────────────────────────────────────────────────────────────
435
436/// Built-in item type covering common mineral pickups.
437///
438/// `DefaultItem` is the item counterpart of [`crate::voxel::DefaultVoxel`]:
439/// it implements [`ItemType`] out of the box and is wired into the default
440/// [`crate::items::drops::DropTable`] entries provided by the framework.
441///
442/// `Empty` is the empty-slot sentinel returned by [`Default`] and by
443/// [`ItemType::from_byte`] for unknown byte values. It should never appear
444/// as a real collectible.
445///
446/// # Examples
447///
448/// ```rust,no_run
449/// use voxel_framework::items::{DefaultItem, Inventory};
450///
451/// let mut inv = Inventory::<DefaultItem>::new(9);
452/// inv.add(DefaultItem::Crystal, 3);
453/// ```
454#[derive(
455 Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
456)]
457pub enum DefaultItem {
458 /// Empty slot sentinel — not a real item; returned by [`Default`].
459 #[default]
460 Empty,
461 /// Dirt block; placeable Dirt voxel item (byte 2, matches DefaultTerrainVoxel::Dirt).
462 Dirt,
463 /// Sand block; placeable Sand voxel item (byte 4, matches DefaultTerrainVoxel::Sand).
464 Sand,
465 /// Wood log block; placeable Wood voxel item (byte 5, matches DefaultTerrainVoxel::Wood).
466 Wood,
467 /// Gravel block; placeable Gravel voxel item (byte 7, matches DefaultTerrainVoxel::Gravel).
468 Gravel,
469 /// Snow block; placeable Snow voxel item (byte 8, matches DefaultTerrainVoxel::Snow).
470 Snow,
471 /// Coal ore block; placeable CoalOre voxel item (byte 10, matches DefaultTerrainVoxel::CoalOre).
472 CoalOre,
473 /// Iron ore block; placeable IronOre voxel item (byte 11, matches DefaultTerrainVoxel::IronOre).
474 IronOre,
475 /// Cobblestone block; placeable Cobblestone voxel item (byte 12).
476 Cobblestone,
477 /// Sandstone block; placeable Sandstone voxel item (byte 13).
478 Sandstone,
479 /// Wooden planks block; placeable Planks voxel item (byte 14).
480 Planks,
481 /// Fired clay brick block; placeable Brick voxel item (byte 15).
482 Brick,
483 /// Coal lump; dropped from CoalOre voxels (byte 16).
484 Coal,
485 /// Smelted iron ingot; produced from IronOre (byte 17).
486 IronIngot,
487 /// Wood log; dropped from Wood voxels (byte 18).
488 Log,
489 /// Snowball; dropped from Snow voxels (byte 19).
490 Snowball,
491 /// Fragment of common rock; drops from Stone voxels (byte 20).
492 RockFragment,
493 /// Silicon crystal shard; drops from crystal voxels (byte 21).
494 Crystal,
495 /// Rare mineral node; drops from high-value voxels (byte 22).
496 RareMineral,
497 /// Wooden pickaxe — tool level 1, normal speed. Crafted from wood (byte 23).
498 WoodenPickaxe,
499 /// Stone pickaxe — tool level 1, 2× speed. Crafted from rock fragments (byte 24).
500 StonePickaxe,
501 /// Iron pickaxe — tool level 2, 4× speed. Crafted from iron ore (byte 25).
502 IronPickaxe,
503 /// Deprecated alias for IronOre block — maps to byte 11 on write, never returned by from_byte.
504 IronOreItem,
505}
506
507impl ItemType for DefaultItem {
508 fn name(&self) -> &'static str {
509 match self {
510 DefaultItem::Empty => "Empty",
511 DefaultItem::Dirt => "Dirt",
512 DefaultItem::Sand => "Sand",
513 DefaultItem::Wood => "Wood",
514 DefaultItem::Gravel => "Gravel",
515 DefaultItem::Snow => "Snow",
516 DefaultItem::CoalOre => "Coal Ore",
517 DefaultItem::IronOre => "Iron Ore",
518 DefaultItem::IronOreItem => "Iron Ore",
519 DefaultItem::Cobblestone => "Cobblestone",
520 DefaultItem::Sandstone => "Sandstone",
521 DefaultItem::Planks => "Planks",
522 DefaultItem::Brick => "Brick",
523 DefaultItem::Coal => "Coal",
524 DefaultItem::IronIngot => "Iron Ingot",
525 DefaultItem::Log => "Log",
526 DefaultItem::Snowball => "Snowball",
527 DefaultItem::RockFragment => "Rock Fragment",
528 DefaultItem::Crystal => "Crystal",
529 DefaultItem::RareMineral => "Rare Mineral",
530 DefaultItem::WoodenPickaxe => "Wooden Pickaxe",
531 DefaultItem::StonePickaxe => "Stone Pickaxe",
532 DefaultItem::IronPickaxe => "Iron Pickaxe",
533 }
534 }
535
536 fn color(&self) -> [f32; 4] {
537 match self {
538 DefaultItem::Empty => [0.0, 0.0, 0.0, 0.0],
539 // Block-items: delegate to the matching voxel color for visual consistency.
540 DefaultItem::Dirt
541 | DefaultItem::Sand
542 | DefaultItem::Wood
543 | DefaultItem::Gravel
544 | DefaultItem::Snow
545 | DefaultItem::CoalOre
546 | DefaultItem::IronOre
547 | DefaultItem::IronOreItem
548 | DefaultItem::Cobblestone
549 | DefaultItem::Sandstone
550 | DefaultItem::Planks
551 | DefaultItem::Brick => DefaultTerrainVoxel::from_byte(self.to_byte()).color(),
552 // Processed / dropped items — explicit colors.
553 DefaultItem::Coal => [0.15, 0.15, 0.15, 1.0],
554 DefaultItem::IronIngot => [0.75, 0.65, 0.55, 1.0],
555 DefaultItem::Log => [0.40, 0.28, 0.12, 1.0],
556 DefaultItem::Snowball => [0.92, 0.95, 1.00, 1.0],
557 DefaultItem::RockFragment => [0.35, 0.30, 0.28, 1.0],
558 DefaultItem::Crystal => [0.40, 0.50, 0.80, 1.0],
559 DefaultItem::RareMineral => [0.20, 0.85, 0.60, 1.0],
560 // Tools.
561 DefaultItem::WoodenPickaxe => [0.55, 0.35, 0.20, 1.0],
562 DefaultItem::StonePickaxe => [0.50, 0.50, 0.50, 1.0],
563 DefaultItem::IronPickaxe => [0.70, 0.75, 0.80, 1.0],
564 }
565 }
566
567 fn to_byte(&self) -> u8 {
568 match self {
569 DefaultItem::Empty => 0,
570 // Block-items: bytes match DefaultTerrainVoxel::to_byte()
571 DefaultItem::Dirt => 2,
572 DefaultItem::Sand => 4,
573 DefaultItem::Wood => 5,
574 DefaultItem::Gravel => 7,
575 DefaultItem::Snow => 8,
576 DefaultItem::CoalOre => 10,
577 DefaultItem::IronOre => 11,
578 DefaultItem::IronOreItem => 11, // deprecated alias; collapses to IronOre byte
579 DefaultItem::Cobblestone => 12,
580 DefaultItem::Sandstone => 13,
581 DefaultItem::Planks => 14,
582 DefaultItem::Brick => 15,
583 // Processed / dropped items
584 DefaultItem::Coal => 16,
585 DefaultItem::IronIngot => 17,
586 DefaultItem::Log => 18,
587 DefaultItem::Snowball => 19,
588 DefaultItem::RockFragment => 20,
589 DefaultItem::Crystal => 21,
590 DefaultItem::RareMineral => 22,
591 DefaultItem::WoodenPickaxe => 23,
592 DefaultItem::StonePickaxe => 24,
593 DefaultItem::IronPickaxe => 25,
594 }
595 }
596
597 fn from_byte(b: u8) -> Self {
598 match b {
599 // Block-items (bytes 2–15 mirror DefaultTerrainVoxel)
600 2 => DefaultItem::Dirt,
601 4 => DefaultItem::Sand,
602 5 => DefaultItem::Wood,
603 7 => DefaultItem::Gravel,
604 8 => DefaultItem::Snow,
605 10 => DefaultItem::CoalOre,
606 11 => DefaultItem::IronOre,
607 12 => DefaultItem::Cobblestone,
608 13 => DefaultItem::Sandstone,
609 14 => DefaultItem::Planks,
610 15 => DefaultItem::Brick,
611 // Processed / dropped items
612 16 => DefaultItem::Coal,
613 17 => DefaultItem::IronIngot,
614 18 => DefaultItem::Log,
615 19 => DefaultItem::Snowball,
616 20 => DefaultItem::RockFragment,
617 21 => DefaultItem::Crystal,
618 22 => DefaultItem::RareMineral,
619 23 => DefaultItem::WoodenPickaxe,
620 24 => DefaultItem::StonePickaxe,
621 25 => DefaultItem::IronPickaxe,
622 // Bytes 0, 1, 3, 6, 9 and anything else → Empty
623 _ => DefaultItem::Empty,
624 }
625 }
626
627 fn is_empty(&self) -> bool {
628 matches!(self, DefaultItem::Empty)
629 }
630
631 fn tool_level(&self) -> u8 {
632 match self {
633 DefaultItem::WoodenPickaxe => 1,
634 DefaultItem::StonePickaxe => 1,
635 DefaultItem::IronPickaxe => 2,
636 _ => 0,
637 }
638 }
639
640 fn tool_speed(&self) -> f32 {
641 match self {
642 DefaultItem::WoodenPickaxe => 1.0,
643 DefaultItem::StonePickaxe => 2.0,
644 DefaultItem::IronPickaxe => 4.0,
645 _ => 1.0,
646 }
647 }
648}
649
650// ─── Tests ───────────────────────────────────────────────────────────────────
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655
656 // ── add ──────────────────────────────────────────────────────────────────
657
658 #[test]
659 fn test_inventory_add_and_count() {
660 let mut inv = Inventory::<DefaultItem>::new(9);
661 let leftover = inv.add(DefaultItem::IronOre, 5);
662 assert_eq!(leftover, 0);
663 assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
664 }
665
666 #[test]
667 fn test_inventory_add_stacks_same_type() {
668 let mut inv = Inventory::<DefaultItem>::new(9);
669 inv.add(DefaultItem::Crystal, 3);
670 inv.add(DefaultItem::Crystal, 7);
671 assert_eq!(inv.count_of(DefaultItem::Crystal), 10);
672 // Should occupy only one slot.
673 let filled = inv.slots.iter().filter(|s| s.is_some()).count();
674 assert_eq!(filled, 1);
675 }
676
677 // ── remove ───────────────────────────────────────────────────────────────
678
679 #[test]
680 fn test_inventory_remove() {
681 let mut inv = Inventory::<DefaultItem>::new(9);
682 inv.add(DefaultItem::RockFragment, 10);
683 let removed = inv.remove(DefaultItem::RockFragment, 4);
684 assert_eq!(removed, 4);
685 assert_eq!(inv.count_of(DefaultItem::RockFragment), 6);
686 }
687
688 #[test]
689 fn test_inventory_remove_more_than_held_returns_actual() {
690 let mut inv = Inventory::<DefaultItem>::new(9);
691 inv.add(DefaultItem::RareMineral, 3);
692 let removed = inv.remove(DefaultItem::RareMineral, 10);
693 assert_eq!(removed, 3);
694 assert_eq!(inv.count_of(DefaultItem::RareMineral), 0);
695 }
696
697 #[test]
698 fn test_inventory_remove_clears_slot() {
699 let mut inv = Inventory::<DefaultItem>::new(9);
700 inv.add(DefaultItem::IronOre, 2);
701 inv.remove(DefaultItem::IronOre, 2);
702 assert!(inv.slots[0].is_none());
703 }
704
705 // ── full ─────────────────────────────────────────────────────────────────
706
707 #[test]
708 fn test_inventory_full() {
709 let mut inv = Inventory::<DefaultItem>::new(2);
710 inv.add(DefaultItem::IronOre, 1);
711 inv.add(DefaultItem::Crystal, 1);
712 assert!(inv.is_full());
713
714 // Adding more should return a leftover.
715 let leftover = inv.add(DefaultItem::RockFragment, 5);
716 assert_eq!(leftover, 5);
717 }
718
719 // ── Container trait via Inventory ─────────────────────────────────────────
720
721 #[test]
722 fn container_trait_add_and_count() {
723 let mut inv = Inventory::<DefaultItem>::new(9);
724 let leftover = Container::add(&mut inv, DefaultItem::IronOre, 5);
725 assert_eq!(leftover, 0);
726 assert_eq!(Container::count_of(&inv, DefaultItem::IronOre), 5);
727 }
728
729 #[test]
730 fn container_slot_at_out_of_bounds_returns_none() {
731 let inv = Inventory::<DefaultItem>::new(9);
732 assert!(Container::slot_at(&inv, 100).is_none());
733 }
734
735 #[test]
736 fn container_iter_slots_yields_capacity_items() {
737 let inv = Inventory::<DefaultItem>::new(9);
738 assert_eq!(Container::iter_slots(&inv).count(), 9);
739 }
740
741 // ── ContainerComponent ───────────────────────────────────────────────────
742
743 #[test]
744 fn container_component_delegates_correctly() {
745 let mut cc = ContainerComponent::<DefaultItem>::new(9);
746 cc.add(DefaultItem::Crystal, 3);
747 assert_eq!(cc.count_of(DefaultItem::Crystal), 3);
748 assert_eq!(cc.0.count_of(DefaultItem::Crystal), 3);
749 }
750
751 #[test]
752 fn container_component_slot_at_oob_no_panic() {
753 let cc = ContainerComponent::<DefaultItem>::new(9);
754 assert!(cc.slot_at(100).is_none());
755 }
756}