monsoon-frontend 0.2.2

Native GUI frontend for the Monsoon NES emulator, built with egui
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
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;

use crossbeam_channel::{Receiver, Sender};
use monsoon_core::emulation::nes::Nes;
use monsoon_core::emulation::ppu_util::{EmulatorFetchable, PaletteData};
use monsoon_core::util::Hashable;

use crate::messages::{ControllerEvent, EmulatorMessage, FrontendMessage, SaveType};

/// Channel-based emulator wrapper for clean frontend/emulator separation.
///
/// This module provides a non-threaded emulator wrapper that uses channels for
/// communication. While it doesn't provide true multi-threading (due to the
/// emulator core using `Rc<RefCell<>>` which is not `Send`), it provides:
///
/// - Clean separation of concerns between frontend and emulator
/// - Message-based communication protocol
/// - Easy upgrade path to multi-threading once core is refactored
/// - Testable architecture
///
/// # Architecture
///
/// ```text
/// Frontend → FrontendMessage → ChannelEmulator → Emulator Core
///              (channels)              ↓
/// Frontend ← EmulatorMessage ←─────────┘
/// ```
///
/// # Example
///
/// ```ignore
/// use lockstep::emulation::channel_emu::ChannelEmulator;
/// use lockstep::emulation::emu::{Console, Consoles};
/// use lockstep::emulation::nes::Nes;
///
/// let console = Nes::default();
/// let (mut emu, tx_to_emu, rx_from_emu) = ChannelEmulator::new(console);
///
/// // In your main loop:
/// emu.step_frame()?; // Run one frame
/// ```
/// A non-threaded emulator wrapper that communicates via channels
/// This provides a clean interface for the frontend without threading
/// complications. The emulator runs in the same thread but is decoupled via
/// message passing.
pub struct ChannelEmulator {
    pub nes: Nes,
    to_frontend: Sender<EmulatorMessage>,
    from_frontend: Receiver<FrontendMessage>,
    input: u8,
    /// Cached palette data for change detection
    last_palette_data: Option<PaletteData>,
    /// Cached hash of pattern table data for efficient change detection
    last_pattern_table_hash: Option<u64>,
}

pub static FETCH_DEPS: OnceLock<HashMap<EmulatorFetchable, Vec<EmulatorFetchable>>> =
    OnceLock::new();

impl ChannelEmulator {
    fn setup_fetch_deps() {
        let mut deps = HashMap::new();

        deps.insert(
            EmulatorFetchable::Tiles(None),
            vec![EmulatorFetchable::Palettes(None)],
        );
        deps.insert(
            EmulatorFetchable::Nametables(None),
            vec![EmulatorFetchable::Tiles(None)],
        );
        deps.insert(
            EmulatorFetchable::Sprites(None),
            vec![EmulatorFetchable::Tiles(None)],
        );

        deps.insert(
            EmulatorFetchable::SoamSprites(None),
            vec![EmulatorFetchable::Tiles(None)],
        );

        FETCH_DEPS.get_or_init(|| deps);
    }

    pub fn new(nes: Nes) -> (Self, Sender<FrontendMessage>, Receiver<EmulatorMessage>) {
        Self::setup_fetch_deps();

        let (tx_to_emu, rx_from_frontend) = crossbeam_channel::unbounded();
        let (tx_from_emu, rx_to_frontend) = crossbeam_channel::unbounded();

        let emu = Self {
            nes,
            to_frontend: tx_from_emu,
            from_frontend: rx_from_frontend,
            input: 0,
            last_palette_data: None,
            last_pattern_table_hash: None,
        };

        (emu, tx_to_emu, rx_to_frontend)
    }

    /// Run one frame of emulation and handle messages
    pub fn process_messages(&mut self) -> Result<(), String> {
        // Controller input is provided by frontend each UI update for bindings
        // currently held. Reset the bitfield once per update so held inputs
        // persist across all frames executed this update, but release cleanly
        // when not re-sent on the next update.
        self.input = 0;

        // Check for messages from frontend
        while let Ok(msg) = self.from_frontend.try_recv() {
            match msg {
                FrontendMessage::Quit => {
                    let state = self.nes.save_state();
                    if let Some(state) = state {
                        let _ = self.to_frontend.send(EmulatorMessage::SaveState(
                            Box::new(state),
                            SaveType::Autosave,
                        ));
                    }
                    let _ = self.to_frontend.send(EmulatorMessage::Stopped);
                    return Err("Quit requested".to_string());
                }
                FrontendMessage::Reset => {
                    self.nes.reset();
                }
                FrontendMessage::StepFrame => {
                    // Execute one frame regardless of pause state
                    self.execute_frame()?;
                }
                FrontendMessage::ControllerInput(event) => {
                    self.handle_controller_event(event);
                }
                FrontendMessage::RequestDebugData(fetchable) => match fetchable {
                    EmulatorFetchable::Palettes(_) => {
                        let _ = self
                            .to_frontend
                            .send(EmulatorMessage::DebugData(self.nes.get_palettes_debug()));
                    }
                    EmulatorFetchable::Tiles(_) => {
                        let _ = self
                            .to_frontend
                            .send(EmulatorMessage::DebugData(self.nes.get_tiles_debug()));
                    }
                    EmulatorFetchable::Nametables(_) => {
                        let _ = self
                            .to_frontend
                            .send(EmulatorMessage::DebugData(self.nes.get_nametable_debug()));
                    }
                    EmulatorFetchable::Sprites(_) => {
                        let _ = self
                            .to_frontend
                            .send(EmulatorMessage::DebugData(self.nes.get_sprites_debug()));
                    }
                    EmulatorFetchable::SoamSprites(_) => {
                        let _ = self.to_frontend.send(EmulatorMessage::DebugData(
                            self.nes.get_soam_sprites_debug(),
                        ));
                    }
                },
                FrontendMessage::WritePpu(address, data) => self.nes.ppu_mem_init(address, data),
                FrontendMessage::WriteCpu(address, data) => self.nes.cpu_mem_init(address, data),
                FrontendMessage::LoadRom((rom, name)) => {
                    let loadable = (&rom.data[..], name);
                    self.nes.load_rom(&loadable);
                    let _ = self.to_frontend.send(EmulatorMessage::RomLoaded(
                        self.nes.rom_file.clone().map(|r| (r, rom)),
                    ));
                }
                FrontendMessage::Power(is_powered) => {
                    if is_powered {
                        self.nes.power();
                    } else {
                        self.nes.power_off()
                    }
                }
                FrontendMessage::CreateSaveState(t) => {
                    if self.nes.rom_file.is_some() {
                        let state = self.nes.save_state();
                        if let Some(state) = state {
                            let _ = self
                                .to_frontend
                                .send(EmulatorMessage::SaveState(Box::new(state), t));
                        }
                    }
                }
                FrontendMessage::LoadSaveState(s) => self.nes.load_state(*s),
                FrontendMessage::StepPpuCycle => self.execute_ppu_cycle()?,
                FrontendMessage::StepCpuCycle => self.execute_cpu_cycle()?,
                FrontendMessage::StepMasterCycle => self.execute_master_cycle()?,
                FrontendMessage::StepScanline => self.execute_scanline()?,
            }
        }

        Ok(())
    }

    pub fn execute_master_cycle(&mut self) -> Result<(), String> {
        self.nes.cpu_mem_init(0x4016, self.input);

        match self.nes.step() {
            Ok(_) => {
                // Frame completed, send it to frontend
                let frame = self.nes.get_pixel_buffer();
                let frame_data = (*frame).to_vec();
                if self
                    .to_frontend
                    .send(EmulatorMessage::FrameReady(frame_data))
                    .is_err()
                {
                    // Frontend disconnected
                    return Err("Frontend disconnected".to_string());
                }

                // Check if debug data has changed and notify frontend
                self.check_debug_data_changed();

                Ok(())
            }
            Err(e) => Err(format!("Emulator error: {}", e)),
        }
    }

    pub fn execute_ppu_cycle(&mut self) -> Result<(), String> {
        self.nes.cpu_mem_init(0x4016, self.input);

        match self.nes.step_ppu_cycle() {
            Ok(_) => {
                // Frame completed, send it to frontend
                let frame = self.nes.get_pixel_buffer();
                let frame_data = (*frame).to_vec();
                if self
                    .to_frontend
                    .send(EmulatorMessage::FrameReady(frame_data))
                    .is_err()
                {
                    // Frontend disconnected
                    return Err("Frontend disconnected".to_string());
                }

                // Check if debug data has changed and notify frontend
                self.check_debug_data_changed();

                Ok(())
            }
            Err(e) => Err(format!("Emulator error: {}", e)),
        }
    }

    pub fn execute_cpu_cycle(&mut self) -> Result<(), String> {
        self.nes.cpu_mem_init(0x4016, self.input);

        match self.nes.step_cpu_cycle() {
            Ok(_) => {
                // Frame completed, send it to frontend
                let frame = self.nes.get_pixel_buffer();
                let frame_data = (*frame).to_vec();
                if self
                    .to_frontend
                    .send(EmulatorMessage::FrameReady(frame_data))
                    .is_err()
                {
                    // Frontend disconnected
                    return Err("Frontend disconnected".to_string());
                }

                // Check if debug data has changed and notify frontend
                self.check_debug_data_changed();

                Ok(())
            }
            Err(e) => Err(format!("Emulator error: {}", e)),
        }
    }

    pub fn execute_scanline(&mut self) -> Result<(), String> {
        self.nes.cpu_mem_init(0x4016, self.input);

        match self.nes.step_scanline() {
            Ok(_) => {
                // Frame completed, send it to frontend
                let frame = self.nes.get_pixel_buffer();
                let frame_data = (*frame).to_vec();
                if self
                    .to_frontend
                    .send(EmulatorMessage::FrameReady(frame_data))
                    .is_err()
                {
                    // Frontend disconnected
                    return Err("Frontend disconnected".to_string());
                }

                // Check if debug data has changed and notify frontend
                self.check_debug_data_changed();

                Ok(())
            }
            Err(e) => Err(format!("Emulator error: {}", e)),
        }
    }

    pub fn execute_frame(&mut self) -> Result<(), String> {
        self.nes.cpu_mem_init(0x4016, self.input);

        match self.nes.step_frame() {
            Ok(_) => {
                // Frame completed, send it to frontend
                let frame = self.nes.get_pixel_buffer();
                let frame_data = (*frame).to_vec();
                if self
                    .to_frontend
                    .send(EmulatorMessage::FrameReady(frame_data))
                    .is_err()
                {
                    // Frontend disconnected
                    return Err("Frontend disconnected".to_string());
                }

                // Check if debug data has changed and notify frontend
                self.check_debug_data_changed();

                Ok(())
            }
            Err(e) => Err(format!("Emulator error: {}", e)),
        }
    }

    /// Check if debug data has changed since last check, and send the data if
    /// so. This enables passive fetching of debug data - the frontend only
    /// rebuilds textures when data actually changes, rather than on a regular
    /// interval.
    fn check_debug_data_changed(&mut self) {
        // Check palette data (32 bytes, cheap comparison)
        if let EmulatorFetchable::Palettes(Some(current_palette)) = self.nes.get_palettes_debug() {
            let current = *current_palette; // Copy the PaletteData (it's 32 bytes)
            let palette_changed = match &self.last_palette_data {
                Some(last) => *last != current,
                None => true, // First time, consider it changed
            };

            if palette_changed {
                self.last_palette_data = Some(current);
                let _ =
                    self.to_frontend
                        .send(EmulatorMessage::DebugData(EmulatorFetchable::Palettes(
                            Some(Box::new(current)),
                        )));
            }
        }

        // Check tile/pattern table data using a fast hash of raw PPU memory
        // Pattern tables occupy 0x0000-0x1FFF (8KB) in PPU address space
        let pattern_table_memory = self.nes.get_memory_debug(Some(0x0000..=0x1FFF))[1].to_vec();
        let current_hash = &pattern_table_memory.hash();

        let tiles_changed = match self.last_pattern_table_hash {
            Some(last_hash) => last_hash != *current_hash,
            None => true, // First time, consider it changed
        };

        if tiles_changed {
            self.last_pattern_table_hash = Some(*current_hash);
            // Send the actual tile data directly to avoid a round-trip request
            let _ = self
                .to_frontend
                .send(EmulatorMessage::DebugData(self.nes.get_tiles_debug()));
        }
    }

    fn handle_controller_event(&mut self, event: ControllerEvent) {
        match event {
            ControllerEvent::A => self.input |= 0x1,
            ControllerEvent::B => self.input |= 0x2,
            ControllerEvent::Select => self.input |= 0x4,
            ControllerEvent::Start => self.input |= 0x8,
            ControllerEvent::Up => self.input |= 0x10,
            ControllerEvent::Down => self.input |= 0x20,
            ControllerEvent::Left => self.input |= 0x40,
            ControllerEvent::Right => self.input |= 0x80,
        }
    }

    pub fn compute_required_fetches(
        enabled: &HashSet<EmulatorFetchable>,
        deps: &HashMap<EmulatorFetchable, Vec<EmulatorFetchable>>,
    ) -> HashSet<EmulatorFetchable> {
        let mut fetch = HashSet::new();
        let mut stack: Vec<_> = Vec::with_capacity(enabled.len());

        for x in enabled.iter() {
            stack.push(EmulatorFetchable::get_empty(x));
        }

        while let Some(to_fetch) = stack.pop() {
            // Only process if we haven't seen this fetchable before
            if fetch.insert(EmulatorFetchable::get_empty(&to_fetch)) {
                // If this fetchable has dependencies, add them to the stack for processing
                if let Some(reqs) = deps.get(&to_fetch) {
                    for x in reqs {
                        let empty = EmulatorFetchable::get_empty(x);
                        // Only add to stack if not already in fetch set
                        if !fetch.contains(&empty) {
                            stack.push(empty);
                        }
                    }
                }
            }
        }

        fetch
    }
}