lemur/src/emulator.rs

271 lines
7.8 KiB
Rust
Raw Normal View History

2024-11-03 16:32:53 +00:00
use std::{
2024-11-11 05:50:57 +00:00
collections::HashMap,
2024-11-03 16:32:53 +00:00
fs,
2024-11-04 14:59:58 +00:00
path::{Path, PathBuf},
2024-11-05 03:18:57 +00:00
sync::{
atomic::{AtomicBool, Ordering},
2024-11-10 21:08:49 +00:00
mpsc::{self, RecvError, TryRecvError},
2024-11-05 03:18:57 +00:00
Arc,
},
2024-11-03 16:32:53 +00:00
};
use anyhow::Result;
use crate::{audio::Audio, graphics::TextureSink};
2024-11-11 05:50:57 +00:00
use shrooms_vb_core::Sim;
pub use shrooms_vb_core::VBKey;
mod shrooms_vb_core;
2024-11-04 14:59:58 +00:00
pub struct EmulatorBuilder {
rom: Option<PathBuf>,
commands: mpsc::Receiver<EmulatorCommand>,
2024-11-05 03:18:57 +00:00
running: Arc<AtomicBool>,
has_game: Arc<AtomicBool>,
2024-11-04 14:59:58 +00:00
}
2024-11-11 05:50:57 +00:00
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
pub enum SimId {
Player1,
Player2,
}
impl SimId {
pub const fn values() -> [Self; 2] {
[Self::Player1, Self::Player2]
}
pub const fn to_index(self) -> usize {
2024-11-11 05:50:57 +00:00
match self {
Self::Player1 => 0,
Self::Player2 => 1,
}
}
}
2024-11-04 14:59:58 +00:00
impl EmulatorBuilder {
pub fn new() -> (Self, EmulatorClient) {
let (queue, commands) = mpsc::channel();
let builder = Self {
rom: None,
commands,
2024-11-05 03:18:57 +00:00
running: Arc::new(AtomicBool::new(false)),
has_game: Arc::new(AtomicBool::new(false)),
2024-11-05 03:18:57 +00:00
};
let client = EmulatorClient {
queue,
running: builder.running.clone(),
has_game: builder.has_game.clone(),
2024-11-04 14:59:58 +00:00
};
(builder, client)
}
pub fn with_rom(self, path: &Path) -> Self {
Self {
rom: Some(path.into()),
..self
}
}
pub fn build(self) -> Result<Emulator> {
let mut emulator = Emulator::new(self.commands, self.running, self.has_game)?;
2024-11-04 14:59:58 +00:00
if let Some(path) = self.rom {
2024-11-11 05:50:57 +00:00
emulator.load_rom_from_file(SimId::Player1, &path)?;
2024-11-04 14:59:58 +00:00
}
Ok(emulator)
}
}
2024-11-03 16:32:53 +00:00
pub struct Emulator {
2024-11-11 05:50:57 +00:00
sims: Vec<Sim>,
2024-11-04 14:59:58 +00:00
audio: Audio,
2024-11-03 16:32:53 +00:00
commands: mpsc::Receiver<EmulatorCommand>,
renderers: HashMap<SimId, TextureSink>,
2024-11-05 03:18:57 +00:00
running: Arc<AtomicBool>,
has_game: Arc<AtomicBool>,
2024-11-03 16:32:53 +00:00
}
impl Emulator {
fn new(
commands: mpsc::Receiver<EmulatorCommand>,
running: Arc<AtomicBool>,
has_game: Arc<AtomicBool>,
) -> Result<Self> {
2024-11-04 14:59:58 +00:00
Ok(Self {
2024-11-11 05:50:57 +00:00
sims: vec![],
2024-11-04 14:59:58 +00:00
audio: Audio::init()?,
commands,
2024-11-11 05:50:57 +00:00
renderers: HashMap::new(),
2024-11-05 03:18:57 +00:00
running,
has_game,
2024-11-04 14:59:58 +00:00
})
2024-11-03 16:32:53 +00:00
}
2024-11-11 05:50:57 +00:00
pub fn load_rom_from_file(&mut self, sim_id: SimId, path: &Path) -> Result<()> {
2024-11-03 16:32:53 +00:00
let bytes = fs::read(path)?;
2024-11-11 05:50:57 +00:00
self.load_rom(sim_id, bytes)?;
Ok(())
}
pub fn start_second_sim(&mut self, rom: Option<PathBuf>) -> Result<()> {
let bytes = if let Some(path) = rom {
fs::read(path)?
} else if let Some(rom) = self.sims.first().and_then(|s| s.clone_rom()) {
rom
} else {
return Ok(());
};
self.load_rom(SimId::Player2, bytes)?;
Ok(())
}
fn load_rom(&mut self, sim_id: SimId, bytes: Vec<u8>) -> Result<()> {
while self.sims.len() <= sim_id.to_index() {
self.sims.push(Sim::new());
}
let sim = &mut self.sims[sim_id.to_index()];
sim.reset();
sim.load_rom(bytes)?;
self.has_game.store(true, Ordering::Release);
2024-11-05 03:18:57 +00:00
self.running.store(true, Ordering::Release);
2024-11-03 16:32:53 +00:00
Ok(())
}
2024-11-11 05:50:57 +00:00
pub fn stop_second_sim(&mut self) {
self.renderers.remove(&SimId::Player2);
self.sims.truncate(1);
}
2024-11-03 16:32:53 +00:00
pub fn run(&mut self) {
let mut eye_contents = vec![0u8; 384 * 224 * 2];
2024-11-04 14:59:58 +00:00
let mut audio_samples = vec![];
2024-11-03 16:32:53 +00:00
loop {
2024-11-10 21:08:49 +00:00
let mut idle = true;
2024-11-05 03:18:57 +00:00
if self.running.load(Ordering::Acquire) {
2024-11-10 21:08:49 +00:00
idle = false;
2024-11-11 05:50:57 +00:00
Sim::emulate_many(&mut self.sims);
2024-11-05 03:18:57 +00:00
}
for sim_id in SimId::values() {
let Some(renderer) = self.renderers.get_mut(&sim_id) else {
continue;
};
let Some(sim) = self.sims.get_mut(sim_id.to_index()) else {
continue;
};
if sim.read_pixels(&mut eye_contents) {
idle = false;
if renderer.queue_render(&eye_contents).is_err() {
self.renderers.remove(&sim_id);
2024-11-11 05:50:57 +00:00
}
2024-11-03 16:32:53 +00:00
}
}
2024-11-11 05:50:57 +00:00
let weight = 1.0 / self.sims.len() as f32;
for sim in self.sims.iter_mut() {
sim.read_samples(&mut audio_samples, weight);
}
2024-11-04 14:59:58 +00:00
if !audio_samples.is_empty() {
2024-11-10 21:08:49 +00:00
idle = false;
2024-11-04 14:59:58 +00:00
self.audio.update(&audio_samples);
audio_samples.clear();
}
2024-11-10 21:08:49 +00:00
if idle {
// The game is paused, and we have output all the video/audio we have.
// Block the thread until a new command comes in.
match self.commands.recv() {
Ok(command) => self.handle_command(command),
Err(RecvError) => {
return;
}
}
}
2024-11-03 16:32:53 +00:00
loop {
match self.commands.try_recv() {
Ok(command) => self.handle_command(command),
Err(TryRecvError::Empty) => {
break;
}
Err(TryRecvError::Disconnected) => {
return;
}
}
}
}
}
fn handle_command(&mut self, command: EmulatorCommand) {
match command {
2024-11-11 05:50:57 +00:00
EmulatorCommand::SetRenderer(sim_id, renderer) => {
self.renderers.insert(sim_id, renderer);
2024-11-03 16:32:53 +00:00
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::LoadGame(sim_id, path) => {
if let Err(error) = self.load_rom_from_file(sim_id, &path) {
2024-11-05 03:18:57 +00:00
eprintln!("error loading rom: {}", error);
}
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::StartSecondSim(path) => {
if let Err(error) = self.start_second_sim(path) {
eprintln!("error starting second sim: {}", error);
}
}
EmulatorCommand::StopSecondSim => {
self.stop_second_sim();
}
2024-11-05 03:18:57 +00:00
EmulatorCommand::Pause => {
self.running.store(false, Ordering::Release);
}
EmulatorCommand::Resume => {
if self.has_game.load(Ordering::Acquire) {
2024-11-05 03:18:57 +00:00
self.running.store(true, Ordering::Relaxed);
}
}
EmulatorCommand::Reset => {
2024-11-11 05:50:57 +00:00
for sim in self.sims.iter_mut() {
sim.reset();
}
if !self.sims.is_empty() {
self.running.store(true, Ordering::Release);
}
2024-11-05 03:18:57 +00:00
}
2024-11-11 05:50:57 +00:00
EmulatorCommand::SetKeys(sim_id, keys) => {
if let Some(sim) = self.sims.get_mut(sim_id.to_index()) {
sim.set_keys(keys);
}
2024-11-03 16:32:53 +00:00
}
}
}
}
#[derive(Debug)]
pub enum EmulatorCommand {
SetRenderer(SimId, TextureSink),
2024-11-11 05:50:57 +00:00
LoadGame(SimId, PathBuf),
StartSecondSim(Option<PathBuf>),
StopSecondSim,
2024-11-05 03:18:57 +00:00
Pause,
Resume,
Reset,
2024-11-11 05:50:57 +00:00
SetKeys(SimId, VBKey),
2024-11-03 16:32:53 +00:00
}
#[derive(Clone)]
2024-11-03 16:32:53 +00:00
pub struct EmulatorClient {
queue: mpsc::Sender<EmulatorCommand>,
2024-11-05 03:18:57 +00:00
running: Arc<AtomicBool>,
has_game: Arc<AtomicBool>,
2024-11-03 16:32:53 +00:00
}
impl EmulatorClient {
2024-11-05 03:18:57 +00:00
pub fn is_running(&self) -> bool {
self.running.load(Ordering::Acquire)
}
pub fn has_game(&self) -> bool {
self.has_game.load(Ordering::Acquire)
}
2024-11-03 16:32:53 +00:00
pub fn send_command(&self, command: EmulatorCommand) {
if let Err(err) = self.queue.send(command) {
eprintln!(
"could not send command {:?} as emulator is shut down",
err.0
);
}
}
}