ferravex_play/gameplay/
crafting.rs

1//! Recipe preview and execution on a copy, committed only after all costs and outputs fit.
2use super::{
3    LoopError,
4    inventory::{Inventory, Stack},
5};
6
7const MAX_RECIPE_STACKS: usize = 32;
8
9/// One missing ingredient, aggregated across every input with the same item ID.
10/// See [`preview`] for an example. Amounts use `u64` so up to 32 `u32` costs
11/// remain exact even when the required total exceeds inventory stack limits.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct MissingIngredient {
14    /// The recipe's item ID.
15    pub item: u32,
16    /// Total input cost, before any outputs are produced.
17    pub required: u64,
18    /// Amount currently held in the inventory.
19    pub available: u32,
20    /// Exact shortfall: `required - u64::from(available)`.
21    pub missing: u64,
22}
23
24/// An owned snapshot of crafting availability and missing ingredients.
25///
26/// Fixed storage holds at most 32 missing items without heap allocation.
27/// This does not reserve inventory; call [`craft`] to check again and commit.
28/// See [`preview`] for an example.
29#[derive(Clone, Debug, PartialEq, Eq)]
30#[must_use]
31pub struct CraftPreview {
32    result: Result<(), LoopError>,
33    missing: [MissingIngredient; MAX_RECIPE_STACKS],
34    missing_len: usize,
35}
36
37impl CraftPreview {
38    /// Whether the entire recipe, including its outputs, can be crafted.
39    pub fn is_available(&self) -> bool {
40        self.result.is_ok()
41    }
42
43    /// The exact result [`craft`] would return for the previewed inventory.
44    ///
45    /// Error ordering is unchanged: recipe lengths first, then input removals
46    /// in order, then output additions in order. A later invalid entry can be
47    /// masked by an earlier unavailable input or full output stack.
48    pub fn result(&self) -> Result<(), LoopError> {
49        self.result
50    }
51
52    /// Every input shortfall, in first-appearance order, with duplicates summed.
53    ///
54    /// For recipe lengths within 1..=32, this describes all input costs even
55    /// if another entry is invalid. Zero costs contribute nothing. Out-of-range
56    /// recipe lengths yield an empty slice and [`LoopError::Invalid`].
57    /// An empty slice alone does not imply availability: outputs must also fit.
58    pub fn missing_ingredients(&self) -> &[MissingIngredient] {
59        &self.missing[..self.missing_len]
60    }
61}
62
63/// Inspect the same trusted recipe accepted by [`craft`] without changing inventory.
64///
65/// Availability includes consuming all inputs before checking outputs, so freed
66/// slots can be reused and outputs cannot pay for missing inputs. All ingredient
67/// shortfalls are reported, including those after the first failed removal.
68/// Duplicate input totals use `u64`; overflowing output amounts yield
69/// [`LoopError::Capacity`], just as they do in [`craft`].
70///
71/// ```
72/// use ferravex_play::gameplay::{
73///     LoopError,
74///     crafting::{craft, preview, MissingIngredient},
75///     inventory::{Inventory, Stack},
76/// };
77///
78/// let mut inventory = Inventory::<1>::new()?;
79/// inventory.add(Stack { item: 1, amount: 3, limit: 10 })?;
80/// let inputs = [(1, 2), (1, 3)];
81/// let outputs = [Stack { item: 2, amount: 1, limit: 5 }];
82/// let report = preview(&inventory, &inputs, &outputs);
83/// assert!(!report.is_available());
84/// assert_eq!(report.result(), Err(LoopError::Unavailable));
85/// assert_eq!(report.missing_ingredients(), &[MissingIngredient {
86///     item: 1, required: 5, available: 3, missing: 2,
87/// }]);
88/// assert_eq!(inventory.count(1), 3);
89///
90/// inventory.add(Stack { item: 1, amount: 2, limit: 10 })?;
91/// let ready = preview(&inventory, &inputs, &outputs);
92/// assert!(ready.is_available()); // Spending all ore frees the only slot.
93/// assert!(ready.missing_ingredients().is_empty());
94/// assert_eq!(craft(&mut inventory, &inputs, &outputs), ready.result());
95/// assert_eq!(inventory.count(2), 1);
96/// # Ok::<(), LoopError>(())
97/// ```
98pub fn preview<const N: usize>(
99    inventory: &Inventory<N>,
100    inputs: &[(u32, u32)],
101    outputs: &[Stack],
102) -> CraftPreview {
103    let mut report = CraftPreview {
104        result: prepare(inventory, inputs, outputs).map(|_| ()),
105        missing: [MissingIngredient {
106            item: 0,
107            required: 0,
108            available: 0,
109            missing: 0,
110        }; MAX_RECIPE_STACKS],
111        missing_len: 0,
112    };
113    if !valid_lengths(inputs, outputs) {
114        return report;
115    }
116    for (index, &(item, _)) in inputs.iter().enumerate() {
117        if inputs[..index].iter().any(|&(id, _)| id == item) {
118            continue;
119        }
120        // At most 32 u32 values: the sum always fits in u64.
121        let required: u64 = inputs[index..]
122            .iter()
123            .filter(|&&(id, _)| id == item)
124            .map(|&(_, amount)| u64::from(amount))
125            .sum();
126        let available = inventory.count(item);
127        if required > u64::from(available) {
128            report.missing[report.missing_len] = MissingIngredient {
129                item,
130                required,
131                available,
132                missing: required - u64::from(available),
133            };
134            report.missing_len += 1;
135        }
136    }
137    report
138}
139
140/// Inputs/outputs are host-authored trusted recipe data, never client prices.
141/// Repeated ingredients are summed by sequential removal. At most 32 of each.
142/// Output capacity is evaluated after consuming inputs, allowing slot reuse.
143/// See [`preview`] for a non-mutating availability check and usage example.
144pub fn craft<const N: usize>(
145    inventory: &mut Inventory<N>,
146    inputs: &[(u32, u32)],
147    outputs: &[Stack],
148) -> Result<(), LoopError> {
149    *inventory = prepare(inventory, inputs, outputs)?;
150    Ok(())
151}
152
153fn valid_lengths(inputs: &[(u32, u32)], outputs: &[Stack]) -> bool {
154    (1..=MAX_RECIPE_STACKS).contains(&inputs.len())
155        && (1..=MAX_RECIPE_STACKS).contains(&outputs.len())
156}
157
158fn prepare<const N: usize>(
159    inventory: &Inventory<N>,
160    inputs: &[(u32, u32)],
161    outputs: &[Stack],
162) -> Result<Inventory<N>, LoopError> {
163    if !valid_lengths(inputs, outputs) {
164        return Err(LoopError::Invalid);
165    }
166    let mut next = *inventory;
167    for &(item, amount) in inputs {
168        next.remove(item, amount)?;
169    }
170    for &stack in outputs {
171        next.add(stack)?;
172    }
173    Ok(next)
174}
175#[cfg(test)]
176mod tests {
177    use super::*;
178
179    fn stack(item: u32, amount: u32, limit: u32) -> Stack {
180        Stack {
181            item,
182            amount,
183            limit,
184        }
185    }
186
187    fn check_preview<const N: usize>(
188        inventory: &Inventory<N>,
189        inputs: &[(u32, u32)],
190        outputs: &[Stack],
191        expected: Result<(), LoopError>,
192    ) -> CraftPreview {
193        let before: Vec<_> = inventory.stacks().collect();
194        let report = preview(inventory, inputs, outputs);
195        assert_eq!(inventory.stacks().collect::<Vec<_>>(), before);
196        assert_eq!(report.result(), expected);
197        assert_eq!(report.is_available(), expected.is_ok());
198        let mut actual = *inventory;
199        assert_eq!(craft(&mut actual, inputs, outputs), expected);
200        if expected.is_err() {
201            assert_eq!(actual.stacks().collect::<Vec<_>>(), before);
202        }
203        report
204    }
205
206    #[test]
207    fn failed_output_rolls_back_costs_and_consumed_slots_can_be_reused() {
208        let mut i = Inventory::<1>::new().unwrap();
209        let ore = Stack {
210            item: 1,
211            amount: 4,
212            limit: 10,
213        };
214        i.add(ore).unwrap();
215        let bar = Stack {
216            item: 2,
217            amount: 1,
218            limit: 5,
219        };
220        assert_eq!(craft(&mut i, &[(1, 2)], &[bar]), Err(LoopError::Capacity));
221        assert_eq!(i.count(1), 4);
222        craft(&mut i, &[(1, 2), (1, 2)], &[bar]).unwrap();
223        assert_eq!(i.count(2), 1);
224        assert_eq!(
225            craft(&mut i, &[(2, 2)], &[ore]),
226            Err(LoopError::Unavailable)
227        );
228        assert_eq!(i.count(2), 1);
229    }
230
231    #[test]
232    fn preview_reports_all_shortfalls_once_in_first_input_order() {
233        let mut inventory = Inventory::<3>::new().unwrap();
234        inventory.add(stack(9, 1, 10)).unwrap();
235        inventory.add(stack(1, 5, 10)).unwrap();
236        inventory.add(stack(0, 2, 10)).unwrap();
237        let report = check_preview(
238            &inventory,
239            &[(9, 2), (1, 2), (9, 5), (0, 4), (1, 3), (7, 1)],
240            &[stack(8, 1, 10)],
241            Err(LoopError::Unavailable),
242        );
243        assert_eq!(
244            report.missing_ingredients(),
245            &[
246                MissingIngredient {
247                    item: 9,
248                    required: 7,
249                    available: 1,
250                    missing: 6,
251                },
252                MissingIngredient {
253                    item: 0,
254                    required: 4,
255                    available: 2,
256                    missing: 2,
257                },
258                MissingIngredient {
259                    item: 7,
260                    required: 1,
261                    available: 0,
262                    missing: 1,
263                },
264            ]
265        );
266    }
267
268    #[test]
269    fn repeated_costs_above_u32_max_remain_exact() {
270        let mut inventory = Inventory::<1>::new().unwrap();
271        inventory.add(stack(1, u32::MAX, u32::MAX)).unwrap();
272        let report = check_preview(
273            &inventory,
274            &[(1, u32::MAX); 32],
275            &[stack(2, 1, 1)],
276            Err(LoopError::Unavailable),
277        );
278        assert_eq!(
279            report.missing_ingredients(),
280            &[MissingIngredient {
281                item: 1,
282                required: 32 * u64::from(u32::MAX),
283                available: u32::MAX,
284                missing: 31 * u64::from(u32::MAX),
285            }]
286        );
287    }
288
289    #[test]
290    fn preview_reuses_consumed_slots_and_sums_outputs() {
291        let mut inventory = Inventory::<1>::new().unwrap();
292        inventory.add(stack(1, 4, 10)).unwrap();
293        let inputs = [(1, 2), (1, 2)];
294        let outputs = [stack(2, 1, 5), stack(2, 2, 5)];
295        let ready = check_preview(&inventory, &inputs, &outputs, Ok(()));
296        assert!(ready.missing_ingredients().is_empty());
297        let full = check_preview(&inventory, &[(1, 3)], &outputs, Err(LoopError::Capacity));
298        assert!(full.missing_ingredients().is_empty());
299        craft(&mut inventory, &inputs, &outputs).unwrap();
300        assert_eq!(inventory.stacks().collect::<Vec<_>>(), [stack(2, 3, 5)]);
301    }
302
303    #[test]
304    fn output_overflow_and_limit_errors_match_atomic_craft() {
305        let mut inventory = Inventory::<2>::new().unwrap();
306        inventory.add(stack(1, 1, 1)).unwrap();
307        inventory.add(stack(2, u32::MAX - 1, u32::MAX)).unwrap();
308        let report = check_preview(
309            &inventory,
310            &[(1, 1)],
311            &[stack(2, 1, u32::MAX), stack(2, 1, u32::MAX)],
312            Err(LoopError::Capacity),
313        );
314        assert!(report.missing_ingredients().is_empty());
315        let _ = check_preview(
316            &inventory,
317            &[(1, 1)],
318            &[stack(2, 1, 5)],
319            Err(LoopError::Invalid),
320        );
321        for invalid in [stack(3, 0, 1), stack(3, 1, 0), stack(3, 2, 1)] {
322            let _ = check_preview(&inventory, &[(1, 1)], &[invalid], Err(LoopError::Invalid));
323        }
324        let _ = check_preview(
325            &inventory,
326            &[(2, u32::MAX - 1)],
327            &[stack(3, 3, 5), stack(3, 3, 5)],
328            Err(LoopError::Capacity),
329        );
330    }
331
332    #[test]
333    fn same_item_outputs_follow_consumption_and_do_not_pay_costs() {
334        let mut inventory = Inventory::<1>::new().unwrap();
335        inventory.add(stack(1, u32::MAX, u32::MAX)).unwrap();
336        let _ = check_preview(&inventory, &[(1, 1)], &[stack(1, 1, u32::MAX)], Ok(()));
337        // Consuming the whole stack permits changing its limit; partial removal does not.
338        let _ = check_preview(&inventory, &[(1, u32::MAX)], &[stack(1, 2, 5)], Ok(()));
339        let _ = check_preview(
340            &inventory,
341            &[(1, 1)],
342            &[stack(1, 2, 5)],
343            Err(LoopError::Invalid),
344        );
345        let empty = Inventory::<1>::new().unwrap();
346        let report = check_preview(
347            &empty,
348            &[(1, 1)],
349            &[stack(1, 1, 1)],
350            Err(LoopError::Unavailable),
351        );
352        assert_eq!(report.missing_ingredients()[0].missing, 1);
353    }
354
355    #[test]
356    fn preview_preserves_first_failure_order_in_malformed_recipes() {
357        let mut inventory = Inventory::<1>::new().unwrap();
358        inventory.add(stack(1, 1, 1)).unwrap();
359        let report = check_preview(
360            &inventory,
361            &[(2, 1), (1, 0)],
362            &[stack(3, 0, 1)],
363            Err(LoopError::Unavailable),
364        );
365        assert_eq!(report.missing_ingredients()[0].item, 2);
366        let report = check_preview(
367            &inventory,
368            &[(1, 0), (2, 1)],
369            &[stack(3, 1, 1)],
370            Err(LoopError::Invalid),
371        );
372        assert_eq!(report.missing_ingredients()[0].item, 2);
373        let _ = check_preview(
374            &inventory,
375            &[(1, 1)],
376            &[stack(2, 1, 1), stack(3, 1, 1), stack(4, 0, 1)],
377            Err(LoopError::Capacity),
378        );
379        let _ = check_preview(
380            &inventory,
381            &[(1, 1)],
382            &[stack(4, 0, 1), stack(2, 1, 1), stack(3, 1, 1)],
383            Err(LoopError::Invalid),
384        );
385    }
386
387    #[test]
388    fn recipe_length_bounds_apply_before_stack_operations() {
389        let mut inventory = Inventory::<1>::new().unwrap();
390        inventory.add(stack(1, 32, 32)).unwrap();
391        let _ = check_preview(&inventory, &[(1, 1); 32], &[stack(2, 1, 32); 32], Ok(()));
392        for inputs in [&[][..], &[(2, 1); 33][..]] {
393            let report = check_preview(
394                &inventory,
395                inputs,
396                &[stack(3, 1, 1)],
397                Err(LoopError::Invalid),
398            );
399            assert!(report.missing_ingredients().is_empty());
400        }
401        for outputs in [&[][..], &[stack(3, 1, 1); 33][..]] {
402            let report = check_preview(&inventory, &[(2, 1)], outputs, Err(LoopError::Invalid));
403            assert!(report.missing_ingredients().is_empty());
404        }
405    }
406
407    #[test]
408    fn all_32_distinct_shortfalls_fit_without_truncation() {
409        let inventory = Inventory::<1>::new().unwrap();
410        let inputs: [(u32, u32); 32] = std::array::from_fn(|index| (31 - index as u32, 1));
411        let report = check_preview(
412            &inventory,
413            &inputs,
414            &[stack(32, 1, 1)],
415            Err(LoopError::Unavailable),
416        );
417        assert_eq!(report.missing_ingredients().len(), 32);
418        for (entry, &(item, _)) in report.missing_ingredients().iter().zip(&inputs) {
419            assert_eq!(
420                *entry,
421                MissingIngredient {
422                    item,
423                    required: 1,
424                    available: 0,
425                    missing: 1,
426                }
427            );
428        }
429    }
430
431    #[test]
432    fn preview_is_a_snapshot_and_craft_rechecks_changed_inventory() {
433        let mut inventory = Inventory::<1>::new().unwrap();
434        inventory.add(stack(1, 1, 1)).unwrap();
435        let ready = preview(&inventory, &[(1, 1)], &[stack(2, 1, 1)]);
436        inventory.remove(1, 1).unwrap();
437        assert!(ready.is_available());
438        assert_eq!(
439            craft(&mut inventory, &[(1, 1)], &[stack(2, 1, 1)]),
440            Err(LoopError::Unavailable)
441        );
442        assert_eq!(inventory.stacks().count(), 0);
443    }
444}