diff --git a/Cargo.lock b/Cargo.lock index 51a07bf28..8f817fea9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -775,6 +775,19 @@ dependencies = [ "feather-util", ] +[[package]] +name = "feather-crafting" +version = "0.1.0" +dependencies = [ + "ahash", + "anyhow", + "arrayvec 0.5.1", + "feather-items", + "serde", + "serde_json", + "smallvec", +] + [[package]] name = "feather-data" version = "0.6.0" diff --git a/Cargo.toml b/Cargo.toml index dfe5fb088..8092e18df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "core/biomes", "core/chunk", "core/chunk_map", + "core/crafting", "core/entity_metadata", "core/item_block", "core/items", diff --git a/core/crafting/Cargo.toml b/core/crafting/Cargo.toml new file mode 100644 index 000000000..bb3d01adc --- /dev/null +++ b/core/crafting/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "feather-crafting" +version = "0.1.0" +authors = ["caelunshun "] +edition = "2018" + +[dependencies] +feather-items = { path = "../items" } + +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +smallvec = "1.4" +arrayvec = { version = "0.5", features = ["serde"] } +anyhow = "1.0" +ahash = "0.3" diff --git a/core/crafting/src/lib.rs b/core/crafting/src/lib.rs new file mode 100644 index 000000000..266fe3b2b --- /dev/null +++ b/core/crafting/src/lib.rs @@ -0,0 +1,19 @@ +//! Loading of recipe files and crafting algorithms ("solving"). + +use feather_items::Item; + +mod model; +mod recipe; +mod solver; + +pub use recipe::convert; +pub use solver::{transpose, Solver}; + +pub const TABLE_WIDTH: usize = 3; +pub const TABLE_SIZE: usize = TABLE_WIDTH * TABLE_WIDTH; + +/// A crafting grid. Origin is at the upper left corner. +/// Stored in column-major format. Indexing by [x][y] +/// will yield the item `x` slots from the left +/// and `y` slots from the top. +pub type Grid = [[Option; TABLE_WIDTH]; TABLE_WIDTH]; diff --git a/core/crafting/src/model.rs b/core/crafting/src/model.rs new file mode 100644 index 000000000..eb5ede66e --- /dev/null +++ b/core/crafting/src/model.rs @@ -0,0 +1,47 @@ +//! Serde data model for recipe files. +use crate::{TABLE_SIZE, TABLE_WIDTH}; +use arrayvec::{ArrayString, ArrayVec}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub type TableEntry = ArrayString<[u8; TABLE_WIDTH]>; +pub type Table = ArrayVec<[TableEntry; TABLE_WIDTH]>; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum Recipe<'a> { + #[serde(rename = "minecraft:crafting_shaped")] + Shaped { + pattern: Table, + #[serde(borrow)] + key: BTreeMap>, + #[serde(rename = "result")] + output: Output<'a>, + }, + #[serde(rename = "minecraft:crafting_shapeless")] + Shapeless { + ingredients: ArrayVec<[Key<'a>; TABLE_SIZE]>, + #[serde(rename = "result")] + output: Output<'a>, + }, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +#[serde(rename_all = "lowercase")] +pub enum Key<'a> { + Item(&'a str), + Tag(&'a str), +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Output<'a> { + /// Identifier of output item. + pub item: &'a str, + #[serde(default = "one")] + pub count: u8, +} + +const fn one() -> u8 { + 1 +} diff --git a/core/crafting/src/recipe.rs b/core/crafting/src/recipe.rs new file mode 100644 index 000000000..d4b75e010 --- /dev/null +++ b/core/crafting/src/recipe.rs @@ -0,0 +1,150 @@ +//! Intermediate representation of a recipe used directly +//! in solving. + +use crate::{model, solver, Grid, TABLE_SIZE}; +use anyhow::anyhow; +use arrayvec::ArrayVec; +use feather_items::{Item, ItemStack}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug)] +pub struct ShapedRecipe { + /// Input grid of required items. + /// Normalized to the upper left corner: + /// all empty rows on top and all empty + /// columns to the left are removed. + pub input: Grid, + /// Output item stack. + pub output: ItemStack, +} + +#[derive(Clone, Debug)] +pub struct ShapelessRecipe { + /// The set of input items required. + /// Must be a sorted vector to allow for efficient + /// comparison. + pub input: ArrayVec<[Item; TABLE_SIZE]>, + /// Output item stack. + pub output: ItemStack, +} + +#[derive(Clone, Debug)] +pub enum Recipe { + Shaped(ShapedRecipe), + Shapeless(ShapelessRecipe), +} + +/// Converts a `model::Recipe` to a `Recipe`. +pub fn convert(model: model::Recipe) -> anyhow::Result { + match model { + model::Recipe::Shaped { + pattern, + key, + output, + } => convert_shaped(pattern, key, output), + model::Recipe::Shapeless { + ingredients, + output, + } => convert_shapeless(&ingredients, output), + } +} + +fn convert_shaped( + pattern: model::Table, + key: BTreeMap, + output: model::Output, +) -> anyhow::Result { + let mut input = Grid::default(); + + for (y, row) in pattern.iter().enumerate() { + for (x, slot) in row.as_str().chars().enumerate() { + let key = key + .get(&slot) + .ok_or_else(|| anyhow!("no entry in key for character '{}'", slot))?; + + let item = convert_key(key)?; + + if let Some(item) = item { + input[x][y] = Some(item); + } + } + } + + solver::normalize(&mut input); + + let output = convert_output(&output)?; + + Ok(Recipe::Shaped(ShapedRecipe { input, output })) +} + +fn convert_shapeless(ingredients: &[model::Key], output: model::Output) -> anyhow::Result { + let mut input = ArrayVec::new(); + + for ingredient in ingredients { + let item = convert_key(ingredient)?; + + if let Some(item) = item { + input.push(item); + } + } + + input.sort_unstable(); + + let output = convert_output(&output)?; + + Ok(Recipe::Shapeless(ShapelessRecipe { input, output })) +} + +fn convert_key(key: &model::Key) -> anyhow::Result> { + match key { + model::Key::Item(identifier) => Ok(Some( + Item::from_identifier(*identifier) + .ok_or_else(|| anyhow!("invalid item '{}'", identifier))?, + )), + model::Key::Tag(_) => Ok(None), // not implemented + } +} + +fn convert_output(output: &model::Output) -> anyhow::Result { + let ty = Item::from_identifier(output.item) + .ok_or_else(|| anyhow!("invalid item '{}'", output.item))?; + Ok(ItemStack::new(ty, output.count)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_convert_output() { + assert_eq!( + convert_output(&model::Output { + item: "minecraft:stone", + count: 5 + }) + .unwrap(), + ItemStack::new(Item::Stone, 5) + ); + } + + #[test] + fn test_convert_output_invalid_item() { + assert!(convert_output(&model::Output { + item: "minecraft:doesnotexist", + count: 1 + }) + .is_err()); + } + + #[test] + fn test_convert_key() { + assert_eq!( + convert_key(&model::Key::Item("minecraft:diamond_sword")).unwrap(), + Some(Item::DiamondSword) + ); + assert_eq!( + convert_key(&model::Key::Tag("unimplemented")).unwrap(), + None + ); + } +} diff --git a/core/crafting/src/solver.rs b/core/crafting/src/solver.rs new file mode 100644 index 000000000..b3225faf7 --- /dev/null +++ b/core/crafting/src/solver.rs @@ -0,0 +1,258 @@ +//! Solves a crafting output given a set of recipes +//! and the input grid. + +use crate::{ + recipe::{Recipe, ShapedRecipe, ShapelessRecipe}, + Grid, TABLE_SIZE, TABLE_WIDTH, +}; +use ahash::AHashMap; +use arrayvec::ArrayVec; +use feather_items::{Item, ItemStack}; + +/// Stores the set of all known recipes. +#[derive(Debug, Clone, Default)] +pub struct Solver { + /// Mapping from the input grid of a shaped recipe + /// to the output stack. + /// Grids are normalized to allow for an efficient O(1) lookup. + shaped: AHashMap, + /// Mapping from the input set of ingredients for a shapeless + /// recipe to the output stack. + /// + /// Input sets should be sorted using the `Ord` impl for `ItemStack`. + shapeless: AHashMap, ItemStack>, +} + +impl Solver { + pub fn new() -> Self { + Self::default() + } + + /// Given an input crafting grid, attempts to find + /// an item to craft. Returns the craftable item stack, + /// or `None` if the grid satisfies no recipes. + pub fn solve(&self, input: &mut Grid) -> Option { + normalize(input); + + // Try shaped first, then shapeless. + if let Some(output) = self.shaped.get(input).copied() { + Some(output) + } else { + // Sort inputs to perform a shapeless lookup. + let mut inputs = ArrayVec::new(); + input + .iter() + .flatten() + .filter_map(|slot| *slot) + .for_each(|item| inputs.push(item)); + inputs.sort_unstable(); + + if let Some(output) = self.shapeless.get(&inputs).copied() { + Some(output) + } else { + None + } + } + } + + /// Registers a recipe with this `Solver`. Future calls to `solve()` + /// will account for the new recipe. + pub fn register(&mut self, recipe: Recipe) { + match recipe { + Recipe::Shaped(shaped) => self.register_shaped(shaped), + Recipe::Shapeless(shapeless) => self.register_shapeless(shapeless), + } + } + + fn register_shaped(&mut self, shaped: ShapedRecipe) { + self.shaped.insert(shaped.input, shaped.output); + } + + fn register_shapeless(&mut self, shapeless: ShapelessRecipe) { + self.shapeless.insert(shapeless.input, shapeless.output); + } +} + +/// Normalizes a crafting grid to remove the upper empty rows and the +/// leftmost empty columns. +pub fn normalize(grid: &mut Grid) { + // Find number of empty upper rows + let mut y = 0; + while is_empty(grid, (0, y), (1, y), (2, y)) && y < TABLE_WIDTH - 1 { + y += 1; + } + + // Find number of empty leftmost columns + let mut x = 0; + while is_empty(grid, (x, 0), (x, 1), (x, 2)) && x < TABLE_WIDTH - 1 { + x += 1; + } + + translate(grid, x, y); +} + +/// Translates a crafting grid by the given amount +/// upward and to the left. +/// Items translated outside of the grid will be eliminated. +pub fn translate(grid: &mut Grid, x: usize, y: usize) { + // Translate to the left + grid.copy_within(x..TABLE_WIDTH, 0); + // Upward + for column in grid.iter_mut() { + column.copy_within(y..TABLE_WIDTH, 0); + } + + // Fill in newly unused space with empty slots + for item in grid.iter_mut().skip(TABLE_WIDTH - x) { + *item = [None, None, None]; + } + for column in TABLE_WIDTH - y..TABLE_WIDTH { + for row in grid.iter_mut() { + row[column] = None; + } + } +} + +/// Transposes a grid (converts between row-major and column-major format.) +pub fn transpose(grid: &Grid) -> Grid { + [ + [grid[0][0], grid[1][0], grid[2][0]], + [grid[0][1], grid[1][1], grid[2][1]], + [grid[0][2], grid[1][2], grid[2][2]], + ] +} + +fn is_empty( + grid: &Grid, + coord1: (usize, usize), + coord2: (usize, usize), + coord3: (usize, usize), +) -> bool { + grid[coord1.0][coord1.1].is_none() + && grid[coord2.0][coord2.1].is_none() + && grid[coord3.0][coord3.1].is_none() +} + +#[cfg(test)] +mod tests { + use super::*; + use feather_items::Item; + + #[test] + fn solve_shaped() { + let mut solver = Solver::new(); + + let recipe = Recipe::Shaped(ShapedRecipe { + input: transpose(&[ + [Some(Item::OakPlanks), None, None], + [Some(Item::OakPlanks), None, None], + [None, None, None], + ]), + output: ItemStack::new(Item::Stick, 4), + }); + solver.register(recipe); + + let mut input = transpose(&[ + [None, None, None], + [None, None, Some(Item::OakPlanks)], + [None, None, Some(Item::OakPlanks)], + ]); + assert_eq!( + solver.solve(&mut input), + Some(ItemStack::new(Item::Stick, 4)) + ); + + let mut input = transpose(&[ + [None, Some(Item::OakPlanks), Some(Item::OakPlanks)], + [None, None, None], + [None, None, None], + ]); + assert_eq!(solver.solve(&mut input), None); + } + + #[test] + fn solve_shapeless() { + let mut solver = Solver::new(); + + let mut input = vec![Item::Flint, Item::IronIngot]; + input.sort_unstable(); + let recipe = Recipe::Shapeless(ShapelessRecipe { + input: input.into_iter().collect(), + output: ItemStack::new(Item::FlintAndSteel, 1), + }); + solver.register(recipe); + + let mut input = [ + [None, None, Some(Item::Flint)], + [None, Some(Item::IronIngot), None], + [None, None, None], + ]; + assert_eq!( + solver.solve(&mut input), + Some(ItemStack::new(Item::FlintAndSteel, 1)) + ); + + let mut input = [ + [None, None, Some(Item::Flint)], + [None, Some(Item::IronIngot), None], + [None, Some(Item::IronIngot), None], + ]; + assert_eq!(solver.solve(&mut input), None); + } + + #[test] + fn test_normalize() { + let stack = Item::Stone; + let stack2 = Item::DiamondSword; + let mut grid = transpose(&[ + [None, None, None], + [None, None, Some(stack)], + [None, None, Some(stack2)], + ]); + + normalize(&mut grid); + + assert_eq!( + grid, + transpose(&[ + [Some(stack), None, None], + [Some(stack2), None, None], + [None, None, None], + ]), + ); + } + + #[test] + fn test_normalize_empty() { + let mut grid = [[None, None, None], [None, None, None], [None, None, None]]; + normalize(&mut grid); + + for row in &mut grid { + for slot in row { + assert_eq!(*slot, None); + } + } + } + + #[test] + fn test_translate() { + let stack = Item::Cactus; + let stack2 = Item::WoodenHoe; + let mut grid = [ + [None, Some(stack), None], + [None, Some(stack2), Some(stack)], + [None, None, Some(stack)], + ]; + + translate(&mut grid, 1, 1); + + assert_eq!( + grid, + [ + [Some(stack2), Some(stack), None], + [None, Some(stack), None], + [None, None, None], + ] + ); + } +}