From f523ee91ff56b63bc7e29a863183f7a52c2f504f Mon Sep 17 00:00:00 2001 From: Atreya Bain Date: Mon, 19 Feb 2024 23:03:33 +0530 Subject: [PATCH] [cln] Code cleanup --- src/args.rs | 4 ++- src/emu/cpu.rs | 15 ---------- src/emu/graphics.rs | 4 --- src/emu/keyboard.rs | 6 ---- src/emu/memory.rs | 19 ++----------- src/graphics/color.rs | 49 ++++---------------------------- src/graphics/graphics_adapter.rs | 3 -- src/main.rs | 44 +++++++++++++++------------- src/misc/error.rs | 4 --- 9 files changed, 34 insertions(+), 114 deletions(-) diff --git a/src/args.rs b/src/args.rs index 102b75c..767e14c 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,6 +1,8 @@ use clap::Parser; #[derive(Debug,Parser)] +#[command(version, about, long_about = "Byte Pusher Emulator")] pub struct BytePusherArgs{ - + #[arg(short,long)] + pub file_name:Option } \ No newline at end of file diff --git a/src/emu/cpu.rs b/src/emu/cpu.rs index 00450fe..ee40fc0 100644 --- a/src/emu/cpu.rs +++ b/src/emu/cpu.rs @@ -3,11 +3,6 @@ use crate::emu::memory::{Memory, RamMemory}; use crate::misc::endian::{read_big_endian_u24, write_big_endian_u24}; use crate::misc::result::EmulatorResult; -#[derive(Debug)] -pub enum CpuState { - Running, - Paused, -} #[derive(Debug)] pub struct Cpu<'a> { @@ -18,7 +13,6 @@ pub struct Cpu<'a> { impl<'a> Cpu<'a> { const PC_START: usize = 2; const PC_LEN: usize = 3; - const PC_ZERO: [u8; 3] = [0; 3]; pub fn new(memory: &'a RamMemory, graphics_processor: &'a GraphicsProcessor<'a>) -> Cpu<'a> { Cpu { graphics_processor, @@ -30,14 +24,6 @@ impl<'a> Cpu<'a> { let data = memory_slice.get(Self::PC_START..(Self::PC_START + Self::PC_LEN)).unwrap(); read_big_endian_u24(data.try_into().unwrap()) } - pub fn set_pc(&self, address: u32) { - let mut memory_slice = self.memory.get_data_ref_mut(); - - let mut pc_big_endian_slice = Self::PC_ZERO; - write_big_endian_u24(address, &mut pc_big_endian_slice); - - memory_slice[Self::PC_START..(Self::PC_START + Self::PC_LEN)].copy_from_slice(&pc_big_endian_slice); - } pub fn cycle(&self) -> EmulatorResult<()> { @@ -52,7 +38,6 @@ impl<'a> Cpu<'a> { program_counter = self.memory.try_get_u24(new_pc_location)?; } - // self.set_pc(program_counter); log::trace!("Finished internal loop"); self.graphics_processor.draw()?; // TODO send audio diff --git a/src/emu/graphics.rs b/src/emu/graphics.rs index 5d1d720..29998f0 100644 --- a/src/emu/graphics.rs +++ b/src/emu/graphics.rs @@ -40,10 +40,6 @@ impl<'a> GraphicsProcessor<'a> { self.ram.try_copy_block(fb_base_register, fb.as_mut())?; Ok(()) } - fn set_framebuffer(&self, memory_slice: &[u8; DEVICE_FRAMEBUFFER_SIZE]) { - let mut fb = self.frame_buffer.borrow_mut(); - fb.copy_from_slice(memory_slice); - } pub fn get_framebuffer(&self) -> Ref> { self.frame_buffer.borrow() } diff --git a/src/emu/keyboard.rs b/src/emu/keyboard.rs index da9a44a..aaddd02 100644 --- a/src/emu/keyboard.rs +++ b/src/emu/keyboard.rs @@ -17,12 +17,6 @@ impl<'a> Keyboard<'a>{ } } - pub fn clear_keyboard(&mut self){ - log::debug!("Keyboard clear"); - self.bitflags = 0; - self.dirty = true; - } - pub fn key_down(&mut self,x:u8){ self.bitflags |= 1< EmulatorResult { - let alloc_result = vec![0; MEM_LENGTH].into_boxed_slice(); - let data = alloc_result.try_into().map_err(|err| { - EmulatorError::AllocationFailure(RAM, "Allocation failed") - })?; - let data_refcell = RefCell::new(data); - Ok(RamMemory { - data: data_refcell - }) - } pub fn try_from(existing_data: &[u8]) -> EmulatorResult { let alloc_result = vec![0u8; MEM_LENGTH].into_boxed_slice(); // get box of fixed size @@ -66,17 +56,12 @@ impl RamMemory { pub fn get_data_ref_mut(&self) -> RefMut> { self.data.borrow_mut() } - /// set keyboard bits - pub fn set_u16(&self, address: u32, keyboard_bits: u16) { - let mut keyboard_slice_ref = self.data.borrow_mut(); - let keyboard_slice = keyboard_slice_ref.get_mut(0..2).unwrap(); - write_big_endian_u16(keyboard_bits, keyboard_slice.try_into().unwrap()); - } + } impl Memory for RamMemory { fn try_get_byte(&self, address: u32) -> EmulatorResult { - log::trace!("Fetch RAM memory at address {}",address); + // log::trace!("Fetch RAM memory at address {}",address); let data = self.data.borrow(); let x = *data.get(address as usize).ok_or(EmulatorError::UnreachableMemory(RAM, address))?; Ok(x) diff --git a/src/graphics/color.rs b/src/graphics/color.rs index f66ac2b..ada1db0 100644 --- a/src/graphics/color.rs +++ b/src/graphics/color.rs @@ -1,5 +1,3 @@ -use crate::misc::error::EmulatorError; -use crate::misc::result::EmulatorResult; /// A Color as represented in BytePusher. /// It is a byte that contains a packed 6 digit red, green and blue @@ -15,31 +13,15 @@ impl Color { /// Only first 216 color indices are used. const COLOR_MAX: u8 = 215; const COLOR_FACTOR_8_BIT: u8 = 0x33; - /// This constructs a valid color from rgb triplet - pub fn from_rgb(red: u8, green: u8, blue: u8) -> Color { - let red = red / Self::COLOR_FACTOR_8_BIT; - let green = green / Self::COLOR_FACTOR_8_BIT; - let blue = blue / Self::COLOR_FACTOR_8_BIT; - Color(red * Self::RED_MULT + green * Self::GREEN_MULT + blue) - } - pub fn try_new(in_mem_color: u8) -> EmulatorResult { - if in_mem_color > Self::COLOR_MAX { - return Err(EmulatorError::InvalidColor(in_mem_color)); - } - Ok(Color(in_mem_color)) - } + /// wrap to black if needed pub fn new(in_mem_color: u8) -> Color { if in_mem_color > Self::COLOR_MAX { - log::trace!("Invalid color {}, using 0", in_mem_color); Color(0) } else { Color(in_mem_color) } } - pub fn get_mem_byte(&self) -> u8 { - self.0 - } /// This fetches the rgb triplet pub fn get_rgb(self) -> (u8, u8, u8) { let r = self.0 / Self::RED_MULT; @@ -48,16 +30,6 @@ impl Color { let b = gb_byte_remainder % Self::GREEN_MULT; (r * Self::COLOR_FACTOR_8_BIT, g * Self::COLOR_FACTOR_8_BIT, b * Self::COLOR_FACTOR_8_BIT) } - - pub fn to_rgb_555(&self)->u16{ - let r = (self.0 / Self::RED_MULT) as u16; - let gb_byte_remainder = self.0 % Self::RED_MULT; - let g = (gb_byte_remainder / Self::GREEN_MULT) as u16; - let b = gb_byte_remainder % Self::GREEN_MULT; - - (r*25)<<10 + (g*25)<<5 + b - } - } @@ -67,31 +39,20 @@ mod tests { #[test] pub fn test_from_mem_zero() { - let color = Color::try_new(0).unwrap(); + let color = Color::new(0); assert_eq!((0, 0, 0), color.get_rgb()) } #[test] pub fn test_from_mem_invalid() { - let color = Color::try_new(0xff); - assert!(color.is_err()) + let color = Color::new(0xff); + assert_eq!((0,0,0),color.get_rgb()) } #[test] pub fn test_from_mem_max() { - let color = Color::try_new(Color::COLOR_MAX).unwrap(); + let color = Color::new(Color::COLOR_MAX); assert_eq!((255, 255, 255), color.get_rgb()) } - #[test] - pub fn from_rgb_zero() { - let color = Color::from_rgb(0, 0, 0); - assert_eq!(0, color.get_mem_byte()) - } - - #[test] - pub fn from_rgb_max() { - let color = Color::from_rgb(255, 255, 255); - assert_eq!(Color::COLOR_MAX, color.get_mem_byte()) - } } \ No newline at end of file diff --git a/src/graphics/graphics_adapter.rs b/src/graphics/graphics_adapter.rs index 8d26182..ac1f7ee 100644 --- a/src/graphics/graphics_adapter.rs +++ b/src/graphics/graphics_adapter.rs @@ -1,12 +1,9 @@ use std::cell::Ref; use std::fmt::{Debug, Formatter}; -use std::mem::size_of; use sdl2::pixels::PixelFormatEnum; -use sdl2::rect::Rect; use sdl2::render::{TextureAccess, WindowCanvas}; use crate::emu::graphics::{DEVICE_FRAMEBUFFER_SIZE, GraphicsProcessor}; use crate::graphics::color::Color; -use crate::misc::error::EmulatorError; use crate::misc::result::EmulatorResult; diff --git a/src/main.rs b/src/main.rs index 356e9c8..0fb9032 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,16 +1,18 @@ use std::fs::File; use std::io::Read; use std::time::Duration; +use clap::Parser; use sdl2::event::Event; use sdl2::EventPump; use sdl2::keyboard::Keycode; use sdl2::pixels::Color; use sdl2::render::{BlendMode, WindowCanvas}; use simple_logger::SimpleLogger; +use crate::args::BytePusherArgs; use crate::emu::cpu::Cpu; use crate::emu::graphics::GraphicsProcessor; use crate::emu::keyboard::Keyboard; -use crate::emu::memory::{MEM_LENGTH, Memory, RamMemory}; +use crate::emu::memory::{MEM_LENGTH, RamMemory}; use crate::graphics::graphics_adapter::SDLGraphicsAdapter; use crate::misc::result::EmulatorResult; @@ -21,11 +23,14 @@ mod misc; mod graphics; fn main() -> EmulatorResult<()> { - let (file_bytes, x) = try_load_rom()?; - assert!(x < MEM_LENGTH); + let BytePusherArgs { file_name } = BytePusherArgs::parse(); SimpleLogger::new().env().init().unwrap(); - let (mut canvas, mut event_pump, draw_factor) = initiate_sdl(); + + let (file_bytes, x) = try_load_rom(&file_name)?; + assert!(x < MEM_LENGTH); + + let (mut canvas, mut event_pump) = initiate_sdl(); let ram = RamMemory::try_from(file_bytes.as_slice())?; @@ -35,9 +40,7 @@ fn main() -> EmulatorResult<()> { let mut sdl2_graphics_adapter = SDLGraphicsAdapter::new(&graphics_processor); - let mut i = 0; 'running: loop { - i = (i+1)%255; canvas.set_draw_color(Color::BLACK); canvas.clear(); for event in event_pump.poll_iter() { @@ -46,20 +49,17 @@ fn main() -> EmulatorResult<()> { Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { break 'running; } - Event::KeyDown { keycode: Some(x),repeat:false,.. } => { + Event::KeyDown { keycode: Some(x), repeat: false, .. } => { if let Some(key_val) = get_key_index(x) { keyboard.key_down(key_val) } - }, - Event::KeyUp { keycode: Some(x), repeat:false, .. } => { + } + Event::KeyUp { keycode: Some(x), repeat: false, .. } => { if let Some(key_val) = get_key_index(x) { keyboard.key_up(key_val) } } - - event => { - log::trace!("Received window event {:?}",event); - } + _ => {} } } @@ -102,16 +102,20 @@ fn get_key_index(p0: Keycode) -> Option { } } -fn try_load_rom() -> EmulatorResult<(Vec, usize)> { +fn try_load_rom(file_name_option: &Option) -> EmulatorResult<(Vec, usize)> { let mut file_bytes = vec![0u8; MEM_LENGTH]; - let mut file_handle = File::open("roms/Keyboard Test(1).BytePusher")?; - let x = file_handle.read(&mut file_bytes)?; + let bytes_read = if let Some(file_name) = file_name_option{ + let mut file_handle = File::open(file_name.as_str())?; + file_handle.read(&mut file_bytes)? + }else{ + 0 + }; - Ok((file_bytes, x)) + Ok((file_bytes, bytes_read)) } -fn initiate_sdl() -> (WindowCanvas, EventPump, u32) { +fn initiate_sdl() -> (WindowCanvas, EventPump) { const BASE_RESOLUTION: u32 = 256; const DRAW_FACTOR: u32 = 4; const WINDOW_RESOLUTION: u32 = BASE_RESOLUTION * DRAW_FACTOR; @@ -127,10 +131,10 @@ fn initiate_sdl() -> (WindowCanvas, EventPump, u32) { canvas.set_draw_color(Color::RGB(0x10, 0x10, 0x10)); canvas.set_integer_scale(true).expect("Setting int scale"); - canvas.set_scale(DRAW_FACTOR as f32,DRAW_FACTOR as f32).expect("Setting scale"); + canvas.set_scale(DRAW_FACTOR as f32, DRAW_FACTOR as f32).expect("Setting scale"); canvas.clear(); canvas.set_blend_mode(BlendMode::None); canvas.present(); let event_pump = sdl_context.event_pump().unwrap(); - (canvas, event_pump, DRAW_FACTOR) + (canvas, event_pump) } diff --git a/src/misc/error.rs b/src/misc/error.rs index d08fc64..85de8ea 100644 --- a/src/misc/error.rs +++ b/src/misc/error.rs @@ -5,9 +5,7 @@ use crate::misc::error::EmulatorError::EmulatorIOError; #[derive(Debug, Copy, Clone)] pub enum DeviceType { - CPU, RAM, - KEYBOARD, AUDIO, GRAPHICS, } @@ -16,9 +14,7 @@ pub enum DeviceType { pub enum EmulatorError { AllocationFailure(DeviceType, &'static str), UnreachableMemory(DeviceType, u32), - InvalidColor(u8), EmulatorIOError(Error), - OtherError(String), } impl From for EmulatorError {