aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/tectech/compatibility/openComputers/AvrArchitecture.java
blob: c12ac0e754a2f36dff23141c783f7c0336fd7847 (plain)
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
package tectech.compatibility.openComputers;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;

import org.apache.commons.compress.utils.IOUtils;

import com.github.technus.avrClone.AvrCore;
import com.github.technus.avrClone.instructions.ExecutionEvent;
import com.github.technus.avrClone.instructions.InstructionRegistry;
import com.github.technus.avrClone.instructions.exceptions.DebugEvent;
import com.github.technus.avrClone.instructions.exceptions.DelayEvent;
import com.github.technus.avrClone.memory.EepromMemory;
import com.github.technus.avrClone.memory.RemovableMemory;
import com.github.technus.avrClone.memory.program.ProgramMemory;

import li.cil.oc.Settings;
import li.cil.oc.api.Driver;
import li.cil.oc.api.driver.Item;
import li.cil.oc.api.driver.item.Memory;
import li.cil.oc.api.machine.Architecture;
import li.cil.oc.api.machine.ExecutionResult;
import li.cil.oc.api.machine.Machine;
import li.cil.oc.api.machine.Signal;
import li.cil.oc.common.SaveHandler;
import tectech.TecTech;
import tectech.util.Converter;

@Architecture.Name("AVR 32Bit Clone")
@Architecture.NoMemoryRequirements
public class AvrArchitecture implements Architecture {

    private final Machine machine;
    private AvrCore core;
    private boolean debugRun;
    private int delay;
    private int[] tempData;
    private int memSize;

    public AvrArchitecture(Machine machine) {
        this.machine = machine;
    }

    @Override
    public boolean isInitialized() {
        return core != null && core.checkValid();
    }

    @Override
    public boolean recomputeMemory(Iterable<ItemStack> components) {
        computeMemory(components);
        return true;
    }

    private void computeMemory(Iterable<ItemStack> components) {
        int memory = 0;
        for (ItemStack component : components) {
            Item driver = Driver.driverFor(component);
            if (driver instanceof Memory memoryDriver) {
                memory += memoryDriver.amount(component) * 256; // in integers
            } // else if (driver instanceof DriverEEPROM$) {

            // }
        }
        memory = Math.min(
            Math.max(memory, 0),
            Settings.get()
                .maxTotalRam());
        if (memory != memSize) {}
    }

    @Override
    public boolean initialize() {
        core = new AvrCore();

        computeMemory(
            this.machine.host()
                .internalComponents());

        if (isInitialized()) {
            machine.beep(".");
            return true;
        }
        return false;
    }

    @Override
    public void close() {
        core = null;
        tempData = null;
        delay = 0;
    }

    @Override
    public void runSynchronized() {
        core.cycle();
    }

    @Override
    public ExecutionResult runThreaded(boolean isSynchronizedReturn) {
        if (core.awoken) {
            delay = 0;
            for (int load = 0; load < 512;) {
                load += core.getInstruction()
                    .getCost(core);
                ExecutionEvent executionEvent = core.cpuCycleForce();
                if (executionEvent != null) {
                    if (executionEvent.throwable instanceof DelayEvent) {
                        delay = executionEvent.data[0];
                        break;
                    } else if (executionEvent.throwable instanceof DebugEvent) {
                        if (debugRun) {
                            // aBaseMetaTileEntity.setActive(false);
                            break;
                        }
                    }
                }
            }
        } else if (delay > 0) {
            delay--;
            if (delay == 0) {
                core.awoken = true;
            }
        }
        return null;
    }

    @Override
    public void onSignal() {
        Signal signal = machine.popSignal();

        core.interruptsHandle();
    }

    @Override
    public void onConnect() {
        // init network components, in case init was called from load logic (pre first tick?)
    }

    @Override
    public void load(NBTTagCompound avr) {
        debugRun = avr.getBoolean("debugRun");
        delay = avr.getInteger("delay");
        core.active = avr.getBoolean("active");
        core.awoken = (avr.getBoolean("awoken"));
        core.programCounter = avr.getInteger("programCounter");
        InstructionRegistry registry = InstructionRegistry.REGISTRIES.get(avr.getString("instructionRegistry"));
        if (registry != null) {
            byte[] instructions = SaveHandler.load(
                avr,
                this.machine.node()
                    .address() + "_instructionsMemory");
            byte[] param0 = SaveHandler.load(
                avr,
                this.machine.node()
                    .address() + "_param0Memory");
            byte[] param1 = SaveHandler.load(
                avr,
                this.machine.node()
                    .address() + "_param1Memory");
            if (instructions != null && param0 != null
                && param1 != null
                && instructions.length > 0
                && param0.length > 0
                && param1.length > 0) {
                int[] instr = null, par0 = null, par1 = null;
                try {
                    GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(instructions));
                    instr = Converter.readInts(IOUtils.toByteArray(gzis));
                    IOUtils.closeQuietly(gzis);
                } catch (IOException e) {
                    TecTech.LOGGER.error("Failed to decompress instructions memory from disk.");
                    e.printStackTrace();
                }
                try {
                    GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(param0));
                    par0 = Converter.readInts(IOUtils.toByteArray(gzis));
                    IOUtils.closeQuietly(gzis);
                } catch (IOException e) {
                    TecTech.LOGGER.error("Failed to decompress param0 memory from disk.");
                    e.printStackTrace();
                }
                try {
                    GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(param1));
                    par1 = Converter.readInts(IOUtils.toByteArray(gzis));
                    IOUtils.closeQuietly(gzis);
                } catch (IOException e) {
                    TecTech.LOGGER.error("Failed to decompress param1 memory from disk.");
                    e.printStackTrace();
                }
                if (instr != null && par0 != null
                    && par1 != null
                    && instr.length == par0.length
                    && instr.length == par1.length) {
                    core.setProgramMemory(new ProgramMemory(registry, avr.getBoolean("immersive"), instr, par0, par1));
                }
            }
        }
        if (avr.hasKey("eepromSize")) {
            core.restoreEepromDefinition(EepromMemory.make(avr.getInteger("eepromSize")));
        }
        byte[] data = SaveHandler.load(
            avr,
            this.machine.node()
                .address() + "_dataMemory");
        if (data != null && data.length > 0) {
            try {
                GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(data));
                tempData = Converter.readInts(IOUtils.toByteArray(gzis));
                IOUtils.closeQuietly(gzis);
            } catch (IOException e) {
                TecTech.LOGGER.error("Failed to decompress data memory from disk.");
                e.printStackTrace();
            }
        }
        core.checkValid();
    }

    @Override
    public void save(NBTTagCompound avr) {
        avr.setBoolean("debugRun", debugRun);
        avr.setInteger("delay", delay);
        avr.setBoolean("active", core.active);
        avr.setBoolean("awoken", core.awoken);
        avr.setInteger("programCounter", core.programCounter);
        ProgramMemory programMemory = core.getProgramMemory();
        if (programMemory != null) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(Converter.writeInts(programMemory.instructions));
                gzos.close();
                SaveHandler.scheduleSave(
                    machine.host(),
                    avr,
                    machine.node()
                        .address() + "_instructionsMemory",
                    baos.toByteArray());
            } catch (IOException e) {
                TecTech.LOGGER.error("Failed to compress instructions memory to disk");
                e.printStackTrace();
            }
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(Converter.writeInts(programMemory.param0));
                gzos.close();
                SaveHandler.scheduleSave(
                    machine.host(),
                    avr,
                    machine.node()
                        .address() + "_param0Memory",
                    baos.toByteArray());
            } catch (IOException e) {
                TecTech.LOGGER.error("Failed to compress param0 memory to disk");
                e.printStackTrace();
            }
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(Converter.writeInts(programMemory.param1));
                gzos.close();
                SaveHandler.scheduleSave(
                    machine.host(),
                    avr,
                    machine.node()
                        .address() + "_param1Memory",
                    baos.toByteArray());
            } catch (IOException e) {
                TecTech.LOGGER.error("Failed to compress param1 memory to disk");
                e.printStackTrace();
            }
            avr.setBoolean("immersive", programMemory.immersiveOperands);
            avr.setString("instructionRegistry", programMemory.registry.toString());
        }
        RemovableMemory<EepromMemory> eeprom = core.getEepromMemory();
        if (eeprom != null) {
            avr.setInteger(
                "eepromSize",
                eeprom.getDefinition()
                    .getSize());
        }
        if (core.dataMemory != null) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(Converter.writeInts(core.dataMemory));
                gzos.close();
                SaveHandler.scheduleSave(
                    machine.host(),
                    avr,
                    machine.node()
                        .address() + "_dataMemory",
                    baos.toByteArray());
            } catch (IOException e) {
                TecTech.LOGGER.error("Failed to compress data memory to disk");
                e.printStackTrace();
            }
        }
    }
}