A GameCube/Wii emulator and debugger written in Rust.
apploader shit
Layle4a9b19956e5e
diff --git a/.gitignore b/.gitignoreindex f81f8c5..e2c38e9 100644--- a/.gitignore+++ b/.gitignore@@ -6,4 +6,5 @@ profile.json.gzout*.txtprivate/*.log-out/\ No newline at end of file+out/+__pycache__/\ No newline at end of filediff --git a/Cargo.lock b/Cargo.lockindex 4f49264..011e012 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -457,18 +457,18 @@ dependencies = [[[package]]name = "chipi-build"-version = "0.9.0"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bc93ee723a2e1024de5fdcb59d2dfac6e06edf9a9ad7a3941920d5d9296b8fdc"+checksum = "b3272bc243a8f30942ec5e6efd9b5fd904e5f051c38d9053f485d35bff204383"dependencies = ["chipi-core",][[package]]name = "chipi-core"-version = "0.9.0"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c334634fcf9d942efa6f676b81d3dbf14c0bcf94fede78738d02a09eb3cc30a"+checksum = "c8f3df7969c229e288b63158f9aabaaaff2aebbab70d642ba8ca7b10b6216581"[[package]]name = "clap"@@ -1263,6 +1263,7 @@ dependencies = ["chipi-build","crc32fast","crossbeam-channel",+ "disasm","glam","image 0.1.0","multiversion",diff --git a/crates/dbglib/src/lib.rs b/crates/dbglib/src/lib.rsindex 36a8b00..fb8c4e3 100644--- a/crates/dbglib/src/lib.rs+++ b/crates/dbglib/src/lib.rs@@ -4,16 +4,13 @@ pub mod windows;#[cfg(not(target_arch = "wasm32"))]use std::io::Write;-use gecko::gamecube::GameCube;use gecko::scheduler::{CPU_CYCLES_PER_DSP_TICK, DSP_BATCH_SIZE, ScheduledFn, dsp_batch_handler};-use gecko::system::GC;--type GameCubeScheduledFn = ScheduledFn<{ GC }>;+use gecko::system::{System, SystemId};/// Identify the DSP batch handler so the debugger can intercept it for per-instruction tracing.#[inline(always)]-fn is_dsp_batch(f: GameCubeScheduledFn) -> bool {- (f as usize) == (dsp_batch_handler as GameCubeScheduledFn as usize)+fn is_dsp_batch<const SYSTEM: SystemId>(f: ScheduledFn<SYSTEM>) -> bool {+ (f as usize) == (dsp_batch_handler::<SYSTEM> as ScheduledFn<SYSTEM> as usize)}#[derive(Debug, PartialEq, Eq, Clone, Copy)]@@ -116,7 +113,7 @@ impl Debugger {}#[cfg(not(target_arch = "wasm32"))]- pub fn trace_step(&mut self, emulator: &GameCube) {+ pub fn trace_step<const SYSTEM: SystemId>(&mut self, emulator: &System<SYSTEM>) {if let Some(ref mut writer) = self.trace_writer {let line = trace::format_trace_line(emulator);let _ = writeln!(writer, "{}", line);@@ -124,7 +121,7 @@ impl Debugger {}#[cfg(target_arch = "wasm32")]- pub fn trace_step(&mut self, _emulator: &GameCube) {}+ pub fn trace_step<const SYSTEM: SystemId>(&mut self, _emulator: &System<SYSTEM>) {}#[cfg(not(target_arch = "wasm32"))]pub fn is_dsp_tracing(&self) -> bool {@@ -149,7 +146,7 @@ impl Debugger {}#[cfg(not(target_arch = "wasm32"))]- fn dsp_trace_step(&mut self, emulator: &GameCube) {+ fn dsp_trace_step<const SYSTEM: SystemId>(&mut self, emulator: &System<SYSTEM>) {if let Some(ref mut writer) = self.dsp_trace_writer {let line = trace::format_dsp_trace_line(&emulator.dsp);let _ = writeln!(writer, "{}", line);@@ -157,13 +154,13 @@ impl Debugger {}#[cfg(target_arch = "wasm32")]- fn dsp_trace_step(&mut self, _emulator: &GameCube) {}+ fn dsp_trace_step<const SYSTEM: SystemId>(&mut self, _emulator: &System<SYSTEM>) {}/// Drain and process scheduler events, tracing DSP ticks when active.#[inline(always)]- fn drain_events(&mut self, emulator: &mut GameCube) {+ fn drain_events<const SYSTEM: SystemId>(&mut self, emulator: &mut System<SYSTEM>) {while let Some(f) = emulator.scheduler.poll() {- if is_dsp_batch(f) && self.is_dsp_tracing() {+ if is_dsp_batch::<SYSTEM>(f) && self.is_dsp_tracing() {for _ in 0..DSP_BATCH_SIZE {self.dsp_trace_step(emulator);if !emulator.step_dsp_instruction() {@@ -173,7 +170,7 @@ impl Debugger {gecko::flipper::dsp::refresh_interrupts(emulator);emulator.scheduler- .schedule_in(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, dsp_batch_handler);+ .schedule_in(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, dsp_batch_handler::<SYSTEM>);} else {f(emulator);}@@ -184,10 +181,10 @@ impl Debugger {/// processed. Used by `RunUntilDsp` to detect when the DSP is about to/// execute.#[inline(always)]- fn drain_events_until_dsp(&mut self, emulator: &mut GameCube) -> bool {+ fn drain_events_until_dsp<const SYSTEM: SystemId>(&mut self, emulator: &mut System<SYSTEM>) -> bool {let mut dsp_hit = false;while let Some(f) = emulator.scheduler.poll() {- if is_dsp_batch(f) {+ if is_dsp_batch::<SYSTEM>(f) {if self.is_dsp_tracing() {for _ in 0..DSP_BATCH_SIZE {self.dsp_trace_step(emulator);@@ -198,7 +195,7 @@ impl Debugger {gecko::flipper::dsp::refresh_interrupts(emulator);emulator.scheduler- .schedule_in(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, dsp_batch_handler);+ .schedule_in(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, dsp_batch_handler::<SYSTEM>);} else {f(emulator);}@@ -214,7 +211,7 @@ impl Debugger {////// After execution, transient states (`Step`, `RunUntilVsync`, `RunUntilAddress`)/// automatically transition to `Paused`.- pub fn tick(&mut self, emulator: &mut GameCube) {+ pub fn tick<const SYSTEM: SystemId>(&mut self, emulator: &mut System<SYSTEM>) {match self.state {EmulatorState::Running => {if self.is_tracing() || self.is_dsp_tracing() || self.has_active_breakpoints() {diff --git a/crates/dbglib/src/trace.rs b/crates/dbglib/src/trace.rsindex fde508b..d5c0808 100644--- a/crates/dbglib/src/trace.rs+++ b/crates/dbglib/src/trace.rs@@ -2,7 +2,7 @@ use disasm::gekko::GekkoInstruction;use disasm::tokenizer::{self, AsmToken};use gecko::flipper::dsp::Dsp;use gecko::flipper::dsp::core::Registers as DspRegisters;-use gecko::gamecube::GameCube;+use gecko::system::{System, SystemId};const DISASM_COL: usize = 22;const COMMENT_COL: usize = 50;@@ -10,7 +10,7 @@ const COMMENT_COL: usize = 50;/// Format a single trace line for the current PC of the emulator.////// Returns a string like `80003100 4E800020 blr ; lr=80001234`-pub fn format_trace_line(emulator: &GameCube) -> String {+pub fn format_trace_line<const SYSTEM: SystemId>(emulator: &System<SYSTEM>) -> String {let pc = emulator.gekko.pc;let raw = emulator.mmio.virt_read_u32(pc);diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex e48624a..65e5e25 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -9,6 +9,7 @@ use winit::window::{Window, WindowId};use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};use gecko::gamecube::GameCube;+use gecko::wii::Wii;use image::Dol;use crate::debugger::DebuggerUi;@@ -17,8 +18,54 @@ use crate::render::RenderState;mod debugger;mod render;+/// Holds either a GameCube or Wii emulator. Runtime dispatch lets the+/// debugger UI work uniformly while keeping `System<SYSTEM>` strongly typed+/// inside each branch.+enum EmulatorVariant {+ Gc(GameCube),+ Wii(Wii),+}++impl EmulatorVariant {+ fn primary_controller_mut(&mut self) -> &mut PadStatus {+ match self {+ Self::Gc(e) => e.primary_controller_mut(),+ Self::Wii(e) => e.primary_controller_mut(),+ }+ }++ fn add_primary_controller(&mut self, pad: PadStatus) {+ match self {+ Self::Gc(e) => e.add_primary_controller(pad),+ Self::Wii(e) => e.add_primary_controller(pad),+ }+ }++ fn install_render_sink(&mut self, sink: Box<dyn gecko::host::RenderSink>) {+ match self {+ Self::Gc(e) => e.render_sink = sink,+ Self::Wii(e) => e.render_sink = sink,+ }+ }++ #[cfg(feature = "efb-writeback")]+ fn install_efb_writeback(&mut self, rx: Option<crossbeam_channel::Receiver<gecko::flipper::gx::WritebackEvent>>) {+ match self {+ Self::Gc(e) => e.gx.efb_writeback_rx = rx,+ Self::Wii(e) => e.gx.efb_writeback_rx = rx,+ }+ }++ fn load_dsp_irom(&mut self, data: &[u8]) {+ match self {+ Self::Gc(e) => e.dsp.load_irom(data),+ Self::Wii(e) => e.dsp.load_irom(data),+ }+ }+}+struct App {- emulator: GameCube,+ emulator: EmulatorVariant,ui: DebuggerUi,window: Option<Arc<Window>>,state: Option<RenderState>,@@ -35,6 +82,41 @@ struct AppInit {surface_format: wgpu::TextureFormat,}+impl App {+ /// Render one frame against whichever emulator variant is loaded.+ fn render_frame(&mut self) {+ let Some(state) = self.state.as_mut() else { return };+ let Some(window) = self.window.as_ref() else { return };++ // Drain Lua-load request before rendering so the script becomes+ // active starting with this frame's tick.+ if self.ui.lua_load_pending {+ self.ui.lua_load_pending = false;+ match &mut self.emulator {+ EmulatorVariant::Gc(emu) => try_load_lua(emu, &mut self.ui),+ EmulatorVariant::Wii(emu) => try_load_lua(emu, &mut self.ui),+ }+ }++ match &mut self.emulator {+ EmulatorVariant::Gc(emu) => state.render(emu, &mut self.ui, window),+ EmulatorVariant::Wii(emu) => state.render(emu, &mut self.ui, window),+ }+ }+}++fn try_load_lua<const SYSTEM: gecko::SystemId>(emu: &mut gecko::System<SYSTEM>, ui: &mut DebuggerUi) {+ match scripting::LuaHost::from_source("editor", &ui.lua_source) {+ Ok(host) => {+ ui.lua_log.push("[lua] script loaded".to_string());+ emu.set_hook_host(Box::new(host));+ }+ Err(err) => {+ ui.lua_log.push(format!("[lua] error: {err}"));+ }+ }+}+impl ApplicationHandler for App {fn resumed(&mut self, event_loop: &ActiveEventLoop) {let window = Arc::new(@@ -112,8 +194,8 @@ impl ApplicationHandler for App {}}WindowEvent::RedrawRequested => {- if let (Some(state), Some(window)) = (&mut self.state, &self.window) {- state.render(&mut self.emulator, &mut self.ui, window);+ self.render_frame();+ if let Some(window) = &self.window {window.request_redraw();}}@@ -123,13 +205,13 @@ impl ApplicationHandler for App {}#[derive(Parser)]-#[command(about = "GameCube debugger")]+#[command(about = "GameCube/Wii debugger")]struct Args {- /// Path to the DOL file+ /// Path to the DOL file (GameCube homebrew)#[arg(long)]dol: Option<String>,- /// Path to an IPL file+ /// Path to an IPL file (boot the real GameCube IPL)#[arg(long)]ipl: Option<String>,@@ -137,11 +219,8 @@ struct Args {#[arg(long)]skip_ipl: bool,- /// Boot from a disc image using HLE IPL (requires --dvd)- #[arg(long)]- ipl_hle: bool,-- /// Path to a GameCube disc image (.iso or .rvz)+ /// Path to a disc image (.iso or .rvz). System (GameCube vs Wii) is+ /// autodetected from the disc magic; Wii discs require .rvz format.#[arg(long)]dvd: Option<String>,@@ -179,31 +258,41 @@ fn main() {wgpu::PresentMode::Fifo};- let mut emulator = if args.ipl_hle {- let Some(ref dvd) = args.dvd else {- panic!("--ipl-hle requires --dvd");- };- GameCube::with_ipl_hle(image::load_dvd(std::fs::read(dvd).expect("failed to read DVD")))+ let mut emulator = if let Some(ref dol) = args.dol {+ EmulatorVariant::Gc(GameCube::with_image(&Dol::parse(+ std::fs::read(dol).expect("failed to read DOL"),+ )))} else if let Some(ref ipl) = args.ipl {let mut gc = GameCube::with_ipl(&std::fs::read(ipl).expect("failed to read IPL"), args.skip_ipl);if let Some(ref dvd) = args.dvd {gc.insert_dvd(image::load_dvd(std::fs::read(dvd).expect("failed to read DVD")));}- gc- } else if let Some(ref dol) = args.dol {- GameCube::with_image(&Dol::parse(std::fs::read(dol).expect("failed to read DOL")))+ EmulatorVariant::Gc(gc)+ } else if let Some(ref dvd_path) = args.dvd {+ let dvd_data = std::fs::read(dvd_path).expect("failed to read DVD");+ let dvd = image::load_dvd(dvd_data);+ if dvd.header().is_wii() {+ eprintln!("Detected Wii disc, booting via apploader HLE");+ EmulatorVariant::Wii(Wii::with_apploader_hle(dvd))+ } else {+ eprintln!("Detected GameCube disc, booting via IPL HLE");+ EmulatorVariant::Gc(GameCube::with_ipl_hle(dvd))+ }} else {- panic!("either --ipl, --ipl-hle, or --dol must be provided");+ panic!("provide one of --dol, --ipl, or --dvd");};if let Some(ref dsp_path) = args.dsp {let dsp_data = std::fs::read(dsp_path).expect("failed to read DSP IROM");- emulator.dsp.load_irom(&dsp_data);+ emulator.load_dsp_irom(&dsp_data);}if let Some(ref path) = args.script {let host = scripting::LuaHost::from_file(path).expect("failed to load script");- emulator.set_hook_host(Box::new(host));+ match &mut emulator {+ EmulatorVariant::Gc(emu) => emu.set_hook_host(Box::new(host)),+ EmulatorVariant::Wii(emu) => emu.set_hook_host(Box::new(host)),+ }}let symbols = args@@ -234,16 +323,13 @@ fn main() {let surface_format = wgpu::TextureFormat::Bgra8Unorm;- // Create the renderer (spawns the worker thread internally).let renderer = backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format);- // Install the renderer as the emulator's render sink.- emulator.render_sink = Box::new(renderer.clone());+ emulator.install_render_sink(Box::new(renderer.clone()));- // Install the EFB-to-texture writeback receiver. Feature-gated.#[cfg(feature = "efb-writeback")]{- emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();+ emulator.install_efb_writeback(renderer.take_writeback_rx());}let ui = DebuggerUi {diff --git a/crates/debugger/src/render.rs b/crates/debugger/src/render.rsindex d5ce0dd..0fe95f7 100644--- a/crates/debugger/src/render.rs+++ b/crates/debugger/src/render.rs@@ -1,7 +1,7 @@use backend_wgpu::capture::{self, CaptureRequest, ScreenshotControl};use dbglib::EmulatorState;use egui::ViewportId;-use gecko::gamecube::GameCube;+use gecko::system::{System, SystemId};use std::sync::Arc;use winit::window::Window;@@ -74,7 +74,12 @@ impl RenderState {self.surface.configure(&self.device, &self.surface_config);}- pub fn render(&mut self, emulator: &mut GameCube, debugger_ui: &mut DebuggerUi, window: &Window) {+ pub fn render<const SYSTEM: SystemId>(+ &mut self,+ emulator: &mut System<SYSTEM>,+ debugger_ui: &mut DebuggerUi,+ window: &Window,+ ) {if let Some(open) = debugger_ui.dvd_cover_open.take() {if open {emulator.open_cover();@@ -83,27 +88,16 @@ impl RenderState {}}- // Drain Lua log messages from the script host+ // Drain Lua log messages from the script host. `drain_logs` is on the+ // generic `Host` trait so this works regardless of system. Loading a+ // new Lua script is handled by the App, since `LuaHost` only impls+ // `Host<{ GC }>`.if debugger_ui.show_lua&& let Some(ref mut host) = emulator.hook_host{debugger_ui.lua_log.extend(host.drain_logs());}- // Load a new Lua script if requested- if debugger_ui.lua_load_pending {- debugger_ui.lua_load_pending = false;- match scripting::LuaHost::from_source("editor", &debugger_ui.lua_source) {- Ok(host) => {- debugger_ui.lua_log.push("[lua] script loaded".to_string());- emulator.set_hook_host(Box::new(host));- }- Err(err) => {- debugger_ui.lua_log.push(format!("[lua] error: {err}"));- }- }- }-debugger_ui.debugger.tick(emulator);let frame = match self.surface.get_current_texture() {diff --git a/crates/disasm/Cargo.toml b/crates/disasm/Cargo.tomlindex ffd1af8..4d192cc 100644--- a/crates/disasm/Cargo.toml+++ b/crates/disasm/Cargo.toml@@ -4,4 +4,4 @@ version = "0.1.0"edition = "2024"[build-dependencies]-chipi-build = "0.9.0"\ No newline at end of file+chipi-build = "0.9.1"\ No newline at end of filediff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.tomlindex ae5f81e..9cdb387 100644--- a/crates/gecko/Cargo.toml+++ b/crates/gecko/Cargo.toml@@ -14,12 +14,13 @@ hooks-mut-traps = ["hooks"]efb-writeback = ["dep:crossbeam-channel"][build-dependencies]-chipi-build = "0.9.0"+chipi-build = "0.9.1"[dependencies]chapa = "0.1.2"tracing = { version = "0.1.44", features = ["release_max_level_off"] }image = { path = "../image", default-features = false }+disasm = { path = "../disasm" }glam = { version = "0.32.1", features = ["bytemuck"] }bytemuck = { version = "1.25.0", features = ["derive"] }twox-hash = "2.1.2"diff --git a/crates/gecko/build.rs b/crates/gecko/build.rsindex 1d70a43..4e343e5 100644--- a/crates/gecko/build.rs+++ b/crates/gecko/build.rs@@ -1,4 +1,5 @@fn main() {chipi_build::generate_bindings("gekko.bindings.chipi").expect("chipi codegen failed (gekko)");+ chipi_build::generate_bindings("wii.bindings.chipi").expect("chipi codegen failed (wii)");chipi_build::generate_bindings("dsp.bindings.chipi").expect("chipi codegen failed (dsp)");}diff --git a/crates/gecko/dsp.bindings.chipi b/crates/gecko/dsp.bindings.chipiindex ff3356a..66aae78 100644--- a/crates/gecko/dsp.bindings.chipi+++ b/crates/gecko/dsp.bindings.chipi@@ -14,7 +14,7 @@ target rust {output "$OUT_DIR/dsp_instr.rs"}- handler control<const OP> {+ handler control {nophaltifcc@@ -26,21 +26,21 @@ target rust {callrcc}- handler loops<const OP> {+ handler loops {loop_regblooploopibloopi}- handler addr_reg<const OP> {+ handler addr_reg {dariarsubarnaddarn}- handler load_store<const OP> {+ handler load_store {lrilrsr@@ -63,7 +63,7 @@ target rust {ilrrn}- handler imm_alu<const OP> {+ handler imm_alu {addixoriandi@@ -76,7 +76,7 @@ target rust {lris}- handler add_sub<const OP> {+ handler add_sub {addraddaxadd@@ -89,7 +89,7 @@ target rust {addpaxz}- handler move_ops<const OP> {+ handler move_ops {movrmovaxmov@@ -98,7 +98,7 @@ target rust {movnp}- handler inc_dec<const OP> {+ handler inc_dec {incmincdecm@@ -107,7 +107,7 @@ target rust {abs_ac}- handler cmp_test<const OP> {+ handler cmp_test {cmpcmpaxhtst@@ -120,7 +120,7 @@ target rust {clrl}- handler logic<const OP> {+ handler logic {xorrandrorr@@ -130,7 +130,7 @@ target rust {not_ac}- handler shifts<const OP> {+ handler shifts {lsllsrasl@@ -146,7 +146,7 @@ target rust {asrnr}- handler status<const OP> {+ handler status {sbclrsbsetm2@@ -157,7 +157,7 @@ target rust {set40}- handler mul<const OP> {+ handler mul {mulmulxmulc@@ -186,23 +186,23 @@ target rust {output "$OUT_DIR/dsp_ext_instr.rs"}- handler ext_addr<const OP> {+ handler ext_addr {ext_drext_irext_nr}- handler ext_load<const OP> {+ handler ext_load {ext_lext_ln}- handler ext_store<const OP> {+ handler ext_store {ext_sext_sn}- handler ext_load_store<const OP> {+ handler ext_load_store {ext_lsext_slext_lsn@@ -213,14 +213,14 @@ target rust {ext_slnm}- handler ext_ld<const OP> {+ handler ext_ld {ext_ld_00ext_ldn_01ext_ldm_10ext_ldnm_11}- handler ext_ldax<const OP> {+ handler ext_ldax {ext_ldaxext_ldaxnext_ldaxmdiff --git a/crates/gecko/gekko.bindings.chipi b/crates/gecko/gekko.bindings.chipiindex d641ebf..2061c94 100644--- a/crates/gecko/gekko.bindings.chipi+++ b/crates/gecko/gekko.bindings.chipi@@ -6,6 +6,7 @@ target rust {context crate::gamecube::GameCubehandlers crate::gekko::interpreter+ handler_const crate::system::GCstrategy fn_ptr_lutinvalid_handler crate::gekko::interpreter::invalid@@ -14,14 +15,14 @@ target rust {output "$OUT_DIR/gekko_instr.rs"}- handler branch<const OP> {+ handler branch {bxbcxbclrxbcctrx}- handler alu<const OP> {+ handler alu {oriorisaddx@@ -52,29 +53,29 @@ target rust {mulli}- handler rotate<const OP> {+ handler rotate {rlwinmxrlwimixrlwnmx}- handler msr<const OP> {+ handler msr {mtmsrmfmsrrfi}- handler spr<const OP> {+ handler spr {mtsprmfspr}- handler segment<const OP> {+ handler segment {mtsrmfsr}- handler store_load<const OP> {+ handler store_load {stwstwusth@@ -111,7 +112,7 @@ target rust {sthbrx}- handler store_load_fp<const OP> {+ handler store_load_fp {lfdlfdustfd@@ -131,7 +132,7 @@ target rust {stfiwx}- handler store_load_psq<const OP> {+ handler store_load_psq {psq_lpsq_lupsq_st@@ -142,14 +143,14 @@ target rust {psq_stux}- handler compare<const OP> {+ handler compare {cmpcmpicmplicmpl}- handler nop<const OP> {+ handler nop {isyncsynceieio@@ -169,7 +170,7 @@ target rust {tlbli}- handler logical<const OP> {+ handler logical {andxorxxorx@@ -187,7 +188,7 @@ target rust {extsbx}- handler cr_ops<const OP> {+ handler cr_ops {mtcrfmfcrcrxor@@ -201,7 +202,7 @@ target rust {mcrf}- handler fp_ops<const OP> {+ handler fp_ops {mtfsfxmffsxmtfsb0x@@ -240,7 +241,7 @@ target rust {frsqrtex}- handler ps_ops<const OP> {+ handler ps_ops {ps_cmpu0ps_cmpo0ps_cmpu1diff --git a/crates/gecko/src/gekko.rs b/crates/gecko/src/gekko.rsindex fbc26b4..881cd67 100644--- a/crates/gecko/src/gekko.rs+++ b/crates/gecko/src/gekko.rs@@ -16,6 +16,11 @@ pub mod lut {include!(concat!(env!("OUT_DIR"), "/gekko_lut.rs"));}+#[allow(dead_code, unused_variables, non_upper_case_globals, clippy::all)]+pub mod lut_wii {+ include!(concat!(env!("OUT_DIR"), "/gekko_lut_wii.rs"));+}+pub const IPL_RESET_VECTOR: u32 = 0xFFF0_0100;pub struct Gekko {@@ -149,18 +154,6 @@ impl Gekko {unsafe { *self.gprs.get_unchecked(index as usize) }}}-- /// Get XER carry bit- #[inline(always)]- pub fn xer_ca(&self) -> u32 {- self.spr.xer.carry() as u32- }-- /// Set XER carry bit- #[inline(always)]- pub fn set_xer_ca(&mut self, ca: bool) {- self.spr.xer = self.spr.xer.with_carry(ca);- }}#[inline(always)]@@ -169,9 +162,10 @@ pub fn dispatch<const SYSTEM: crate::system::SystemId>(instr: instruction::Instruction,) {if SYSTEM == crate::system::GC {- let ctx: &mut crate::system::System<{ crate::system::GC }> = unsafe { core::mem::transmute(ctx) };+ let ctx: &mut crate::gamecube::GameCube = unsafe { core::mem::transmute(ctx) };self::lut::dispatch(ctx, instr);} else {- todo!()+ let ctx: &mut crate::wii::Wii = unsafe { core::mem::transmute(ctx) };+ self::lut_wii::dispatch(ctx, instr);}}diff --git a/crates/gecko/src/gekko/interpreter.rs b/crates/gecko/src/gekko/interpreter.rsindex c2c8a2a..fe4d99d 100644--- a/crates/gecko/src/gekko/interpreter.rs+++ b/crates/gecko/src/gekko/interpreter.rs@@ -22,6 +22,9 @@ pub use system::{mfsrin, mftb, msr, mtsrin, nop, sc, segment, spr, tw, twi};#[cold]#[inline(never)]-pub fn invalid(_ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn invalid<const SYSTEM: crate::system::SystemId>(+ _ctx: &mut crate::system::System<SYSTEM>,+ instr: crate::gekko::instruction::Instruction,+) {panic!("unimplemented Gekko opcode {:#010x}", instr.0);}diff --git a/crates/gecko/src/gekko/interpreter/alu.rs b/crates/gecko/src/gekko/interpreter/alu.rsindex e93ed36..42f7e48 100644--- a/crates/gecko/src/gekko/interpreter/alu.rs+++ b/crates/gecko/src/gekko/interpreter/alu.rs@@ -1,7 +1,11 @@+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};+#[inline(always)]-pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn alu<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_ADDX => {+ OP_ADDX => {let res = ctx.gekko.read_gpr(instr.ra())@@ -11,33 +15,33 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_ADDI | crate::gekko::lut::OP_ADDIS => {+ OP_ADDI | OP_ADDIS => {let ra = ctx.gekko.read_gpr_or_zero(instr.ra());- let simm = if OP == crate::gekko::lut::OP_ADDIS {+ let simm = if OP == OP_ADDIS {instr.simm() << 16} else {instr.simm()};ctx.gekko.write_gpr(instr.rd(), ra.wrapping_add_signed(simm));}- crate::gekko::lut::OP_ORI | crate::gekko::lut::OP_ORIS => {- let imm = if OP == crate::gekko::lut::OP_ORIS {+ OP_ORI | OP_ORIS => {+ let imm = if OP == OP_ORIS {(instr.uimm() as u32) << 16} else {instr.uimm() as u32};ctx.gekko.write_gpr(instr.ra(), ctx.gekko.read_gpr(instr.rs()) | imm);}- crate::gekko::lut::OP_XORI | crate::gekko::lut::OP_XORIS => {- let imm = if OP == crate::gekko::lut::OP_XORIS {+ OP_XORI | OP_XORIS => {+ let imm = if OP == OP_XORIS {(instr.uimm() as u32) << 16} else {instr.uimm() as u32};ctx.gekko.write_gpr(instr.ra(), ctx.gekko.read_gpr(instr.rs()) ^ imm);}- crate::gekko::lut::OP_ANDI_DOT | crate::gekko::lut::OP_ANDIS_DOT => {- let mask = if OP == crate::gekko::lut::OP_ANDIS_DOT {+ OP_ANDI_DOT | OP_ANDIS_DOT => {+ let mask = if OP == OP_ANDIS_DOT {(instr.uimm() as u32) << 16} else {instr.uimm() as u32@@ -46,7 +50,7 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.write_gpr(instr.ra(), val);ctx.gekko.update_cr0(val);}- crate::gekko::lut::OP_SUBFX => {+ OP_SUBFX => {let res = ctx.gekko.read_gpr(instr.rb())@@ -56,100 +60,100 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_NEGX => {+ OP_NEGX => {let res = (!ctx.gekko.read_gpr(instr.ra())).wrapping_add(1);ctx.gekko.write_gpr(instr.rd(), res);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_ADDCX => {+ OP_ADDCX => {let ra = ctx.gekko.read_gpr(instr.ra());let rb = ctx.gekko.read_gpr(instr.rb());let (res, carry) = ra.overflowing_add(rb);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(carry);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_SUBFCX => {+ OP_SUBFCX => {let ra = ctx.gekko.read_gpr(instr.ra());let rb = ctx.gekko.read_gpr(instr.rb());let res = rb.wrapping_sub(ra);- ctx.gekko.set_xer_ca(rb >= ra);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(rb >= ra);ctx.gekko.write_gpr(instr.rd(), res);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_ADDEX => {+ OP_ADDEX => {let ra = ctx.gekko.read_gpr(instr.ra());let rb = ctx.gekko.read_gpr(instr.rb());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (t1, c1) = ra.overflowing_add(rb);let (res, c2) = t1.overflowing_add(ca);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(c1 || c2);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_SUBFEX => {+ OP_SUBFEX => {let ra = ctx.gekko.read_gpr(instr.ra());let rb = ctx.gekko.read_gpr(instr.rb());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (t1, c1) = (!ra).overflowing_add(rb);let (res, c2) = t1.overflowing_add(ca);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(c1 || c2);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_ADDZEX => {+ OP_ADDZEX => {let ra = ctx.gekko.read_gpr(instr.ra());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (res, carry) = ra.overflowing_add(ca);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(carry);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_SUBFZEX => {+ OP_SUBFZEX => {let ra = ctx.gekko.read_gpr(instr.ra());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (res, carry) = (!ra).overflowing_add(ca);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(carry);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_ADDMEX => {+ OP_ADDMEX => {let ra = ctx.gekko.read_gpr(instr.ra());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (t1, c1) = ra.overflowing_add(ca);let (res, c2) = t1.overflowing_add(0xFFFF_FFFF);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(c1 || c2);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_SUBFMEX => {+ OP_SUBFMEX => {let ra = ctx.gekko.read_gpr(instr.ra());- let ca = ctx.gekko.xer_ca();+ let ca = ctx.gekko.spr.xer.carry() as u32;let (t1, c1) = (!ra).overflowing_add(ca);let (res, c2) = t1.overflowing_add(0xFFFF_FFFF);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(c1 || c2);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(c1 || c2);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_MULLWX => {+ OP_MULLWX => {let res = (ctx.gekko.read_gpr(instr.ra()) as i32 as i64).wrapping_mul(ctx.gekko.read_gpr(instr.rb()) as i32 as i64) as u32;ctx.gekko.write_gpr(instr.rd(), res);@@ -157,7 +161,7 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_DIVWUX => {+ OP_DIVWUX => {let ra = ctx.gekko.read_gpr(instr.ra());let rb = ctx.gekko.read_gpr(instr.rb());let res = if rb == 0 { 0 } else { ra / rb };@@ -166,7 +170,7 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_DIVWX => {+ OP_DIVWX => {let ra = ctx.gekko.read_gpr(instr.ra()) as i32;let rb = ctx.gekko.read_gpr(instr.rb()) as i32;let res = if rb == 0 || (ra == i32::MIN && rb == -1) {@@ -179,14 +183,14 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_MULHWUX => {+ OP_MULHWUX => {let res = ((ctx.gekko.read_gpr(instr.ra()) as u64 * ctx.gekko.read_gpr(instr.rb()) as u64) >> 32) as u32;ctx.gekko.write_gpr(instr.rd(), res);if instr.rc() {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_MULHWX => {+ OP_MULHWX => {let res = ((ctx.gekko.read_gpr(instr.ra()) as i32 as i64 * ctx.gekko.read_gpr(instr.rb()) as i32 as i64)>> 32) as u32;ctx.gekko.write_gpr(instr.rd(), res);@@ -194,22 +198,22 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_SUBFIC => {+ OP_SUBFIC => {let ra = ctx.gekko.read_gpr(instr.ra());let simm = instr.simm() as u32;ctx.gekko.write_gpr(instr.rd(), simm.wrapping_sub(ra));- ctx.gekko.set_xer_ca(simm >= ra);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(simm >= ra);}- crate::gekko::lut::OP_ADDIC | crate::gekko::lut::OP_ADDIC_DOT => {+ OP_ADDIC | OP_ADDIC_DOT => {let ra = ctx.gekko.read_gpr(instr.ra());let (res, carry) = ra.overflowing_add(instr.simm() as u32);ctx.gekko.write_gpr(instr.rd(), res);- ctx.gekko.set_xer_ca(carry);- if OP == crate::gekko::lut::OP_ADDIC_DOT {+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(carry);+ if OP == OP_ADDIC_DOT {ctx.gekko.update_cr0(res);}}- crate::gekko::lut::OP_MULLI => {+ OP_MULLI => {let res = (ctx.gekko.read_gpr(instr.ra()) as i32 as i64).wrapping_mul(instr.simm() as i64) as u32;ctx.gekko.write_gpr(instr.rd(), res);}@@ -218,57 +222,57 @@ pub fn alu<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gek}#[inline(always)]-pub fn logical<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn logical<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let rs = ctx.gekko.read_gpr(instr.rs());let rb = ctx.gekko.read_gpr(instr.rb());let res = match OP {- crate::gekko::lut::OP_ANDX => rs & rb,- crate::gekko::lut::OP_ORX => rs | rb,- crate::gekko::lut::OP_XORX => rs ^ rb,- crate::gekko::lut::OP_NANDX => !(rs & rb),- crate::gekko::lut::OP_NORX => !(rs | rb),- crate::gekko::lut::OP_ANDCX => rs & !rb,- crate::gekko::lut::OP_ORCX => rs | !rb,- crate::gekko::lut::OP_EQVX => !(rs ^ rb),- crate::gekko::lut::OP_SLWX => {+ OP_ANDX => rs & rb,+ OP_ORX => rs | rb,+ OP_XORX => rs ^ rb,+ OP_NANDX => !(rs & rb),+ OP_NORX => !(rs | rb),+ OP_ANDCX => rs & !rb,+ OP_ORCX => rs | !rb,+ OP_EQVX => !(rs ^ rb),+ OP_SLWX => {let sh = rb & 0x3F;if sh >= 32 { 0 } else { rs << sh }}- crate::gekko::lut::OP_SRWX => {+ OP_SRWX => {let sh = rb & 0x3F;if sh >= 32 { 0 } else { rs >> sh }}- crate::gekko::lut::OP_SRAWX => {+ OP_SRAWX => {let sh = rb & 0x3F;let signed = rs as i32;if sh >= 32 {- ctx.gekko.set_xer_ca(signed < 0);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(signed < 0);(signed >> 31) as u32} else if sh == 0 {- ctx.gekko.set_xer_ca(false);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(false);rs} else {let mask = (1u32 << sh) - 1;- ctx.gekko.set_xer_ca(signed < 0 && (rs & mask) != 0);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(signed < 0 && (rs & mask) != 0);(signed >> sh) as u32}}- crate::gekko::lut::OP_SRAWIX => {+ OP_SRAWIX => {let sh = instr.sh() as u32;let signed = rs as i32;if sh == 0 {- ctx.gekko.set_xer_ca(false);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(false);rs} else {let mask = (1u32 << sh) - 1;- ctx.gekko.set_xer_ca(signed < 0 && (rs & mask) != 0);+ ctx.gekko.spr.xer = ctx.gekko.spr.xer.with_carry(signed < 0 && (rs & mask) != 0);(signed >> sh) as u32}}- crate::gekko::lut::OP_CNTLZWX => rs.leading_zeros(),- crate::gekko::lut::OP_EXTSHX => rs as i16 as i32 as u32,- crate::gekko::lut::OP_EXTSBX => rs as i8 as i32 as u32,+ OP_CNTLZWX => rs.leading_zeros(),+ OP_EXTSHX => rs as i16 as i32 as u32,+ OP_EXTSBX => rs as i8 as i32 as u32,_ => todo!("Logical instruction with OP = {OP:#x}"),};diff --git a/crates/gecko/src/gekko/interpreter/branch.rs b/crates/gecko/src/gekko/interpreter/branch.rsindex afc44d9..fb7ba1e 100644--- a/crates/gecko/src/gekko/interpreter/branch.rs+++ b/crates/gecko/src/gekko/interpreter/branch.rs@@ -1,7 +1,10 @@use crate::gekko::condition::BranchControl;+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn branch<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn branch<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {// Read LR before potentially overwriting LR with CIA+4 (matters for blrl/bctrl)let old_lr = ctx.gekko.spr.lr;@@ -10,14 +13,14 @@ pub fn branch<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::}match OP {- crate::gekko::lut::OP_BX => {+ OP_BX => {ctx.gekko.nia = if instr.aa() {instr.li() as u32} else {ctx.gekko.cia.wrapping_add_signed(instr.li())}}- crate::gekko::lut::OP_BCLRX | crate::gekko::lut::OP_BCX | crate::gekko::lut::OP_BCCTRX => {+ OP_BCLRX | OP_BCX | OP_BCCTRX => {let ctrl = BranchControl::from_bo(instr.bo());tracing::trace!("Branch control: {ctrl:?}");@@ -31,15 +34,15 @@ pub fn branch<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::}match OP {- crate::gekko::lut::OP_BCLRX => ctx.gekko.nia = old_lr,- crate::gekko::lut::OP_BCX => {+ OP_BCLRX => ctx.gekko.nia = old_lr,+ OP_BCX => {ctx.gekko.nia = if instr.aa() {instr.bd() as u32} else {ctx.gekko.cia.wrapping_add_signed(instr.bd())}}- crate::gekko::lut::OP_BCCTRX => ctx.gekko.nia = ctx.gekko.spr.ctr,+ OP_BCCTRX => ctx.gekko.nia = ctx.gekko.spr.ctr,_ => tracing::error!("missing OP = {OP:#x}"),}}diff --git a/crates/gecko/src/gekko/interpreter/compare.rs b/crates/gecko/src/gekko/interpreter/compare.rsindex 5ba4787..bbec3af 100644--- a/crates/gecko/src/gekko/interpreter/compare.rs+++ b/crates/gecko/src/gekko/interpreter/compare.rs@@ -1,20 +1,19 @@use crate::gekko::condition::ConditionRegister;+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn compare<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn compare<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let field = match OP {- crate::gekko::lut::OP_CMP => ConditionRegister::field_from_ord(+ OP_CMP => ConditionRegister::field_from_ord((ctx.gekko.read_gpr(instr.ra()) as i32).cmp(&(ctx.gekko.read_gpr(instr.rb()) as i32)),),- crate::gekko::lut::OP_CMPI => {- ConditionRegister::field_from_ord((ctx.gekko.read_gpr(instr.ra()) as i32).cmp(&instr.simm()))- }- crate::gekko::lut::OP_CMPL => {+ OP_CMPI => ConditionRegister::field_from_ord((ctx.gekko.read_gpr(instr.ra()) as i32).cmp(&instr.simm())),+ OP_CMPL => {ConditionRegister::field_from_ord(ctx.gekko.read_gpr(instr.ra()).cmp(&ctx.gekko.read_gpr(instr.rb())))}- crate::gekko::lut::OP_CMPLI => {- ConditionRegister::field_from_ord(ctx.gekko.read_gpr(instr.ra()).cmp(&(instr.uimm() as u32)))- }+ OP_CMPLI => ConditionRegister::field_from_ord(ctx.gekko.read_gpr(instr.ra()).cmp(&(instr.uimm() as u32))),_ => todo!("Compare instruction with OP = {OP:#x}"),};diff --git a/crates/gecko/src/gekko/interpreter/cr_ops.rs b/crates/gecko/src/gekko/interpreter/cr_ops.rsindex 902cbea..3f93b2c 100644--- a/crates/gecko/src/gekko/interpreter/cr_ops.rs+++ b/crates/gecko/src/gekko/interpreter/cr_ops.rs@@ -1,7 +1,10 @@-use crate::gekko::condition::ConditionField;+use crate::gekko::condition::{ConditionField, ConditionRegister};+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn mcrxr(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn mcrxr<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let xer = ctx.gekko.spr.xer;let field = ConditionField::new().with_lt(xer.summary_overflow())@@ -13,9 +16,9 @@ pub fn mcrxr(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructi}#[inline(always)]-pub fn cr_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn cr_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_MTCRF => {+ OP_MTCRF => {let crm = instr.crm();let rs = ctx.gekko.read_gpr(instr.rs());let mut cr = ctx.gekko.cr.raw();@@ -26,12 +29,12 @@ pub fn cr_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::cr = (cr & !mask) | (rs & mask);}}- ctx.gekko.cr = crate::gekko::condition::ConditionRegister::from(cr);+ ctx.gekko.cr = ConditionRegister::from(cr);}- crate::gekko::lut::OP_MFCR => {+ OP_MFCR => {ctx.gekko.write_gpr(instr.rd(), ctx.gekko.cr.raw());}- crate::gekko::lut::OP_MCRF => {+ OP_MCRF => {let src = ctx.gekko.cr.get_field(instr.crfs());ctx.gekko.cr.set_field(instr.crfd(), src);}@@ -40,14 +43,14 @@ pub fn cr_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::let a = ctx.gekko.cr.get_bit(instr.crba());let b = ctx.gekko.cr.get_bit(instr.crbb());let result = match OP {- crate::gekko::lut::OP_CRXOR => a ^ b,- crate::gekko::lut::OP_CROR => a | b,- crate::gekko::lut::OP_CRAND => a & b,- crate::gekko::lut::OP_CREQV => a == b,- crate::gekko::lut::OP_CRNOR => !(a | b),- crate::gekko::lut::OP_CRNAND => !(a & b),- crate::gekko::lut::OP_CRANDC => a & !b,- crate::gekko::lut::OP_CRORC => a | !b,+ OP_CRXOR => a ^ b,+ OP_CROR => a | b,+ OP_CRAND => a & b,+ OP_CREQV => a == b,+ OP_CRNOR => !(a | b),+ OP_CRNAND => !(a & b),+ OP_CRANDC => a & !b,+ OP_CRORC => a | !b,_ => todo!("CR instruction with OP = {OP:#x}"),};ctx.gekko.cr.set_bit(instr.crbd(), result);diff --git a/crates/gecko/src/gekko/interpreter/fp_ops.rs b/crates/gecko/src/gekko/interpreter/fp_ops.rsindex dcac615..c234dc5 100644--- a/crates/gecko/src/gekko/interpreter/fp_ops.rs+++ b/crates/gecko/src/gekko/interpreter/fp_ops.rs@@ -1,14 +1,17 @@use crate::gekko::condition::ConditionField;use crate::gekko::fpscr::Fpscr;+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn fp_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {if !ctx.check_fp_available() {return;}match OP {- crate::gekko::lut::OP_MTFSFX => {+ OP_MTFSFX => {let fm = instr.fm();let fb = ctx.gekko.read_fpr(instr.rb()).to_bits() as u32;let mut mask = 0u32;@@ -20,22 +23,22 @@ pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.fpscr = Fpscr::from((ctx.gekko.fpscr.raw() & !mask) | (fb & mask));ctx.gekko.recompute_fpscr_summary();}- crate::gekko::lut::OP_MFFSX => {+ OP_MFFSX => {ctx.gekko.write_fpr(instr.rd(), f64::from_bits(ctx.gekko.fpscr.raw() as u64));if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_MTFSB0X => {+ OP_MTFSB0X => {ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() & !(1 << (31 - instr.crbd())));ctx.gekko.recompute_fpscr_summary();}- crate::gekko::lut::OP_MTFSB1X => {+ OP_MTFSB1X => {ctx.gekko.fpscr = Fpscr::from(ctx.gekko.fpscr.raw() | (1 << (31 - instr.crbd())));ctx.gekko.recompute_fpscr_summary();}- crate::gekko::lut::OP_MTFSFIX => {+ OP_MTFSFIX => {let crfd = instr.crfd();let imm = (instr.0 >> 12) & 0xF;let shift = (7 - crfd) * 4;@@ -43,7 +46,7 @@ pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.fpscr = Fpscr::from((ctx.gekko.fpscr.raw() & !mask) | (imm << shift));ctx.gekko.recompute_fpscr_summary();}- crate::gekko::lut::OP_MCRFS => {+ OP_MCRFS => {let src_field = instr.crfs();let shift = (7 - src_field) * 4;let fpscr_nibble = (ctx.gekko.fpscr.raw() >> shift) & 0xF;@@ -55,49 +58,49 @@ pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.recompute_fpscr_summary();}}- crate::gekko::lut::OP_FMRX => {+ OP_FMRX => {ctx.gekko.write_fpr(instr.rd(), ctx.gekko.read_fpr(instr.rb()));if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FNEGX => {+ OP_FNEGX => {ctx.gekko.write_fpr(instr.rd(), -ctx.gekko.read_fpr(instr.rb()));if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FABSX => {+ OP_FABSX => {ctx.gekko.write_fpr(instr.rd(), ctx.gekko.read_fpr(instr.rb()).abs());if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FNABSX => {+ OP_FNABSX => {ctx.gekko.write_fpr(instr.rd(), -ctx.gekko.read_fpr(instr.rb()).abs());if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FRSPX => {+ OP_FRSPX => {let val = ctx.gekko.read_fpr(instr.rb()) as f32 as f64;fp_write_single(ctx, &instr, val);}- crate::gekko::lut::OP_FCTIWX => {+ OP_FCTIWX => {let res = ctx.gekko.read_fpr(instr.rb()).round() as i32;ctx.gekko.write_fpr(instr.rd(), f64::from_bits(res as u32 as u64));if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FCTIWZX => {+ OP_FCTIWZX => {let res = ctx.gekko.read_fpr(instr.rb()) as i32;ctx.gekko.write_fpr(instr.rd(), f64::from_bits(res as u32 as u64));if instr.rc() {ctx.gekko.update_cr1();}}- crate::gekko::lut::OP_FCMPU | crate::gekko::lut::OP_FCMPO => {+ OP_FCMPU | OP_FCMPO => {let fa = ctx.gekko.read_fpr(instr.ra());let fb = ctx.gekko.read_fpr(instr.rb());let cf = if fa.is_nan() || fb.is_nan() {@@ -111,99 +114,95 @@ pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::};ctx.gekko.cr.set_field(instr.crfd(), cf);}- crate::gekko::lut::OP_FADDX => fp_write(+ OP_FADDX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) + ctx.gekko.read_fpr(instr.rb()),),- crate::gekko::lut::OP_FSUBX => fp_write(+ OP_FSUBX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) - ctx.gekko.read_fpr(instr.rb()),),- crate::gekko::lut::OP_FMULX => fp_write(+ OP_FMULX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()),),- crate::gekko::lut::OP_FDIVX => fp_write(+ OP_FDIVX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) / ctx.gekko.read_fpr(instr.rb()),),- crate::gekko::lut::OP_FMADDX => fp_write(+ OP_FMADDX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) + ctx.gekko.read_fpr(instr.rb()),),- crate::gekko::lut::OP_FMSUBX => fp_write(+ OP_FMSUBX => fp_write(ctx,&instr,ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) - ctx.gekko.read_fpr(instr.rb()),),- crate::gekko::lut::OP_FNMADDX => fp_write(+ OP_FNMADDX => fp_write(ctx,&instr,-(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) + ctx.gekko.read_fpr(instr.rb())),),- crate::gekko::lut::OP_FNMSUBX => fp_write(+ OP_FNMSUBX => fp_write(ctx,&instr,-(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) - ctx.gekko.read_fpr(instr.rb())),),- crate::gekko::lut::OP_FADDSX => fp_write_single(+ OP_FADDSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) + ctx.gekko.read_fpr(instr.rb())) as f32 as f64,),- crate::gekko::lut::OP_FSUBSX => fp_write_single(+ OP_FSUBSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) - ctx.gekko.read_fpr(instr.rb())) as f32 as f64,),- crate::gekko::lut::OP_FMULSX => fp_write_single(+ OP_FMULSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc())) as f32 as f64,),- crate::gekko::lut::OP_FDIVSX => fp_write_single(+ OP_FDIVSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) / ctx.gekko.read_fpr(instr.rb())) as f32 as f64,),- crate::gekko::lut::OP_FMADDSX => fp_write_single(+ OP_FMADDSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) + ctx.gekko.read_fpr(instr.rb())) as f32as f64,),- crate::gekko::lut::OP_FMSUBSX => fp_write_single(+ OP_FMSUBSX => fp_write_single(ctx,&instr,(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) - ctx.gekko.read_fpr(instr.rb())) as f32as f64,),- crate::gekko::lut::OP_FNMADDSX => fp_write_single(+ OP_FNMADDSX => fp_write_single(ctx,&instr,(-(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) + ctx.gekko.read_fpr(instr.rb()))) as f32as f64,),- crate::gekko::lut::OP_FNMSUBSX => fp_write_single(+ OP_FNMSUBSX => fp_write_single(ctx,&instr,(-(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) - ctx.gekko.read_fpr(instr.rb()))) as f32as f64,),- crate::gekko::lut::OP_FSQRTX => fp_write(ctx, &instr, ctx.gekko.read_fpr(instr.rb()).sqrt()),- crate::gekko::lut::OP_FSQRTSX => {- fp_write_single(ctx, &instr, (ctx.gekko.read_fpr(instr.rb()).sqrt()) as f32 as f64)- }- crate::gekko::lut::OP_FRESX => {- fp_write_single(ctx, &instr, (1.0f32 / ctx.gekko.read_fpr(instr.rb()) as f32) as f64)- }- crate::gekko::lut::OP_FRSQRTEX => fp_write(ctx, &instr, 1.0 / ctx.gekko.read_fpr(instr.rb()).sqrt()),- crate::gekko::lut::OP_FSELX => {+ OP_FSQRTX => fp_write(ctx, &instr, ctx.gekko.read_fpr(instr.rb()).sqrt()),+ OP_FSQRTSX => fp_write_single(ctx, &instr, (ctx.gekko.read_fpr(instr.rb()).sqrt()) as f32 as f64),+ OP_FRESX => fp_write_single(ctx, &instr, (1.0f32 / ctx.gekko.read_fpr(instr.rb()) as f32) as f64),+ OP_FRSQRTEX => fp_write(ctx, &instr, 1.0 / ctx.gekko.read_fpr(instr.rb()).sqrt()),+ OP_FSELX => {let fa = ctx.gekko.read_fpr(instr.ra());let fb = ctx.gekko.read_fpr(instr.rb());let fc = ctx.gekko.read_fpr(instr.fc());@@ -218,7 +217,7 @@ pub fn fp_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::/// Write FP result to fD and optionally update CR1#[inline(always)]-fn fp_write(ctx: &mut crate::gamecube::GameCube, instr: &crate::gekko::instruction::Instruction, val: f64) {+fn fp_write<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: &Instruction, val: f64) {ctx.gekko.write_fpr(instr.rd(), val);if instr.rc() {ctx.gekko.update_cr1();@@ -228,7 +227,7 @@ fn fp_write(ctx: &mut crate::gamecube::GameCube, instr: &crate::gekko::instructi/// Write single-precision FP result to fD./// On Gekko, single-precision instructions duplicate the result into both ps0 and ps1.#[inline(always)]-fn fp_write_single(ctx: &mut crate::gamecube::GameCube, instr: &crate::gekko::instruction::Instruction, val: f64) {+fn fp_write_single<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: &Instruction, val: f64) {ctx.gekko.write_fpr(instr.rd(), val);ctx.gekko.write_ps1(instr.rd(), val);if instr.rc() {diff --git a/crates/gecko/src/gekko/interpreter/ps_ops.rs b/crates/gecko/src/gekko/interpreter/ps_ops.rsindex f70a62f..13073e6 100644--- a/crates/gecko/src/gekko/interpreter/ps_ops.rs+++ b/crates/gecko/src/gekko/interpreter/ps_ops.rs@@ -1,95 +1,98 @@use crate::gekko::condition::ConditionField;+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn ps_ops<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {if !ctx.check_fp_available() {return;}match OP {- crate::gekko::lut::OP_PS_ADD => {+ OP_PS_ADD => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) + ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) + ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_SUB => {+ OP_PS_SUB => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) - ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) - ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MUL => {+ OP_PS_MUL => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * ctx.gekko.read_ps1(instr.fc())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_DIV => {+ OP_PS_DIV => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) / ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) / ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MADD => {+ OP_PS_MADD => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) + ctx.gekko.read_fpr(instr.rb()))as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * ctx.gekko.read_ps1(instr.fc()) + ctx.gekko.read_ps1(instr.rb()))as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MSUB => {+ OP_PS_MSUB => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc()) - ctx.gekko.read_fpr(instr.rb()))as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * ctx.gekko.read_ps1(instr.fc()) - ctx.gekko.read_ps1(instr.rb()))as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_NMADD => {+ OP_PS_NMADD => {let ps0 = -(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc())+ ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = -(ctx.gekko.read_ps1(instr.ra()) * ctx.gekko.read_ps1(instr.fc())+ ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_NMSUB => {+ OP_PS_NMSUB => {let ps0 = -(ctx.gekko.read_fpr(instr.ra()) * ctx.gekko.read_fpr(instr.fc())- ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = -(ctx.gekko.read_ps1(instr.ra()) * ctx.gekko.read_ps1(instr.fc())- ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MULS0 => {+ OP_PS_MULS0 => {let c0 = ctx.gekko.read_fpr(instr.fc());let ps0 = (ctx.gekko.read_fpr(instr.ra()) * c0) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * c0) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MULS1 => {+ OP_PS_MULS1 => {let c1 = ctx.gekko.read_ps1(instr.fc());let ps0 = (ctx.gekko.read_fpr(instr.ra()) * c1) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * c1) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MADDS0 => {+ OP_PS_MADDS0 => {let c0 = ctx.gekko.read_fpr(instr.fc());let ps0 = (ctx.gekko.read_fpr(instr.ra()) * c0 + ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * c0 + ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MADDS1 => {+ OP_PS_MADDS1 => {let c1 = ctx.gekko.read_ps1(instr.fc());let ps0 = (ctx.gekko.read_fpr(instr.ra()) * c1 + ctx.gekko.read_fpr(instr.rb())) as f32 as f64;let ps1 = (ctx.gekko.read_ps1(instr.ra()) * c1 + ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_SUM0 => {+ OP_PS_SUM0 => {let ps0 = (ctx.gekko.read_fpr(instr.ra()) + ctx.gekko.read_ps1(instr.rb())) as f32 as f64;let ps1 = ctx.gekko.read_ps1(instr.fc());ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_SUM1 => {+ OP_PS_SUM1 => {let ps0 = ctx.gekko.read_fpr(instr.fc());let ps1 = (ctx.gekko.read_fpr(instr.ra()) + ctx.gekko.read_ps1(instr.rb())) as f32 as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_MR => {+ OP_PS_MR => {ps_write(ctx,&instr,@@ -97,7 +100,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_ps1(instr.rb()),);}- crate::gekko::lut::OP_PS_NEG => {+ OP_PS_NEG => {ps_write(ctx,&instr,@@ -105,7 +108,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::-ctx.gekko.read_ps1(instr.rb()),);}- crate::gekko::lut::OP_PS_ABS => {+ OP_PS_ABS => {ps_write(ctx,&instr,@@ -113,7 +116,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_ps1(instr.rb()).abs(),);}- crate::gekko::lut::OP_PS_NABS => {+ OP_PS_NABS => {ps_write(ctx,&instr,@@ -121,7 +124,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::-ctx.gekko.read_ps1(instr.rb()).abs(),);}- crate::gekko::lut::OP_PS_MERGE00 => {+ OP_PS_MERGE00 => {ps_write(ctx,&instr,@@ -129,7 +132,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_fpr(instr.rb()),);}- crate::gekko::lut::OP_PS_MERGE01 => {+ OP_PS_MERGE01 => {ps_write(ctx,&instr,@@ -137,7 +140,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_ps1(instr.rb()),);}- crate::gekko::lut::OP_PS_MERGE10 => {+ OP_PS_MERGE10 => {ps_write(ctx,&instr,@@ -145,7 +148,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_fpr(instr.rb()),);}- crate::gekko::lut::OP_PS_MERGE11 => {+ OP_PS_MERGE11 => {ps_write(ctx,&instr,@@ -153,7 +156,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::ctx.gekko.read_ps1(instr.rb()),);}- crate::gekko::lut::OP_PS_SEL => {+ OP_PS_SEL => {let ps0 = if ctx.gekko.read_fpr(instr.ra()) >= 0.0 {ctx.gekko.read_fpr(instr.fc())} else {@@ -166,22 +169,22 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::};ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_CMPU0 | crate::gekko::lut::OP_PS_CMPO0 => {+ OP_PS_CMPU0 | OP_PS_CMPO0 => {let fa = ctx.gekko.read_fpr(instr.ra());let fb = ctx.gekko.read_fpr(instr.rb());ctx.gekko.cr.set_field(instr.crfd(), fp_compare(fa, fb));}- crate::gekko::lut::OP_PS_CMPU1 | crate::gekko::lut::OP_PS_CMPO1 => {+ OP_PS_CMPU1 | OP_PS_CMPO1 => {let fa = ctx.gekko.read_ps1(instr.ra());let fb = ctx.gekko.read_ps1(instr.rb());ctx.gekko.cr.set_field(instr.crfd(), fp_compare(fa, fb));}- crate::gekko::lut::OP_PS_RES => {+ OP_PS_RES => {let ps0 = (1.0f32 / ctx.gekko.read_fpr(instr.rb()) as f32) as f64;let ps1 = (1.0f32 / ctx.gekko.read_ps1(instr.rb()) as f32) as f64;ps_write(ctx, &instr, ps0, ps1);}- crate::gekko::lut::OP_PS_RSQRTE => {+ OP_PS_RSQRTE => {let ps0 = (1.0f32 / (ctx.gekko.read_fpr(instr.rb()) as f32).sqrt()) as f64;let ps1 = (1.0f32 / (ctx.gekko.read_ps1(instr.rb()) as f32).sqrt()) as f64;ps_write(ctx, &instr, ps0, ps1);@@ -193,7 +196,7 @@ pub fn ps_ops<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::}#[inline(always)]-fn ps_write(ctx: &mut crate::gamecube::GameCube, instr: &crate::gekko::instruction::Instruction, ps0: f64, ps1: f64) {+fn ps_write<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: &Instruction, ps0: f64, ps1: f64) {ctx.gekko.write_fpr(instr.rd(), ps0);ctx.gekko.write_ps1(instr.rd(), ps1);if instr.rc() {diff --git a/crates/gecko/src/gekko/interpreter/psq.rs b/crates/gecko/src/gekko/interpreter/psq.rsindex 7813621..c75c8c9 100644--- a/crates/gecko/src/gekko/interpreter/psq.rs+++ b/crates/gecko/src/gekko/interpreter/psq.rs@@ -1,3 +1,7 @@+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};+// Dequantize lookup table (64 entries, indexed by 6-bit unsigned scale)// Scale 0-31: 1.0 / 2^i, Scale 32-63: 2^(64-i) (signed interpretation: -32..-1)const DEQUANT_TABLE: [f32; 64] = {@@ -52,7 +56,7 @@ fn quant_element_size(qtype: u8) -> u32 {}}-fn dequantize(ctx: &mut crate::gamecube::GameCube, addr: u32, ld_type: u8, ld_scale: u8) -> f64 {+fn dequantize<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, addr: u32, ld_type: u8, ld_scale: u8) -> f64 {let scale = DEQUANT_TABLE[ld_scale as usize];match ld_type {0 => ctx.read_f32(addr),@@ -64,7 +68,7 @@ fn dequantize(ctx: &mut crate::gamecube::GameCube, addr: u32, ld_type: u8, ld_sc}}-fn quantize(ctx: &mut crate::gamecube::GameCube, addr: u32, value: f64, st_type: u8, st_scale: u8) {+fn quantize<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, addr: u32, value: f64, st_type: u8, st_scale: u8) {let scale = QUANT_TABLE[st_scale as usize];match st_type {0 => ctx.write_f32(addr, value),@@ -88,7 +92,7 @@ fn quantize(ctx: &mut crate::gamecube::GameCube, addr: u32, value: f64, st_type:}}-fn psq_load(ctx: &mut crate::gamecube::GameCube, fd: u8, addr: u32, w: bool, gqr: u32) {+fn psq_load<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, fd: u8, addr: u32, w: bool, gqr: u32) {let ld_type = gqr_ld_type(gqr);let ld_scale = gqr_ld_scale(gqr);let ps0 = dequantize(ctx, addr, ld_type, ld_scale);@@ -102,7 +106,7 @@ fn psq_load(ctx: &mut crate::gamecube::GameCube, fd: u8, addr: u32, w: bool, gqrctx.gekko.write_ps1(fd, ps1);}-fn psq_store(ctx: &mut crate::gamecube::GameCube, fs: u8, addr: u32, w: bool, gqr: u32) {+fn psq_store<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, fs: u8, addr: u32, w: bool, gqr: u32) {let st_type = gqr_st_type(gqr);let st_scale = gqr_st_scale(gqr);let ps0 = ctx.gekko.read_fpr(fs);@@ -115,12 +119,7 @@ fn psq_store(ctx: &mut crate::gamecube::GameCube, fs: u8, addr: u32, w: bool, gq}#[inline(always)]-pub fn store_load_psq<const OP: u32>(- ctx: &mut crate::gamecube::GameCube,- instr: crate::gekko::instruction::Instruction,-) {- use crate::gekko::lut::*;-+pub fn store_load_psq<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {if !ctx.check_fp_available() {return;}diff --git a/crates/gecko/src/gekko/interpreter/rotate.rs b/crates/gecko/src/gekko/interpreter/rotate.rsindex 2c1f1d4..d7d494b 100644--- a/crates/gecko/src/gekko/interpreter/rotate.rs+++ b/crates/gecko/src/gekko/interpreter/rotate.rs@@ -1,3 +1,7 @@+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};+#[inline]fn mask(mb: u32, me: u32) -> u32 {let begin = 0xFFFF_FFFFu32 >> mb;@@ -6,19 +10,19 @@ fn mask(mb: u32, me: u32) -> u32 {}#[inline(always)]-pub fn rotate<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn rotate<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let rs = ctx.gekko.read_gpr(instr.rs());let mb = instr.mb() as u32;let me = instr.me() as u32;let res = match OP {- crate::gekko::lut::OP_RLWINMX => rs.rotate_left(instr.sh() as u32) & mask(mb, me),- crate::gekko::lut::OP_RLWIMIX => {+ OP_RLWINMX => rs.rotate_left(instr.sh() as u32) & mask(mb, me),+ OP_RLWIMIX => {let m = mask(mb, me);let r = rs.rotate_left(instr.sh() as u32);(r & m) | (ctx.gekko.read_gpr(instr.ra()) & !m)}- crate::gekko::lut::OP_RLWNMX => {+ OP_RLWNMX => {let sh = ctx.gekko.read_gpr(instr.rb()) & 0x1F;rs.rotate_left(sh) & mask(mb, me)}diff --git a/crates/gecko/src/gekko/interpreter/store_load.rs b/crates/gecko/src/gekko/interpreter/store_load.rsindex 0efa3e2..86c312b 100644--- a/crates/gecko/src/gekko/interpreter/store_load.rs+++ b/crates/gecko/src/gekko/interpreter/store_load.rs@@ -1,62 +1,65 @@use crate::gekko::condition::ConditionField;+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;+use crate::system::{System, SystemId};#[inline(always)]-pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn store_load<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_STW | crate::gekko::lut::OP_STWU => {+ OP_STW | OP_STWU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());ctx.write_u32(addr, ctx.gekko.read_gpr(instr.rs()));- if OP == crate::gekko::lut::OP_STWU {+ if OP == OP_STWU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STH | crate::gekko::lut::OP_STHU => {+ OP_STH | OP_STHU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());ctx.write_u16(addr, ctx.gekko.read_gpr(instr.rs()) as u16);- if OP == crate::gekko::lut::OP_STHU {+ if OP == OP_STHU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STB | crate::gekko::lut::OP_STBU => {+ OP_STB | OP_STBU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());ctx.write_u8(addr, ctx.gekko.read_gpr(instr.rs()) as u8);- if OP == crate::gekko::lut::OP_STBU {+ if OP == OP_STBU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LWZ | crate::gekko::lut::OP_LWZU => {+ OP_LWZ | OP_LWZU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_u32(addr);ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LWZU {+ if OP == OP_LWZU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LBZ | crate::gekko::lut::OP_LBZU => {+ OP_LBZ | OP_LBZU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_u8(addr) as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LBZU {+ if OP == OP_LBZU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LHZ | crate::gekko::lut::OP_LHZU => {+ OP_LHZ | OP_LHZU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_u16(addr) as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LHZU {+ if OP == OP_LHZU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LHA | crate::gekko::lut::OP_LHAU => {+ OP_LHA | OP_LHAU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_u16(addr) as i16 as i32 as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LHAU {+ if OP == OP_LHAU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LMW => {+ OP_LMW => {let mut addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());for r in instr.rd()..32 {let val = ctx.read_u32(addr);@@ -64,7 +67,7 @@ pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: craaddr = addr.wrapping_add(4);}}- crate::gekko::lut::OP_STMW => {+ OP_STMW => {let mut addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());for r in instr.rs()..32 {let val = ctx.gekko.read_gpr(r);@@ -72,81 +75,81 @@ pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: craaddr = addr.wrapping_add(4);}}- crate::gekko::lut::OP_LWZX | crate::gekko::lut::OP_LWZUX => {+ OP_LWZX | OP_LWZUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));let val = ctx.read_u32(addr);ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LWZUX {+ if OP == OP_LWZUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LBZX | crate::gekko::lut::OP_LBZUX => {+ OP_LBZX | OP_LBZUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));let val = ctx.read_u8(addr) as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LBZUX {+ if OP == OP_LBZUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LHZX | crate::gekko::lut::OP_LHZUX => {+ OP_LHZX | OP_LHZUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));let val = ctx.read_u16(addr) as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LHZUX {+ if OP == OP_LHZUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LHAX | crate::gekko::lut::OP_LHAUX => {+ OP_LHAX | OP_LHAUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));let val = ctx.read_u16(addr) as i16 as i32 as u32;ctx.gekko.write_gpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LHAUX {+ if OP == OP_LHAUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STWX | crate::gekko::lut::OP_STWUX => {+ OP_STWX | OP_STWUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_u32(addr, ctx.gekko.read_gpr(instr.rs()));- if OP == crate::gekko::lut::OP_STWUX {+ if OP == OP_STWUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STBX | crate::gekko::lut::OP_STBUX => {+ OP_STBX | OP_STBUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_u8(addr, ctx.gekko.read_gpr(instr.rs()) as u8);- if OP == crate::gekko::lut::OP_STBUX {+ if OP == OP_STBUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STHX | crate::gekko::lut::OP_STHUX => {+ OP_STHX | OP_STHUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_u16(addr, ctx.gekko.read_gpr(instr.rs()) as u16);- if OP == crate::gekko::lut::OP_STHUX {+ if OP == OP_STHUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LWBRX => {+ OP_LWBRX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -154,7 +157,7 @@ pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: cralet val = ctx.read_u32(addr).swap_bytes();ctx.gekko.write_gpr(instr.rd(), val);}- crate::gekko::lut::OP_LHBRX => {+ OP_LHBRX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -162,14 +165,14 @@ pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: cralet val = ctx.read_u16(addr).swap_bytes() as u32;ctx.gekko.write_gpr(instr.rd(), val);}- crate::gekko::lut::OP_STWBRX => {+ OP_STWBRX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_u32(addr, ctx.gekko.read_gpr(instr.rs()).swap_bytes());}- crate::gekko::lut::OP_STHBRX => {+ OP_STHBRX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -181,7 +184,7 @@ pub fn store_load<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: cra}#[inline(always)]-pub fn lwarx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn lwarx<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -192,7 +195,7 @@ pub fn lwarx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructi}#[inline(always)]-pub fn stwcx_dot(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn stwcx_dot<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -209,47 +212,44 @@ pub fn stwcx_dot(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instr}#[inline(always)]-pub fn store_load_fp<const OP: u32>(- ctx: &mut crate::gamecube::GameCube,- instr: crate::gekko::instruction::Instruction,-) {+pub fn store_load_fp<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {if !ctx.check_fp_available() {return;}match OP {- crate::gekko::lut::OP_LFD | crate::gekko::lut::OP_LFDU => {+ OP_LFD | OP_LFDU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_f64(addr);ctx.gekko.write_fpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LFDU {+ if OP == OP_LFDU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STFD | crate::gekko::lut::OP_STFDU => {+ OP_STFD | OP_STFDU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());ctx.write_f64(addr, ctx.gekko.read_fpr(instr.rs()));- if OP == crate::gekko::lut::OP_STFDU {+ if OP == OP_STFDU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LFS | crate::gekko::lut::OP_LFSU => {+ OP_LFS | OP_LFSU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());let val = ctx.read_f32(addr);ctx.gekko.write_fpr(instr.rd(), val);ctx.gekko.write_ps1(instr.rd(), val);- if OP == crate::gekko::lut::OP_LFSU {+ if OP == OP_LFSU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STFS | crate::gekko::lut::OP_STFSU => {+ OP_STFS | OP_STFSU => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add_signed(instr.disp());ctx.write_f32(addr, ctx.gekko.read_fpr(instr.rs()));- if OP == crate::gekko::lut::OP_STFSU {+ if OP == OP_STFSU {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LFSX | crate::gekko::lut::OP_LFSUX => {+ OP_LFSX | OP_LFSUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -257,42 +257,42 @@ pub fn store_load_fp<const OP: u32>(let val = ctx.read_f32(addr);ctx.gekko.write_fpr(instr.rd(), val);ctx.gekko.write_ps1(instr.rd(), val);- if OP == crate::gekko::lut::OP_LFSUX {+ if OP == OP_LFSUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_LFDX | crate::gekko::lut::OP_LFDUX => {+ OP_LFDX | OP_LFDUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));let val = ctx.read_f64(addr);ctx.gekko.write_fpr(instr.rd(), val);- if OP == crate::gekko::lut::OP_LFDUX {+ if OP == OP_LFDUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STFSX | crate::gekko::lut::OP_STFSUX => {+ OP_STFSX | OP_STFSUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_f32(addr, ctx.gekko.read_fpr(instr.rs()));- if OP == crate::gekko::lut::OP_STFSUX {+ if OP == OP_STFSUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STFDX | crate::gekko::lut::OP_STFDUX => {+ OP_STFDX | OP_STFDUX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra()).wrapping_add(ctx.gekko.read_gpr(instr.rb()));ctx.write_f64(addr, ctx.gekko.read_fpr(instr.rs()));- if OP == crate::gekko::lut::OP_STFDUX {+ if OP == OP_STFDUX {ctx.gekko.write_gpr(instr.ra(), addr);}}- crate::gekko::lut::OP_STFIWX => {+ OP_STFIWX => {let addr = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -304,7 +304,7 @@ pub fn store_load_fp<const OP: u32>(}#[inline(always)]-pub fn lswx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn lswx<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -335,7 +335,7 @@ pub fn lswx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructio}#[inline(always)]-pub fn stswx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn stswx<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -360,7 +360,7 @@ pub fn stswx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructi}#[inline(always)]-pub fn lswi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn lswi<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra());let nb = instr.nb();let mut n = if nb == 0 { 32u32 } else { nb as u32 };@@ -386,7 +386,7 @@ pub fn lswi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructio}#[inline(always)]-pub fn stswi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn stswi<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra());let nb = instr.nb();let mut n = if nb == 0 { 32u32 } else { nb as u32 };@@ -409,7 +409,7 @@ pub fn stswi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructi}#[inline(always)]-pub fn eciwx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn eciwx<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra())@@ -419,7 +419,7 @@ pub fn eciwx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructi}#[inline(always)]-pub fn ecowx(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn ecowx<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let ea = ctx.gekko.read_gpr_or_zero(instr.ra())diff --git a/crates/gecko/src/gekko/interpreter/system.rs b/crates/gecko/src/gekko/interpreter/system.rsindex 6d53af1..9147164 100644--- a/crates/gecko/src/gekko/interpreter/system.rs+++ b/crates/gecko/src/gekko/interpreter/system.rs@@ -1,15 +1,18 @@+use crate::gekko::instruction::Instruction;+use crate::gekko::lut::*;use crate::gekko::sr::Sr;+use crate::system::{System, SystemId};#[inline(always)]-pub fn msr<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn msr<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_MTMSR => {+ OP_MTMSR => {ctx.gekko.msr = crate::gekko::msr::Msr::from(ctx.gekko.read_gpr(instr.rs()));}- crate::gekko::lut::OP_MFMSR => {+ OP_MFMSR => {ctx.gekko.write_gpr(instr.rd(), ctx.gekko.msr.raw());}- crate::gekko::lut::OP_RFI => {+ OP_RFI => {const RFI_MSR_MASK: u32 = 0x0000_FF73;ctx.gekko.msr = crate::gekko::msr::Msr::from((ctx.gekko.msr.raw() & !RFI_MSR_MASK) | (ctx.gekko.spr.srr1 & RFI_MSR_MASK),@@ -21,19 +24,19 @@ pub fn msr<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gek}#[inline(always)]-pub fn spr<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn spr<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_MTSPR => {+ OP_MTSPR => {let spr_num = instr.spr_swapped();let val = ctx.gekko.read_gpr(instr.rs());match spr_num {22 => {- ctx.scheduler.cancel(crate::gekko::dec::underflow_handler);+ ctx.scheduler.cancel(crate::gekko::dec::underflow_handler::<SYSTEM>);ctx.gekko.dec.write(ctx.scheduler.cycles, val);ctx.gekko.spr.dec = val;ctx.scheduler.schedule_in(crate::gekko::dec::cycles_until_underflow(val),- crate::gekko::dec::underflow_handler,+ crate::gekko::dec::underflow_handler::<SYSTEM>,);tracing::debug!(cycles = ctx.scheduler.cycles, value = val, "decrementer set");}@@ -49,7 +52,7 @@ pub fn spr<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gek_ => ctx.gekko.spr.write(spr_num, val),}}- crate::gekko::lut::OP_MFSPR => {+ OP_MFSPR => {let spr_num = instr.spr_swapped();let val = match spr_num {22 => {@@ -67,12 +70,12 @@ pub fn spr<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gek}#[inline(always)]-pub fn segment<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn segment<const OP: u32, const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {match OP {- crate::gekko::lut::OP_MTSR => {+ OP_MTSR => {ctx.gekko.sr[instr.sr() as usize] = Sr::from_raw(ctx.gekko.read_gpr(instr.rs()));}- crate::gekko::lut::OP_MFSR => {+ OP_MFSR => {ctx.gekko.write_gpr(instr.rd(), ctx.gekko.sr[instr.sr() as usize].raw());}_ => todo!("Segment Register instruction with OP = {OP:#x}"),@@ -80,19 +83,19 @@ pub fn segment<const OP: u32>(ctx: &mut crate::gamecube::GameCube, instr: crate:}#[inline(always)]-pub fn mtsrin(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn mtsrin<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let sr_idx = (ctx.gekko.read_gpr(instr.rb()) >> 28) as usize;ctx.gekko.sr[sr_idx] = Sr::from_raw(ctx.gekko.read_gpr(instr.rs()));}#[inline(always)]-pub fn mfsrin(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn mfsrin<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let sr_idx = (ctx.gekko.read_gpr(instr.rb()) >> 28) as usize;ctx.gekko.write_gpr(instr.rd(), ctx.gekko.sr[sr_idx].raw());}#[inline(always)]-pub fn mftb(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn mftb<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let tbr = instr.spr_swapped();let val = match tbr {268 => ctx.scheduler.timebase_lower(),@@ -103,7 +106,7 @@ pub fn mftb(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instructio}#[inline(always)]-pub fn twi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn twi<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let a = ctx.gekko.read_gpr(instr.ra()) as i32;let simm = instr.simm();let to = instr.to();@@ -120,7 +123,7 @@ pub fn twi(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction}#[inline(always)]-pub fn tw(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction::Instruction) {+pub fn tw<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, instr: Instruction) {let a = ctx.gekko.read_gpr(instr.ra()) as i32;let b = ctx.gekko.read_gpr(instr.rb()) as i32;let to = instr.to();@@ -137,9 +140,9 @@ pub fn tw(ctx: &mut crate::gamecube::GameCube, instr: crate::gekko::instruction:}#[inline(always)]-pub fn nop<const OP: u32>(_ctx: &mut crate::gamecube::GameCube, _instr: crate::gekko::instruction::Instruction) {}+pub fn nop<const OP: u32, const SYSTEM: SystemId>(_ctx: &mut System<SYSTEM>, _instr: Instruction) {}#[inline(always)]-pub fn sc(ctx: &mut crate::gamecube::GameCube, _instr: crate::gekko::instruction::Instruction) {+pub fn sc<const SYSTEM: SystemId>(ctx: &mut System<SYSTEM>, _instr: Instruction) {ctx.cause_syscall_interrupt();}diff --git a/crates/gecko/src/gekko/spr.rs b/crates/gecko/src/gekko/spr.rsindex a9ff62e..19a022e 100644--- a/crates/gecko/src/gekko/spr.rs+++ b/crates/gecko/src/gekko/spr.rs@@ -79,6 +79,23 @@ pub struct Spr {pub dbat2l: u32,pub dbat3u: u32,pub dbat3l: u32,+ // Extended BATs, Wii only+ pub ibat4u: u32,+ pub ibat4l: u32,+ pub ibat5u: u32,+ pub ibat5l: u32,+ pub ibat6u: u32,+ pub ibat6l: u32,+ pub ibat7u: u32,+ pub ibat7l: u32,+ pub dbat4u: u32,+ pub dbat4l: u32,+ pub dbat5u: u32,+ pub dbat5l: u32,+ pub dbat6u: u32,+ pub dbat6l: u32,+ pub dbat7u: u32,+ pub dbat7l: u32,pub dabr: u32,pub gqr0: u32,pub gqr1: u32,@@ -91,6 +108,7 @@ pub struct Spr {pub hid0: u32,pub hid1: u32,pub hid2: u32,+ pub hid4: u32,pub iabr: u32,pub wpar: u32,pub dmau: DmaUpper,@@ -168,6 +186,22 @@ impl Spr {541 => self.dbat2l,542 => self.dbat3u,543 => self.dbat3l,+ 560 => self.ibat4u,+ 561 => self.ibat4l,+ 562 => self.ibat5u,+ 563 => self.ibat5l,+ 564 => self.ibat6u,+ 565 => self.ibat6l,+ 566 => self.ibat7u,+ 567 => self.ibat7l,+ 568 => self.dbat4u,+ 569 => self.dbat4l,+ 570 => self.dbat5u,+ 571 => self.dbat5l,+ 572 => self.dbat6u,+ 573 => self.dbat6l,+ 574 => self.dbat7u,+ 575 => self.dbat7l,912 => self.gqr0,913 => self.gqr1,914 => self.gqr2,@@ -199,6 +233,7 @@ impl Spr {1008 => self.hid0,1009 => self.hid1,1010 => self.iabr,+ 1011 => self.hid4,1013 => self.dabr,1017 => self.l2cr,1019 => self.ictc,@@ -228,7 +263,7 @@ impl Spr {284 => self.tbl = value,285 => self.tbu = value,287 => self.pvr = value,- 528..=543 => {+ 528..=543 | 560..=575 => {tracing::warn!(spr_num, value = format!("{value:08X}"), "BAT register changed");match spr_num {528 => self.ibat0u = value,@@ -247,6 +282,22 @@ impl Spr {541 => self.dbat2l = value,542 => self.dbat3u = value,543 => self.dbat3l = value,+ 560 => self.ibat4u = value,+ 561 => self.ibat4l = value,+ 562 => self.ibat5u = value,+ 563 => self.ibat5l = value,+ 564 => self.ibat6u = value,+ 565 => self.ibat6l = value,+ 566 => self.ibat7u = value,+ 567 => self.ibat7l = value,+ 568 => self.dbat4u = value,+ 569 => self.dbat4l = value,+ 570 => self.dbat5u = value,+ 571 => self.dbat5l = value,+ 572 => self.dbat6u = value,+ 573 => self.dbat6l = value,+ 574 => self.dbat7u = value,+ 575 => self.dbat7l = value,_ => unreachable!(),}}@@ -281,6 +332,7 @@ impl Spr {1008 => self.hid0 = value,1009 => self.hid1 = value,1010 => self.iabr = value,+ 1011 => self.hid4 = value,1013 => self.dabr = value,1017 => self.l2cr = value,1019 => self.ictc = value,diff --git a/crates/gecko/src/mmio/bus.rs b/crates/gecko/src/mmio/bus.rsindex 275359f..2f40307 100644--- a/crates/gecko/src/mmio/bus.rs+++ b/crates/gecko/src/mmio/bus.rs@@ -88,13 +88,23 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {return ea & 0x3FFFFFFF;}- // Check all 4 DBATs- let dbats = [+ // Check DBATs. GC has 4, Wii's Broadway has 8 (extended BATs).+ let mut dbats: [(u32, u32); 8] = [(self.gekko.spr.dbat0u, self.gekko.spr.dbat0l),(self.gekko.spr.dbat1u, self.gekko.spr.dbat1l),(self.gekko.spr.dbat2u, self.gekko.spr.dbat2l),(self.gekko.spr.dbat3u, self.gekko.spr.dbat3l),+ (0, 0),+ (0, 0),+ (0, 0),+ (0, 0),];+ if SYSTEM == WII {+ dbats[4] = (self.gekko.spr.dbat4u, self.gekko.spr.dbat4l);+ dbats[5] = (self.gekko.spr.dbat5u, self.gekko.spr.dbat5l);+ dbats[6] = (self.gekko.spr.dbat6u, self.gekko.spr.dbat6l);+ dbats[7] = (self.gekko.spr.dbat7u, self.gekko.spr.dbat7l);+ }for (batu, batl) in dbats {// Valid in supervisor (Vs) or problem (Vp) modediff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rsindex 3777350..e3b0dd6 100644--- a/crates/gecko/src/scheduler.rs+++ b/crates/gecko/src/scheduler.rs@@ -1,7 +1,7 @@use std::collections::VecDeque;use crate::flipper::vi::regs::RefreshRate;-use crate::system::{GC, System, SystemId};+use crate::system::{System, SystemId};pub const TIMEBASE_DIVISOR: u64 = 12;pub const CPU_CYCLES_PER_DSP_TICK: u64 = 6; // ~486MHz CPU / ~81MHz DSP@@ -96,7 +96,7 @@ impl<const SYSTEM: SystemId> Scheduler<SYSTEM> {}}-impl Scheduler<{ GC }> {+impl Scheduler<{ crate::system::GC }> {pub fn new_gamecube() -> Self {Self::with_default_events()}diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex 9c4bfb9..12894cb 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -163,6 +163,13 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {self.step_cpu();}+ pub fn run_until(&mut self, pc: u32, predicate: impl Fn(&Self) -> bool) {+ self.gekko.pc = pc;+ while !predicate(self) {+ self.step();+ }+ }+#[inline(always)]pub fn prepare_frame(&mut self) {self.begin_frame();diff --git a/crates/gecko/src/wii.rs b/crates/gecko/src/wii.rsindex edfa7e1..56b098a 100644--- a/crates/gecko/src/wii.rs+++ b/crates/gecko/src/wii.rs@@ -1,10 +1,290 @@use crate::scheduler::Scheduler;use crate::system::{System, WII};+use image::dvd::DVD_APPLOADER_OFFSET;pub type Wii = System<{ WII }>;+const APPLOADER_BASE: u32 = 0x8120_0000;++/// Stack pointer for apploader execution matching Dolphin.+const APPLOADER_STACK: u32 = 0x816F_FFF0;++/// Wii: 0x8000_4000 (GC: 0x8000_3100). TODO: Verify?+const APPLOADER_ARG_BASE: u32 = 0x8000_4000;++/// Address of the OSReport function pointer passed to apploader's init().+/// Write a `blr` here to stub it out.+const OSREPORT_STUB: u32 = 0x8130_0000;++/// PPC `blr` instruction.+const PPC_BLR: u32 = 0x4E80_0020;+impl Wii {pub fn new(entrypoint: u32) -> Self {Self::with_scheduler(entrypoint, Scheduler::new_wii())}++ pub fn with_apploader_hle(dvd: Box<dyn image::Dvd>) -> Self {+ assert!(dvd.header().is_wii(), "apploader HLE only supports Wii discs");++ let game_name = String::from_utf8_lossy(&dvd.header().game_name);+ let game_name = game_name.trim_end_matches('\0');+ tracing::info!("Wii boot: {game_name}");++ let apploader_version = String::from_utf8_lossy(&dvd.apploader().timestamp);+ tracing::info!("Apploader: {apploader_version}");++ let mut emu = Self::new(0);++ Self::setup_bats(&mut emu);+ Self::setup_msr_hid(&mut emu);+ Self::setup_low_memory(&mut emu, dvd.as_ref());++ let apploader = *dvd.apploader();+ let apploader_entry = apploader.entrypoint.get();+ let apploader_size = (apploader.size.get() + apploader.trailer_size.get()) as usize;+ let apploader_code_start = DVD_APPLOADER_OFFSET + 0x20;+ tracing::info!(+ addr = format!("{apploader_entry:08X}"),+ size = apploader_size,+ "loading apploader from disc"+ );++ {+ let buffer = emu.mmio.virt_slice_mut(APPLOADER_BASE, apploader_size);+ dvd.read_disc_into(apploader_code_start, buffer);+ }++ emu.mmio.virt_write_u32(OSREPORT_STUB, PPC_BLR);++ emu.gekko.gprs[1] = APPLOADER_STACK;++ Self::run_apploader(&mut emu, dvd.as_ref(), apploader_entry);++ emu.insert_dvd(dvd);+ emu+ }++ fn setup_bats(emu: &mut Wii) {+ emu.gekko.spr.ibat0u = 0x8000_1FFF;+ emu.gekko.spr.ibat0l = 0x0000_0002;+ emu.gekko.spr.dbat0u = 0x8000_1FFF;+ emu.gekko.spr.dbat0l = 0x0000_0002;++ emu.gekko.spr.dbat1u = 0xC000_1FFF;+ emu.gekko.spr.dbat1l = 0x0000_002A;++ emu.gekko.spr.ibat4u = 0x9000_1FFF;+ emu.gekko.spr.ibat4l = 0x1000_0002;+ emu.gekko.spr.dbat4u = 0x9000_1FFF;+ emu.gekko.spr.dbat4l = 0x1000_0002;++ emu.gekko.spr.dbat5u = 0xD000_1FFF;+ emu.gekko.spr.dbat5l = 0x1000_002A;+ }++ fn setup_msr_hid(emu: &mut Wii) {+ emu.gekko.msr.set_floating_point_available(true);+ emu.gekko.msr.set_data_address_translation(true);+ emu.gekko.msr.set_instruction_address_translation(true);++ emu.gekko.spr.hid0 = 0x0011_C664;+ emu.gekko.spr.hid2 = 0xE000_0000;+ emu.gekko.spr.hid4 = 0x8390_0000;+ }++ // Cross referenced with beanwii and Dolphin!!+ fn setup_low_memory(emu: &mut Wii, dvd: &dyn image::Dvd) {+ let header = dvd.header();+ let game_id = u32::from_be_bytes(header.game_code);+ let maker_code = u16::from_be_bytes(header.maker_code);++ // Disc header copies (from boot1).+ emu.mmio.phys_write_u32(0x0000_0000, game_id);+ emu.mmio.phys_write_u16(0x0000_0004, maker_code);+ emu.mmio.phys_write_u8(0x0000_0006, header.disk_id);+ emu.mmio.phys_write_u8(0x0000_0007, header.version);+ emu.mmio.phys_write_u8(0x0000_0008, header.audio_streaming);+ emu.mmio.phys_write_u8(0x0000_0009, header.streaming_buffer_size);++ // Ripped from the apploader.+ emu.mmio+ .phys_write_u32(0x0000_0018, u32::from_be_bytes(image::WII_MAGIC));++ // MEM1 size, board model.+ emu.mmio.phys_write_u32(0x0000_0028, 0x0180_0000);+ emu.mmio.phys_write_u32(0x0000_002C, 0x0000_0023);++ // Exception handlers and IRQ masks.+ emu.mmio.phys_write_u32(0x0000_0048, 0x8134_0000);+ emu.mmio.phys_write_u32(0x0000_00C4, 0xFFFF_FF00);++ // OSVideoMode: 0 = NTSC, 1 = PAL/MPAL.+ let video_mode: u32 = if header.is_ntsc() { 0 } else { 1 };+ emu.mmio.phys_write_u32(0x0000_00CC, video_mode);++ // lol.+ emu.mmio.phys_write_u32(0x0000_00E4, 0x8008_F7B8);++ // Bus/CPU speeds.+ emu.mmio.phys_write_u32(0x0000_00F8, 0x0E7B_E2C0);+ emu.mmio.phys_write_u32(0x0000_00FC, 0x2B73_A840);++ // Dolphin shit.+ emu.mmio.phys_write_u32(0x0000_30D8, 0xFFFF_FFFF);++ // ???+ emu.mmio.phys_write_u16(0x0000_30E6, 0x8201);++ // MEM1 arena end. Conditionally overwritten by the apploader when the+ // DOL entry is >= 0x80004000; this is the fallback.+ emu.mmio.phys_write_u32(0x0000_3110, 0x8180_0000);++ // MEM2 sizing + arena (ref Dolphin).+ emu.mmio.phys_write_u32(0x0000_3118, 0x0400_0000);+ emu.mmio.phys_write_u32(0x0000_311C, 0x0400_0000);+ emu.mmio.phys_write_u32(0x0000_3120, 0x9360_0000);+ emu.mmio.phys_write_u32(0x0000_3124, 0x9000_0800);+ emu.mmio.phys_write_u32(0x0000_3128, 0x935E_0000);++ // IPC buffer (ARM <-> PPC shared region).+ emu.mmio.phys_write_u32(0x0000_3130, 0x935E_0000);+ emu.mmio.phys_write_u32(0x0000_3134, 0x9360_0000);++ // Hollywood revision (0x11 = retail Wii).+ emu.mmio.phys_write_u32(0x0000_3138, 0x0000_0011);++ // IOS56.+ emu.mmio.phys_write_u32(0x0000_3140, 0x0038_161E);+ emu.mmio.phys_write_u32(0x0000_3144, 0x0003_0310);+ emu.mmio.phys_write_u32(0x0000_3148, 0x9360_0000);+ emu.mmio.phys_write_u32(0x0000_314C, 0x9362_0000);++ // GDDR vendor code.+ emu.mmio.phys_write_u32(0x0000_3158, 0x0000_FF16);++ // Boot flag, devkit boot version.+ emu.mmio.phys_write_u8(0x0000_315C, 0x80);+ emu.mmio.phys_write_u16(0x0000_315E, 0x0113);++ // Game ID dup, app type.+ emu.mmio.phys_write_u32(0x0000_3180, game_id);+ emu.mmio.phys_write_u8(0x0000_3184, 0x80);++ // Min IOS version requirement.+ emu.mmio.phys_write_u32(0x0000_3188, 0x0035_1011);++ // Data partition magic + offset (Sonic Colors / NSMBW read these).+ emu.mmio.phys_write_u32(0x0000_3194, 0x8000_0000);+ emu.mmio+ .phys_write_u32(0x0000_3198, (dvd.data_partition_offset() >> 2) as u32);+ }++ fn run_apploader(emu: &mut Wii, dvd: &dyn image::Dvd, apploader_entry: u32) {+ let blr_predicate = |sys: &Wii| {+ use disasm::gekko::GekkoInstruction;+ let buffer = sys.mmio.virt_slice(sys.gekko.pc, 4);+ let (instr, _) = GekkoInstruction::decode(buffer).unwrap();+ matches!(+ instr,+ GekkoInstruction::Bclrx {+ bo: 20,+ bi: 0,+ lk: false+ }+ )+ };++ // void __fastcall Apploader_Entry(void **init_func, void **main_func, void **final_func)+ // {+ // *init_func = (void *)0x81200470;+ // *main_func = (void *)0x81200490;+ // *final_func = (void *)0x812004B0;+ // memmove((void *)0x8132FF80, (const void *)0x81200420, 0x4Cu);+ // DCStoreRange((void *)0x8132FF80, 0x4Cu);+ // ICInvalidateRange((void *)0x8132FF80, 0x4Cu);+ // }+ emu.gekko.gprs[3] = APPLOADER_ARG_BASE;+ emu.gekko.gprs[4] = APPLOADER_ARG_BASE + 4;+ emu.gekko.gprs[5] = APPLOADER_ARG_BASE + 8;+ emu.run_until(apploader_entry, blr_predicate);++ let init_ptr = emu.read_u32(APPLOADER_ARG_BASE);+ let main_ptr = emu.read_u32(APPLOADER_ARG_BASE + 4);+ let close_ptr = emu.read_u32(APPLOADER_ARG_BASE + 8);+ tracing::info!(+ init = format!("{init_ptr:08X}"),+ main = format!("{main_ptr:08X}"),+ close = format!("{close_ptr:08X}"),+ "Apploader_Entry() returned"+ );+ assert!(init_ptr != 0 && main_ptr != 0 && close_ptr != 0);++ // unsigned int __fastcall Apploader_Init(void (*report)(const char *fmt, ...))+ // {+ // unsigned int result; // r3+ // memset((void *)0x81201C60, 0, 0x20u);+ // memset((void *)0x81201C80, 0, 0x100u);+ // MEMORY[0x81201D80] = 0;+ // MEMORY[0x81201D84] = 0;+ // MEMORY[0x81201D88] = 0;+ // MEMORY[0x81201C58] = (int (__fastcall *)(_DWORD))report;+ // MEMORY[0x81201C54] = 2;+ // copy_lowmem_boot_info((void *)0x81201D8C);+ // MEMORY[0x81201C58](-2128603796);+ // MEMORY[0x81201C58](-2128603768);+ // MEMORY[0x8000315D] = 0x80;+ // if ( MEMORY[0x8000315E] < 0x107u )+ // MEMORY[0x81201C58](-2128603704);+ // MEMORY[0x80003188] = 3674906;+ // result = MEMORY[0x80000018];+ // if ( MEMORY[0x80000018] == 1562156707 )+ // MEMORY[0x81201C54] = 0;+ // else+ // MEMORY[0x81201C54] = 2;+ // return result;+ // }+ emu.gekko.gprs[3] = OSREPORT_STUB;+ emu.run_until(init_ptr, blr_predicate);+ tracing::info!("Apploader_Init() returned");++ // Apploader_Main() loads text, data, set up OS globals, etc.+ // Returns 1 in r3 if there is more work to do+ loop {+ emu.gekko.gprs[3] = APPLOADER_ARG_BASE;+ emu.gekko.gprs[4] = APPLOADER_ARG_BASE + 4;+ emu.gekko.gprs[5] = APPLOADER_ARG_BASE + 8;+ emu.run_until(main_ptr, blr_predicate);++ if emu.gekko.gprs[3] == 0 {+ break;+ }++ let addr = emu.read_u32(APPLOADER_ARG_BASE);+ let length = emu.read_u32(APPLOADER_ARG_BASE + 4) as usize;+ let offset = (emu.read_u32(APPLOADER_ARG_BASE + 8) as u64) << 2;+ tracing::debug!(+ dst = format!("{addr:08X}"),+ len = length,+ offset = format!("{offset:X}"),+ "Apploader_Main() disc read"+ );++ let buffer = emu.mmio.virt_slice_mut(addr, length);+ dvd.read_disc_into(offset as usize, buffer);+ }++ // u32 Apploader_ReturnEpilogue()+ // {+ // return g_apploader_dol.entry_point;+ // }+ emu.run_until(close_ptr, blr_predicate);+ let entrypoint = emu.gekko.gprs[3];+ assert!(entrypoint != 0, "Apploader_ReturnEpilogue() returned null entrypoint");+ emu.gekko.pc = entrypoint;+ tracing::info!(+ entrypoint = format!("{entrypoint:08X}"),+ "Apploader_ReturnEpilogue() returned, ready to run game"+ );+ }}diff --git a/crates/gecko/wii.bindings.chipi b/crates/gecko/wii.bindings.chipinew file mode 100644index 0000000..611fe24--- /dev/null+++ b/crates/gecko/wii.bindings.chipi@@ -0,0 +1,276 @@+include "../../submodules/chipi-spec/gamecube/gekko.chipi"++target rust {+ dispatch Gekko {+ output "$OUT_DIR/gekko_lut_wii.rs"++ context crate::wii::Wii+ handlers crate::gekko::interpreter+ handler_const crate::system::WII+ strategy fn_ptr_lut++ invalid_handler crate::gekko::interpreter::invalid++ instruction_type crate::gekko::instruction::Instruction {+ output "$OUT_DIR/gekko_instr_wii.rs"+ }++ handler branch {+ bx+ bcx+ bclrx+ bcctrx+ }++ handler alu {+ ori+ oris+ addx+ addi+ addis+ xori+ xoris+ andi_dot+ andis_dot+ subfx+ negx+ addcx+ subfcx+ addex+ subfex+ addzex+ subfzex+ addmex+ subfmex+ mullwx+ divwux+ divwx+ mulhwux+ mulhwx+ subfic+ addic+ addic_dot+ mulli+ }++ handler rotate {+ rlwinmx+ rlwimix+ rlwnmx+ }++ handler msr {+ mtmsr+ mfmsr+ rfi+ }++ handler spr {+ mtspr+ mfspr+ }++ handler segment {+ mtsr+ mfsr+ }++ handler store_load {+ stw+ stwu+ sth+ sthu+ lwz+ lwzu+ lbz+ lbzu+ stb+ stbu+ lhz+ lhzu+ lha+ lhau+ lmw+ stmw+ lwzx+ lbzx+ lhzx+ lhax+ stwx+ stbx+ sthx+ lwzux+ lbzux+ lhzux+ lhaux+ stwux+ stbux+ sthux+ lwbrx+ lhbrx+ stwbrx+ sthbrx+ }++ handler store_load_fp {+ lfd+ lfdu+ stfd+ stfdu+ lfs+ lfsu+ stfs+ stfsu+ lfsx+ lfsux+ lfdx+ lfdux+ stfsx+ stfsux+ stfdx+ stfdux+ stfiwx+ }++ handler store_load_psq {+ psq_l+ psq_lu+ psq_st+ psq_stu+ psq_lx+ psq_lux+ psq_stx+ psq_stux+ }++ handler compare {+ cmp+ cmpi+ cmpli+ cmpl+ }++ handler nop {+ isync+ sync+ eieio+ dcbf+ dcbi+ dcbst+ dcbt+ dcbtst+ dcba+ dcbz+ dcbz_l+ icbi+ tlbie+ tlbia+ tlbsync+ tlbld+ tlbli+ }++ handler logical {+ andx+ orx+ xorx+ nandx+ norx+ andcx+ orcx+ eqvx+ slwx+ srwx+ srawx+ srawix+ cntlzwx+ extshx+ extsbx+ }++ handler cr_ops {+ mtcrf+ mfcr+ crxor+ cror+ crand+ creqv+ crnor+ crnand+ crandc+ crorc+ mcrf+ }++ handler fp_ops {+ mtfsfx+ mffsx+ mtfsb0x+ mtfsb1x+ mtfsfix+ mcrfs+ fmrx+ fnegx+ fabsx+ fnabsx+ frspx+ fctiwx+ fctiwzx+ fcmpu+ fcmpo+ faddx+ fsubx+ fmulx+ fdivx+ fmaddx+ fmsubx+ fnmaddx+ fnmsubx+ faddsx+ fsubsx+ fmulsx+ fdivsx+ fmaddsx+ fmsubsx+ fnmaddsx+ fnmsubsx+ fsqrtsx+ fresx+ fsqrtx+ fselx+ frsqrtex+ }++ handler ps_ops {+ ps_cmpu0+ ps_cmpo0+ ps_cmpu1+ ps_cmpo1+ ps_res+ ps_rsqrte+ ps_neg+ ps_mr+ ps_nabs+ ps_abs+ ps_merge00+ ps_merge01+ ps_merge10+ ps_merge11+ ps_sum0+ ps_sum1+ ps_muls0+ ps_muls1+ ps_madds0+ ps_madds1+ ps_div+ ps_sub+ ps_add+ ps_sel+ ps_mul+ ps_msub+ ps_madd+ ps_nmsub+ ps_nmadd+ }+ }+}diff --git a/crates/image/src/dvd.rs b/crates/image/src/dvd.rsindex 142cfae..7aeddd5 100644--- a/crates/image/src/dvd.rs+++ b/crates/image/src/dvd.rs@@ -12,15 +12,16 @@ pub const DVD_APPLOADER_OFFSET: usize = DVD_HEADER_INFO_OFFSET + DVD_HEADER_INFO#[repr(C, packed)]#[derive(FromBytes, IntoBytes, Immutable, KnownLayout, Debug, Clone, Copy)]pub struct Header {- pub game_code: [u8; 4],- pub maker_code: [u8; 2],- pub disk_id: u8,- pub version: u8,- pub audio_streaming: u8,- pub streaming_buffer_size: u8,- _unused1: [u8; 0x12],- pub magic: [u8; 4],- pub game_name: [u8; 0x3E0],+ pub game_code: [u8; 4], // 0x00+ pub maker_code: [u8; 2], // 0x04+ pub disk_id: u8, // 0x06+ pub version: u8, // 0x07+ pub audio_streaming: u8, // 0x08+ pub streaming_buffer_size: u8, // 0x09+ _unused1: [u8; 0x0E], // 0x0A..0x18+ pub wii_magic: [u8; 4], // 0x18: 0x5D1C9EA3 on Wii discs, zero otherwise+ pub gc_magic: [u8; 4], // 0x1C: 0xC2339F3D on GC discs, zero otherwise+ pub game_name: [u8; 0x3E0], // 0x20pub offset_debug_monitor: U32,pub vaddr_debug_monitor: U32,_unused2: [u8; 0x18],@@ -33,6 +34,28 @@ pub struct Header {_unused3: [u8; 0x8],}+impl Header {+ pub fn magic(&self) -> u32 {+ if self.is_wii() {+ u32::from_be_bytes(self.wii_magic)+ } else {+ u32::from_be_bytes(self.gc_magic)+ }+ }++ pub fn is_wii(&self) -> bool {+ self.wii_magic == crate::WII_MAGIC+ }++ pub fn is_gc(&self) -> bool {+ self.gc_magic == crate::GC_MAGIC+ }++ pub fn is_ntsc(&self) -> bool {+ matches!(self.game_code[3], b'E' | b'B' | b'N' | b'J' | b'W' | b'K' | b'Q' | b'T')+ }+}+#[repr(C, packed)]#[derive(FromBytes, IntoBytes, Immutable, KnownLayout, Debug)]pub struct HeaderInfo {diff --git a/crates/image/src/iso.rs b/crates/image/src/iso.rsindex c06576d..2688ab4 100644--- a/crates/image/src/iso.rs+++ b/crates/image/src/iso.rs@@ -20,7 +20,7 @@ impl Iso {let fst_start = header.offset_filesystem.get() as usize;let fst_end = fst_start + header.filesystem_size.get() as usize;- let file_offset_shift = if header.magic == [0xC2, 0x33, 0x9F, 0x3D] { 0 } else { 2 };+ let file_offset_shift = if header.gc_magic == crate::GC_MAGIC { 0 } else { 2 };let filesystem = FstNode::parse(&data[fst_start..fst_end], file_offset_shift);Iso {@@ -49,4 +49,8 @@ impl crate::Dvd for Iso {fn read_disc_into(&self, offset: usize, buf: &mut [u8]) {buf.copy_from_slice(&self.data[offset..offset + buf.len()]);}++ fn data_partition_offset(&self) -> u64 {+ if self.header.is_wii() { 0xF80_0000 } else { 0 }+ }}diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rsindex b04b82c..82c04c8 100644--- a/crates/image/src/lib.rs+++ b/crates/image/src/lib.rs@@ -17,10 +17,16 @@ pub use rvz::Rvz;use dvd::{Apploader, Header};+/// Wii disc magic word at header offset 0x18.+pub const WII_MAGIC: [u8; 4] = [0x5D, 0x1C, 0x9E, 0xA3];+/// GameCube disc magic word at header offset 0x1C.+pub const GC_MAGIC: [u8; 4] = [0xC2, 0x33, 0x9F, 0x3D];+pub trait Dvd: Send {fn header(&self) -> &Header;fn apploader(&self) -> &Apploader;fn read_disc_into(&self, offset: usize, buf: &mut [u8]);+ fn data_partition_offset(&self) -> u64;}impl<T: Dvd + ?Sized> Dvd for Box<T> {@@ -35,6 +41,10 @@ impl<T: Dvd + ?Sized> Dvd for Box<T> {fn read_disc_into(&self, offset: usize, buf: &mut [u8]) {(**self).read_disc_into(offset, buf)}++ fn data_partition_offset(&self) -> u64 {+ (**self).data_partition_offset()+ }}pub fn load_dvd(data: Vec<u8>) -> Box<dyn Dvd> {diff --git a/crates/image/src/rvz.rs b/crates/image/src/rvz.rsindex bae01c4..021ad17 100644--- a/crates/image/src/rvz.rs+++ b/crates/image/src/rvz.rs@@ -759,6 +759,13 @@ impl crate::Dvd for Rvz {),}}++ fn data_partition_offset(&self) -> u64 {+ match self.data_partition {+ Some(idx) => (self.partitions[idx].data[0].first_sector as u64) * 0x8000,+ None => 0,+ }+ }}#[inline(always)]diff --git a/crates/multitool/src/dvd.rs b/crates/multitool/src/dvd.rsindex 2823a01..1c448a5 100644--- a/crates/multitool/src/dvd.rs+++ b/crates/multitool/src/dvd.rs@@ -28,7 +28,7 @@ pub fn info(data: Vec<u8>) {header.disk_id,header.version);- println!(" {:<24} {:08X}", "Magic:".bold(), u32::from_be_bytes(header.magic));+ println!(" {:<24} {:08X}", "Magic:".bold(), header.magic());println!(" {:<24} {}","Apploader Date:".bold(),@@ -62,7 +62,7 @@ fn read_filesystem(dvd: &dyn Dvd) -> FstNode {let fst_size = header.filesystem_size.get() as usize;let mut buf = vec![0u8; fst_size];dvd.read_disc_into(fst_offset, &mut buf);- let file_offset_shift = if header.magic == [0xC2, 0x33, 0x9F, 0x3D] { 0 } else { 2 };+ let file_offset_shift = if header.is_wii() { 2 } else { 0 };FstNode::parse(&buf, file_offset_shift)}diff --git a/crates/scripting/src/lib.rs b/crates/scripting/src/lib.rsindex 24ae266..2fffce7 100644--- a/crates/scripting/src/lib.rs+++ b/crates/scripting/src/lib.rs@@ -5,8 +5,8 @@ use std::sync::{atomic::{AtomicBool, Ordering},};-use gecko::gamecube::GameCube;use gecko::hooks::{AddressFilter, BusAddressFilter, HookFilters, HookFlags, HookState, Host};+use gecko::system::{System, SystemId};use mlua::{Function, Lua, RegistryKey, Result as LuaResult, Table, UserDataMethods, Value};pub struct LuaHost {@@ -207,7 +207,7 @@ impl LuaHost {Ok(state)}- fn register_emu_methods(methods: &mut impl UserDataMethods<GameCubeRef>) {+ fn register_emu_methods<const SYSTEM: SystemId>(methods: &mut impl UserDataMethods<SystemRef<SYSTEM>>) {methods.add_method("gpr", |_, this, i: u8| Ok(this.gekko.read_gpr(i)));methods.add_method_mut("set_gpr", |_, this, (i, val): (u8, u32)| {this.gekko.write_gpr(i, val);@@ -279,39 +279,44 @@ impl LuaHost {});}- fn call_cpu_hook(&self, hook_name: &str, callback: &LuaCallback, emu: &mut GameCube) -> LuaResult<()> {+ fn call_cpu_hook<const SYSTEM: SystemId>(+ &self,+ hook_name: &str,+ callback: &LuaCallback,+ emu: &mut System<SYSTEM>,+ ) -> LuaResult<()> {self.lua.scope(|scope| {- let ud = scope.create_userdata(GameCubeRef(emu as *mut GameCube))?;+ let ud = scope.create_userdata(SystemRef::<SYSTEM>(emu as *mut System<SYSTEM>))?;let func = callback.resolve(&self.lua)?;func.call::<()>(&ud)}).map_err(|err| annotate_hook_error(hook_name, err))}- fn call_bus_read_pre_hook(+ fn call_bus_read_pre_hook<const SYSTEM: SystemId>(&self,hook_name: &str,callback: &LuaCallback,- emu: &mut GameCube,+ emu: &mut System<SYSTEM>,virt_addr: u32,phys_addr: u32,size: u8,) -> LuaResult<Option<u32>> {self.lua.scope(|scope| {- let ud = scope.create_userdata(GameCubeRef(emu as *mut GameCube))?;+ let ud = scope.create_userdata(SystemRef::<SYSTEM>(emu as *mut System<SYSTEM>))?;let func = callback.resolve(&self.lua)?;func.call::<Option<u32>>((&ud, virt_addr, phys_addr, size))}).map_err(|err| annotate_hook_error(hook_name, err))}- fn call_bus_read_post_hook(+ fn call_bus_read_post_hook<const SYSTEM: SystemId>(&self,hook_name: &str,callback: &LuaCallback,- emu: &mut GameCube,+ emu: &mut System<SYSTEM>,virt_addr: u32,phys_addr: u32,size: u8,@@ -319,18 +324,18 @@ impl LuaHost {) -> LuaResult<Option<u32>> {self.lua.scope(|scope| {- let ud = scope.create_userdata(GameCubeRef(emu as *mut GameCube))?;+ let ud = scope.create_userdata(SystemRef::<SYSTEM>(emu as *mut System<SYSTEM>))?;let func = callback.resolve(&self.lua)?;func.call::<Option<u32>>((&ud, virt_addr, phys_addr, size, value))}).map_err(|err| annotate_hook_error(hook_name, err))}- fn call_bus_write_pre_hook(+ fn call_bus_write_pre_hook<const SYSTEM: SystemId>(&self,hook_name: &str,callback: &LuaCallback,- emu: &mut GameCube,+ emu: &mut System<SYSTEM>,virt_addr: u32,phys_addr: u32,size: u8,@@ -338,18 +343,18 @@ impl LuaHost {) -> LuaResult<Option<u32>> {self.lua.scope(|scope| {- let ud = scope.create_userdata(GameCubeRef(emu as *mut GameCube))?;+ let ud = scope.create_userdata(SystemRef::<SYSTEM>(emu as *mut System<SYSTEM>))?;let func = callback.resolve(&self.lua)?;func.call::<Option<u32>>((&ud, virt_addr, phys_addr, size, value))}).map_err(|err| annotate_hook_error(hook_name, err))}- fn call_bus_write_post_hook(+ fn call_bus_write_post_hook<const SYSTEM: SystemId>(&self,hook_name: &str,callback: &LuaCallback,- emu: &mut GameCube,+ emu: &mut System<SYSTEM>,virt_addr: u32,phys_addr: u32,size: u8,@@ -357,7 +362,7 @@ impl LuaHost {) -> LuaResult<()> {self.lua.scope(|scope| {- let ud = scope.create_userdata(GameCubeRef(emu as *mut GameCube))?;+ let ud = scope.create_userdata(SystemRef::<SYSTEM>(emu as *mut System<SYSTEM>))?;let func = callback.resolve(&self.lua)?;func.call::<()>((&ud, virt_addr, phys_addr, size, value))})@@ -437,31 +442,31 @@ fn parse_address_key(value: Value, context: &str) -> LuaResult<u32> {}}-struct GameCubeRef(*mut GameCube);+struct SystemRef<const SYSTEM: SystemId>(*mut System<SYSTEM>);-unsafe impl Send for GameCubeRef {}+unsafe impl<const SYSTEM: SystemId> Send for SystemRef<SYSTEM> {}-impl mlua::UserData for GameCubeRef {+impl<const SYSTEM: SystemId> mlua::UserData for SystemRef<SYSTEM> {fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {- LuaHost::register_emu_methods(methods);+ LuaHost::register_emu_methods::<SYSTEM>(methods);}}-impl std::ops::Deref for GameCubeRef {- type Target = GameCube;+impl<const SYSTEM: SystemId> std::ops::Deref for SystemRef<SYSTEM> {+ type Target = System<SYSTEM>;- fn deref(&self) -> &GameCube {+ fn deref(&self) -> &System<SYSTEM> {unsafe { &*self.0 }}}-impl std::ops::DerefMut for GameCubeRef {- fn deref_mut(&mut self) -> &mut GameCube {+impl<const SYSTEM: SystemId> std::ops::DerefMut for SystemRef<SYSTEM> {+ fn deref_mut(&mut self) -> &mut System<SYSTEM> {unsafe { &mut *self.0 }}}-impl Host<{ gecko::system::GC }> for LuaHost {+impl<const SYSTEM: SystemId> Host<SYSTEM> for LuaHost {fn hook_state(&self) -> HookState {HookState {flags: self.flags,@@ -490,7 +495,7 @@ impl Host<{ gecko::system::GC }> for LuaHost {self.reload_dispatches().map(Some).map_err(|err| err.to_string())}- fn on_cpu_pre(&mut self, emu: &mut GameCube) {+ fn on_cpu_pre(&mut self, emu: &mut System<SYSTEM>) {let pc = emu.gekko.pc;if let Some(callback) = self.cpu_pre.get(&pc)&& let Err(err) = self.call_cpu_hook("cpu_pre", callback, emu)@@ -499,7 +504,7 @@ impl Host<{ gecko::system::GC }> for LuaHost {}}- fn on_cpu_post(&mut self, emu: &mut GameCube) {+ fn on_cpu_post(&mut self, emu: &mut System<SYSTEM>) {let pc = emu.gekko.cia;if let Some(callback) = self.cpu_post.get(&pc)&& let Err(err) = self.call_cpu_hook("cpu_post", callback, emu)@@ -508,7 +513,7 @@ impl Host<{ gecko::system::GC }> for LuaHost {}}- fn on_bus_read_pre(&mut self, emu: &mut GameCube, virt_addr: u32, phys_addr: u32, size: u8) -> Option<u32> {+ fn on_bus_read_pre(&mut self, emu: &mut System<SYSTEM>, virt_addr: u32, phys_addr: u32, size: u8) -> Option<u32> {let callback = self.bus_read_pre.resolve(virt_addr, phys_addr)?;match self.call_bus_read_pre_hook("bus_read_pre", callback, emu, virt_addr, phys_addr, size) {Ok(value) => value,@@ -519,7 +524,14 @@ impl Host<{ gecko::system::GC }> for LuaHost {}}- fn on_bus_read_post(&mut self, emu: &mut GameCube, virt_addr: u32, phys_addr: u32, size: u8, value: u32) -> u32 {+ fn on_bus_read_post(+ &mut self,+ emu: &mut System<SYSTEM>,+ virt_addr: u32,+ phys_addr: u32,+ size: u8,+ value: u32,+ ) -> u32 {if let Some(callback) = self.bus_read_post.resolve(virt_addr, phys_addr) {match self.call_bus_read_post_hook("bus_read_post", callback, emu, virt_addr, phys_addr, size, value) {Ok(Some(v)) => return v,@@ -530,7 +542,14 @@ impl Host<{ gecko::system::GC }> for LuaHost {value}- fn on_bus_write_pre(&mut self, emu: &mut GameCube, virt_addr: u32, phys_addr: u32, size: u8, value: u32) -> u32 {+ fn on_bus_write_pre(+ &mut self,+ emu: &mut System<SYSTEM>,+ virt_addr: u32,+ phys_addr: u32,+ size: u8,+ value: u32,+ ) -> u32 {let Some(callback) = self.bus_write_pre.resolve(virt_addr, phys_addr) else {return value;};@@ -545,7 +564,7 @@ impl Host<{ gecko::system::GC }> for LuaHost {}}- fn on_bus_write_post(&mut self, emu: &mut GameCube, virt_addr: u32, phys_addr: u32, size: u8, value: u32) {+ fn on_bus_write_post(&mut self, emu: &mut System<SYSTEM>, virt_addr: u32, phys_addr: u32, size: u8, value: u32) {if let Some(callback) = self.bus_write_post.resolve(virt_addr, phys_addr)&& let Err(err) =self.call_bus_write_post_hook("bus_write_post", callback, emu, virt_addr, phys_addr, size, value)diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex d4a8069..0580fa9 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -5,19 +5,21 @@ use clap::Parser;use crossbeam_channel::bounded;use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER};use gecko::gamecube::GameCube;+use gecko::system::{System, SystemId};+use gecko::wii::Wii;use image::Dol;use std::sync::{Arc, Mutex};use winit::event_loop::EventLoop;use winit::keyboard::KeyCode;#[derive(Parser)]-#[command(about = "GameCube emulator")]+#[command(about = "GameCube/Wii emulator")]struct Args {- /// Path to the DOL file+ /// Path to the DOL file (GameCube homebrew)#[arg(long)]dol: Option<String>,- /// Path to an IPL file+ /// Path to an IPL file (boot the real GameCube IPL)#[arg(long)]ipl: Option<String>,@@ -25,11 +27,8 @@ struct Args {#[arg(long)]skip_ipl: bool,- /// Boot from a disc image using HLE IPL (requires --dvd)- #[arg(long)]- ipl_hle: bool,-- /// Path to a GameCube disc image (.iso or .rvz)+ /// Path to a disc image (.iso or .rvz). System (GameCube vs Wii) is+ /// autodetected from the disc magic; Wii discs require .rvz format.#[arg(long)]dvd: Option<String>,@@ -69,23 +68,43 @@ fn main() {).init();- let mut emulator = if args.ipl_hle {- let Some(ref dvd) = args.dvd else {- panic!("--ipl-hle requires --dvd");- };- GameCube::with_ipl_hle(image::load_dvd(std::fs::read(dvd).expect("failed to read DVD")))- } else if let Some(ref ipl) = args.ipl {- let mut gc = GameCube::with_ipl(&std::fs::read(ipl).expect("failed to read IPL"), args.skip_ipl);- if let Some(ref dvd) = args.dvd {- gc.insert_dvd(image::load_dvd(std::fs::read(dvd).expect("failed to read DVD")));+ // Boot dispatch:+ // --dol : GameCube homebrew (with_image)+ // --ipl [+ --dvd] : GameCube real IPL boot (with_ipl)+ // --dvd <path> : autodetect Wii vs GC, HLE boot via apploader+ if let Some(ref dol) = args.dol {+ let mut emulator = GameCube::with_image(&Dol::parse(std::fs::read(dol).expect("failed to read DOL")));+ configure(&mut emulator, &args);+ run(emulator, present_mode);+ } else if let Some(ref ipl_path) = args.ipl {+ let ipl_data = std::fs::read(ipl_path).expect("failed to read IPL");+ let mut emulator = GameCube::with_ipl(&ipl_data, args.skip_ipl);+ if let Some(ref dvd_path) = args.dvd {+ let dvd_data = std::fs::read(dvd_path).expect("failed to read DVD");+ emulator.insert_dvd(image::load_dvd(dvd_data));+ }+ configure(&mut emulator, &args);+ run(emulator, present_mode);+ } else if let Some(ref dvd_path) = args.dvd {+ let dvd_data = std::fs::read(dvd_path).expect("failed to read DVD");+ let dvd = image::load_dvd(dvd_data);+ if dvd.header().is_wii() {+ println!("Detected Wii disc, booting via apploader HLE");+ let mut emulator = Wii::with_apploader_hle(dvd);+ configure(&mut emulator, &args);+ run(emulator, present_mode);+ } else {+ println!("Detected GameCube disc, booting via IPL HLE");+ let mut emulator = GameCube::with_ipl_hle(dvd);+ configure(&mut emulator, &args);+ run(emulator, present_mode);}- gc- } else if let Some(ref dol) = args.dol {- GameCube::with_image(&Dol::parse(std::fs::read(dol).expect("failed to read DOL")))} else {- panic!("either --ipl, --ipl-hle, or --dol must be provided");- };+ panic!("provide one of --dol, --ipl, or --dvd");+ }+}+fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args) {if let Some(ref dsp_path) = args.dsp {let dsp_data = std::fs::read(dsp_path).expect("failed to read DSP IROM");emulator.dsp.load_irom(&dsp_data);@@ -97,12 +116,13 @@ fn main() {emulator.set_hook_host(Box::new(host));}- // Channel 0 always has a controller connectedemulator.add_primary_controller(PadStatus {connected: true,..PadStatus::default()});+}+fn run<const SYSTEM: SystemId>(mut emulator: System<SYSTEM>, present_mode: wgpu::PresentMode) {let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {backends: wgpu::Backends::all(),..Default::default()@@ -120,15 +140,10 @@ fn main() {let surface_format = wgpu::TextureFormat::Bgra8Unorm;- // Create the renderer (spawns the worker thread internally).let renderer = backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format);- // Install the renderer as the emulator's render sink.emulator.render_sink = Box::new(renderer.clone());- // Install the EFB-to-texture writeback receiver so the emu thread- // can copy encoded texture bytes back into RAM after each readback.- // Only present with the `efb-writeback` feature.#[cfg(feature = "efb-writeback")]{emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();@@ -144,7 +159,7 @@ fn main() {let emu_input = input.clone();std::thread::Builder::new().name("emu".into())- .spawn(move || thread::emu_thread(emulator, frame_tx, emu_input, proxy))+ .spawn(move || thread::emu_thread::<SYSTEM>(emulator, frame_tx, emu_input, proxy)).expect("failed to spawn emulator thread");let mut app = app::App {diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rsindex e4280ae..19cb11b 100644--- a/crates/tinyapp/src/thread.rs+++ b/crates/tinyapp/src/thread.rs@@ -1,8 +1,6 @@use crossbeam_channel::Sender;-use gecko::{- flipper::{si::pad::PadStatus, vi::regs::RefreshRate},- gamecube::GameCube,-};+use gecko::flipper::{si::pad::PadStatus, vi::regs::RefreshRate};+use gecko::system::{System, SystemId};use std::sync::{Arc, Mutex};use winit::event_loop::EventLoopProxy;@@ -10,8 +8,8 @@ pub struct FrameMessage {pub native_hz: f64,}-pub fn emu_thread(- mut emulator: GameCube,+pub fn emu_thread<const SYSTEM: SystemId>(+ mut emulator: System<SYSTEM>,frame_tx: Sender<FrameMessage>,input: Arc<Mutex<PadStatus>>,proxy: EventLoopProxy<()>,diff --git a/other/ida/apploader_loader.py b/other/ida/apploader_loader.pynew file mode 100644index 0000000..25d27e3--- /dev/null+++ b/other/ida/apploader_loader.py@@ -0,0 +1,194 @@+import struct+import os++import idaapi+import ida_bytes+import ida_entry+import ida_ida+import ida_name+import ida_segment+++APPLOADER_FILE_CODE_OFFSET = 0x20+APPLOADER_RUNTIME_BASE = 0x81200000+APPLOADER_FILE_LOAD_BASE = APPLOADER_RUNTIME_BASE - APPLOADER_FILE_CODE_OFFSET+APPLOADER_HEADER_SIZE = 0x20+++SYSTEM_REGIONS = [+ (0x80000000, 0x80004000, ".os_lowmem", "DATA"),+ (0xC0000000, 0xC0004000, ".os_lowmem_unc", "DATA"),+ (0xCC000000, 0xCC008004, ".mmio_gc", "DATA"),+ (0xCD000000, 0xCD008000, ".mmio_wii", "DATA"),+]++OS_GLOBALS = {+ 0x80000000: ("OSGameCode", 4),+ 0x80000004: ("OSMakerCode", 2),+ 0x80000006: ("OSDiscNumber", 1),+ 0x80000007: ("OSDiscVersion", 1),+ 0x80000008: ("OSAudioStreaming", 1),+ 0x80000009: ("OSStreamingBufferSize", 1),+ 0x80000018: ("OSWiiMagic", 4),+ 0x8000001C: ("OSGameCubeMagic", 4),+ 0x80000020: ("OSNintendoBootCode", 4),+ 0x80000024: ("OSVersion", 4),+ 0x80000028: ("OSPhysicalMEM1Size", 4),+ 0x8000002C: ("OSConsoleType", 4),+ 0x80000030: ("OSArenaLo", 4),+ 0x80000034: ("OSArenaHi", 4),+ 0x80000038: ("OSFstLocation", 4),+ 0x8000003C: ("OSFstMaxLength", 4),+ 0x80000040: ("OSDebuggerHook", 4),+ 0x80000044: ("OSDebuggerHookSize", 4),+ 0x80000048: ("OSCurrentContextPhys", 4),+ 0x8000004C: ("OSExceptionHandlerVector", 4),+ 0x800000C0: ("OSCurrentContext", 4),+ 0x800000C4: ("OSUserInterruptMask", 4),+ 0x800000C8: ("OSExceptionType", 4),+ 0x800000CC: ("OSVideoMode", 4),+ 0x800000D0: ("OSARAMSize", 4),+ 0x800000D4: ("OSCurrentFunction", 4),+ 0x800000D8: ("OSDefaultThread", 4),+ 0x800000DC: ("OSEarliestThread", 4),+ 0x800000E0: ("OSLastThread", 4),+ 0x800000E4: ("OSCurrentThread", 4),+ 0x800000F0: ("OSPhysicalMEM2Size", 4),+ 0x800000F4: ("OSConsoleSimulatedMEM2Size", 4),+ 0x800000F8: ("OSBusClockSpeed", 4),+ 0x800000FC: ("OSCpuClockSpeed", 4),+ 0x80003100: ("BI2_PhysicalMEM1Size", 4),+ 0x80003104: ("BI2_SimulatedMEM1Size", 4),+ 0x8000310C: ("BI2_MEM1ArenaStart", 4),+ 0x80003110: ("BI2_MEM1ArenaEnd", 4),+ 0x80003118: ("BI2_PhysicalMEM2Size", 4),+ 0x8000311C: ("BI2_SimulatedMEM2Size", 4),+ 0x80003120: ("BI2_MEM2EndForPPC", 4),+ 0x80003124: ("BI2_UsableMEM2Start", 4),+ 0x80003128: ("BI2_UsableMEM2End", 4),+ 0x80003130: ("BI2_IPCBufferStart", 4),+ 0x80003134: ("BI2_IPCBufferEnd", 4),+ 0x80003138: ("BI2_HollywoodVersion", 4),+ 0x80003140: ("BI2_IOSVersion", 4),+ 0x80003144: ("BI2_IOSBuildDate", 4),+ 0x80003148: ("BI2_IOSReservedHeapStart", 4),+ 0x8000314C: ("BI2_IOSReservedHeapEnd", 4),+ 0x80003158: ("BI2_GDDRVendorCode", 4),+ 0x8000315C: ("BI2_BootIndicator", 1),+ 0x8000315D: ("BI2_LegacyDIModeFlag", 1),+ 0x8000315E: ("BI2_DevkitBootProgramVersion", 2),+ 0x80003180: ("BI2_GameID", 4),+ 0x80003184: ("BI2_ApplicationType", 1),+ 0x80003186: ("BI2_ApplicationType2", 1),+ 0x80003188: ("BI2_MinimumIOSVersion", 4),+ 0x80003198: ("BI2_DataPartitionOffset", 4),+ 0x8000319C: ("BI2_DiscLayerType", 1),+}+++def _file_size(li):+ here = li.tell()+ li.seek(0, 2)+ size = li.tell()+ li.seek(here)+ return size+++def _read_at(li, off, size):+ here = li.tell()+ li.seek(off)+ data = li.read(size)+ li.seek(here)+ return data+++def _u32be(raw, off):+ return struct.unpack(">I", raw[off:off + 4])[0]+++def _add_segment(start, end, name, sclass, perm):+ seg = idaapi.segment_t()+ seg.start_ea = start+ seg.end_ea = end+ seg.bitness = 1+ seg.align = idaapi.saRelByte+ seg.comb = idaapi.scPub+ seg.perm = perm+ return ida_segment.add_segm_ex(seg, name, sclass, idaapi.ADDSEG_NOSREG)+++def _name_dword(ea, name):+ ida_bytes.create_dword(ea, 4)+ ida_name.set_name(ea, name, ida_name.SN_FORCE)+++def _define_function(ea, name):+ ida_name.set_name(ea, name, ida_name.SN_FORCE)+ ida_entry.add_entry(ea, ea, name, True)+++def _add_system_regions():+ rw = ida_segment.SEGPERM_READ | ida_segment.SEGPERM_WRITE+ for start, end, name, sclass in SYSTEM_REGIONS:+ if _add_segment(start, end, name, sclass, rw):+ ida_bytes.put_bytes(start, b"\x00" * (end - start))+++def _apply_os_globals():+ for ea, (name, size) in OS_GLOBALS.items():+ if not ida_segment.getseg(ea):+ continue+ if size == 1:+ ida_bytes.create_byte(ea, 1)+ elif size == 2:+ ida_bytes.create_word(ea, 2)+ elif size == 4:+ ida_bytes.create_dword(ea, 4)+ ida_name.set_name(ea, name, ida_name.SN_FORCE)+++def accept_file(li, filename):+ if os.path.basename(filename).lower() != "apploader.bin":+ return 0+ return {"format": "Nintendo GameCube/Wii apploader"}+++def load_file(li, neflags, format):+ size = _file_size(li)+ raw = _read_at(li, 0, size)++ idaapi.set_processor_type("PPC", idaapi.SETPROC_LOADER)+ ida_ida.inf_set_be(True)+ ida_ida.inf_set_app_bitness(32)++ image_start = APPLOADER_FILE_LOAD_BASE+ image_end = APPLOADER_FILE_LOAD_BASE + size++ _add_segment(image_start, image_start + APPLOADER_HEADER_SIZE, ".apploader_header", "DATA", ida_segment.SEGPERM_READ)+ ida_bytes.put_bytes(image_start, raw[:APPLOADER_HEADER_SIZE])++ _add_segment(+ APPLOADER_RUNTIME_BASE,+ image_end,+ ".apploader",+ "CODE",+ ida_segment.SEGPERM_READ | ida_segment.SEGPERM_WRITE | ida_segment.SEGPERM_EXEC,+ )+ ida_bytes.put_bytes(APPLOADER_RUNTIME_BASE, raw[APPLOADER_FILE_CODE_OFFSET:])++ ida_name.set_name(image_start, "apploader_build_date", ida_name.SN_FORCE)+ ida_bytes.create_strlit(image_start, 10, idaapi.STRTYPE_C)+ _name_dword(image_start + 0x10, "apploader_entry")+ _name_dword(image_start + 0x14, "apploader_size")+ _name_dword(image_start + 0x18, "apploader_trailer_size")++ _add_system_regions()+ _apply_os_globals()++ entry_addr = _u32be(raw, 0x10)+ if APPLOADER_RUNTIME_BASE <= entry_addr < image_end:+ _define_function(entry_addr, "Apploader_Entry")+ else:+ _define_function(APPLOADER_RUNTIME_BASE, "apploader_start")++ return 1