mindustry logic execution, map- and schematic- parsing and rendering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! logic processors and stuff
use std::borrow::Cow;
use std::string::FromUtf8Error;

use crate::block::simple::*;
use crate::block::*;
use crate::data::dynamic::DynType;
use crate::data::{self, CompressError, DataRead, DataWrite};

make_simple!(LogicBlock);

make_register! {
    "reinforced-message" => MessageLogic::new(1, true, cost!(Graphite: 10, Beryllium: 5));
    "message" => MessageLogic::new(1, true, cost!(Copper: 5, Graphite: 5));
    "switch" => SwitchLogic::new(1, true, cost!(Copper: 5, Graphite: 5));
    "micro-processor" => ProcessorLogic::new(1, true, cost!(Copper: 90, Lead: 50, Silicon: 50));
    "logic-processor" => ProcessorLogic::new(2, true, cost!(Lead: 320, Graphite: 60, Thorium: 50, Silicon: 80));
    "hyper-processor" => ProcessorLogic::new(3, true, cost!(Lead: 450, Thorium: 75, Silicon: 150, SurgeAlloy: 50));
    "memory-cell" => LogicBlock::new(1, true, cost!(Copper: 30, Graphite: 30, Silicon: 30));
    "memory-bank" => LogicBlock::new(2, true, cost!(Copper: 30, Graphite: 80, Silicon: 80, PhaseFabric: 30));
    "logic-display" => LogicBlock::new(3, true, cost!(Lead: 100, Metaglass: 50, Silicon: 50));
    "large-logic-display" => LogicBlock::new(6, true, cost!(Lead: 200, Metaglass: 100, Silicon: 150, PhaseFabric: 75));
    // todo canvas (cost!(Silicon: 30, Beryllium: 10))
    // editor only
    "world-processor" => LogicBlock::new(1, true, &[]);
    "world-message" => MessageLogic::new(1, true, &[]);
    "world-cell" => LogicBlock::new(1, true, &[]);
}

pub struct MessageLogic {
    size: u8,
    symmetric: bool,
    build_cost: BuildCost,
}

impl MessageLogic {
    #[must_use]
    pub const fn new(size: u8, symmetric: bool, build_cost: BuildCost) -> Self {
        assert!(size != 0, "invalid size");
        Self {
            size,
            symmetric,
            build_cost,
        }
    }

    state_impl!(pub String);
}

impl BlockLogic for MessageLogic {
    impl_block!();

    fn data_from_i32(&self, _: i32, _: GridPos) -> Result<DynData, DataConvertError> {
        Ok(DynData::Empty)
    }

    fn deserialize_state(&self, data: DynData) -> Result<Option<State>, DeserializeError> {
        match data {
            DynData::Empty | DynData::String(None) => Ok(Some(Self::create_state(String::new()))),
            DynData::String(Some(s)) => Ok(Some(Self::create_state(s))),
            _ => Err(DeserializeError::InvalidType {
                have: data.get_type(),
                expect: DynType::String,
            }),
        }
    }

    fn clone_state(&self, state: &State) -> State {
        Box::new(Self::get_state(state).clone())
    }

    fn mirror_state(&self, _: &mut State, _: bool, _: bool) {}

    fn rotate_state(&self, _: &mut State, _: bool) {}

    fn serialize_state(&self, state: &State) -> Result<DynData, SerializeError> {
        Ok(DynData::String(Some(Self::get_state(state).clone())))
    }
}

pub struct SwitchLogic {
    size: u8,
    symmetric: bool,
    build_cost: BuildCost,
}

impl SwitchLogic {
    #[must_use]
    pub const fn new(size: u8, symmetric: bool, build_cost: BuildCost) -> Self {
        assert!(size != 0, "invalid size");
        Self {
            size,
            symmetric,
            build_cost,
        }
    }

    state_impl!(pub bool);
}

impl BlockLogic for SwitchLogic {
    impl_block!();

    fn data_from_i32(&self, _: i32, _: GridPos) -> Result<DynData, DataConvertError> {
        Ok(DynData::Empty)
    }

    fn deserialize_state(&self, data: DynData) -> Result<Option<State>, DeserializeError> {
        match data {
            DynData::Empty => Ok(Some(Self::create_state(true))),
            DynData::Boolean(enabled) => Ok(Some(Self::create_state(enabled))),
            _ => Err(DeserializeError::InvalidType {
                have: data.get_type(),
                expect: DynType::Boolean,
            }),
        }
    }

    fn clone_state(&self, state: &State) -> State {
        Box::new(*Self::get_state(state))
    }

    fn mirror_state(&self, _: &mut State, _: bool, _: bool) {}

    fn rotate_state(&self, _: &mut State, _: bool) {}

    fn serialize_state(&self, state: &State) -> Result<DynData, SerializeError> {
        Ok(DynData::Boolean(*Self::get_state(state)))
    }
}

pub struct ProcessorLogic {
    size: u8,
    symmetric: bool,
    build_cost: BuildCost,
}

impl ProcessorLogic {
    #[must_use]
    pub const fn new(size: u8, symmetric: bool, build_cost: BuildCost) -> Self {
        assert!(size != 0, "invalid size");
        Self {
            size,
            symmetric,
            build_cost,
        }
    }

    state_impl!(pub ProcessorState);
}

impl BlockLogic for ProcessorLogic {
    impl_block!();

    fn data_from_i32(&self, _: i32, _: GridPos) -> Result<DynData, DataConvertError> {
        Ok(DynData::Empty)
    }

    fn deserialize_state(&self, data: DynData) -> Result<Option<State>, DeserializeError> {
        match data {
            DynData::Empty => Ok(Some(Self::create_state(ProcessorState::default()))),
            DynData::ByteArray(arr) => {
                let input = arr.as_ref();
                let buff = DataRead::new(input).deflate()?;
                let mut buff = DataRead::new(&buff);
                let ver = ProcessorDeserializeError::forward(buff.read_u8())?;
                if ver != 1 {
                    return Err(DeserializeError::Custom(Box::new(
                        ProcessorDeserializeError::Version(ver),
                    )));
                }

                let code_len = ProcessorDeserializeError::forward(buff.read_i32())?;
                if !(0..=500 * 1024).contains(&code_len) {
                    return Err(DeserializeError::Custom(Box::new(
                        ProcessorDeserializeError::CodeLength(code_len),
                    )));
                }
                let mut code = Vec::<u8>::new();
                code.resize(code_len as usize, 0);
                ProcessorDeserializeError::forward(buff.read_bytes(&mut code))?;
                let code = ProcessorDeserializeError::forward(String::from_utf8(code))?;
                let link_cnt = ProcessorDeserializeError::forward(buff.read_i32())?;
                if link_cnt < 0 {
                    return Err(DeserializeError::Custom(Box::new(
                        ProcessorDeserializeError::LinkCount(link_cnt),
                    )));
                }
                let mut links = Vec::<ProcessorLink>::new();
                links.reserve(link_cnt as usize);
                for _ in 0..link_cnt {
                    let name = ProcessorDeserializeError::forward(buff.read_utf())?;
                    let x = ProcessorDeserializeError::forward(buff.read_i16())?;
                    let y = ProcessorDeserializeError::forward(buff.read_i16())?;
                    links.push(ProcessorLink {
                        name: String::from(name),
                        x,
                        y,
                    });
                }
                Ok(Some(Self::create_state(ProcessorState { code, links })))
            }
            _ => Err(DeserializeError::InvalidType {
                have: data.get_type(),
                expect: DynType::Boolean,
            }),
        }
    }

    fn clone_state(&self, state: &State) -> State {
        Box::new(Self::get_state(state).clone())
    }

    fn mirror_state(&self, state: &mut State, horizontally: bool, vertically: bool) {
        for link in &mut Self::get_state_mut(state).links {
            if horizontally {
                link.x = -link.x;
            }
            if vertically {
                link.y = -link.y;
            }
        }
    }

    fn rotate_state(&self, state: &mut State, clockwise: bool) {
        for link in &mut Self::get_state_mut(state).links {
            let (cdx, cdy) = link.get_pos();
            link.x = if clockwise { cdy } else { -cdy };
            link.y = if clockwise { -cdx } else { cdx };
        }
    }

    fn serialize_state(&self, state: &State) -> Result<DynData, SerializeError> {
        let state = Self::get_state(state);
        let mut rbuff = DataWrite::default();
        ProcessorSerializeError::forward(rbuff.write_u8(1))?;
        assert!(state.code.len() < 500 * 1024);
        ProcessorSerializeError::forward(rbuff.write_i32(state.code.len() as i32))?;
        ProcessorSerializeError::forward(rbuff.write_bytes(state.code.as_bytes()))?;
        assert!(state.links.len() < i32::MAX as usize);
        ProcessorSerializeError::forward(rbuff.write_i32(state.links.len() as i32))?;
        for link in &state.links {
            ProcessorSerializeError::forward(rbuff.write_utf(&link.name))?;
            ProcessorSerializeError::forward(rbuff.write_i16(link.x))?;
            ProcessorSerializeError::forward(rbuff.write_i16(link.y))?;
        }
        let mut out = DataWrite::default();
        rbuff.inflate(&mut out)?;
        Ok(DynData::ByteArray(out.consume()))
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ProcessorDeserializeError {
    #[error("failed to read state data")]
    Read(#[from] data::ReadError),
    #[error("malformed utf-8 in processor code")]
    FromUtf8(#[from] FromUtf8Error),
    #[error("unsupported version ({0})")]
    Version(u8),
    #[error("invalid code length ({0})")]
    CodeLength(i32),
    #[error("invalid link count {0}")]
    LinkCount(i32),
}

impl ProcessorDeserializeError {
    pub fn forward<T, E: Into<Self>>(result: Result<T, E>) -> Result<T, DeserializeError> {
        match result {
            Ok(v) => Ok(v),
            Err(e) => Err(DeserializeError::Custom(Box::new(e.into()))),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ProcessorSerializeError {
    #[error("failed to write state data")]
    Write(#[from] data::WriteError),
    #[error(transparent)]
    Compress(#[from] CompressError),
}

impl ProcessorSerializeError {
    pub fn forward<T, E: Into<Self>>(result: Result<T, E>) -> Result<T, SerializeError> {
        match result {
            Ok(v) => Ok(v),
            Err(e) => Err(SerializeError::Custom(Box::new(e.into()))),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct ProcessorLink {
    name: String,
    x: i16,
    y: i16,
}

impl ProcessorLink {
    #[must_use]
    pub fn new(name: Cow<'_, str>, x: i16, y: i16) -> Self {
        assert!(
            u16::try_from(name.len()).is_ok(),
            "name too long ({})",
            name.len()
        );
        Self {
            name: name.into_owned(),
            x,
            y,
        }
    }

    #[must_use]
    pub fn get_name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub fn get_pos(&self) -> (i16, i16) {
        (self.x, self.y)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct ProcessorState {
    code: String,
    links: Vec<ProcessorLink>,
}

impl ProcessorState {
    #[must_use]
    pub fn get_code(&self) -> &str {
        &self.code
    }

    pub fn set_code(&mut self, code: Cow<'_, str>) -> Result<(), CodeError> {
        let as_str = &code as &str;
        if as_str.len() > 500 * 1024 {
            return Err(CodeError::TooLong(as_str.len()));
        }
        match code {
            Cow::Borrowed(s) => {
                self.code.clear();
                self.code.push_str(s);
            }
            Cow::Owned(s) => self.code = s,
        }
        Ok(())
    }

    #[must_use]
    pub fn get_links(&self) -> &[ProcessorLink] {
        &self.links
    }

    pub fn create_link(
        &mut self,
        mut name: String,
        x: i16,
        y: i16,
    ) -> Result<&ProcessorLink, CreateError> {
        if name.len() > u16::MAX as usize {
            return Err(CreateError::NameLength(name.len()));
        }
        for curr in &self.links {
            if name == curr.name {
                return Err(CreateError::DuplicateName(name));
            }
            if x == curr.x && y == curr.y {
                name.clear();
                name.push_str(&curr.name);
                return Err(CreateError::DuplicatePos { name, x, y });
            }
        }
        let idx = self.links.len();
        self.links.push(ProcessorLink { name, x, y });
        Ok(&self.links[idx])
    }

    pub fn add_link(&mut self, link: ProcessorLink) -> Result<&ProcessorLink, CreateError> {
        self.create_link(link.name, link.x, link.y)
    }

    pub fn remove_link(&mut self, idx: usize) -> Option<ProcessorLink> {
        if idx < self.links.len() {
            Some(self.links.remove(idx))
        } else {
            None
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum CodeError {
    #[error("code too long ({0} bytes)")]
    TooLong(usize),
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum CreateError {
    #[error("link name too long ({0} bytes)")]
    NameLength(usize),
    #[error("there is already a link named {0}")]
    DuplicateName(String),
    #[error("link {name} already points to ({x}, {y})")]
    DuplicatePos { name: String, x: i16, y: i16 },
}