gte-core 0.19.1

Core of the GameTank Rust Emulator
Documentation
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use gte_w65c02s::{System, W65C02S};
use log::{debug, error, info, warn};
use gte_w65c02s::State::AwaitingInterrupt;
use core::fmt::{Debug, Formatter};
use bytemuck::bytes_of;
use heapless::{FnvIndexMap};
use rtrb::PushError;
use gte_acp::audio_output::GameTankAudio;
use crate::blitter::Blitter;
use crate::cartridges::CartridgeType;
use crate::emulator::PlayState::{Paused, Playing, WasmInit};
use crate::gametank_bus::{CpuBus};
use gte_acp::AcpBus;
use crate::inputs::{ControllerButton, InputCommand, KeyState};
use crate::inputs::ControllerButton::{Down, Left, Right, Start, Up, A, B, C};
use crate::inputs::InputCommand::{Controller1, Controller2, HardReset, PlayPause, SoftReset};
use crate::inputs::KeyState::JustReleased;

pub const WIDTH: u32 = 128;
pub const HEIGHT: u32 = 128;

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PlayState {
    WasmInit,
    Paused,
    Playing,
}

pub trait TimeDaemon {
    fn get_now_ms(&self) -> f64;
}

/// Snapshot measuring the last 1 second-ish of ACP load
#[derive(Copy, Clone, Debug, Default)]
pub struct AcpLoadStats {
    /// Worst-case ACP cycles the audio ISR took to run in the last window.
    pub worst_case_cycles: i32,
    /// ACP cycle budget available per sample at the current sample rate.
    pub budget_cycles: i32,
    /// Percentage (0-100) of samples in the last window where the ISR was
    /// still running when the next sample's IRQ came due (i.e. dropped).
    pub overrun_percent: u32,
    /// The ACP's current sample rate in Hz, derived from the rate register.
    pub sample_rate_hz: u32,
    /// Number of sample periods the last window covers (for context).
    pub periods_measured: u32,
}

/// Tracks whether the ACP firmware is keeping up with its sample deadline.
#[derive(Default, Debug)]
struct AcpStats {
    periods: u32,
    overruns: u32,
    worst_compute: i32,

    cycles_awake: i32,
    asleep: bool,

    last_worst_compute: i32,
    last_budget: i32,
    last_overrun_percent: u32,
    last_sample_rate: u32,
    last_periods: u32,
}

impl AcpStats {
    fn tick(&mut self, cycles: i32, waiting: bool) {
        if self.asleep {
            return;
        }
        self.cycles_awake += cycles;
        if waiting {
            self.worst_compute = self.worst_compute.max(self.cycles_awake);
            self.asleep = true;
        }
    }

    fn record(&mut self) {
        self.periods += 1;
        if self.asleep {
            // woken by this IRQ; start timing the next sample
            self.asleep = false;
            self.cycles_awake = 0;
        } else {
            // still computing when the next sample came due
            self.overruns += 1;
        }
    }

    fn report(&mut self, interval: u32, budget: i32, reg: u8) {
        if self.periods < interval {
            return;
        }
        if self.overruns > 0 {
            warn!(
            "ACP: {}cy/sample, ${:02X} budgets {}cy - {}% of samples duplicated",
            self.worst_compute,
            reg,
            budget,
            self.overruns * 100 / self.periods,
        );
        }
        self.last_worst_compute = self.worst_compute;
        self.last_budget = budget;
        self.last_overrun_percent = self.overruns * 100 / self.periods.max(1);
        self.last_sample_rate = interval;
        self.last_periods = self.periods;
        self.periods = 0;
        self.overruns = 0;
        self.worst_compute = 0;
    }
}

pub struct Emulator<Clock: TimeDaemon> {
    pub cpu_bus: CpuBus,
    pub acp_bus: AcpBus,
    pub cpu: W65C02S,
    pub acp: W65C02S,
    pub blitter: Blitter,
    pub clock_cycles_to_vblank: i32,
    pub last_emu_tick: f64,
    pub cpu_ns_per_cycle: f64,
    pub cpu_frequency_hz: f64,
    pub last_render_time: f64,
    pub audio_out: Option<GameTankAudio>,
    pub target_sample_rate: f64,
    pub play_state: PlayState,
    pub wait_counter: u64,
    pub input_state: FnvIndexMap<InputCommand, KeyState, 32>, // capacity of 32 entries
    pub clock: Clock,
    pub mouse_paddle_enabled: bool,

    acp_stats: AcpStats,
}

impl <Clock: TimeDaemon> Emulator<Clock> {
    pub fn load_rom(&mut self, bytes: &[u8]) {
        warn!("loading new rom from memory, size: {}", bytes.len());
        self.cpu_bus.cartridge = CartridgeType::from_slice(bytes);
        warn!(" - cartridge loaded from memory");
        self.cpu.reset();
        warn!(" - cpu reset");
        self.acp.reset();
        warn!(" - acp reset");
        self.blitter.clear_irq_trigger();
        warn!(" - blitter irq cleared");
    }
}

impl <Clock: TimeDaemon> Debug for Emulator<Clock> {
    fn fmt(&self, f: &mut Formatter) -> core::fmt::Result {
        f.debug_struct("Emulator")
            .field("cpu_bus", &self.cpu_bus)
            .field("acp_bus", &self.acp_bus)
            .field("cpu", &self.cpu)
            .field("acp", &self.acp)
            .field("blitter", &self.blitter)
            .field("clock_cycles_to_vblank", &self.clock_cycles_to_vblank)
            .field("last_emu_tick", &self.last_emu_tick)
            .finish()
    }
}

impl <Clock: TimeDaemon> Emulator<Clock> {
    pub fn wasm_init(&mut self) {
        if self.play_state == WasmInit {
            self.play_state = Playing;
            self.last_emu_tick = self.clock.get_now_ms();
            self.last_render_time = self.clock.get_now_ms();
        }
    }

    pub fn init(clock: Clock, target_sample_rate: f64) -> Self {
        let play_state = WasmInit;

        let mut bus = CpuBus::default();
        let mut cpu = W65C02S::new();
        cpu.step(&mut bus); // take one initial step, to get through the reset vector

        let acp = W65C02S::new();
        let blitter = Blitter::default();

        let last_cpu_tick_ms = clock.get_now_ms();
        let cpu_frequency_hz = 3_579_545.0; // Precise frequency
        let cpu_ns_per_cycle = 1_000_000_000.0 / cpu_frequency_hz; // Nanoseconds per cycle
        let last_render_time = last_cpu_tick_ms;

        Emulator {
            play_state,
            cpu_bus: bus,
            acp_bus: AcpBus::default(),
            cpu,
            acp,
            blitter,
            clock_cycles_to_vblank: 59659,
            last_emu_tick: last_cpu_tick_ms,
            cpu_frequency_hz,
            cpu_ns_per_cycle,
            last_render_time,
            audio_out: None,
            target_sample_rate,
            wait_counter: 0,
            input_state: Default::default(),
            clock,
            acp_stats: AcpStats::default(),
            mouse_paddle_enabled: false
        }
    }

    pub fn process_cycles(&mut self, is_web: bool) {
        self.process_inputs();

        if self.play_state != Playing {
            return
        }

        let now_ms = self.clock.get_now_ms();
        let mut elapsed_ms = now_ms - self.last_emu_tick;

        if elapsed_ms > 33.0 {
            warn!("emulator took more than 33ms to process cycles");
            elapsed_ms = 16.667;
        }

        let elapsed_ns = elapsed_ms * 1000000.0;
        let mut remaining_cycles: i32 = (elapsed_ns / self.cpu_ns_per_cycle) as i32;
        let mut acp_cycle_accumulator = 0;

        while remaining_cycles > 0 {
            if self.cpu.get_state() == AwaitingInterrupt {
                self.wait_counter += 1;
                // get cpu's current asm code
            } else if self.wait_counter > 0 {
                debug!("waited {} cycles", self.wait_counter);
                self.wait_counter = 0;
            }

            let cpu_cycles = self.cpu.step(&mut self.cpu_bus);
            remaining_cycles -= cpu_cycles;
            acp_cycle_accumulator += cpu_cycles * 4;

            // pass aram to acp
            if self.cpu_bus.system_control.acp_enabled() {
                self.run_acp(&mut acp_cycle_accumulator);
            }

            // blit
            for _ in 0..cpu_cycles {
                self.blitter.cycle(&mut self.cpu_bus);
            }

            // TODO: instant blit option
            let blit_irq = self.blitter.irq_trigger;
            if blit_irq {
                debug!("blit irq");
            }
            self.cpu.set_irq(blit_irq);

            self.clock_cycles_to_vblank -= cpu_cycles;
            if self.clock_cycles_to_vblank <= 0 {
                self.vblank();
            }
        }

        self.last_emu_tick = now_ms;

        if !is_web && (now_ms - self.last_render_time) >= 16.67 {
            debug!("time since last render: {}", now_ms - self.last_render_time);
            self.last_render_time = now_ms;
        }
    }

    fn run_acp(&mut self, acp_cycle_accumulator: &mut i32) {
        if self.cpu_bus.system_control.clear_acp_reset() {
            self.acp.reset();
        }

        if self.cpu_bus.system_control.clear_acp_nmi() {
            self.acp.set_nmi(true);
        }

        while *acp_cycle_accumulator > 0 {
            let acp_cycles = self.acp.step(&mut self.acp_bus);
            *acp_cycle_accumulator -= acp_cycles;
            self.acp_bus.irq_counter -= acp_cycles;
            self.acp_bus.cycles_since_write += acp_cycles;
            self.acp_stats.tick(acp_cycles, self.acp.get_state() == AwaitingInterrupt);

            // clear stuff ig
            self.acp.set_irq(false);
            self.acp.set_nmi(false);

            if self.acp_bus.irq_counter <= 0 {
                let divisor = self.cpu_bus.system_control.sample_divisor() as i32;
                let budget = divisor * 4;

                self.acp_bus.irq_counter = budget;
                self.acp.set_irq(true);

                self.acp_stats.record();
                self.acp_stats.report(
                    (self.cpu_frequency_hz / divisor as f64) as u32,
                    budget,
                    self.cpu_bus.system_control.audio_enable_sample_rate,
                );

                self.emit_sample(divisor);
            }
        }
    }

    /// Push the latched DAC value into the audio pipeline, recreating the
    /// output stream if the program changed the sample rate.
    fn emit_sample(&mut self, divisor: i32) {
        let sample_rate = self.cpu_frequency_hz / divisor as f64;

        if self.audio_out.as_ref().is_none_or(|gta| gta.sample_rate != sample_rate) {
            warn!(
                "recreated audio stream with new sample rate: {:.3}Hz (${:02X})",
                sample_rate, self.cpu_bus.system_control.audio_enable_sample_rate
            );
            self.audio_out = Some(GameTankAudio::new(sample_rate, self.target_sample_rate));
        }

        if let Some(audio) = &mut self.audio_out {
            if let Err(e) = audio.producer.push(self.acp_bus.sample) {
                error!("not enough slots in audio producer: {e}");
            }
            audio.convert_to_output_buffers();
        }
    }

    fn vblank(&mut self) {
        self.clock_cycles_to_vblank += 59659;

        if self.cpu_bus.vblank_nmi_enabled() {
            self.cpu.set_nmi(true);
            debug!("vblanked");
        }
    }

    pub fn set_input_state(&mut self, input_command: InputCommand, state: KeyState) {
        self.input_state.insert(input_command, state).expect("shit's full dog ://");
    }

    pub fn opcode_cycle_profile(&self) -> gte_w65c02s::OpcodeCycleProfile {
        self.cpu.get_cycle_profile()
    }

    pub fn set_opcode_cycle_profile(&mut self, profile: gte_w65c02s::OpcodeCycleProfile) {
        self.cpu.set_cycle_profile(profile);
        self.acp.set_cycle_profile(profile);
    }

    pub fn acp_load_stats(&self) -> AcpLoadStats {
        AcpLoadStats {
            worst_case_cycles: self.acp_stats.last_worst_compute,
            budget_cycles: self.acp_stats.last_budget,
            overrun_percent: self.acp_stats.last_overrun_percent,
            sample_rate_hz: self.acp_stats.last_sample_rate,
            periods_measured: self.acp_stats.last_periods,
        }
    }

    fn process_inputs(&mut self) {
        let keys: Vec<_> = self.input_state.keys().cloned().collect();  // Clone keys to avoid borrowing conflicts

        if keys.len() > 0 && self.play_state == WasmInit {
            self.play_state = Playing;
        }

        for key in &keys {
            match key {
                Controller1(button) => { self.set_gamepad_input(0, &key, &button); }
                Controller2(button) => { self.set_gamepad_input(1, &key, &button); }
                PlayPause => {
                    if self.input_state[key] == JustReleased {
                        match self.play_state {
                            Paused => { self.play_state = Playing; }
                            Playing => { self.play_state = Paused; }
                            WasmInit => { self.play_state = Playing; }
                        }
                    }
                }
                SoftReset => {
                    self.cpu.reset();
                }
                HardReset => {
                    // hard reset reinitializes memory/cpus
                    let cart = self.cpu_bus.cartridge.clone();
                    self.cpu_bus = CpuBus::default();
                    self.cpu_bus.cartridge = cart;
                    self.cpu = W65C02S::new();
                    self.cpu.step(&mut self.cpu_bus); // take one initial step, to get through the reset vector
                    self.acp = W65C02S::new();
                    self.blitter = Blitter::default();
                }
            }

            self.input_state.insert(*key, self.input_state[key].update()).expect("shit's full dog ://");
        }
    }

    pub fn apply_paddle_delta(&mut self, delta: i8) {
        self.cpu_bus.system_control.apply_paddle_delta(delta);
    }
    
    pub fn set_mouse_paddle_enabled(&mut self, enabled: bool) {
        self.mouse_paddle_enabled = enabled;
    }

    fn set_gamepad_input(&mut self, gamepad: usize, key: &InputCommand, button: &ControllerButton) {
        let gamepad = &mut self.cpu_bus.system_control.gamepads[gamepad];
        match button {
            Up =>     { gamepad.up    = self.input_state[&key].is_pressed(); }
            Down =>   { gamepad.down  = self.input_state[&key].is_pressed(); }
            Left =>   { gamepad.left  = self.input_state[&key].is_pressed(); }
            Right =>  { gamepad.right = self.input_state[&key].is_pressed(); }
            B =>      { gamepad.b     = self.input_state[&key].is_pressed(); }
            A =>      { gamepad.a     = self.input_state[&key].is_pressed(); }
            Start =>  { gamepad.start = self.input_state[&key].is_pressed(); }
            C =>      { gamepad.c     = self.input_state[&key].is_pressed(); }
        }
    }
}