Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ members = [
"core/biomes",
"core/chunk",
"core/chunk_map",
"core/crafting",
"core/entity_metadata",
"core/item_block",
"core/items",
Expand Down
15 changes: 15 additions & 0 deletions core/crafting/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "feather-crafting"
version = "0.1.0"
authors = ["caelunshun <[email protected]>"]
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"
19 changes: 19 additions & 0 deletions core/crafting/src/lib.rs
Original file line number Diff line number Diff line change
@@ -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<Item>; TABLE_WIDTH]; TABLE_WIDTH];
47 changes: 47 additions & 0 deletions core/crafting/src/model.rs
Original file line number Diff line number Diff line change
@@ -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<char, Key<'a>>,
#[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
}
150 changes: 150 additions & 0 deletions core/crafting/src/recipe.rs
Original file line number Diff line number Diff line change
@@ -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<Recipe> {
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<char, model::Key>,
output: model::Output,
) -> anyhow::Result<Recipe> {
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<Recipe> {
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<Option<Item>> {
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<ItemStack> {
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
);
}
}
Loading