CLEANUP: cleans up dependencies to use workspace version

CLEANUP: standardizes on pretty_env_logger
NEWBIN: Adds gemmarat to use Ratatui as an interface
CLEANUP: removes debugging display from computer.rs
ENHANCEMENT: Constants for locations of test roms built from environment
BUGFIX: SoundTimer was using i32 internally when it needs to be u8
CLEANUP: removes commented code used during diagnostics
This commit is contained in:
Trevor Merritt 2025-05-29 13:26:41 -04:00
parent 6c902de16f
commit 9b64a959f3
20 changed files with 1184 additions and 56 deletions

893
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -5,19 +5,21 @@ members = [
"gemmaimgui",
"gemmatelnet",
"gemmautil",
"gemmarat"
]
resolver = "2"
[workspace.dependencies]
pretty_env_logger = { version = "0.5" }
log = { version = "0.4" }
log = { version = "0.4" }
rand = { version = "0.9.0-alpha.2" }
chrono = { version = "0.4" }
dimensioned = { version = "0.8" }
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0" }
clap = { version = "4.5", features = ["derive"] }
flate2 = { version = "1.1" }
hex = { version = "0.4" }
# EGUI
egui = { version = "0.29" }
eframe = { version = "0.29" }

View File

@ -7,13 +7,11 @@ autobenches = true
[dependencies]
pretty_env_logger.workspace = true
rand.workspace = true
log.workspace = true
# beep = "0.3.0"
chrono.workspace = true
dimensioned.workspace = true
serde.workspace = true
serde_json.workspace = true
flate2 = "1.0"
clap = { version = "4.5.20", features = ["derive"] }
hex = "0.4.3"
env_logger = "0.10.2"
flate2.workspace = true
clap.workspace = true
hex.workspace = true
log.workspace = true

View File

@ -103,7 +103,7 @@ fn decompress_file(input_path: &PathBuf) -> io::Result<()> {
}
fn main() {
env_logger::init();
pretty_env_logger::init();
let cli = Cli::parse();

View File

@ -91,7 +91,7 @@ impl Chip8Computer {
pub fn step_system(&mut self) -> &mut Chip8Computer {
println!("Stepping System 1 Step");
// println!("Stepping System 1 Step");
// read the next instruction
let local_memory = &self.memory;

View File

@ -1019,7 +1019,7 @@ impl Chip8CpuInstructions {
}
Chip8CpuInstructions::LDIS(new_time) => {
let new_value = input.registers.peek(*new_time);
input.sound_timer.set_timer(new_value as i32);
input.sound_timer.set_timer(new_value);
}
Chip8CpuInstructions::ADDI(x) => {
// Fx1E - ADD I, Vx

View File

@ -1,9 +1,11 @@
use log::trace;
extern crate pretty_env_logger;
use log::warn;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Serialize, Deserialize, Debug)]
pub struct SoundTimer {
counter: i32,
counter: u8,
}
impl Default for SoundTimer {
@ -13,32 +15,25 @@ impl Default for SoundTimer {
}
impl SoundTimer {
pub fn current(&self) -> i32 {
pub fn current(&self) -> u8 {
self.counter
}
pub fn new() -> Self {
SoundTimer { counter: 0 }
}
pub fn set_timer(&mut self, new_value: i32) {
trace!("SETTING SOUND TIMER TO {new_value}");
pub fn set_timer(&mut self, new_value: u8) {
warn!("SETTING SOUND TIMER TO {new_value}");
self.counter = new_value
}
pub fn tick(&mut self) {
trace!(
warn!(
"TICKING SOUND FROM {} to {}",
self.counter,
self.counter - 1
);
if self.counter > 0 {
self.counter -= 1;
/*
todo: this breaks tests. maybe its wrong?
if let good_thread = thread::spawn(|| {
beep(440).expect("Unable to beep");
thread::sleep(time::Duration::from_millis(500));
}).join().unwrap().
*/
}
}

View File

@ -1,3 +1,8 @@
use std::borrow::ToOwned;
use std::clone::Clone;
use std::net::ToSocketAddrs;
use std::string::ToString;
pub const CHIP8_REGISTER_COUNT: i32 = 16;
pub const CHIP8_MEMORY_SIZE: i32 = 4096i32;
pub const CHIP8_VIDEO_WIDTH: i32 = 64i32;
@ -9,9 +14,10 @@ pub const LABEL_QUIRK_CHIP8: &str = "Chip8";
pub const LABEL_QUIRK_XOCHIP: &str = "XO Chip";
pub const LABEL_QUIRK_SCHIP: &str = "SChip-Modern";
pub const RESOURCES_ROOT: &str = "../resources";
pub const TESTS_ROOT: &str = "../resources/test/";
pub const TEST_ROM_ROOT: &str = "../resources/test/roms";
pub const BASE_ROOT: &'static str = &(env!("CARGO_MANIFEST_DIR"));
pub const RESOURCES_ROOT: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/../resources");
pub const TESTS_ROOT: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/../resources/test");
pub const TEST_ROM_ROOT: &'static str =concat!(env!("CARGO_MANIFEST_DIR"), "/../resources/test/roms");
pub const CHIP8_KEYBOARD: [[u8; 4]; 4] = [
[0x01, 0x02, 0x03, 0x0C],

View File

@ -6,7 +6,7 @@ use gemma::chip8::computer_manager::Chip8ComputerManager;
use gemma::chip8::quirk_modes::QuirkMode;
use gemma::chip8::quirk_modes::QuirkMode::{Chip8, SChipModern, XOChip};
use gemma::chip8::registers::Chip8Registers;
use gemma::constants::{CHIP8_VIDEO_MEMORY, TESTS_ROOT};
use gemma::constants::{CHIP8_VIDEO_MEMORY, TESTS_ROOT, TEST_ROM_ROOT};
use crate::test_utils::{load_compressed_result, load_result, load_rom};
#[test]
@ -187,7 +187,7 @@ fn quirks_mode_test() {
fn load_rom_allows_starting() {
let mut new_manager = Chip8ComputerManager::default();
assert!(!new_manager.core_should_run);
let p = format!("{}/../resources/test/roms/1-chip8-logo.ch8" , std::env::current_dir().unwrap().display());
let p = TEST_ROM_ROOT.to_string() + "/1-chip8-logo.ch8";
let full_path = Path::new(p.as_str());
new_manager.load_new_program_from_disk_to_system_memory(full_path);
assert!(new_manager.core_should_run)

View File

@ -11,20 +11,6 @@ fn load_result(to_load: &str) -> String {
std::fs::read_to_string(full_path).unwrap()
}
// fn load_compressed_result(file_path: &str) -> io::Result<String> {
// // Load the compressed file contents
// let compressed_data = fs::read(file_path)?;
//
// // Create a GzDecoder to uncompress the data
// let mut decoder = GzDecoder::new(&mut compressed_data[..]);
// let mut decompressed_data = String::new();
//
// // Read the decompressed data directly into a String
// decoder.read_to_string(&mut decompressed_data)?;
//
// Ok(decompressed_data)
// }
fn load_rom(to_load: &str) -> Vec<u8> {
fs::read(format!("resources/test/roms/{}", to_load)).unwrap()
}

View File

@ -8,3 +8,5 @@ gemma = { path = "../gemma" }
egui.workspace = true
eframe.workspace = true
catppuccin-egui = { version = "5.3.0", default-features = false, features = ["egui29"] }
pretty_env_logger.workspace = true
log.workspace = true

View File

@ -6,8 +6,8 @@ edition = "2021"
[dependencies]
gemma = { path = "../gemma" }
pretty_env_logger.workspace = true
rand.workspace = true
log.workspace = true
rand.workspace = true
chrono.workspace = true
dimensioned.workspace = true
clap.workspace = true

12
gemmarat/Cargo.toml Normal file
View File

@ -0,0 +1,12 @@
[package]
name = "gemmarat"
version = "0.1.0"
edition = "2024"
[dependencies]
gemma = { path = "../gemma" }
clap.workspace = true
pretty_env_logger.workspace = true
log.workspace = true
color-eyre = "0.6"
ratatui = "0.30.0-alpha.4"

View File

@ -0,0 +1,135 @@
use std::path::Path;
use std::rc::Rc;
use ratatui::prelude::*;
use std::time::Duration;
use color_eyre::{eyre::Context, Result};
use ratatui::{
crossterm::event::{self, Event, KeyCode},
widgets::Paragraph,
DefaultTerminal, Frame,
};
use ratatui::layout::Rect;
use ratatui::layout::{Constraint, Direction};
use ratatui::prelude::Layout;
use ratatui::widgets::{Block, Borders};
use gemma::chip8::computer::Chip8Computer;
use gemma::chip8::computer_manager::Chip8ComputerManager;
use gemmarat::register_widget::RegisterWidget;
use gemmarat::timer_widget::TimerWidget;
use gemmarat::video_widget::VideoWidget;
struct GemmaRat {
pub computer: Chip8ComputerManager
}
impl Default for GemmaRat {
fn default() -> Self {
GemmaRat {
computer: Chip8ComputerManager::default()
}
}
}
fn main() -> Result<()> {
color_eyre::install()?;
let terminal = ratatui::init();
let app_result = run(terminal).context("app loop failed");
ratatui::restore();
app_result
}
fn run(mut terminal: DefaultTerminal) -> Result<()> {
let mut manager = Chip8ComputerManager::default();
manager.load_new_program_from_disk_to_system_memory(Path::new("/home/tmerritt/Projects/trevors_chip8_toy/resources/roms/2-ibm-logo.ch8"));
for _ in 0..30 {
manager.tick();
}
loop {
terminal.draw(|frame| {
do_draw(frame, &mut manager);
}).expect("unable to render display.");
if should_quit()? {
break;
}
}
Ok(())
}
fn do_draw(frame: &mut Frame, draw_with: &mut Chip8ComputerManager) {
// build the layout...
let main_layout = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![
Constraint::Length(32),
Constraint::Max(3)
])
.split(frame.area());
let upper_block = Layout::default()
.direction(Direction::Horizontal)
.constraints(vec![
Constraint::Length(64),
Constraint::Fill(1)
])
.split(main_layout[0]);
let column_block = Layout::default()
.direction(Direction::Vertical)
.constraints(vec![
// Registers
Constraint::Min(20),
// Timers
Constraint::Min(6),
// Keypad
Constraint::Min(8)
])
.split(upper_block[1]);
// ...then put the parts in the layout.
// Video Block
let state = draw_with.state().clone().video_memory;
frame.render_widget(
VideoWidget::with_display(state), upper_block[0]
);
// Registers Block
let mut state = draw_with.state().registers;
frame.render_stateful_widget(
RegisterWidget::new(),
column_block[0],
&mut state);
// Times Block
frame.render_stateful_widget(
TimerWidget::new(),
column_block[1],
&mut TimerWidget::with_values(
draw_with.state().sound_timer.current(),
draw_with.state().delay_timer.current()
)
);
// Keypad Block
frame.render_widget(
Paragraph::new("Keypad Goes Here")
.block(Block::new().borders(Borders::ALL)), column_block[2]
);
// Footer Bar
frame.render_widget(
Paragraph::new("F1 - Step | F2 - Run | F3 - Stop | Q - Quit")
.centered()
.block(Block::new().borders(Borders::ALL)), main_layout[1]);
}
fn should_quit() -> Result<bool> {
if event::poll(Duration::from_millis(250)).context("event poll failed")? {
if let Event::Key(key) = event::read().context("event read failed")? {
return Ok(KeyCode::Char('q') == key.code);
}
}
Ok(false)
}

3
gemmarat/src/lib.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod timer_widget;
pub mod register_widget;
pub mod video_widget;

View File

@ -0,0 +1,43 @@
use ratatui::layout::Rect;
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, List, ListItem, ListState};
use gemma::chip8::registers::Chip8Registers;
pub struct RegisterWidget {
state: Chip8Registers
}
impl RegisterWidget {
pub fn new() -> RegisterWidget {
RegisterWidget { state: Chip8Registers::default() }
}
pub fn with_values(state: Chip8Registers) -> RegisterWidget {
RegisterWidget {
state
}
}
}
impl StatefulWidget for RegisterWidget {
type State = Chip8Registers;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Chip8Registers) {
let mut working_lines: Vec<ListItem> = vec![];
// build the lines for the display...
let working_text = state.format_as_string();
for current_line in working_text.lines() {
working_lines.push(ListItem::new(current_line));
}
let my_list = List::new(working_lines)
.block(Block::new()
.title(Line::raw("Registers").centered())
.borders(Borders::ALL));
// ...draw it out;
StatefulWidget::render(my_list, area, buf, &mut ListState::default());
}
}

View File

@ -0,0 +1,39 @@
use ratatui::prelude::*;
use ratatui::widgets::{Block, Paragraph};
use ratatui::text::Line;
pub struct TimerWidget {
sound_timer_value: u8,
delay_timer_value: u8
}
impl TimerWidget {
pub fn new() -> TimerWidget {
TimerWidget { sound_timer_value: 0, delay_timer_value: 0 }
}
pub fn with_values(sound: u8, delay: u8) -> TimerWidget {
TimerWidget {
sound_timer_value: sound,
delay_timer_value: delay
}
}
}
impl StatefulWidget for TimerWidget {
type State = TimerWidget;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut TimerWidget) {
let line_1 = Span::raw(format!("Sound Timer: {} [{:02x}]", state.sound_timer_value, state.sound_timer_value));
let line_2 = Span::raw(format!("Delay Timer: {} [{:02x}]", state.delay_timer_value, state.delay_timer_value));
let text = vec![
Line::from(vec![line_1]),
Line::from(vec![line_2])
];
let line = Paragraph::new(text)
.block(Block::bordered().title("Timers"));
line.render(area, buf);
}
}

View File

@ -0,0 +1,31 @@
use ratatui::prelude::*;
use ratatui::widgets::Paragraph;
use gemma::chip8::video::Chip8Video;
pub struct VideoWidget {
video: Chip8Video
}
impl VideoWidget {
pub fn new() -> Self {
VideoWidget {
video : Chip8Video::default()
}
}
pub fn with_display(new_display: Chip8Video) -> Self {
VideoWidget {
video: new_display
}
}
}
impl Widget for VideoWidget {
fn render(self, area: Rect, buf: &mut Buffer) {
let working_text = self.video.format_as_string();
//println!("WORKING_TEXT = {}", working_text);
let text = Paragraph::new(working_text);
Widget::render(text, area, buf);
}
}

View File

@ -5,5 +5,6 @@ edition = "2024"
[dependencies]
gemma = { path = "../gemma" }
log = "0.4.22"
clap = { version = "4.5.20", features = ["derive"] }
pretty_env_logger.workspace = true
log.workspace = true
clap.workspace = true

View File

@ -8,3 +8,5 @@ gemma = { path = "../gemma" }
clap.workspace = true
pest = "2.7.14"
pest_derive = "2.7.14"
pretty_env_logger.workspace = true
log.workspace = true