Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

gpu-side efb copy cache

Laylef65189eafd06
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index b0fd5d8..ed49794 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -106,10 +106,23 @@ impl GxRenderer {
},
);
let view = tex.create_view(&Default::default());
+
// Invalidate bind groups that referenced the old texture.
let tid = *id;
self.bind_group_cache
.retain(|key, _| !key.tex_keys.iter().any(|k| *k == Some(tid)));
+
+ // A fresh RAM upload means the game wrote this address
+ // after a prior EFB copy. Return the stale GPU
+ // copy to its pool and let the RAM-decoded entry win.
+ if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&tid) {
+ let old_size = old_tex.size();
+ self.efb_copy_pool
+ .entry((old_size.width, old_size.height))
+ .or_default()
+ .push((old_tex, old_view));
+ }
+
self.texture_cache.insert(*id, (tex, view));
}
GxAction::SetTexture {
@@ -243,13 +256,13 @@ impl GxRenderer {
}
GxAction::CopyEfbToTexture {
- dest_addr: _dest_addr,
+ dest_addr,
src_x,
src_y,
src_w,
src_h,
copy_format: _copy_format,
- mipmap: _mipmap,
+ mipmap,
stride: _stride,
clear,
clear_color,
@@ -258,7 +271,7 @@ impl GxRenderer {
alpha_update,
z_update,
alpha_supported,
- depth_copy: _depth_copy,
+ depth_copy,
} => {
self.flush_pending_draws(device, queue);
@@ -269,15 +282,15 @@ impl GxRenderer {
self.execute_copy_efb_to_texture(
device,
queue,
- *_dest_addr,
+ *dest_addr,
*src_x,
*src_y,
*src_w,
*src_h,
*_copy_format,
- *_mipmap,
+ *mipmap,
*_stride,
- *_depth_copy,
+ *depth_copy,
*clear,
*clear_color,
*clear_z,
@@ -287,10 +300,11 @@ impl GxRenderer {
*alpha_supported,
);
- // Default path: no readback, no encode, no RAM touch. Texture
- // invalidation happens on the emu side via a `texture_hashes`
- // drop. We only need to honor the post-copy clear here.
- #[cfg(not(feature = "efb-writeback"))]
+ // Blit the resolved EFB region into a GPU texture keyed by `dest_addr`.
+ if !*depth_copy {
+ self.cache_efb_copy_color(device, queue, *dest_addr, *src_x, *src_y, *src_w, *src_h, *mipmap);
+ }
+
if *clear {
self.efb_clear.clear_region_masked(
device,
@@ -350,9 +364,12 @@ impl GxRenderer {
for slot in 0..8 {
if let Some(tid) = &bg_key.tex_keys[slot] {
- if let Some((_, view)) = self.texture_cache.get(tid) {
+ // The EFB-copy cache wins over the RAM-decoded
+ // `texture_cache`.
+ if let Some((_, view)) = self.efb_copy_cache.get(tid).or_else(|| self.texture_cache.get(tid)) {
tex_views[slot] = view;
}
+
if let Some(sk) = &bg_key.sampler_keys[slot] {
if let Some(sampler) = self.sampler_cache.get(sk) {
tex_samplers[slot] = sampler;
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 4c5afed..57bbf91 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -108,6 +108,12 @@ pub struct GxRenderer {
pub(crate) efb_needs_clear: bool,
pub(crate) sampler_cache: FxHashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
pub(crate) texture_cache: FxHashMap<Address, (wgpu::Texture, wgpu::TextureView)>,
+ // GPU textures holding EFB copy results, checked before `texture_cache` on every texture bind.
+ pub(crate) efb_copy_cache: FxHashMap<Address, (wgpu::Texture, wgpu::TextureView)>,
+ // Retired EFB-copy textures grouped by size, popped by the next copy to skip reallocating.
+ pub(crate) efb_copy_pool: FxHashMap<(u32, u32), Vec<(wgpu::Texture, wgpu::TextureView)>>,
+ // Blits a sub-rect of `efb_view` into an `Rgba8Unorm` target, reusing xfb_copy's shader and layout.
+ pub(crate) efb_copy_pipeline: wgpu::RenderPipeline,
pub(crate) fallback_view: wgpu::TextureView,
pub(crate) scratch_vertices: Vec<GpuVertex>,
pub(crate) scratch_draws: Vec<(u32, u32)>,
@@ -393,6 +399,7 @@ impl GxRenderer {
},
],
});
+
let xfb_copy_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("xfb_copy_layout"),
bind_group_layouts: &[&xfb_copy_bind_group_layout],
@@ -430,6 +437,41 @@ impl GxRenderer {
multiview_mask: None,
cache: None,
});
+
+ // Same shader and layout as xfb_copy, but writes `Rgba8Unorm` so the output matches `LoadTexture`.
+ let efb_copy_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("efb_copy_pipeline"),
+ layout: Some(&xfb_copy_pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &xfb_copy_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &xfb_copy_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState {
+ count: 1,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ multiview_mask: None,
+ cache: None,
+ });
+
let xfb_copy_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("xfb_copy_sampler"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
@@ -440,6 +482,7 @@ impl GxRenderer {
mipmap_filter: wgpu::MipmapFilterMode::Nearest,
..Default::default()
});
+
let xfb_copy_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("xfb_copy_uniforms"),
size: std::mem::size_of::<render::XfbCopyUniforms>() as u64,
@@ -481,6 +524,9 @@ impl GxRenderer {
m
},
texture_cache: FxHashMap::default(),
+ efb_copy_cache: FxHashMap::default(),
+ efb_copy_pool: FxHashMap::default(),
+ efb_copy_pipeline,
fallback_view,
scratch_vertices: Vec::new(),
scratch_draws: Vec::new(),
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index ebc5aad..033d19a 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,7 +1,6 @@
use crate::{FrameUniforms, GxRenderer};
use crate::{GpuVertex, align_up};
use encase::ShaderType as _;
-#[cfg(feature = "efb-writeback")]
use gecko::common::Address;
#[cfg(feature = "efb-writeback")]
use gecko::flipper::gx::texture;
@@ -252,6 +251,137 @@ impl GxRenderer {
}
}
+ /// Blits the resolved EFB region into a GPU texture keyed by `dest_addr` for later texture binds to sample. Color only.
+ pub(crate) fn cache_efb_copy_color(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ dest_addr: Address,
+ src_x: u32,
+ src_y: u32,
+ src_w: u32,
+ src_h: u32,
+ half: bool,
+ ) {
+ let width = src_w.min(crate::EFB_WIDTH.saturating_sub(src_x));
+ let height = src_h.min(crate::EFB_HEIGHT.saturating_sub(src_y));
+ if width == 0 || height == 0 {
+ tracing::warn!(
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ "efb_copy_cache: zero-area region after clamping, skipping"
+ );
+ return;
+ }
+ let divisor = if half { 2 } else { 1 };
+ let dst_w = (width / divisor).max(1);
+ let dst_h = (height / divisor).max(1);
+
+ // Evict any prior cached copy at this address, returning the
+ // texture to the pool bucket for its own size so it can be
+ // reused by a future copy at the same dimensions.
+ if let Some((old_tex, old_view)) = self.efb_copy_cache.remove(&dest_addr) {
+ let old_size = old_tex.size();
+ self.efb_copy_pool
+ .entry((old_size.width, old_size.height))
+ .or_default()
+ .push((old_tex, old_view));
+ }
+ // Drop bind groups that referenced `dest_addr`. They captured
+ // the old view and would still point at a pooled, stale texture
+ // on next use. This is the same invalidation `LoadTexture` does.
+ self.bind_group_cache
+ .retain(|key, _| !key.tex_keys.contains(&Some(dest_addr)));
+
+ let (tex, view) = self
+ .efb_copy_pool
+ .get_mut(&(dst_w, dst_h))
+ .and_then(Vec::pop)
+ .unwrap_or_else(|| {
+ let label = format!("efb_copy addr={dest_addr:#010x} size={dst_w}x{dst_h}");
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(&label),
+ size: wgpu::Extent3d {
+ width: dst_w,
+ height: dst_h,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ let view = tex.create_view(&Default::default());
+ (tex, view)
+ });
+
+ let uniforms = XfbCopyUniforms {
+ src_rect: [src_x as f32, src_y as f32, width as f32, height as f32],
+ dst_size: [dst_w as f32, dst_h as f32],
+ gamma: 1.0,
+ filter_mode: 0,
+ };
+ queue.write_buffer(&self.xfb_copy_uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("efb_copy_bg"),
+ layout: &self.xfb_copy_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: self.xfb_copy_uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&self.efb_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.xfb_copy_sampler),
+ },
+ ],
+ });
+
+ let group_label = format!(
+ "CopyEfbToTexture addr={dest_addr:#010x} src=({src_x},{src_y} {width}x{height}) dst={dst_w}x{dst_h}"
+ );
+ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
+ label: Some("efb_copy_encoder"),
+ });
+ encoder.push_debug_group(&group_label);
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("efb_copy"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: None,
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_pipeline(&self.efb_copy_pipeline);
+ rpass.set_bind_group(0, &bind_group, &[]);
+ rpass.draw(0..3, 0..1);
+ }
+ encoder.pop_debug_group();
+ queue.submit([encoder.finish()]);
+
+ self.efb_copy_cache.insert(dest_addr, (tex, view));
+ }
+
pub(crate) fn execute_present_xfb(
&mut self,
device: &wgpu::Device,
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index 104c68d..33ca9d2 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -106,7 +106,7 @@ impl ApplicationHandler for App {
}
}
}
-
+
if !egui_consumed {
update_pad(self.emulator.primary_controller_mut(), key, pressed);
}
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 43dde49..c694bd3 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -415,12 +415,8 @@ impl GraphicsProcessor {
depth_copy: self.cur_pe_control.pixel_format().is_depth_only(),
});
- // Default path (feature off): the renderer doesn't do a readback
- // and RAM at `dest_addr` is not modified, so "invalidating" the
- // texture at that address means dropping the hash so the next
- // `TX_SETIMAGE3` forces a fresh re-decode + re-upload. That
- // evicts any stale GPU texture / bind groups tied to the old
- // cache entry.
+ // Writeback overwrites RAM, so drop the hash to force a re-decode. The default path keeps it GPU-side.
+ #[cfg(feature = "efb-writeback")]
self.texture_hashes.remove(&dest_addr);
let _ = ram;
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index dad1d6f..f06d7ef 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -1,16 +1,16 @@
-use std::collections::VecDeque;
-use std::sync::{Arc, Mutex};
-use std::time::Instant;
+use crate::thread::FrameMessage;
use backend_wgpu::capture::{self, CaptureRequest, ScreenshotControl};
use crossbeam_channel::Receiver;
use egui::ViewportId;
use gecko::flipper::si::pad::PadStatus;
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
+use std::time::Instant;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::{KeyCode, PhysicalKey};
use winit::window::{Window, WindowId};
-use crate::thread::FrameMessage;
pub struct State {
surface: wgpu::Surface<'static>,