Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

screenshots!

Layle36cf1c82afe8
diff --git a/Cargo.lock b/Cargo.lock
index e495681..83a83a7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -236,6 +236,7 @@ dependencies = [
"encase",
"gecko",
"glam",
+ "png",
"rustc-hash 2.1.2",
"tracing",
"wesl",
diff --git a/README.md b/README.md
index 95d3c33..777a2ec 100644
--- a/README.md
+++ b/README.md
@@ -2,9 +2,10 @@
# Gecko
-A work-in-progress GameCube and Wii emulator and debugger written in Rust.
+A WIP GameCube/Wii emulator and debugger written in Rust.
-<img src="images/wario.png" width="30%"> <img src="images/debugger.png" width="30%">
+<img src="images/wario.png" width="30%"> <img src="images/sunshine.png" width="30%"> <img src="images/windwaker.png" width="30%">
+<img src="images/luigi.png" width="30%"> <img src="images/re4.png" width="30%"> <img src="images/debugger.png" width="30%">
</div>
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.toml
index d2e8e75..3328e70 100644
--- a/crates/backend-wgpu/Cargo.toml
+++ b/crates/backend-wgpu/Cargo.toml
@@ -16,6 +16,7 @@ glam = { version = "0.32.1", features = ["encase"] }
crossbeam-channel = "0.5.15"
tracing = "0.1.44"
rustc-hash = "2.1.2"
+png = "0.18.1"
[build-dependencies]
wesl = "0.3.2"
diff --git a/crates/backend-wgpu/src/capture.rs b/crates/backend-wgpu/src/capture.rs
new file mode 100644
index 0000000..dad8fdc
--- /dev/null
+++ b/crates/backend-wgpu/src/capture.rs
@@ -0,0 +1,179 @@
+use std::fs::{self, File};
+use std::io::BufWriter;
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use crate::align_up;
+
+pub struct CapturedFrame {
+ pub width: u32,
+ pub height: u32,
+ pub rgba: Vec<u8>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CaptureRequest {
+ None,
+ FullWindow,
+ GameOnly,
+}
+
+pub struct ScreenshotControl {
+ pending: CaptureRequest,
+}
+
+impl ScreenshotControl {
+ pub fn new() -> Self {
+ Self {
+ pending: CaptureRequest::None,
+ }
+ }
+
+ pub fn request(&mut self, req: CaptureRequest) {
+ if req != CaptureRequest::None {
+ self.pending = req;
+ }
+ }
+
+ pub fn take_pending(&mut self) -> CaptureRequest {
+ std::mem::replace(&mut self.pending, CaptureRequest::None)
+ }
+}
+
+impl Default for ScreenshotControl {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+pub fn capture_texture(device: &wgpu::Device, queue: &wgpu::Queue, texture: &wgpu::Texture) -> Option<CapturedFrame> {
+ let size = texture.size();
+ let width = size.width;
+ let height = size.height;
+ if width == 0 || height == 0 {
+ return None;
+ }
+
+ let format = texture.format();
+ let swap = match format {
+ wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb => true,
+ wgpu::TextureFormat::Rgba8Unorm | wgpu::TextureFormat::Rgba8UnormSrgb => false,
+ _ => {
+ tracing::warn!(?format, "capture_texture: unsupported texture format");
+ return None;
+ }
+ };
+
+ let bytes_per_row = align_up(width as u64 * 4, 256);
+ let staging_size = bytes_per_row * height as u64;
+
+ let staging = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("screenshot_staging"),
+ size: staging_size,
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ });
+
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("screenshot_encoder"),
+ });
+ encoder.copy_texture_to_buffer(
+ wgpu::TexelCopyTextureInfo {
+ texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::default(),
+ },
+ wgpu::TexelCopyBufferInfo {
+ buffer: &staging,
+ layout: wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(bytes_per_row as u32),
+ rows_per_image: Some(height),
+ },
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ queue.submit([encoder.finish()]);
+
+ let slice = staging.slice(..staging_size);
+ slice.map_async(wgpu::MapMode::Read, |_| {});
+ if let Err(err) = device.poll(wgpu::PollType::Wait {
+ submission_index: None,
+ timeout: Some(Duration::from_secs(5)),
+ }) {
+ tracing::warn!(?err, "capture_texture: device poll failed");
+ return None;
+ }
+
+ let mut rgba = vec![0u8; (width * height * 4) as usize];
+ {
+ let mapped = slice.get_mapped_range();
+ let row_bytes = (width * 4) as usize;
+ let src_row_bytes = bytes_per_row as usize;
+ for y in 0..height as usize {
+ let src_row = &mapped[y * src_row_bytes..y * src_row_bytes + row_bytes];
+ let dst_row = &mut rgba[y * row_bytes..y * row_bytes + row_bytes];
+ if swap {
+ for i in 0..width as usize {
+ dst_row[i * 4] = src_row[i * 4 + 2];
+ dst_row[i * 4 + 1] = src_row[i * 4 + 1];
+ dst_row[i * 4 + 2] = src_row[i * 4];
+ dst_row[i * 4 + 3] = src_row[i * 4 + 3];
+ }
+ } else {
+ dst_row.copy_from_slice(src_row);
+ }
+ }
+ }
+ staging.unmap();
+
+ Some(CapturedFrame { width, height, rgba })
+}
+
+pub fn save_png_async(path: PathBuf, frame: CapturedFrame, force_opaque: bool) {
+ std::thread::Builder::new()
+ .name("screenshot-encode".into())
+ .spawn(move || match self::write_png(&path, frame, force_opaque) {
+ Ok(()) => tracing::info!(path = %path.display(), "saved screenshot"),
+ Err(err) => tracing::error!(path = %path.display(), ?err, "screenshot save failed"),
+ })
+ .ok();
+}
+
+fn write_png(path: &Path, mut frame: CapturedFrame, force_opaque: bool) -> std::io::Result<()> {
+ if force_opaque {
+ for px in frame.rgba.chunks_exact_mut(4) {
+ px[3] = 255;
+ }
+ }
+
+ if let Some(parent) = path.parent() {
+ fs::create_dir_all(parent)?;
+ }
+
+ let file = File::create(path)?;
+ let writer = BufWriter::new(file);
+ let mut encoder = png::Encoder::new(writer, frame.width, frame.height);
+ encoder.set_color(png::ColorType::Rgba);
+ encoder.set_depth(png::BitDepth::Eight);
+
+ let mut png_writer = encoder.write_header().map_err(std::io::Error::other)?;
+ png_writer
+ .write_image_data(&frame.rgba)
+ .map_err(std::io::Error::other)?;
+
+ Ok(())
+}
+
+pub fn timestamped_path(prefix: &str) -> PathBuf {
+ let millis = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0);
+ PathBuf::from("screenshots").join(format!("{prefix}_{millis}.png"))
+}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index ff2d0e4..4c5afed 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -1,4 +1,5 @@
mod action;
+pub mod capture;
mod clear;
mod helpers;
mod pipeline;
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index eb460a8..104c68d 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -1,3 +1,4 @@
+use backend_wgpu::capture::CaptureRequest;
use clap::Parser;
use std::sync::Arc;
use winit::application::ApplicationHandler;
@@ -52,7 +53,9 @@ impl ApplicationHandler for App {
let size = window.inner_size();
let surface_caps = surface.get_capabilities(&init.adapter);
let surface_config = wgpu::SurfaceConfiguration {
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC,
format: init.surface_format,
width: size.width.max(1),
height: size.height.max(1),
@@ -91,10 +94,22 @@ impl ApplicationHandler for App {
state.resize(size.width, size.height);
}
}
- WindowEvent::KeyboardInput { event, .. } if !egui_consumed => {
+ WindowEvent::KeyboardInput { event, .. } => {
let pressed = event.state.is_pressed();
if let PhysicalKey::Code(key) = event.physical_key {
- update_pad(self.emulator.primary_controller_mut(), key, pressed);
+ if pressed && !event.repeat {
+ if let Some(state) = &mut self.state {
+ match key {
+ KeyCode::F11 => state.request_screenshot(CaptureRequest::FullWindow),
+ KeyCode::F12 => state.request_screenshot(CaptureRequest::GameOnly),
+ _ => {}
+ }
+ }
+ }
+
+ if !egui_consumed {
+ update_pad(self.emulator.primary_controller_mut(), key, pressed);
+ }
}
}
WindowEvent::RedrawRequested => {
diff --git a/crates/debugger/src/render.rs b/crates/debugger/src/render.rs
index 7b7a950..aeb9e8f 100644
--- a/crates/debugger/src/render.rs
+++ b/crates/debugger/src/render.rs
@@ -1,3 +1,4 @@
+use backend_wgpu::capture::{self, CaptureRequest, ScreenshotControl};
use dbglib::EmulatorState;
use egui::ViewportId;
use gecko::gamecube::GameCube;
@@ -15,6 +16,7 @@ pub struct RenderState {
pub egui_ctx: egui::Context,
pub egui_renderer: egui_wgpu::Renderer,
pub egui_winit: egui_winit::State,
+ screenshots: ScreenshotControl,
}
impl RenderState {
@@ -55,9 +57,14 @@ impl RenderState {
egui_ctx,
egui_renderer,
egui_winit,
+ screenshots: ScreenshotControl::new(),
}
}
+ pub fn request_screenshot(&mut self, req: CaptureRequest) {
+ self.screenshots.request(req);
+ }
+
pub fn resize(&mut self, width: u32, height: u32) {
if width == 0 || height == 0 {
return;
@@ -107,10 +114,20 @@ impl RenderState {
}
};
let view = frame.texture.create_view(&Default::default());
+ let pending_capture = self.screenshots.take_pending();
// Blit the latest XFB output from the renderer worker to the swapchain.
self.renderer.blit(&self.queue, &view);
+ // Capture the game-only screen before the egui overlay is drawn. Reads
+ // the swapchain instead of the XFB directly so the blit's fullscreen
+ // sample resolves any partial-update state in the XFB accumulator.
+ if let CaptureRequest::GameOnly = pending_capture
+ && let Some(cap) = capture::capture_texture(&self.device, &self.queue, &frame.texture)
+ {
+ capture::save_png_async(capture::timestamped_path("game"), cap, true);
+ }
+
let cpu = &emulator.cpu;
let mmio = &emulator.mmio;
let gx = &emulator.gx;
@@ -334,6 +351,12 @@ impl RenderState {
self.egui_renderer.free_texture(&id);
}
+ if let CaptureRequest::FullWindow = pending_capture
+ && let Some(cap) = capture::capture_texture(&self.device, &self.queue, &frame.texture)
+ {
+ capture::save_png_async(capture::timestamped_path("full"), cap, true);
+ }
+
frame.present();
}
}
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index 3031adb..dad1d6f 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -1,18 +1,16 @@
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::time::Instant;
-
+use backend_wgpu::capture::{self, CaptureRequest, ScreenshotControl};
use crossbeam_channel::Receiver;
use egui::ViewportId;
use gecko::flipper::si::pad::PadStatus;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
-use winit::keyboard::PhysicalKey;
+use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
-
use crate::thread::FrameMessage;
-use crate::update_pad;
pub struct State {
surface: wgpu::Surface<'static>,
@@ -28,6 +26,7 @@ pub struct State {
start_time: Instant,
last_frame: Instant,
last_native_hz: f64,
+ screenshots: ScreenshotControl,
}
impl State {
@@ -57,6 +56,7 @@ impl State {
start_time: Instant::now(),
last_frame: Instant::now(),
last_native_hz: 60.0,
+ screenshots: ScreenshotControl::new(),
}
}
@@ -97,10 +97,20 @@ impl State {
}
};
let view = frame.texture.create_view(&Default::default());
+ let pending_capture = self.screenshots.take_pending();
// Blit the latest XFB output from the renderer worker to the swapchain.
self.renderer.blit(&self.queue, &view);
+ // Capture the game-only screen before the egui overlay is drawn. Reads
+ // the swapchain instead of the XFB directly so the blit's fullscreen
+ // sample resolves any partial-update state in the XFB accumulator.
+ if let CaptureRequest::GameOnly = pending_capture
+ && let Some(cap) = capture::capture_texture(&self.device, &self.queue, &frame.texture)
+ {
+ capture::save_png_async(capture::timestamped_path("game"), cap, true);
+ }
+
// egui overlay
let raw_input = self.egui_winit.take_egui_input(window);
let fps_points: Vec<[f64; 2]> = self.fps_history.iter().copied().collect();
@@ -179,6 +189,12 @@ impl State {
self.egui_renderer.free_texture(&id);
}
+ if let CaptureRequest::FullWindow = pending_capture
+ && let Some(cap) = capture::capture_texture(&self.device, &self.queue, &frame.texture)
+ {
+ capture::save_png_async(capture::timestamped_path("full"), cap, true);
+ }
+
frame.present();
}
}
@@ -218,7 +234,9 @@ impl ApplicationHandler for App {
let size = window.inner_size();
let surface_caps = surface.get_capabilities(&init.adapter);
let surface_config = wgpu::SurfaceConfiguration {
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::COPY_SRC,
format: init.surface_format,
width: size.width.max(1),
height: size.height.max(1),
@@ -258,8 +276,17 @@ impl ApplicationHandler for App {
WindowEvent::KeyboardInput { event, .. } => {
let pressed = event.state.is_pressed();
if let PhysicalKey::Code(key) = event.physical_key {
+ if pressed && !event.repeat {
+ if let Some(state) = &mut self.state {
+ match key {
+ KeyCode::F11 => state.screenshots.request(CaptureRequest::FullWindow),
+ KeyCode::F12 => state.screenshots.request(CaptureRequest::GameOnly),
+ _ => {}
+ }
+ }
+ }
let mut pad = self.input.lock().unwrap();
- update_pad(&mut pad, key, pressed);
+ crate::update_pad(&mut pad, key, pressed);
}
}
WindowEvent::RedrawRequested => {
diff --git a/images/debugger.png b/images/debugger.png
index 812ad8e..363620d 100644
Binary files a/images/debugger.png and b/images/debugger.png differ
diff --git a/images/luigi.png b/images/luigi.png
new file mode 100644
index 0000000..d3b2b7e
Binary files /dev/null and b/images/luigi.png differ
diff --git a/images/re4.png b/images/re4.png
new file mode 100644
index 0000000..42229af
Binary files /dev/null and b/images/re4.png differ
diff --git a/images/sunshine.png b/images/sunshine.png
new file mode 100644
index 0000000..0313236
Binary files /dev/null and b/images/sunshine.png differ
diff --git a/images/wario.png b/images/wario.png
index 44da0b6..8d18ff9 100644
Binary files a/images/wario.png and b/images/wario.png differ
diff --git a/images/windwaker.png b/images/windwaker.png
new file mode 100644
index 0000000..fd762ec
Binary files /dev/null and b/images/windwaker.png differ