Merge branch 'main' into nes

fix
This commit is contained in:
2025-11-19 11:05:03 -07:00
50 changed files with 920 additions and 397 deletions

13
user_apps/gboy/Cargo.toml Normal file
View File

@@ -0,0 +1,13 @@
[package]
name = "gboy"
version = "0.1.0"
edition = "2024"
[build-dependencies]
bindgen = "0.71.0"
cc = "1.2.44"
[dependencies]
userlib = { path = "../../userlib" }
selection_ui = { path = "../../selection_ui" }
embedded-graphics = "0.8.1"

64
user_apps/gboy/build.rs Normal file
View File

@@ -0,0 +1,64 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
fn main() {
bindgen();
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("../memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}
fn bindgen() {
let bindings = bindgen::Builder::default()
.header("Peanut-GB/peanut_gb.h")
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.disable_nested_struct_naming()
.clang_arg("-I../../picolibc/newlib/libc/include/")
.clang_arg("-I../../picolibc/build/")
.use_core()
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
cc::Build::new()
.define("PEANUT_GB_IS_LITTLE_ENDIAN", None)
.define("ENABLE_LCD", None)
.file("peanut_gb_stub.c")
.include("Peanut-GB")
// optimization flags
.flag("-Ofast")
.flag("-fdata-sections")
.flag("-ffunction-sections")
.flag("-mcpu=cortex-m33")
.flag("-mthumb")
.flag("-g0")
.compile("peanut_gb");
println!("cargo:rustc-link-search=Peanut-GB");
println!("cargo:rustc-link-lib=peanut_gb");
}

View File

@@ -0,0 +1 @@
#include <peanut_gb.h>

206
user_apps/gboy/src/main.rs Normal file
View File

@@ -0,0 +1,206 @@
#![no_std]
#![no_main]
#![allow(static_mut_refs)]
extern crate alloc;
use alloc::{vec, vec::Vec};
use core::{cell::LazyCell, mem::MaybeUninit, panic::PanicInfo};
use embedded_graphics::{
mono_font::{MonoTextStyle, ascii::FONT_6X10},
pixelcolor::Rgb565,
prelude::RgbColor,
};
use selection_ui::{SelectionUi, SelectionUiError, draw_text_center};
use userlib::{
display::Display,
format,
fs::{Entries, file_len, list_dir, read_file, write_file},
get_key,
keyboard::{KeyCode, KeyState},
println,
};
mod peanut;
use peanut::gb_run_frame;
use crate::peanut::{
JOYPAD_A, JOYPAD_B, JOYPAD_DOWN, JOYPAD_LEFT, JOYPAD_RIGHT, JOYPAD_SELECT, JOYPAD_START,
JOYPAD_UP, gb_cart_ram_read, gb_cart_ram_write, gb_error, gb_get_rom_name, gb_get_save_size,
gb_init, gb_init_lcd, gb_reset, gb_rom_read, gb_s, lcd_draw_line,
};
static mut DISPLAY: LazyCell<Display> = LazyCell::new(|| Display::take().unwrap());
const RAM_SIZE: usize = 32 * 1024; // largest ram size is 32k
static mut RAM: [u8; RAM_SIZE] = [0; RAM_SIZE];
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
const GAME_PATH: &'static str = "/games/gameboy";
static mut GAME_ROM: Option<Vec<u8>> = None;
pub fn main() {
println!("Starting Gameboy app");
let mut entries = Entries::new();
list_dir(GAME_PATH, &mut entries);
let mut files = entries.entries();
files.retain(|e| {
let ext = e.extension().unwrap_or("");
ext == "gb" || ext == "GB"
});
let mut roms = files.iter().map(|e| e.full_name()).collect::<Vec<&str>>();
roms.sort();
let selection = {
let display = unsafe { &mut *DISPLAY };
let mut selection_ui = SelectionUi::new(&roms);
match selection_ui.run_selection_ui(display) {
Ok(maybe_sel) => maybe_sel,
Err(e) => match e {
SelectionUiError::SelectionListEmpty => {
draw_text_center(
display,
&format!("No Roms were found in {}", GAME_PATH),
MonoTextStyle::new(&FONT_6X10, Rgb565::RED),
)
.expect("Display Error");
None
}
SelectionUiError::DisplayError(_) => panic!("Display Error"),
},
}
};
assert!(selection.is_some());
let file_name = format!("{}/{}", GAME_PATH, roms[selection.unwrap()]);
let size = file_len(&file_name);
unsafe { GAME_ROM = Some(vec![0_u8; size]) };
let read = read_file(&file_name, 0, unsafe { GAME_ROM.as_mut().unwrap() });
assert!(size == read);
println!("Rom size: {}", read);
let mut gb = MaybeUninit::<gb_s>::uninit();
let init_status = unsafe {
gb_init(
gb.as_mut_ptr(),
Some(gb_rom_read),
Some(gb_cart_ram_read),
Some(gb_cart_ram_write),
Some(gb_error),
core::ptr::null_mut(),
)
};
println!("gb init status: {}", init_status);
unsafe {
load_save(&mut gb.assume_init());
}
unsafe {
gb_init_lcd(gb.as_mut_ptr(), Some(lcd_draw_line));
// enable frame skip
// gb.assume_init().direct.set_frame_skip(!true); // active low
};
loop {
let event = get_key();
let button = match event.key {
KeyCode::Esc => {
unsafe { write_save(&mut gb.assume_init()) };
break;
}
KeyCode::Char('r') => {
unsafe { gb_reset(gb.as_mut_ptr()) };
continue;
}
KeyCode::Tab => JOYPAD_START as u8,
KeyCode::Del => JOYPAD_SELECT as u8,
KeyCode::Enter => JOYPAD_A as u8,
KeyCode::Backspace => JOYPAD_B as u8,
KeyCode::Up => JOYPAD_UP as u8,
KeyCode::Down => JOYPAD_DOWN as u8,
KeyCode::Left => JOYPAD_LEFT as u8,
KeyCode::Right => JOYPAD_RIGHT as u8,
_ => 0,
};
if button != 0 {
unsafe {
// bindgen incorrectly generates direct so manual manipulation is required :(
let direct_ptr = &mut gb.assume_init().direct as *mut _ as *mut u8;
let joypad_ptr = direct_ptr.add(2); // this is the joypad bitfield byte
if let KeyState::Pressed = event.state {
*joypad_ptr &= !button;
} else if let KeyState::Released = event.state {
*joypad_ptr |= button;
}
println!("joypad: {:b}", *joypad_ptr);
}
}
unsafe {
gb_run_frame(gb.as_mut_ptr());
}
}
}
unsafe fn load_save(gb: &mut gb_s) {
let mut buf = [0; 16];
unsafe {
gb_get_rom_name(gb, buf.as_mut_ptr());
let save_size = gb_get_save_size(gb);
if save_size > 0 {
read_file(
&format!(
"{}/saves/{}.sav",
GAME_PATH,
str::from_utf8(&buf).expect("bad rom name")
),
0,
&mut RAM,
);
}
}
}
unsafe fn write_save(gb: &mut gb_s) {
let mut buf = [0; 16];
unsafe {
gb_get_rom_name(gb, buf.as_mut_ptr());
let save_size = gb_get_save_size(gb);
if save_size > 0 {
write_file(
&format!(
"{}/saves/{}.sav",
GAME_PATH,
str::from_utf8(&buf).expect("bad rom name")
),
0,
&mut RAM,
);
}
}
}

View File

@@ -0,0 +1,102 @@
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use crate::{DISPLAY, GAME_ROM, RAM};
#[allow(unused)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
use embedded_graphics::{pixelcolor::Rgb565, prelude::Point, Drawable};
use userlib::{display::Pixel565, println};
pub const GBOY_WIDTH: usize = 160;
pub const GBOY_HEIGHT: usize = 144;
pub unsafe extern "C" fn gb_rom_read(_gb: *mut gb_s, addr: u32) -> u8 {
unsafe { GAME_ROM.as_ref().unwrap()[addr as usize] }
}
pub unsafe extern "C" fn gb_cart_ram_read(_gb: *mut gb_s, addr: u32) -> u8 {
unsafe { RAM[addr as usize] }
}
pub unsafe extern "C" fn gb_cart_ram_write(_gb: *mut gb_s, addr: u32, val: u8) {
unsafe { RAM[addr as usize] = val }
}
pub unsafe extern "C" fn gb_error(_gb: *mut gb_s, err: gb_error_e, addr: u16) {
let e = match err {
0 => "UNKNOWN ERROR",
1 => "INVALID OPCODE",
2 => "INVALID READ",
3 => "INVALID WRITE",
4 => "HALT FOREVER",
5 => "INVALID MAX",
_ => unreachable!(),
};
println!("PeanutGB error: {}, addr: {}", e, addr);
}
const NUM_PALETTES: usize = 3;
const SHADES_PER_PALETTE: usize = 4;
const PALETTES: [[Rgb565; SHADES_PER_PALETTE]; NUM_PALETTES] = [
[
Rgb565::new(8, 24, 32),
Rgb565::new(52, 104, 86),
Rgb565::new(136, 192, 112),
Rgb565::new(224, 248, 208),
], // BG
[
Rgb565::new(8, 24, 32),
Rgb565::new(52, 104, 86),
Rgb565::new(136, 192, 112),
Rgb565::new(224, 248, 208),
], // OBJ0
[
Rgb565::new(8, 24, 32),
Rgb565::new(52, 104, 86),
Rgb565::new(136, 192, 112),
Rgb565::new(224, 248, 208),
], // OBJ1
];
pub unsafe extern "C" fn lcd_draw_line(_gb: *mut gb_s, pixels: *const u8, line: u8) {
if line < GBOY_HEIGHT as u8 {
let pixels = unsafe { core::slice::from_raw_parts(pixels, GBOY_WIDTH) };
let y = line as u16;
for (x, &p) in pixels.iter().enumerate() {
let palette_idx = ((p & 0xF0) >> 4) as usize;
let shade_idx = (p & 0x03) as usize;
let color = PALETTES
.get(palette_idx)
.and_then(|pal| pal.get(shade_idx))
.copied()
.unwrap_or(Rgb565::new(0, 0, 0));
// let sx = (x as u16) * 2;
// let sy = y * 2;
// draw_color(color, sx, sy);
// draw_color(color, sx + 1, sy);
// draw_color(color, sx, sy + 1);
// draw_color(color, sx + 1, sy + 1);
//
draw_color(color, x as u16, y as u16);
}
}
}
fn draw_color(color: Rgb565, x: u16, y: u16) {
let mut pixel = Pixel565::default();
pixel.0 = Point::new(x.into(), y.into());
pixel.1 = color;
unsafe {
pixel.draw(&mut *DISPLAY).unwrap();
}
}