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
mod builder;

use super::{
    instructions::{DrawInstr, DrawInstruction, Flow, Instr, LInstruction},
    lexer::Token,
    memory::{LAddress, LRegistry, LVar},
};
pub use builder::ExecutorBuilderInternal;
use fimg::Image;
use std::{collections::VecDeque, io::Write, num::NonZeroUsize, pin::Pin};

#[derive(Debug, Copy, Clone, Default)]
pub struct Display(pub usize);
#[derive(Debug, Copy, Clone)]
// negative means bank, positive means cell
pub struct Memory(pub(crate) i8);
impl Memory {
    pub(crate) const fn fits(self, i: usize) -> bool {
        if self.0 < 0 {
            i < BANK_SIZE
        } else {
            i < CELL_SIZE
        }
    }

    pub(crate) fn size(self) -> usize {
        if self.0 < 0 {
            BANK_SIZE
        } else {
            CELL_SIZE
        }
    }
}
pub const BANK_SIZE: usize = 512;
pub const CELL_SIZE: usize = 64;

#[derive(Copy, Clone)]
pub struct Instruction(usize);

impl Instruction {
    /// # Safety
    /// verify n is valid.
    pub const unsafe fn new(n: usize) -> Self {
        Self(n)
    }

    pub fn get(self) -> usize {
        self.0
    }
}

impl std::fmt::Debug for Instruction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Instruction#{}", self.0)
    }
}

#[derive(Debug)]
pub enum PInstr<'s> {
    Instr(Instr<'s>),
    Draw(DrawInstr<'s>),
    Code(Box<[Token<'s>]>),
    NoOp,
}

#[derive(Debug, Copy, Clone)]
pub enum Limit {
    /// limited to n
    Limited(NonZeroUsize),
    /// unlimited
    Unlimited,
}

impl Limit {
    /// panics if n != 0
    pub fn limited(n: usize) -> Self {
        Self::Limited(n.try_into().expect("nonzero"))
    }
}

impl Limit {
    pub(crate) const fn reached(self, n: usize) -> bool {
        match self {
            Self::Limited(v) => v.get() <= n,
            Self::Unlimited => false,
        }
    }
}

/// One time use logic executor.
pub struct Executor<'varnames, W: Write> {
    /// if limited, will run n instructions before exiting.
    pub instruction_limit: Limit,
    /// if limtited, will loop(go from a end to the start) n times before exiting
    /// both unlimited does not mean this function will never return;
    /// a `Stop` instruction will break the loop.
    pub iteration_limit: Limit,
    pub(crate) inner: ExecutorContext<'varnames, W>,
    /// gets pointed to by drawbuf
    pub(crate) program: Pin<Box<[PInstr<'varnames>]>>,
    /// Counter for the number of instructions we have run so far.
    pub instructions_ran: usize,
}

pub enum UPInstr<'s> {
    Instr(Instr<'s>),
    Draw(DrawInstr<'s>),
    UnfinishedJump,
    Code(Box<[Token<'s>]>),
    NoOp,
}

pub struct Drawing<'v> {
    pub displays: Box<[fimg::Image<Vec<u8>, 4>]>,
    /// points to `Executor.program`
    pub buffer: VecDeque<*const DrawInstr<'v>>,
}

impl<'v> Drawing<'v> {
    fn buffer(&mut self, i: &DrawInstr<'v>) {
        self.buffer.push_back(i);
    }
}
pub struct ExecutorContext<'varnames, W: Write> {
    // maximum of 128 elements, so can use ~60KB
    pub cells: Box<[[f64; CELL_SIZE]]>, // screw world cells
    // maximum of 127 elements, so can use ~500KB
    pub banks: Box<[[f64; BANK_SIZE]]>,
    pub memory: LRegistry<'varnames>,
    pub counter: usize,
    pub display: Drawing<'varnames>,
    pub output: Option<W>,
    /// Counter for the number of iterations we have run so far.
    pub iterations: usize,
}

pub struct DisplayState {
    pub color: (u8, u8, u8, u8),
    pub stroke: f64,
}

impl DisplayState {
    pub const fn col(&self) -> [u8; 4] {
        [self.color.0, self.color.1, self.color.2, self.color.3]
    }
}

impl Default for DisplayState {
    fn default() -> Self {
        Self {
            color: Default::default(),
            stroke: 1.0,
        }
    }
}

impl<'s, W: Write> ExecutorContext<'s, W> {
    pub fn flush(&mut self, to: Display) {
        let mut state = DisplayState::default();
        // SAFETY: safe as long as the instruction isnt held too long
        while let Some(d) = unsafe { self.display.buffer.pop_front().map(|v| &*v) } {
            d.draw(
                &mut self.memory,
                &mut self.display.displays[to.0].as_mut(),
                &mut state,
            );
        }
    }

    pub fn mem(&mut self, Memory(m): Memory) -> &mut [f64] {
        if m < 0 {
            let m = (m + 1).unsigned_abs() as usize;
            &mut self.banks[m]
        } else {
            let m = m as usize;
            &mut self.cells[m]
        }
    }

    pub fn set(&mut self, a: &LAddress<'s>, b: LAddress<'s>) -> bool {
        self.memory.set(a, b)
    }

    pub fn get_mut(&mut self, a: &LAddress<'s>) -> Option<&mut LVar<'s>> {
        self.memory.get_mut(a)
    }

    pub fn jump(&mut self, Instruction(n): Instruction) {
        self.counter = n;
    }

    pub fn get<'a>(&'a self, a: &'a LAddress<'s>) -> &LVar<'s> {
        self.memory.get(a)
    }
}

/// Returned by the [`output`](Executor::output).function.
pub struct Output<W: Write> {
    /// Everything created by a `print` instruction.
    pub output: Option<W>,
    /// Logic displays that were drawn with `draw` instructions.
    pub displays: Box<[Image<Vec<u8>, 4>]>,
    /// Memory banks, written to with the `write`/`read` instructions
    pub cells: Box<[[f64; CELL_SIZE]]>,
    /// Memory cells, written to with the `write`/`read` instructions
    pub banks: Box<[[f64; BANK_SIZE]]>,
}

impl<'s, W: Write> Executor<'s, W> {
    /// Consume this executor, returning all output.
    pub fn output(mut self) -> Output<W> {
        for display in &mut *self.inner.display.displays {
            // TODO make the instructions draw flipped-ly
            display.flip_v();
        }
        Output {
            output: self.inner.output,
            displays: self.inner.display.displays,
            cells: self.inner.cells,
            banks: self.inner.banks,
        }
    }

    /// # Safety
    ///
    /// `counter` *must* be in bounds.
    unsafe fn run_current(&mut self) -> Flow {
        // SAFETY: yee
        match unsafe { self.program.get_unchecked(self.inner.counter) } {
            PInstr::Instr(i) => {
                // println!("run {i:?} ({:?})", self.inner.memory);
                i.run(&mut self.inner)
            }
            PInstr::Draw(i) => {
                self.inner.display.buffer(i);
                Flow::Continue
            }
            _ => Flow::Continue,
        }
    }

    /// Begin code execution.
    pub fn run(&mut self) {
        while !self.instruction_limit.reached(self.instructions_ran)
            && !self.iteration_limit.reached(self.inner.iterations)
        {
            // SAFETY: we have a check
            match unsafe { self.run_current() } {
                Flow::Continue => {}
                Flow::Exit => break,
                Flow::Stay => {
                    self.instructions_ran += 1;
                    continue;
                }
            };
            self.instructions_ran += 1;
            self.inner.counter += 1;
            if self.inner.counter >= self.program.len() {
                self.inner.counter = 0;
                self.inner.iterations += 1;
                self.inner.memory.clear();
            }
        }
    }
}