Skip to main content

voxel_framework/crafting/
mod.rs

1//! Crafting system — shapeless recipes, registry, and in-game crafting menu.
2//!
3//! # Data model
4//!
5//! [`CraftingRegistry<I>`] is a Bevy resource that holds a list of
6//! [`CraftingRecipe<I>`] values. Each recipe describes a set of input
7//! ingredients and output items. Recipes are *shapeless* — only item types and
8//! counts matter, not arrangement in a grid.
9//!
10//! # Crafting logic
11//!
12//! [`try_craft`] is a pure function: it verifies that the inventory holds
13//! enough of every ingredient and produces the outputs. Built-in containers
14//! exchange atomically; legacy external containers may partially mutate on
15//! failure. [`can_craft`] checks ingredients only, without side effects.
16//!
17//! # UI
18//!
19//! [`CraftingPlugin<I>`] adds a crafting menu toggled by the `C` key.
20//! The menu lists every registered recipe and highlights those the player can
21//! currently craft. Clicking a highlighted row invokes [`try_craft`].
22//!
23//! # Integration
24//!
25//! ```no_run
26//! use bevy::prelude::*;
27//! use voxel_framework::crafting::{CraftingPlugin, CraftingRecipe, CraftingIngredient, CraftingRegistry};
28//! use voxel_framework::items::DefaultItem;
29//!
30//! App::new()
31//!     .add_plugins(CraftingPlugin::<DefaultItem>::new())
32//!     .add_systems(Startup, register_recipes);
33//!
34//! fn register_recipes(mut registry: ResMut<CraftingRegistry<DefaultItem>>) {
35//!     registry.add(CraftingRecipe {
36//!         name: "Crystal from Ore",
37//!         ingredients: vec![CraftingIngredient { item: DefaultItem::IronOre, count: 4 }],
38//!         outputs:     vec![CraftingIngredient { item: DefaultItem::Crystal,  count: 1 }],
39//!     });
40//! }
41//! ```
42
43use std::marker::PhantomData;
44
45use bevy::prelude::*;
46
47use crate::items::ItemType;
48use crate::items::inventory::{
49    Container, ContainerComponent, ContainerExchangeError, PrimaryContainer, normalize_quantities,
50};
51
52// ─── Data layer ───────────────────────────────────────────────────────────────
53
54/// A single ingredient entry: the item type and the required or produced quantity.
55#[derive(Debug, Clone)]
56pub struct CraftingIngredient<I> {
57    /// The item type consumed or produced.
58    pub item: I,
59    /// How many items are consumed or produced.
60    pub count: u32,
61}
62
63/// A shapeless crafting recipe: consume [`ingredients`](CraftingRecipe::ingredients),
64/// produce [`outputs`](CraftingRecipe::outputs).
65///
66/// "Shapeless" means arrangement in a crafting grid is not modelled — only item
67/// types and counts matter. Duplicate entries aggregate by item equality in
68/// first-occurrence order with checked `u32` totals. Zero entries are ignored;
69/// empty recipes are allowed. Positive default/empty sentinels are invalid.
70#[derive(Debug, Clone)]
71pub struct CraftingRecipe<I> {
72    /// Short human-readable name shown in the crafting menu.
73    pub name: &'static str,
74    /// Items consumed from the player's inventory when this recipe is crafted.
75    pub ingredients: Vec<CraftingIngredient<I>>,
76    /// Items added to the player's inventory when this recipe is crafted.
77    pub outputs: Vec<CraftingIngredient<I>>,
78}
79
80/// Registry of all crafting recipes available in the game.
81///
82/// Inserted automatically by [`CraftingPlugin`] as an empty resource.
83/// Populate it from a startup system before the crafting menu is first opened.
84#[derive(Resource, Debug, Clone, Default)]
85pub struct CraftingRegistry<I: ItemType> {
86    /// Ordered list of registered recipes. Indices are stable for the session.
87    pub recipes: Vec<CraftingRecipe<I>>,
88}
89
90impl<I: ItemType> CraftingRegistry<I> {
91    /// Appends a recipe to the registry.
92    pub fn add(&mut self, recipe: CraftingRecipe<I>) {
93        self.recipes.push(recipe);
94    }
95}
96
97// ─── Pure crafting functions ──────────────────────────────────────────────────
98
99/// Reason a craft attempt failed.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub enum CraftingError {
102    /// The index is missing, or the recipe contains a sentinel or quantity overflow.
103    InvalidRecipe,
104    /// The inventory does not hold enough of one or more ingredients.
105    InsufficientIngredients,
106    /// The container is invalid or lacks slot/numeric capacity for the outputs.
107    InventoryFull,
108}
109
110// Both lists are validated before ingredients or capacity are considered.
111fn normalized_recipe<I: ItemType>(
112    recipe: &CraftingRecipe<I>,
113) -> Result<NormalizedRecipe<I>, CraftingError> {
114    let normalize = |entries: &[CraftingIngredient<I>]| {
115        let quantities: Vec<_> = entries
116            .iter()
117            .map(|entry| (entry.item, entry.count))
118            .collect();
119        normalize_quantities(&quantities).map_err(|_| CraftingError::InvalidRecipe)
120    };
121    Ok(NormalizedRecipe {
122        remove: normalize(&recipe.ingredients)?,
123        add: normalize(&recipe.outputs)?,
124    })
125}
126
127struct NormalizedRecipe<I> {
128    remove: Vec<(I, u32)>,
129    add: Vec<(I, u32)>,
130}
131
132/// Returns `true` for a valid recipe whose aggregate ingredients are available.
133///
134/// Does **not** mutate or check output capacity. Invalid outputs still make the
135/// recipe invalid, even though this check otherwise concerns ingredients only.
136pub fn can_craft<I: ItemType>(
137    registry: &CraftingRegistry<I>,
138    inventory: &impl Container<I>,
139    recipe_index: usize,
140) -> bool {
141    registry
142        .recipes
143        .get(recipe_index)
144        .and_then(|recipe| normalized_recipe(recipe).ok())
145        .is_some_and(|recipe| {
146            recipe
147                .remove
148                .iter()
149                .all(|&(item, count)| inventory.count_of(item) >= count)
150        })
151}
152
153/// Attempts to craft a normalized recipe, consuming ingredients and producing outputs.
154///
155/// # Atomicity
156///
157/// Built-in containers and external containers opting into
158/// [`Container::try_exchange_atomic`] complete the whole exchange or leave the
159/// container unchanged, evaluating capacity after consumption.
160///
161/// Legacy containers returning `None` use conservative **current** free space
162/// (no credit for slots consumption might free). All preflight checks happen
163/// before mutation, but a subsequent short removal or leftover output returns
164/// an error immediately and **may leave partial mutation**. No rollback is
165/// invented for arbitrary external storage. Success requires exact removal and
166/// insertion returns for every normalized quantity.
167pub fn try_craft<I: ItemType>(
168    registry: &CraftingRegistry<I>,
169    inventory: &mut impl Container<I>,
170    recipe_index: usize,
171) -> Result<(), CraftingError> {
172    let recipe = normalized_recipe(
173        registry
174            .recipes
175            .get(recipe_index)
176            .ok_or(CraftingError::InvalidRecipe)?,
177    )?;
178
179    if let Some(result) = inventory.try_exchange_atomic(&recipe.remove, &recipe.add) {
180        // The public neutral enum is extensible; future errors remain failures.
181        #[allow(unreachable_patterns)]
182        return result.map_err(|error| match error {
183            ContainerExchangeError::InvalidRequest => CraftingError::InvalidRecipe,
184            ContainerExchangeError::InsufficientItems => CraftingError::InsufficientIngredients,
185            ContainerExchangeError::InvalidContainer | ContainerExchangeError::CapacityExceeded => {
186                CraftingError::InventoryFull
187            }
188            _ => CraftingError::InventoryFull,
189        });
190    }
191
192    for &(item, count) in &recipe.remove {
193        if inventory.count_of(item) < count {
194            return Err(CraftingError::InsufficientIngredients);
195        }
196    }
197    let occupied = inventory.iter_slots().filter(|slot| slot.is_some()).count();
198    let free_slots = inventory
199        .capacity()
200        .checked_sub(occupied)
201        .ok_or(CraftingError::InventoryFull)?;
202    let new_types = recipe
203        .add
204        .iter()
205        .filter(|&&(item, _)| inventory.count_of(item) == 0)
206        .count();
207    if new_types > free_slots {
208        return Err(CraftingError::InventoryFull);
209    }
210    for &(item, count) in &recipe.add {
211        let removed = recipe
212            .remove
213            .iter()
214            .find(|&&(input, _)| input == item)
215            .map_or(0, |&(_, count)| count);
216        let projected = u64::from(inventory.count_of(item))
217            .checked_sub(u64::from(removed))
218            .ok_or(CraftingError::InsufficientIngredients)?
219            + u64::from(count);
220        if projected > u64::from(u32::MAX) {
221            return Err(CraftingError::InventoryFull);
222        }
223    }
224    for (item, count) in recipe.remove {
225        if inventory.remove(item, count) != count {
226            return Err(CraftingError::InsufficientIngredients);
227        }
228    }
229    for (item, count) in recipe.add {
230        if inventory.add(item, count) != 0 {
231            return Err(CraftingError::InventoryFull);
232        }
233    }
234    Ok(())
235}
236
237// ─── UI state ────────────────────────────────────────────────────────────────
238
239/// Runtime state of the crafting menu.
240#[derive(Resource, Default)]
241pub struct CraftingMenuState {
242    /// Whether the crafting menu is currently visible.
243    pub visible: bool,
244    /// Dirty flag: set to `true` to trigger a full UI rebuild on next frame.
245    rebuild: bool,
246}
247
248// ─── UI markers ───────────────────────────────────────────────────────────────
249
250/// Marker component on the root crafting menu panel.
251#[derive(Component)]
252struct CraftingMenuRoot;
253
254/// Marker component on each recipe row in the crafting menu.
255///
256/// `usize::MAX` is used as a sentinel for header/footer rows that are not
257/// interactive recipes.
258#[derive(Component)]
259struct CraftingRecipeRow {
260    recipe_index: usize,
261}
262
263// ─── Systems ──────────────────────────────────────────────────────────────────
264
265fn spawn_crafting_menu(mut commands: Commands) {
266    commands.spawn((
267        CraftingMenuRoot,
268        Node {
269            position_type: PositionType::Absolute,
270            right: Val::Px(10.0),
271            top: Val::Px(60.0),
272            width: Val::Px(340.0),
273            max_height: Val::Vh(75.0),
274            flex_direction: FlexDirection::Column,
275            padding: UiRect::all(Val::Px(10.0)),
276            row_gap: Val::Px(4.0),
277            overflow: Overflow::clip_y(),
278            ..default()
279        },
280        BackgroundColor(Color::srgba(0.04, 0.04, 0.04, 0.88)),
281        Visibility::Hidden,
282    ));
283}
284
285fn toggle_crafting_menu(keys: Res<ButtonInput<KeyCode>>, mut state: ResMut<CraftingMenuState>) {
286    if keys.just_pressed(KeyCode::KeyC) {
287        state.visible = !state.visible;
288        if state.visible {
289            state.rebuild = true;
290        }
291    }
292    // ESC closes crafting menu if open (without consuming the event — pause menu
293    // handles its own ESC separately).
294    if keys.just_pressed(KeyCode::Escape) && state.visible {
295        state.visible = false;
296    }
297}
298
299fn sync_crafting_visibility(
300    state: Res<CraftingMenuState>,
301    mut root_q: Query<&mut Visibility, With<CraftingMenuRoot>>,
302) {
303    if !state.is_changed() {
304        return;
305    }
306    let Ok(mut vis) = root_q.single_mut() else {
307        return;
308    };
309    *vis = if state.visible {
310        Visibility::Visible
311    } else {
312        Visibility::Hidden
313    };
314}
315
316fn rebuild_crafting_menu<I: ItemType>(
317    mut commands: Commands,
318    mut state: ResMut<CraftingMenuState>,
319    registry: Res<CraftingRegistry<I>>,
320    root_q: Query<Entity, With<CraftingMenuRoot>>,
321    row_q: Query<Entity, With<CraftingRecipeRow>>,
322) {
323    if !state.rebuild {
324        return;
325    }
326    state.rebuild = false;
327
328    // Despawn stale rows.
329    for e in row_q.iter() {
330        commands.entity(e).despawn();
331    }
332
333    let Ok(root) = root_q.single() else {
334        return;
335    };
336
337    // Header.
338    let header = commands
339        .spawn((
340            CraftingRecipeRow {
341                recipe_index: usize::MAX,
342            },
343            Node {
344                padding: UiRect::bottom(Val::Px(6.0)),
345                ..default()
346            },
347            Text::new("-- Crafting (C to close) --"),
348            TextFont {
349                font_size: 15.0,
350                ..default()
351            },
352            TextColor(Color::WHITE),
353        ))
354        .id();
355    commands.entity(root).add_child(header);
356
357    if registry.recipes.is_empty() {
358        let empty = commands
359            .spawn((
360                CraftingRecipeRow {
361                    recipe_index: usize::MAX,
362                },
363                Text::new("No recipes registered."),
364                TextFont {
365                    font_size: 13.0,
366                    ..default()
367                },
368                TextColor(Color::srgb(0.55, 0.55, 0.55)),
369            ))
370            .id();
371        commands.entity(root).add_child(empty);
372        return;
373    }
374
375    // One row per recipe.
376    for (i, recipe) in registry.recipes.iter().enumerate() {
377        let ing_str = recipe
378            .ingredients
379            .iter()
380            .map(|ing| format!("{} ×{}", ing.item.name(), ing.count))
381            .collect::<Vec<_>>()
382            .join(", ");
383        let out_str = recipe
384            .outputs
385            .iter()
386            .map(|out| format!("{} ×{}", out.item.name(), out.count))
387            .collect::<Vec<_>>()
388            .join(", ");
389
390        let label = format!("[{}]  {} > {}", recipe.name, ing_str, out_str);
391
392        let row = commands
393            .spawn((
394                CraftingRecipeRow { recipe_index: i },
395                Button,
396                Node {
397                    padding: UiRect::all(Val::Px(6.0)),
398                    width: Val::Percent(100.0),
399                    ..default()
400                },
401                BackgroundColor(Color::srgba(0.15, 0.15, 0.15, 0.90)),
402                Text::new(label),
403                TextFont {
404                    font_size: 12.0,
405                    ..default()
406                },
407                TextColor(Color::srgb(0.70, 0.70, 0.70)),
408            ))
409            .id();
410        commands.entity(root).add_child(row);
411    }
412
413    // Footer hint.
414    let footer = commands
415        .spawn((
416            CraftingRecipeRow {
417                recipe_index: usize::MAX,
418            },
419            Node {
420                padding: UiRect::top(Val::Px(6.0)),
421                ..default()
422            },
423            Text::new("Green = craftable  |  click to craft"),
424            TextFont {
425                font_size: 11.0,
426                ..default()
427            },
428            TextColor(Color::srgb(0.45, 0.45, 0.45)),
429        ))
430        .id();
431    commands.entity(root).add_child(footer);
432}
433
434fn update_crafting_row_colors<I: ItemType>(
435    mut row_q: Query<(
436        &CraftingRecipeRow,
437        &mut BackgroundColor,
438        &mut TextColor,
439        &Interaction,
440    )>,
441    registry: Res<CraftingRegistry<I>>,
442    container_query: Query<&ContainerComponent<I>, With<PrimaryContainer>>,
443    state: Res<CraftingMenuState>,
444) {
445    if !state.visible {
446        return;
447    }
448    let Ok(container) = container_query.single() else {
449        return;
450    };
451    for (row, mut bg, mut tc, interaction) in row_q.iter_mut() {
452        if row.recipe_index == usize::MAX {
453            continue;
454        }
455        let craftable = can_craft(&registry, &container.0, row.recipe_index);
456        let hovered = matches!(interaction, Interaction::Hovered | Interaction::Pressed);
457
458        *bg = match (craftable, hovered) {
459            (true, true) => BackgroundColor(Color::srgba(0.18, 0.50, 0.18, 0.95)),
460            (true, false) => BackgroundColor(Color::srgba(0.10, 0.28, 0.10, 0.90)),
461            (false, true) => BackgroundColor(Color::srgba(0.25, 0.25, 0.25, 0.90)),
462            (false, false) => BackgroundColor(Color::srgba(0.15, 0.15, 0.15, 0.90)),
463        };
464        *tc = if craftable {
465            TextColor(Color::srgb(0.82, 1.0, 0.82))
466        } else {
467            TextColor(Color::srgb(0.45, 0.45, 0.45))
468        };
469    }
470}
471
472fn handle_craft_click<I: ItemType>(
473    row_q: Query<(&CraftingRecipeRow, &Interaction), Changed<Interaction>>,
474    registry: Res<CraftingRegistry<I>>,
475    mut container_query: Query<&mut ContainerComponent<I>, With<PrimaryContainer>>,
476    state: Res<CraftingMenuState>,
477) {
478    if !state.visible {
479        return;
480    }
481    let Ok(mut container) = container_query.single_mut() else {
482        return;
483    };
484    for (row, interaction) in row_q.iter() {
485        if row.recipe_index == usize::MAX {
486            continue;
487        }
488        if matches!(interaction, Interaction::Pressed) {
489            let _ = try_craft(&registry, &mut container.0, row.recipe_index);
490        }
491    }
492}
493
494// ─── Plugins ──────────────────────────────────────────────────────────────────
495
496/// Core crafting plugin — registers [`CraftingRegistry<I>`] only.
497///
498/// No UI, no input, no systems. Use alongside [`CraftingUiPlugin<I>`] when you
499/// want the built-in `C`-key crafting menu, or provide your own UI by reading
500/// [`CraftingRegistry<I>`] and calling [`can_craft`] / [`try_craft`] directly.
501///
502/// Mirrors the [`crate::world::MiningPlugin`] / [`crate::world::MiningInputPlugin`] split pattern.
503pub struct CraftingPlugin<I: ItemType> {
504    _m: PhantomData<I>,
505}
506
507impl<I: ItemType> CraftingPlugin<I> {
508    pub fn new() -> Self {
509        Self { _m: PhantomData }
510    }
511}
512
513impl<I: ItemType> Default for CraftingPlugin<I> {
514    fn default() -> Self {
515        Self::new()
516    }
517}
518
519impl<I: ItemType> Plugin for CraftingPlugin<I> {
520    fn build(&self, app: &mut App) {
521        app.init_resource::<CraftingRegistry<I>>();
522    }
523}
524
525/// Batteries-included crafting UI plugin.
526///
527/// Adds [`CraftingMenuState`], spawns the in-game crafting panel, and wires the
528/// `C`-key toggle, recipe highlighting, and click-to-craft. Requires
529/// [`CraftingPlugin<I>`] to have been added first (for the registry).
530///
531/// # Example
532///
533/// ```no_run
534/// use bevy::prelude::*;
535/// use voxel_framework::crafting::{CraftingPlugin, CraftingUiPlugin, CraftingRecipe, CraftingIngredient};
536/// use voxel_framework::items::DefaultItem;
537///
538/// App::new()
539///     .add_plugins(CraftingPlugin::<DefaultItem>::new())
540///     .add_plugins(CraftingUiPlugin::<DefaultItem>::new())
541///     .add_systems(Startup, register_recipes);
542///
543/// fn register_recipes(mut registry: ResMut<voxel_framework::crafting::CraftingRegistry<DefaultItem>>) {
544///     registry.add(CraftingRecipe {
545///         name: "Iron Block",
546///         ingredients: vec![CraftingIngredient { item: DefaultItem::IronOre, count: 9 }],
547///         outputs:     vec![CraftingIngredient { item: DefaultItem::Crystal,  count: 1 }],
548///     });
549/// }
550/// ```
551pub struct CraftingUiPlugin<I: ItemType> {
552    _m: PhantomData<I>,
553}
554
555impl<I: ItemType> CraftingUiPlugin<I> {
556    pub fn new() -> Self {
557        Self { _m: PhantomData }
558    }
559}
560
561impl<I: ItemType> Default for CraftingUiPlugin<I> {
562    fn default() -> Self {
563        Self::new()
564    }
565}
566
567impl<I: ItemType> Plugin for CraftingUiPlugin<I> {
568    fn build(&self, app: &mut App) {
569        app.init_resource::<CraftingMenuState>();
570        app.add_systems(Startup, spawn_crafting_menu);
571        app.add_systems(
572            Update,
573            (
574                toggle_crafting_menu,
575                sync_crafting_visibility,
576                rebuild_crafting_menu::<I>,
577                update_crafting_row_colors::<I>,
578                handle_craft_click::<I>,
579            )
580                .chain(),
581        );
582    }
583}
584
585// ─── Tests ────────────────────────────────────────────────────────────────────
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use crate::items::{DefaultItem, Inventory};
591
592    fn make_registry() -> CraftingRegistry<DefaultItem> {
593        let mut r = CraftingRegistry::default();
594        r.add(CraftingRecipe {
595            name: "Crystal from Ore",
596            ingredients: vec![CraftingIngredient {
597                item: DefaultItem::IronOre,
598                count: 4,
599            }],
600            outputs: vec![CraftingIngredient {
601                item: DefaultItem::Crystal,
602                count: 1,
603            }],
604        });
605        r.add(CraftingRecipe {
606            name: "Rare from Ore+Crystal",
607            ingredients: vec![
608                CraftingIngredient {
609                    item: DefaultItem::IronOre,
610                    count: 2,
611                },
612                CraftingIngredient {
613                    item: DefaultItem::Crystal,
614                    count: 1,
615                },
616            ],
617            outputs: vec![CraftingIngredient {
618                item: DefaultItem::RareMineral,
619                count: 1,
620            }],
621        });
622        r
623    }
624
625    #[test]
626    fn can_craft_true_when_enough_items() {
627        let registry = make_registry();
628        let mut inv = Inventory::new(9);
629        inv.add(DefaultItem::IronOre, 4);
630        assert!(can_craft(&registry, &inv, 0));
631    }
632
633    #[test]
634    fn can_craft_false_when_insufficient() {
635        let registry = make_registry();
636        let mut inv = Inventory::new(9);
637        inv.add(DefaultItem::IronOre, 3); // need 4
638        assert!(!can_craft(&registry, &inv, 0));
639    }
640
641    #[test]
642    fn can_craft_false_for_invalid_index() {
643        let registry = make_registry();
644        let inv = Inventory::<DefaultItem>::new(9);
645        assert!(!can_craft(&registry, &inv, 99));
646    }
647
648    #[test]
649    fn try_craft_consumes_ingredients_and_produces_outputs() {
650        let registry = make_registry();
651        let mut inv = Inventory::new(9);
652        inv.add(DefaultItem::IronOre, 5);
653
654        let result = try_craft(&registry, &mut inv, 0);
655        assert_eq!(result, Ok(()));
656        assert_eq!(inv.count_of(DefaultItem::IronOre), 1); // 5 - 4
657        assert_eq!(inv.count_of(DefaultItem::Crystal), 1);
658    }
659
660    #[test]
661    fn try_craft_fails_with_insufficient_ingredients() {
662        let registry = make_registry();
663        let mut inv = Inventory::new(9);
664        inv.add(DefaultItem::IronOre, 2);
665
666        let result = try_craft(&registry, &mut inv, 0);
667        assert_eq!(result, Err(CraftingError::InsufficientIngredients));
668        // Inventory unchanged.
669        assert_eq!(inv.count_of(DefaultItem::IronOre), 2);
670    }
671
672    #[test]
673    fn try_craft_fails_with_invalid_recipe() {
674        let registry = make_registry();
675        let mut inv = Inventory::new(9);
676        assert_eq!(
677            try_craft(&registry, &mut inv, 99),
678            Err(CraftingError::InvalidRecipe)
679        );
680    }
681
682    #[test]
683    fn try_craft_multi_ingredient_recipe() {
684        let registry = make_registry();
685        let mut inv = Inventory::new(9);
686        inv.add(DefaultItem::IronOre, 2);
687        inv.add(DefaultItem::Crystal, 1);
688
689        let result = try_craft(&registry, &mut inv, 1);
690        assert_eq!(result, Ok(()));
691        assert_eq!(inv.count_of(DefaultItem::IronOre), 0);
692        assert_eq!(inv.count_of(DefaultItem::Crystal), 0);
693        assert_eq!(inv.count_of(DefaultItem::RareMineral), 1);
694    }
695
696    #[test]
697    fn try_craft_inventory_full_returns_error() {
698        let registry = make_registry();
699        // Retaining an ingredient stack leaves no slot for the new output.
700        let mut inv = Inventory::new(1);
701        inv.add(DefaultItem::IronOre, 5); // one remains after consumption
702
703        // Now inventory is full (1 slot used).
704        // Crystal is a new type — needs a free slot, but none available.
705        let result = try_craft(&registry, &mut inv, 0);
706        assert_eq!(result, Err(CraftingError::InventoryFull));
707        // Ingredients not consumed.
708        assert_eq!(inv.count_of(DefaultItem::IronOre), 5);
709    }
710
711    fn registry_for<I: ItemType>(remove: &[(I, u32)], add: &[(I, u32)]) -> CraftingRegistry<I> {
712        let mut registry = CraftingRegistry::default();
713        let entries = |quantities: &[(I, u32)]| {
714            quantities
715                .iter()
716                .map(|&(item, count)| CraftingIngredient { item, count })
717                .collect()
718        };
719        registry.add(CraftingRecipe {
720            name: "regression",
721            ingredients: entries(remove),
722            outputs: entries(add),
723        });
724        registry
725    }
726
727    #[test]
728    fn duplicate_ingredients_require_aggregate_and_failure_preserves_layout() {
729        let registry = registry_for(
730            &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
731            &[(DefaultItem::Crystal, 1)],
732        );
733        let mut inv = Inventory::new(2);
734        inv.add(DefaultItem::IronOre, 3);
735        let before = inv.slots.clone();
736        assert!(!can_craft(&registry, &inv, 0));
737        assert_eq!(
738            try_craft(&registry, &mut inv, 0),
739            Err(CraftingError::InsufficientIngredients)
740        );
741        assert_eq!(inv.slots, before);
742        inv.add(DefaultItem::IronOre, 1);
743        assert!(can_craft(&registry, &inv, 0));
744        assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
745        assert_eq!(inv.count_of(DefaultItem::IronOre), 0);
746        assert_eq!(inv.count_of(DefaultItem::Crystal), 1);
747    }
748
749    #[test]
750    fn full_builtin_consumption_frees_slot_for_duplicate_outputs() {
751        let registry = registry_for(
752            &[(DefaultItem::IronOre, 4)],
753            &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
754        );
755        let mut inv = Inventory::new(1);
756        inv.add(DefaultItem::IronOre, 4);
757        assert!(can_craft(&registry, &inv, 0));
758        assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
759        assert_eq!(inv.count_of(DefaultItem::Crystal), 3);
760        assert_eq!(inv.capacity, 1);
761    }
762
763    #[test]
764    fn existing_output_stacks_and_same_input_use_post_consumption_headroom() {
765        let registry = registry_for(
766            &[(DefaultItem::IronOre, 4)],
767            &[
768                (DefaultItem::IronOre, 2),
769                (DefaultItem::IronOre, 2),
770                (DefaultItem::Crystal, 3),
771            ],
772        );
773        let mut inv = Inventory::new(2);
774        inv.add(DefaultItem::IronOre, u32::MAX);
775        inv.add(DefaultItem::Crystal, 1);
776        assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
777        assert_eq!(inv.count_of(DefaultItem::IronOre), u32::MAX);
778        assert_eq!(inv.count_of(DefaultItem::Crystal), 4);
779    }
780
781    #[test]
782    fn projected_overflow_or_late_capacity_failure_is_atomic_builtin() {
783        for outputs in [
784            vec![(DefaultItem::Crystal, 1)],
785            vec![(DefaultItem::Wood, 1), (DefaultItem::Sand, 1)],
786        ] {
787            let registry = registry_for(&[(DefaultItem::IronOre, 1)], &outputs);
788            let mut inv = Inventory::new(3);
789            inv.add(DefaultItem::IronOre, 2);
790            inv.add(DefaultItem::Crystal, u32::MAX);
791            let before = inv.slots.clone();
792            assert!(can_craft(&registry, &inv, 0));
793            assert_eq!(
794                try_craft(&registry, &mut inv, 0),
795                Err(CraftingError::InventoryFull)
796            );
797            assert_eq!(inv.slots, before);
798        }
799    }
800
801    #[test]
802    fn recipe_overflow_and_positive_sentinels_are_invalid_before_mutation() {
803        let invalid_lists = [
804            vec![(DefaultItem::Empty, 1)],
805            vec![(DefaultItem::IronOre, u32::MAX), (DefaultItem::IronOre, 1)],
806        ];
807        for invalid in invalid_lists {
808            for registry in [registry_for(&invalid, &[]), registry_for(&[], &invalid)] {
809                let mut inv = Inventory::new(1);
810                inv.add(DefaultItem::IronOre, u32::MAX);
811                let before = inv.slots.clone();
812                assert!(!can_craft(&registry, &inv, 0));
813                assert_eq!(
814                    try_craft(&registry, &mut inv, 0),
815                    Err(CraftingError::InvalidRecipe)
816                );
817                assert_eq!(inv.slots, before);
818            }
819        }
820    }
821
822    #[test]
823    fn zero_and_empty_recipe_semantics_and_ingredients_only_check() {
824        let mut inv = Inventory::<DefaultItem>::new(0);
825        for registry in [
826            registry_for(&[], &[]),
827            registry_for(&[(DefaultItem::Empty, 0)], &[(DefaultItem::Empty, 0)]),
828        ] {
829            assert!(can_craft(&registry, &inv, 0));
830            assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
831        }
832        let registry = registry_for(&[], &[(DefaultItem::Crystal, 1)]);
833        assert!(can_craft(&registry, &inv, 0));
834        assert_eq!(
835            try_craft(&registry, &mut inv, 0),
836            Err(CraftingError::InventoryFull)
837        );
838    }
839
840    #[test]
841    fn malformed_inventory_maps_to_inventory_full_without_mutation() {
842        let registry = registry_for(&[], &[]);
843        let mut inv = Inventory::<DefaultItem>::new(1);
844        inv.capacity = 2;
845        let before = inv.slots.clone();
846        assert_eq!(
847            try_craft(&registry, &mut inv, 0),
848            Err(CraftingError::InventoryFull)
849        );
850        assert_eq!(inv.slots, before);
851        assert_eq!(inv.capacity, 2);
852    }
853
854    // A legacy implementor with no Clone/Debug/Serialize or exchange method.
855    struct LegacyContainer {
856        inventory: Inventory<DefaultItem>,
857        remove_limit: Option<u32>,
858        add_limit: Option<u32>,
859        removes: Vec<(DefaultItem, u32)>,
860        adds: Vec<(DefaultItem, u32)>,
861        reported_capacity: Option<usize>,
862    }
863
864    impl LegacyContainer {
865        fn new(capacity: usize) -> Self {
866            Self {
867                inventory: Inventory::new(capacity),
868                remove_limit: None,
869                add_limit: None,
870                removes: vec![],
871                adds: vec![],
872                reported_capacity: None,
873            }
874        }
875    }
876
877    impl Container<DefaultItem> for LegacyContainer {
878        fn add(&mut self, item: DefaultItem, count: u32) -> u32 {
879            self.adds.push((item, count));
880            let accepted = count.min(self.add_limit.unwrap_or(count));
881            count - accepted + self.inventory.add(item, accepted)
882        }
883        fn remove(&mut self, item: DefaultItem, count: u32) -> u32 {
884            self.removes.push((item, count));
885            self.inventory
886                .remove(item, count.min(self.remove_limit.unwrap_or(count)))
887        }
888        fn count_of(&self, item: DefaultItem) -> u32 {
889            self.inventory.count_of(item)
890        }
891        fn capacity(&self) -> usize {
892            self.reported_capacity.unwrap_or(self.inventory.capacity)
893        }
894        fn is_full(&self) -> bool {
895            self.inventory.is_full()
896        }
897        fn iter_slots(
898            &self,
899        ) -> impl Iterator<Item = Option<&crate::items::InventorySlot<DefaultItem>>> {
900            self.inventory.slots.iter().map(Option::as_ref)
901        }
902        fn slot_at(&self, index: usize) -> Option<&crate::items::InventorySlot<DefaultItem>> {
903            self.inventory.slots.get(index).and_then(Option::as_ref)
904        }
905    }
906
907    #[test]
908    fn legacy_default_hook_is_nonmutating_and_normalized_fallback_succeeds() {
909        let mut legacy = LegacyContainer::new(2);
910        legacy.inventory.add(DefaultItem::IronOre, 4);
911        let before = legacy.inventory.slots.clone();
912        assert_eq!(
913            legacy.try_exchange_atomic(&[(DefaultItem::IronOre, 4)], &[]),
914            None
915        );
916        assert_eq!(legacy.inventory.slots, before);
917        let registry = registry_for(
918            &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
919            &[(DefaultItem::Crystal, 1), (DefaultItem::Crystal, 2)],
920        );
921        assert_eq!(try_craft(&registry, &mut legacy, 0), Ok(()));
922        assert_eq!(legacy.removes, vec![(DefaultItem::IronOre, 4)]);
923        assert_eq!(legacy.adds, vec![(DefaultItem::Crystal, 3)]);
924        assert_eq!(legacy.count_of(DefaultItem::Crystal), 3);
925    }
926
927    #[test]
928    fn legacy_preflight_is_conservative_and_ingredients_remain_aggregate() {
929        let registry = registry_for(
930            &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
931            &[(DefaultItem::Crystal, 1)],
932        );
933        let mut legacy = LegacyContainer::new(1);
934        legacy.inventory.add(DefaultItem::IronOre, 3);
935        let before = legacy.inventory.slots.clone();
936        assert_eq!(
937            try_craft(&registry, &mut legacy, 0),
938            Err(CraftingError::InsufficientIngredients)
939        );
940        assert_eq!(legacy.inventory.slots, before);
941        legacy.inventory.add(DefaultItem::IronOre, 1);
942        let before = legacy.inventory.slots.clone();
943        assert!(can_craft(&registry, &legacy, 0));
944        assert_eq!(
945            try_craft(&registry, &mut legacy, 0),
946            Err(CraftingError::InventoryFull)
947        );
948        assert_eq!(legacy.inventory.slots, before);
949        assert!(legacy.removes.is_empty());
950        assert!(legacy.adds.is_empty());
951    }
952
953    #[test]
954    fn legacy_short_removal_stops_before_later_inputs_or_any_outputs() {
955        let registry = registry_for(
956            &[(DefaultItem::IronOre, 4), (DefaultItem::Wood, 1)],
957            &[(DefaultItem::Crystal, 1)],
958        );
959        let mut legacy = LegacyContainer::new(3);
960        legacy.inventory.add(DefaultItem::IronOre, 4);
961        legacy.inventory.add(DefaultItem::Wood, 1);
962        legacy.remove_limit = Some(2);
963        assert_eq!(
964            try_craft(&registry, &mut legacy, 0),
965            Err(CraftingError::InsufficientIngredients)
966        );
967        assert_eq!(legacy.removes, vec![(DefaultItem::IronOre, 4)]);
968        assert!(legacy.adds.is_empty());
969        assert_eq!(legacy.count_of(DefaultItem::IronOre), 2); // No invented rollback.
970        assert_eq!(legacy.count_of(DefaultItem::Wood), 1);
971    }
972
973    #[test]
974    fn legacy_partial_add_stops_before_later_outputs_without_false_success() {
975        let registry = registry_for(
976            &[(DefaultItem::IronOre, 4)],
977            &[(DefaultItem::Crystal, 3), (DefaultItem::Wood, 1)],
978        );
979        let mut legacy = LegacyContainer::new(3);
980        legacy.inventory.add(DefaultItem::IronOre, 4);
981        legacy.add_limit = Some(1);
982        assert_eq!(
983            try_craft(&registry, &mut legacy, 0),
984            Err(CraftingError::InventoryFull)
985        );
986        assert_eq!(legacy.removes, vec![(DefaultItem::IronOre, 4)]);
987        assert_eq!(legacy.adds, vec![(DefaultItem::Crystal, 3)]);
988        assert_eq!(legacy.count_of(DefaultItem::IronOre), 0);
989        assert_eq!(legacy.count_of(DefaultItem::Crystal), 1);
990        assert_eq!(legacy.count_of(DefaultItem::Wood), 0);
991    }
992
993    #[test]
994    fn legacy_numeric_and_capacity_preflight_fail_without_mutation() {
995        let registry = registry_for(&[], &[(DefaultItem::Crystal, 1)]);
996        let mut legacy = LegacyContainer::new(1);
997        legacy.inventory.add(DefaultItem::Crystal, u32::MAX);
998        let before = legacy.inventory.slots.clone();
999        assert_eq!(
1000            try_craft(&registry, &mut legacy, 0),
1001            Err(CraftingError::InventoryFull)
1002        );
1003        assert_eq!(legacy.inventory.slots, before);
1004        legacy.reported_capacity = Some(0); // checked subtraction, no panic.
1005        let empty = registry_for(&[], &[]);
1006        assert_eq!(
1007            try_craft(&empty, &mut legacy, 0),
1008            Err(CraftingError::InventoryFull)
1009        );
1010        assert!(legacy.removes.is_empty());
1011        assert!(legacy.adds.is_empty());
1012    }
1013
1014    #[test]
1015    fn legacy_same_input_outputs_and_duplicate_existing_outputs() {
1016        let registry = registry_for(
1017            &[(DefaultItem::IronOre, 4)],
1018            &[
1019                (DefaultItem::IronOre, 1),
1020                (DefaultItem::Crystal, 2),
1021                (DefaultItem::IronOre, 3),
1022                (DefaultItem::Crystal, 1),
1023            ],
1024        );
1025        let mut legacy = LegacyContainer::new(2);
1026        legacy.inventory.add(DefaultItem::IronOre, u32::MAX);
1027        legacy.inventory.add(DefaultItem::Crystal, 1);
1028        assert_eq!(try_craft(&registry, &mut legacy, 0), Ok(()));
1029        assert_eq!(legacy.removes, vec![(DefaultItem::IronOre, 4)]);
1030        assert_eq!(
1031            legacy.adds,
1032            vec![(DefaultItem::IronOre, 4), (DefaultItem::Crystal, 3)]
1033        );
1034        assert_eq!(legacy.count_of(DefaultItem::IronOre), u32::MAX);
1035        assert_eq!(legacy.count_of(DefaultItem::Crystal), 4);
1036    }
1037
1038    struct OptedInContainer {
1039        legacy: LegacyContainer,
1040        error: Option<ContainerExchangeError>,
1041        exchanges: Vec<(Vec<(DefaultItem, u32)>, Vec<(DefaultItem, u32)>)>,
1042    }
1043
1044    impl Container<DefaultItem> for OptedInContainer {
1045        fn add(&mut self, item: DefaultItem, count: u32) -> u32 {
1046            self.legacy.add(item, count)
1047        }
1048        fn remove(&mut self, item: DefaultItem, count: u32) -> u32 {
1049            self.legacy.remove(item, count)
1050        }
1051        fn count_of(&self, item: DefaultItem) -> u32 {
1052            self.legacy.count_of(item)
1053        }
1054        fn capacity(&self) -> usize {
1055            self.legacy.capacity()
1056        }
1057        fn is_full(&self) -> bool {
1058            self.legacy.is_full()
1059        }
1060        fn iter_slots(
1061            &self,
1062        ) -> impl Iterator<Item = Option<&crate::items::InventorySlot<DefaultItem>>> {
1063            self.legacy.iter_slots()
1064        }
1065        fn slot_at(&self, index: usize) -> Option<&crate::items::InventorySlot<DefaultItem>> {
1066            self.legacy.slot_at(index)
1067        }
1068        fn try_exchange_atomic(
1069            &mut self,
1070            remove: &[(DefaultItem, u32)],
1071            add: &[(DefaultItem, u32)],
1072        ) -> Option<Result<(), ContainerExchangeError>> {
1073            self.exchanges.push((remove.to_vec(), add.to_vec()));
1074            if let Some(error) = self.error {
1075                Some(Err(error))
1076            } else {
1077                self.legacy.inventory.try_exchange_atomic(remove, add)
1078            }
1079        }
1080    }
1081
1082    #[test]
1083    fn opted_in_hook_gets_normalized_lists_and_bypasses_legacy_mutators() {
1084        let mut container = OptedInContainer {
1085            legacy: LegacyContainer::new(1),
1086            error: None,
1087            exchanges: vec![],
1088        };
1089        container.legacy.inventory.add(DefaultItem::IronOre, 4);
1090        let registry = registry_for(
1091            &[(DefaultItem::IronOre, 2), (DefaultItem::IronOre, 2)],
1092            &[
1093                (DefaultItem::Crystal, 1),
1094                (DefaultItem::Empty, 0),
1095                (DefaultItem::Crystal, 2),
1096            ],
1097        );
1098        assert_eq!(try_craft(&registry, &mut container, 0), Ok(()));
1099        assert_eq!(
1100            container.exchanges,
1101            vec![(
1102                vec![(DefaultItem::IronOre, 4)],
1103                vec![(DefaultItem::Crystal, 3)]
1104            )]
1105        );
1106        assert!(container.legacy.removes.is_empty());
1107        assert!(container.legacy.adds.is_empty());
1108        assert_eq!(container.count_of(DefaultItem::Crystal), 3);
1109    }
1110
1111    #[test]
1112    fn all_neutral_hook_errors_map_to_the_existing_three_crafting_variants() {
1113        // Deliberately exhaustive: adding a CraftingError variant breaks compatibility.
1114        fn exhaustive(error: CraftingError) -> u8 {
1115            match error {
1116                CraftingError::InvalidRecipe => 0,
1117                CraftingError::InsufficientIngredients => 1,
1118                CraftingError::InventoryFull => 2,
1119            }
1120        }
1121        let registry = registry_for(&[], &[]);
1122        for (error, expected) in [
1123            (
1124                ContainerExchangeError::InvalidRequest,
1125                CraftingError::InvalidRecipe,
1126            ),
1127            (
1128                ContainerExchangeError::InsufficientItems,
1129                CraftingError::InsufficientIngredients,
1130            ),
1131            (
1132                ContainerExchangeError::InvalidContainer,
1133                CraftingError::InventoryFull,
1134            ),
1135            (
1136                ContainerExchangeError::CapacityExceeded,
1137                CraftingError::InventoryFull,
1138            ),
1139        ] {
1140            let mut container = OptedInContainer {
1141                legacy: LegacyContainer::new(1),
1142                error: Some(error),
1143                exchanges: vec![],
1144            };
1145            container.legacy.inventory.add(DefaultItem::IronOre, 1);
1146            let before = container.legacy.inventory.slots.clone();
1147            let actual = try_craft(&registry, &mut container, 0).unwrap_err();
1148            assert_eq!(actual, expected);
1149            assert_eq!(exhaustive(actual), exhaustive(expected));
1150            assert_eq!(container.legacy.inventory.slots, before);
1151            assert!(container.legacy.removes.is_empty());
1152            assert!(container.legacy.adds.is_empty());
1153        }
1154    }
1155
1156    #[test]
1157    fn component_crafting_matches_resource_atomicity() {
1158        let registry = registry_for(&[(DefaultItem::IronOre, 4)], &[(DefaultItem::Crystal, 1)]);
1159        for count in [3, 4, 5] {
1160            let mut inv = Inventory::new(1);
1161            inv.add(DefaultItem::IronOre, count);
1162            let mut component = ContainerComponent(inv.clone());
1163            assert_eq!(
1164                try_craft(&registry, &mut component, 0),
1165                try_craft(&registry, &mut inv, 0)
1166            );
1167            assert_eq!(component.0.slots, inv.slots);
1168        }
1169    }
1170
1171    #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
1172    enum MinimalItem {
1173        #[default]
1174        DefaultSentinel,
1175        OtherSentinel,
1176        Live,
1177    }
1178
1179    // No Debug or serde bounds, and Default is not reported by is_empty().
1180    impl ItemType for MinimalItem {
1181        fn name(&self) -> &'static str {
1182            "minimal"
1183        }
1184        fn color(&self) -> [f32; 4] {
1185            [1.0; 4]
1186        }
1187        fn to_byte(&self) -> u8 {
1188            1
1189        }
1190        fn from_byte(_: u8) -> Self {
1191            Self::default()
1192        }
1193        fn is_empty(&self) -> bool {
1194            *self == Self::OtherSentinel
1195        }
1196    }
1197
1198    #[test]
1199    fn crafting_adds_no_item_bounds_and_rejects_default_or_is_empty_sentinels() {
1200        let mut inv = Inventory::<MinimalItem>::new(1);
1201        assert_eq!(inv.add(MinimalItem::Live, 2), 0);
1202        for sentinel in [MinimalItem::DefaultSentinel, MinimalItem::OtherSentinel] {
1203            for registry in [
1204                registry_for(&[(sentinel, 1)], &[]),
1205                registry_for(&[], &[(sentinel, 1)]),
1206            ] {
1207                assert!(!can_craft(&registry, &inv, 0));
1208                assert_eq!(
1209                    try_craft(&registry, &mut inv, 0),
1210                    Err(CraftingError::InvalidRecipe)
1211                );
1212                assert_eq!(inv.count_of(MinimalItem::Live), 2);
1213            }
1214            let registry = registry_for(
1215                &[(sentinel, 0), (MinimalItem::Live, 1)],
1216                &[(sentinel, 0), (MinimalItem::Live, 1)],
1217            );
1218            assert!(can_craft(&registry, &inv, 0));
1219            assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
1220            assert_eq!(inv.count_of(MinimalItem::Live), 2);
1221        }
1222    }
1223
1224    #[test]
1225    fn invalid_recipe_never_reaches_opted_in_hook_or_legacy_mutators() {
1226        let registry = registry_for(&[(DefaultItem::IronOre, 1)], &[(DefaultItem::Empty, 1)]);
1227        let mut container = OptedInContainer {
1228            legacy: LegacyContainer::new(1),
1229            error: None,
1230            exchanges: vec![],
1231        };
1232        // Invalid recipe takes precedence over insufficient ingredients.
1233        assert_eq!(
1234            try_craft(&registry, &mut container, 0),
1235            Err(CraftingError::InvalidRecipe)
1236        );
1237        assert!(container.exchanges.is_empty());
1238        assert!(container.legacy.removes.is_empty());
1239        assert!(container.legacy.adds.is_empty());
1240    }
1241
1242    #[test]
1243    fn output_first_occurrence_order_is_retained_in_builtin_slots() {
1244        let registry = registry_for(
1245            &[],
1246            &[
1247                (DefaultItem::Wood, 1),
1248                (DefaultItem::Crystal, 1),
1249                (DefaultItem::Wood, 2),
1250                (DefaultItem::Sand, 1),
1251            ],
1252        );
1253        let mut inv = Inventory::new(3);
1254        assert_eq!(try_craft(&registry, &mut inv, 0), Ok(()));
1255        let actual: Vec<_> = inv
1256            .iter_slots()
1257            .flatten()
1258            .map(|slot| (slot.item, slot.count))
1259            .collect();
1260        assert_eq!(
1261            actual,
1262            vec![
1263                (DefaultItem::Wood, 3),
1264                (DefaultItem::Crystal, 1),
1265                (DefaultItem::Sand, 1)
1266            ]
1267        );
1268    }
1269}