Skip to main content

wackasm_opencomputers/
pattern_provider.rs

1//! The Computer Pattern Provider: autocrafting patterns for Applied
2//! Energistics 2 that a program fulfils.
3//!
4//! The block exists when AE2 is installed alongside the wackasm mod. It's an
5//! ME network device and an OpenComputers component (`pattern_provider`)
6//! at once:
7//!
8//! 1. The program declares processing patterns ([`PatternProvider::set_patterns`]).
9//!    AE2 sees them as ordinary processing patterns: they show up as
10//!    craftable, and the crafting planner uses them.
11//! 2. When a crafting job needs one, AE2 hands the block the inputs. The block
12//!    holds them as a [`Job`] and sends [`Signal::PatternRequest`](crate::Signal::PatternRequest).
13//! 3. The program moves the inputs out ([`PatternProvider::push_inputs`]),
14//!    does the work, and gets the outputs **imported into the ME network**:
15//!    through an ME Interface, an import bus, or by inserting them into this
16//!    block (with a transposer, say), which forwards them. AE2's crafting
17//!    CPUs claim them as they arrive, the same as for any processing pattern.
18//!
19//! Nothing creates items: the outputs have to come from somewhere real.
20//!
21//! ```no_run
22//! use wackasm_opencomputers::prelude::*;
23//! use wackasm_opencomputers::pattern_provider::{Pattern, PatternProvider, Stack};
24//!
25//! let provider = PatternProvider::first().expect("no pattern provider");
26//! provider.set_patterns(&[Pattern::new(
27//!     vec![Stack::item("minecraft:cobblestone", 1)],
28//!     vec![Stack::item("minecraft:stone", 1)],
29//! )])?;
30//! loop {
31//!     // Jobs from before this program started are waiting too.
32//!     for job in provider.jobs()? {
33//!         provider.push_inputs(job.id, Side::Top)?; // into a furnace, say
34//!     }
35//!     signal::pull_filtered(None, |s| matches!(s, Signal::PatternRequest { .. }));
36//! }
37//! # Ok::<(), wackasm_opencomputers::Error>(())
38//! ```
39
40use crate::{
41    component::{Address, Component, single},
42    error::{Error, Result},
43    types::Side,
44    value::Value,
45};
46
47/// The `pattern_provider` component.
48#[derive(Clone, Debug, PartialEq, Eq, Hash)]
49pub struct PatternProvider(pub Address);
50
51impl Component for PatternProvider {
52    const KIND: &'static str = "pattern_provider";
53    fn from_address(address: Address) -> Self {
54        Self(address)
55    }
56    fn address(&self) -> &Address {
57        &self.0
58    }
59}
60
61/// An item or fluid and an amount.
62#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct Stack {
64    /// The registry name, such as `minecraft:iron_ingot`.
65    pub name: String,
66    /// Items, or millibuckets for fluids.
67    pub count: i64,
68    pub fluid: bool,
69    /// AE2's description of the exact stack (SNBT), for items with data
70    /// components such as enchantments. When set, it's used and `name` and
71    /// `fluid` are ignored. Stacks the component returns have it whenever
72    /// it's needed, so they can be passed back as they are.
73    pub key: Option<String>,
74    /// The display name. Only filled in on stacks the component returns.
75    pub label: Option<String>,
76}
77
78impl Stack {
79    pub fn item(name: impl Into<String>, count: i64) -> Stack {
80        Stack { name: name.into(), count, fluid: false, key: None, label: None }
81    }
82
83    /// `millibuckets` of a fluid.
84    pub fn fluid(name: impl Into<String>, millibuckets: i64) -> Stack {
85        Stack { name: name.into(), count: millibuckets, fluid: true, key: None, label: None }
86    }
87
88    fn to_value(&self) -> Value {
89        let mut entries = vec![
90            ("name".into(), self.name.as_str().into()),
91            ("count".into(), self.count.into()),
92            ("fluid".into(), self.fluid.into()),
93        ];
94        if let Some(key) = &self.key {
95            entries.push(("key".into(), key.as_str().into()));
96        }
97        Value::Map(entries)
98    }
99
100    fn from_value(value: &Value) -> Option<Stack> {
101        Some(Stack {
102            name: value.get("name")?.as_str()?.to_owned(),
103            count: value.get("count")?.as_i64()?,
104            fluid: value.get("fluid").and_then(Value::as_bool).unwrap_or(false),
105            key: value.get("key").and_then(Value::as_str).map(str::to_owned),
106            label: value.get("label").and_then(Value::as_str).map(str::to_owned),
107        })
108    }
109}
110
111/// A processing pattern: AE2 hands over `inputs` and expects `outputs` back.
112/// It needs at least one input (AE2 requires it) and at least one output; the
113/// first output is the one AE2 lists it under.
114#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct Pattern {
116    pub inputs: Vec<Stack>,
117    pub outputs: Vec<Stack>,
118}
119
120impl Pattern {
121    pub fn new(inputs: Vec<Stack>, outputs: Vec<Stack>) -> Pattern {
122        Pattern { inputs, outputs }
123    }
124
125    fn to_value(&self) -> Value {
126        Value::Map(vec![
127            ("inputs".into(), stacks_value(&self.inputs)),
128            ("outputs".into(), stacks_value(&self.outputs)),
129        ])
130    }
131
132    fn from_value(value: &Value) -> Option<Pattern> {
133        Some(Pattern { inputs: stacks(value.get("inputs")?)?, outputs: stacks(value.get("outputs")?)? })
134    }
135}
136
137/// One use of a pattern that AE2 handed over.
138#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct Job {
140    pub id: i64,
141    /// The pattern's index (from 1) when the job arrived.
142    pub pattern: i64,
143    /// The inputs still held by the block.
144    pub inputs: Vec<Stack>,
145    /// What the crafting job expects to be imported into the network.
146    pub outputs: Vec<Stack>,
147}
148
149impl Job {
150    fn from_value(value: &Value) -> Option<Job> {
151        Some(Job {
152            id: value.get("id")?.as_i64()?,
153            pattern: value.get("pattern")?.as_i64()?,
154            inputs: stacks(value.get("inputs")?)?,
155            outputs: stacks(value.get("outputs")?)?,
156        })
157    }
158}
159
160fn stacks_value(stacks: &[Stack]) -> Value {
161    Value::Array(stacks.iter().map(Stack::to_value).collect())
162}
163
164fn stacks(value: &Value) -> Option<Vec<Stack>> {
165    // An empty Lua table has no keys to tell a sequence from a map.
166    if matches!(value, Value::Map(m) if m.is_empty()) {
167        return Some(Vec::new());
168    }
169    value.as_array()?.into_iter().map(Stack::from_value).collect()
170}
171
172fn list<T>(reply: Vec<Value>, what: &str, parse: impl Fn(&Value) -> Option<T>) -> Result<Vec<T>> {
173    let value: Value = single(reply)?;
174    if matches!(&value, Value::Map(m) if m.is_empty()) {
175        return Ok(Vec::new());
176    }
177    value
178        .as_array()
179        .and_then(|items| items.into_iter().map(parse).collect())
180        .ok_or_else(|| Error::UnexpectedReply(format!("expected a list of {what}, got {value:?}")))
181}
182
183fn job(reply: Vec<Value>) -> Result<Option<Job>> {
184    match single::<Value>(reply)? {
185        Value::Nil => Ok(None),
186        value => Job::from_value(&value)
187            .map(Some)
188            .ok_or_else(|| Error::UnexpectedReply(format!("expected a job, got {value:?}"))),
189    }
190}
191
192macro_rules! methods {
193    ($(
194        $(#[$doc:meta])*
195        fn $name:ident / $name_async:ident ($($arg:ident: $ty:ty),*) -> $ret:ty =
196            $lua:literal [$($value:expr),*] => $decode:expr;
197    )*) => {
198        impl PatternProvider {$(
199            $(#[$doc])*
200            pub fn $name(&self, $($arg: $ty),*) -> Result<$ret> {
201                let reply = self.invoke($lua, vec![$($value),*])?;
202                ($decode)(reply)
203            }
204
205            #[doc = concat!("[`Self::", stringify!($name), "`] without blocking; see [`crate::task`].")]
206            #[cfg(feature = "async")]
207            pub async fn $name_async(&self, $($arg: $ty),*) -> Result<$ret> {
208                let reply = self.invoke_async($lua, vec![$($value),*]).await?;
209                ($decode)(reply)
210            }
211        )*}
212    };
213}
214
215methods! {
216    /// Replaces every pattern. Returns how many there are.
217    fn set_patterns / set_patterns_async(patterns: &[Pattern]) -> usize =
218        "setPatterns" [Value::Array(patterns.iter().map(Pattern::to_value).collect())]
219        => |r| single::<crate::Number>(r).map(|n| n.as_i64() as usize);
220
221    /// Adds a pattern. Returns its index (from 1).
222    fn add_pattern / add_pattern_async(pattern: &Pattern) -> i64 =
223        "addPattern" [stacks_value(&pattern.inputs), stacks_value(&pattern.outputs)]
224        => |r| single::<crate::Number>(r).map(|n| n.as_i64());
225
226    /// Removes the pattern at `index` (from 1); later ones move down. Jobs
227    /// already handed over are kept. `false` if there was none.
228    fn remove_pattern / remove_pattern_async(index: i64) -> bool =
229        "removePattern" [index.into()] => single::<bool>;
230
231    /// Every pattern, in order.
232    fn patterns / patterns_async() -> Vec<Pattern> =
233        "getPatterns" [] => |r| list(r, "patterns", Pattern::from_value);
234
235    /// The jobs waiting, oldest first.
236    fn jobs / jobs_async() -> Vec<Job> =
237        "getJobs" [] => |r| list(r, "jobs", Job::from_value);
238
239    /// One job; `None` once it's done or cancelled.
240    fn job / job_async(id: i64) -> Option<Job> =
241        "getJob" [id.into()] => job;
242
243    /// Moves a job's inputs into the inventory or tank on `side` of the
244    /// block. `true` once everything is out, which ends the job; `false` if
245    /// some didn't fit (it stays held, for another try).
246    fn push_inputs / push_inputs_async(id: i64, side: Side) -> bool =
247        "pushInputs" [id.into(), side.into()] => single::<bool>;
248
249    /// Gives up on a job, returning its inputs to the ME network. `true` if
250    /// they all went back, ending the job. AE2's crafting job keeps waiting
251    /// for its outputs until it's cancelled in a terminal.
252    fn cancel_job / cancel_job_async(id: i64) -> bool =
253        "cancelJob" [id.into()] => single::<bool>;
254
255    /// Whether the block is on a powered ME network with a channel.
256    fn is_online / is_online_async() -> bool =
257        "isOnline" [] => single::<bool>;
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn stacks_round_trip() {
266        let stack = Stack { key: Some("{id:\"x\"}".into()), ..Stack::fluid("minecraft:water", 1000) };
267        assert_eq!(Stack::from_value(&stack.to_value()), Some(stack));
268    }
269
270    #[test]
271    fn jobs_decode_from_lua_style_tables() {
272        let stack = |n: &str| Value::Map(vec![("name".into(), n.into()), ("count".into(), 2.into())]);
273        let job = Value::Map(vec![
274            ("id".into(), 7.into()),
275            ("pattern".into(), 1.into()),
276            ("inputs".into(), Value::Map(vec![(1.into(), stack("minecraft:cobblestone"))])),
277            ("outputs".into(), Value::Array(vec![stack("minecraft:stone")])),
278        ]);
279        let job = Job::from_value(&job).unwrap();
280        assert_eq!((job.id, job.inputs[0].name.as_str(), job.outputs[0].count), (7, "minecraft:cobblestone", 2));
281        assert_eq!(list(vec![Value::Map(vec![])], "jobs", Job::from_value), Ok(vec![]));
282    }
283}