A GameCube/Wii emulator and debugger written in Rust.
get rid of backend threading
Laylefbd73adf7900
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex 09c37c3..3e0a263 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -355,12 +355,6 @@ impl GxRenderer {GxAction::PresentXfb { width, height, parts } => {self.flush_pending_draws(device, queue);self.execute_present_xfb(device, queue, *width, *height, parts);- self.drain_pending_writebacks(device, queue);- }-- GxAction::FlushEfbWritebacks => {- self.flush_pending_draws(device, queue);- self.drain_pending_writebacks(device, queue);}GxAction::CopyEfbToTexture {diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 5acff5e..6a94d1a 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -17,7 +17,7 @@ use gecko::flipper::gx::draw::Primitive;use gecko::flipper::gx::draw::{Scissor, TextureFormat, Viewport};use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, MagFilter, MinFilter, WrapMode, ZMode};-use gecko::host::{EfbWriteback, TextureKey};+use gecko::host::TextureKey;use glam::Mat4;use pipeline::FullPipelineKey;use rustc_hash::FxHashMap;@@ -211,7 +211,6 @@ pub struct GxRenderer {pub(crate) efb_depth_resolve_uniform_write_pending: bool,pub(crate) efb_readback_staging_pool: FxHashMap<u64, Vec<wgpu::Buffer>>,pub(crate) pending_writebacks: Vec<PendingWriteback>,- pub(crate) efb_writeback_tx: Option<crossbeam_channel::Sender<EfbWriteback>>,}pub(crate) struct PendingWriteback {@@ -226,7 +225,6 @@ pub(crate) struct PendingWriteback {pub stride: u32,pub swap_bgra: bool,pub box_filter_downsample: bool,- pub label: &'static str,}impl GxRenderer {@@ -732,19 +730,12 @@ impl GxRenderer {efb_readback_staging_pool: FxHashMap::default(),pending_writebacks: Vec::new(),- efb_writeback_tx: None,efb_depth_writeback_pipeline,efb_depth_writeback_target: None,}}- /// Install the sender used to ship encoded EFB-to-texture bytes back- /// to the emulator thread. Called by `sink::Renderer` during setup.- pub fn set_efb_writeback_tx(&mut self, tx: crossbeam_channel::Sender<EfbWriteback>) {- self.efb_writeback_tx = Some(tx);- }-pub(crate) fn submit_pending(&mut self, queue: &wgpu::Queue) {if self.pending_command_buffers.is_empty() {return;diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex b94ebc8..72d4f5e 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -1,7 +1,7 @@use crate::{GpuVertex, GxRenderer, PendingWriteback, align_up};use gecko::common::Address;use gecko::flipper::gx::texture::{self, CopyFormat};-use gecko::host::{EfbWriteback, XfbPart};+use gecko::host::XfbPart;#[repr(C)]#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]@@ -691,7 +691,6 @@ impl GxRenderer {stride,swap_bgra,box_filter_downsample: mipmap,- label: "efb_to_texture",});}@@ -837,7 +836,6 @@ impl GxRenderer {stride,swap_bgra: false,box_filter_downsample: false,- label: "efb_depth_writeback",});}@@ -867,7 +865,12 @@ impl GxRenderer {}}- pub(crate) fn drain_pending_writebacks(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {+ pub(crate) fn drain_pending_writebacks(+ &mut self,+ device: &wgpu::Device,+ queue: &wgpu::Queue,+ ram: &mut gecko::mmio::RamViewMut<'_>,+ ) {if self.pending_writebacks.is_empty() {return;}@@ -936,17 +939,7 @@ impl GxRenderer {let row_count = texture::encoded_row_count(encode_h, w.copy_format);let dest_stride_bytes = w.stride as usize;- if let Some(tx) = &self.efb_writeback_tx {- if let Err(err) = tx.try_send(EfbWriteback {- dest_addr: w.dest_addr,- bytes: encoded,- row_bytes,- row_count,- dest_stride_bytes,- }) {- tracing::warn!(?err, label = w.label, "writeback channel send failed");- }- }+ texture::write_strided_copy_to_ram(ram, w.dest_addr, &encoded, row_bytes, row_count, dest_stride_bytes);self.return_readback_staging(w.staging, w.staging_capacity);}diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex f11ecd6..7bff815 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -14,22 +14,16 @@ macro_rules! instrument_channel {};}-use gecko::host::{DrawData, EfbWriteback, GxAction, RenderSink};-use std::sync::atomic::{AtomicU64, Ordering};+use gecko::host::{DrawData, GxAction, RenderSink};use std::sync::{Arc, Mutex, OnceLock};-#[cfg(feature = "renderdoc-capture")]-use std::time::Duration;use std::time::Instant;pub type FrameReadyCallback = Box<dyn Fn(Instant) + Send + Sync>;-const CHANNEL_CAPACITY: usize = 65536;const RECYCLE_CAPACITY: usize = 8192;-const BATCH_SIZE: usize = 256;-const BATCH_RECYCLE_CAPACITY: usize = 64;-/// Holds the XFB output texture view that the worker updates and the main-/// thread reads for blitting.+/// Holds the XFB output texture view that the emu thread updates and the+/// windowing thread reads for blitting.pub struct Shared {pub output: Mutex<wgpu::TextureView>,}@@ -43,175 +37,84 @@ pub enum TargetAspect {Ratio(f32),}-enum WorkerMsg {- ActionBatch(Vec<GxAction>),- Shutdown,- #[cfg(feature = "renderdoc-capture")]- BeginEmulatedFrame {- ack: Sender<()>,- },- #[cfg(feature = "renderdoc-capture")]- EndEmulatedFrame,- #[cfg(feature = "renderdoc-capture")]- CaptureNextEmulatedFrame,- #[cfg(feature = "renderdoc-capture")]- StartFrameCapture,- #[cfg(feature = "renderdoc-capture")]- EndFrameCapture,- #[cfg(feature = "renderdoc-capture")]- TriggerCapture,-}--struct Recyclers {- boxes: Sender<Box<DrawData>>,- batches: Sender<Vec<GxAction>>,-}--fn worker(- mut gx: GxRenderer,+pub struct InlineSink {+ gx: GxRenderer,device: wgpu::Device,queue: wgpu::Queue,shared: Arc<Shared>,- rx: Receiver<WorkerMsg>,- recyclers: Recyclers,frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,-) {- #[cfg(feature = "renderdoc-capture")]- let mut renderdoc = crate::renderdoc_capture::RenderDocCapture::new();-- while let Ok(msg) = rx.recv() {- let mut batch = match msg {- WorkerMsg::ActionBatch(batch) => batch,- WorkerMsg::Shutdown => break,- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::BeginEmulatedFrame { ack } => {- renderdoc.begin_emulated_frame();- submit_debug_marker(&device, &queue, "Emulated Frame Begin", "GX FIFO execution begins");- let _ = ack.send(());- continue;- }- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::EndEmulatedFrame => {- submit_debug_marker(&device, &queue, "Emulated Frame End", "GX FIFO execution ends");- renderdoc.end_emulated_frame();- continue;- }- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::CaptureNextEmulatedFrame => {- renderdoc.request_next_emulated_frame();- continue;- }- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::StartFrameCapture => {- renderdoc.start_frame_capture();- continue;- }- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::EndFrameCapture => {- renderdoc.end_frame_capture();- continue;- }- #[cfg(feature = "renderdoc-capture")]- WorkerMsg::TriggerCapture => {- renderdoc.trigger_capture();- continue;- }- };-- for action in batch.drain(..) {- gx.process_action(&device, &queue, &action);+ boxes_tx: Sender<Box<DrawData>>,+}- match action {- GxAction::PresentXfb { .. } => {- let view = gx.xfb_view.clone();- *shared.output.lock().unwrap() = view;- if let Some(cb) = frame_ready_cb.get() {- cb(Instant::now());- }- }- GxAction::Draw(mut boxed) => {- boxed.vertices.clear();- let _ = recyclers.boxes.try_send(boxed);+impl RenderSink for InlineSink {+ fn exec(&mut self, action: GxAction) {+ self.gx.process_action(&self.device, &self.queue, &action);++ match action {+ GxAction::PresentXfb { .. } => {+ let view = self.gx.xfb_view.clone();+ *self.shared.output.lock().unwrap() = view;+ if let Some(cb) = self.frame_ready_cb.get() {+ cb(Instant::now());}- _ => {}}+ GxAction::Draw(mut boxed) => {+ boxed.vertices.clear();+ let _ = self.boxes_tx.try_send(boxed);+ }+ _ => {}}-- // Hand the drained Vec back to the producer for capacity reuse.- // On full or closed channel, drop and the producer will allocate- // a fresh batch on its next flush.- let _ = recyclers.batches.try_send(batch);- }-- gx.submit_pending(&queue);-- match gx.save_shader_cache() {- Ok(n) => tracing::info!(num_variants = n, "saved shader cache"),- Err(err) => tracing::warn!(?err, "failed to save shader cache"),}- match gx.save_pipeline_cache() {- Ok(n) => tracing::info!(num_pipelines = n, "saved pipeline cache"),- Err(err) => tracing::warn!(?err, "failed to save pipeline cache"),+ fn flush_efb_copies(&mut self, ram: &mut gecko::mmio::RamViewMut<'_>) {+ self.gx.drain_pending_writebacks(&self.device, &self.queue, ram);}}-#[cfg(feature = "renderdoc-capture")]-fn submit_debug_marker(device: &wgpu::Device, queue: &wgpu::Queue, group: &'static str, marker: &'static str) {- let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some(group) });- encoder.push_debug_group(group);- encoder.insert_debug_marker(marker);- encoder.pop_debug_group();- queue.submit([encoder.finish()]);+impl Drop for InlineSink {+ fn drop(&mut self) {+ self.gx.submit_pending(&self.queue);+ match self.gx.save_shader_cache() {+ Ok(n) => tracing::info!(num_variants = n, "saved shader cache"),+ Err(err) => tracing::warn!(?err, "failed to save shader cache"),+ }+ match self.gx.save_pipeline_cache() {+ Ok(n) => tracing::info!(num_pipelines = n, "saved pipeline cache"),+ Err(err) => tracing::warn!(?err, "failed to save pipeline cache"),+ }+ }}#[derive(Clone)]pub struct Renderer {- tx: Sender<WorkerMsg>,shared: Arc<Shared>,device: wgpu::Device,blit_pipeline: wgpu::RenderPipeline,blit_bind_group_layout: wgpu::BindGroupLayout,blit_sampler: wgpu::Sampler,target_aspect: TargetAspect,- actions_sent: Arc<AtomicU64>,frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,- /// Receiver end of the EFB-to-texture writeback channel. Taken by the- /// emulator setup code (via [`Renderer::take_writeback_rx`]) and- /// installed into `GraphicsProcessor::efb_writeback_rx`. Wrapped in- /// `Arc<Mutex<Option<_>>>` so `Renderer` stays `Clone`.- writeback_rx: Arc<Mutex<Option<Receiver<EfbWriteback>>>>,recycle_rx: Arc<Mutex<Option<Receiver<Box<DrawData>>>>>,- batch_recycle_rx: Arc<Mutex<Option<Receiver<Vec<GxAction>>>>>,+ #[cfg(feature = "renderdoc-capture")]+ renderdoc: Arc<Mutex<crate::renderdoc_capture::RenderDocCapture>>,}impl Renderer {- /// Create the renderer, spawning the worker thread. The caller must- /// provide a wgpu device and queue.pub fn new(device: wgpu::Device,queue: wgpu::Queue,surface_format: wgpu::TextureFormat,target_aspect: TargetAspect,- ) -> (Self, RendererWorker) {+ ) -> (Self, InlineSink) {let mut gx = GxRenderer::new(&device, &queue, surface_format);gx.prewarm_pipeline_cache(&device);- // Writeback channel: GxRenderer sends encoded EFB-to-texture bytes,- // GraphicsProcessor consumes them synchronously on the emu thread.- let writeback_rx = {- let (writeback_tx, writeback_rx) =- instrument_channel!(bounded::<EfbWriteback>(CHANNEL_CAPACITY), "efb_writeback");- gx.set_efb_writeback_tx(writeback_tx);- writeback_rx- };-// Initial shared output: the XFB view (black until first PresentXfb).let shared = Arc::new(Shared {output: Mutex::new(gx.xfb_view.clone()),});- // Build the blit pipeline on the main-thread side.+ // Build the blit pipeline.let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {label: Some("efb_blit_shader"),source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_blit.wgsl").into()),@@ -277,108 +180,97 @@ impl Renderer {..Default::default()});- let (tx, rx) = instrument_channel!(bounded::<WorkerMsg>(CHANNEL_CAPACITY), "gx_actions");let (boxes_tx, recycle_rx) =instrument_channel!(bounded::<Box<DrawData>>(RECYCLE_CAPACITY), "draw_data_recycle");- let (batches_tx, batch_recycle_rx) =- instrument_channel!(bounded::<Vec<GxAction>>(BATCH_RECYCLE_CAPACITY), "batch_recycle");- let recyclers = Recyclers {- boxes: boxes_tx,- batches: batches_tx,- };let frame_ready_cb: Arc<OnceLock<FrameReadyCallback>> = Arc::new(OnceLock::new());- let worker_shared = shared.clone();- let worker_device = device.clone();- let worker_queue = queue.clone();- let worker_cb = frame_ready_cb.clone();- let join = std::thread::Builder::new()- .name("gx-renderer".into())- .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx, recyclers, worker_cb))- .expect("failed to spawn renderer worker");+ let sink = InlineSink {+ gx,+ device: device.clone(),+ queue,+ shared: shared.clone(),+ frame_ready_cb: frame_ready_cb.clone(),+ boxes_tx,+ };let renderer = Renderer {- tx: tx.clone(),shared,device,blit_pipeline,blit_bind_group_layout,blit_sampler,target_aspect,- actions_sent: Arc::new(AtomicU64::new(0)),frame_ready_cb,- writeback_rx: Arc::new(Mutex::new(Some(writeback_rx))),recycle_rx: Arc::new(Mutex::new(Some(recycle_rx))),- batch_recycle_rx: Arc::new(Mutex::new(Some(batch_recycle_rx))),+ #[cfg(feature = "renderdoc-capture")]+ renderdoc: Arc::new(Mutex::new(crate::renderdoc_capture::RenderDocCapture::new())),};- (renderer, RendererWorker { tx, join })- }-- pub fn set_frame_ready_callback<F>(&self, cb: F)- where- F: Fn(Instant) + Send + Sync + 'static,- {- let _ = self.frame_ready_cb.set(Box::new(cb));- }-- /// Take the writeback receiver once. Returns `Some` on the first call,- /// `None` thereafter. The caller installs it into- /// `GraphicsProcessor::efb_writeback_rx`.- pub fn take_writeback_rx(&self) -> Option<Receiver<EfbWriteback>> {- self.writeback_rx.lock().ok()?.take()- }-- pub fn take_recycle_rx(&self) -> Option<Receiver<Box<DrawData>>> {- self.recycle_rx.lock().ok()?.take()- }-- pub fn target_aspect(&self) -> TargetAspect {- self.target_aspect+ (renderer, sink)}#[cfg(feature = "renderdoc-capture")]pub fn begin_renderdoc_emulated_frame(&self) {- let (ack_tx, ack_rx) = bounded::<()>(0);- if self.tx.send(WorkerMsg::BeginEmulatedFrame { ack: ack_tx }).is_err() {- tracing::warn!("failed to send RenderDoc frame-begin marker to renderer worker");- return;- }-- if ack_rx.recv_timeout(Duration::from_secs(1)).is_err() {- tracing::warn!("timed out waiting for renderer worker to begin RenderDoc frame");+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.begin_emulated_frame();}}#[cfg(feature = "renderdoc-capture")]pub fn end_renderdoc_emulated_frame(&self) {- let _ = self.tx.send(WorkerMsg::EndEmulatedFrame);+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.end_emulated_frame();+ }}#[cfg(feature = "renderdoc-capture")]pub fn capture_next_renderdoc_emulated_frame(&self) {- let _ = self.tx.send(WorkerMsg::CaptureNextEmulatedFrame);+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.request_next_emulated_frame();+ }}#[cfg(feature = "renderdoc-capture")]pub fn start_renderdoc_frame_capture(&self) {- let _ = self.tx.send(WorkerMsg::StartFrameCapture);+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.start_frame_capture();+ }}#[cfg(feature = "renderdoc-capture")]pub fn end_renderdoc_frame_capture(&self) {- let _ = self.tx.send(WorkerMsg::EndFrameCapture);+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.end_frame_capture();+ }}#[cfg(feature = "renderdoc-capture")]pub fn trigger_renderdoc_capture(&self) {- let _ = self.tx.send(WorkerMsg::TriggerCapture);+ if let Ok(mut rd) = self.renderdoc.lock() {+ rd.trigger_capture();+ }+ }++ pub fn set_frame_ready_callback<F>(&self, cb: F)+ where+ F: Fn(Instant) + Send + Sync + 'static,+ {+ let _ = self.frame_ready_cb.set(Box::new(cb));+ }++ pub fn take_recycle_rx(&self) -> Option<Receiver<Box<DrawData>>> {+ self.recycle_rx.lock().ok()?.take()+ }++ pub fn target_aspect(&self) -> TargetAspect {+ self.target_aspect}/// Blit the latest XFB output to the given render target. `target_size`/// is the destination view's pixel size; used to letterbox/pillarbox the- /// XFB to `self.target_aspect`. Called by the main thread on each redraw.+ /// XFB to `self.target_aspect`. Called by the windowing thread on each+ /// redraw.pub fn blit(&self, queue: &wgpu::Queue, target: &wgpu::TextureView, target_size: (u32, u32)) {let output = self.shared.output.lock().unwrap();let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {@@ -430,99 +322,6 @@ impl Renderer {}}-impl Renderer {- /// Build a producer-side sink that batches `GxAction`s before sending- /// them to the worker. The first call returns a sink with the- /// recycler receiver installed; subsequent calls return a sink that- /// allocates a fresh `Vec` on each flush. Mirrors the `take_*_rx`- /// pattern so the renderer handle remains usable for blitting and- /// renderdoc markers afterward.- pub fn take_batching_sink(&self) -> BatchingSink {- let batch_recycle_rx = self.batch_recycle_rx.lock().ok().and_then(|mut g| g.take());- BatchingSink {- tx: self.tx.clone(),- actions_sent: self.actions_sent.clone(),- channel_capacity: CHANNEL_CAPACITY,- batch: Vec::with_capacity(BATCH_SIZE),- batch_recycle_rx,- }- }-}--pub struct BatchingSink {- tx: Sender<WorkerMsg>,- actions_sent: Arc<AtomicU64>,- channel_capacity: usize,- batch: Vec<GxAction>,- batch_recycle_rx: Option<Receiver<Vec<GxAction>>>,-}--impl BatchingSink {- fn flush(&mut self) {- if self.batch.is_empty() {- return;- }-- let next = self- .batch_recycle_rx- .as_ref()- .and_then(|rx| rx.try_recv().ok())- .unwrap_or_else(|| Vec::with_capacity(BATCH_SIZE));- let to_send = std::mem::replace(&mut self.batch, next);- let len = to_send.len() as u64;-- if self.tx.send(WorkerMsg::ActionBatch(to_send)).is_ok() {- self.actions_sent.fetch_add(len, Ordering::Relaxed);- }- }-}--impl Drop for BatchingSink {- fn drop(&mut self) {- self.flush();- }-}--pub struct RendererWorker {- tx: Sender<WorkerMsg>,- join: std::thread::JoinHandle<()>,-}--impl RendererWorker {- pub fn shutdown_and_join(self) -> std::thread::Result<()> {- let _ = self.tx.send(WorkerMsg::Shutdown);- drop(self.tx);- self.join.join()- }-}--impl RenderSink for BatchingSink {- fn exec(&mut self, action: GxAction) {- let force_flush = matches!(- action,- GxAction::PresentXfb { .. } | GxAction::CopyEfbToTexture { .. } | GxAction::FlushEfbWritebacks- );-- self.batch.push(action);-- if force_flush || self.batch.len() >= BATCH_SIZE {- self.flush();- }- }-- fn actions_sent_total(&self) -> u64 {- self.actions_sent.load(Ordering::Relaxed)- }-- fn channel_len(&self) -> usize {- self.tx.len()- }-- fn channel_capacity(&self) -> Option<usize> {- Some(self.channel_capacity)- }-}-/// Snap a requested window size to the largest rectangle with/// `target_aspect` that fits inside it. For Stretch this returns the input/// unchanged. The window code calls this on resize so the OS window itselfdiff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex 64f48c2..3472408 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -57,13 +57,6 @@ impl EmulatorVariant {}}- fn install_efb_writeback(&mut self, rx: Option<crossbeam_channel::Receiver<gecko::host::EfbWriteback>>) {- match self {- Self::Gc(e) => e.gx.efb_writeback_rx = rx,- Self::Wii(e) => e.gx.efb_writeback_rx = rx,- }- }-fn install_recycle_rx(&mut self, rx: Option<crossbeam_channel::Receiver<Box<gecko::host::DrawData>>>) {match self {Self::Gc(e) => e.gx.draw_box_recycle_rx = rx,@@ -525,13 +518,11 @@ fn main() {let surface_format = wgpu::TextureFormat::Bgra8Unorm;let target_aspect = resolve_aspect(&args.aspect, matches!(emulator, EmulatorVariant::Wii(_)));- let (renderer, renderer_worker) =+ let (renderer, sink) =backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);emulator.install_recycle_rx(renderer.take_recycle_rx());- emulator.install_render_sink(Box::new(renderer.take_batching_sink()));-- emulator.install_efb_writeback(renderer.take_writeback_rx());+ emulator.install_render_sink(Box::new(sink));let ui = DebuggerUi {symbols,@@ -590,10 +581,6 @@ fn main() {app.emulator.install_audio_sink(Box::new(EmptyAudioSink));- if let Err(err) = renderer_worker.shutdown_and_join() {- eprintln!("gx-renderer thread panicked: {err:?}");- }-std::mem::forget(app);}diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex a1accba..cc88bd6 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -17,7 +17,7 @@ use crate::flipper::gx::draw::Matrix4;use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode,};-use crate::host::{DrawData, DrawVertex, EfbWriteback, GxAction, LightData, TextureKey, XfbPart};+use crate::host::{DrawData, DrawVertex, GxAction, LightData, TextureKey, XfbPart};use crate::system::{System, SystemId};use rustc_hash::FxHashMap;@@ -95,10 +95,6 @@ pub struct GraphicsProcessor {// sends. Keyed by the same `TextureKey` sent to the renderer in// [`GxAction::LoadTexture`].pub texture_hashes: FxHashMap<TextureKey, u64>,- // Receiver for encoded EFB-to-texture bytes coming back from the- // renderer worker.- pub efb_writeback_rx: Option<crossbeam_channel::Receiver<EfbWriteback>>,- pub pending_efb_writebacks: u32,pub draw_box_pool: Vec<Box<DrawData>>,pub draw_box_recycle_rx: Option<crossbeam_channel::Receiver<Box<DrawData>>>,}@@ -183,8 +179,6 @@ impl GraphicsProcessor {#[cfg(feature = "gx-stats")]stats: GxStats::default(),texture_hashes: FxHashMap::default(),- efb_writeback_rx: None,- pending_efb_writebacks: 0,draw_box_pool: {const POOL_PREALLOC: usize = 1024;let mut v: Vec<Box<crate::host::DrawData>> = Vec::with_capacity(POOL_PREALLOC);diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex 8325406..78b3a49 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -1,25 +1,9 @@use super::constants::*;use super::regs::*;use super::{GraphicsProcessor, draw, texture};-use crate::host::{EfbWriteback, GxAction, RenderSink, TextureKey};+use crate::host::{GxAction, RenderSink, TextureKey};use crate::mmio::{RamView, RamViewMut};-const EFB_WRITEBACK_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);--fn efb_copy_will_writeback(src_x: u32, src_y: u32, src_w: u32, src_h: u32, copy_format: u8, depth: bool) -> bool {- let w = src_w.min(EFB_WIDTH.saturating_sub(src_x));- let h = src_h.min(EFB_HEIGHT.saturating_sub(src_y));- if w == 0 || h == 0 {- return false;- }-- if depth {- texture::CopyFormat::from_u8_depth(copy_format).is_some()- } else {- texture::CopyFormat::from_u8_color(copy_format).is_some()- }-}-impl GraphicsProcessor {#[cfg_attr(feature = "hotpath", hotpath::measure)]pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, ram: &mut RamViewMut<'_>, data: &[u8]) {@@ -202,14 +186,14 @@ impl GraphicsProcessor {// PE finishif idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {self.raise_interrupt = true;- self.wait_for_efb_writebacks(renderer, ram);+ renderer.flush_efb_copies(ram);}// PE token (0x47): store token value onlyif idx == BP_PE_TOKEN {self.pending_token = (val & 0xFFFF) as u16;self.token_dirty = true;- self.wait_for_efb_writebacks(renderer, ram);+ renderer.flush_efb_copies(ram);}// PE token interrupt (0x48): store token value + raise interrupt@@ -218,7 +202,7 @@ impl GraphicsProcessor {self.pending_token = (val & 0xFFFF) as u16;self.token_dirty = true;self.raise_token_interrupt = true;- self.wait_for_efb_writebacks(renderer, ram);+ renderer.flush_efb_copies(ram);}// Scissor registers (BP 0x20 = TL, 0x21 = BR, 0x59 = OFFSET).@@ -237,7 +221,7 @@ impl GraphicsProcessor {// EFB copy trigger (BP 0x52)if idx == BP_PE_COPY_CMD {- self.efb_copy(renderer, ram, val);+ self.efb_copy(renderer, val);}}@@ -438,7 +422,7 @@ impl GraphicsProcessor {}#[cfg_attr(feature = "hotpath", hotpath::measure)]- fn efb_copy(&mut self, renderer: &mut dyn RenderSink, ram: &mut RamViewMut<'_>, trigger: u32) {+ fn efb_copy(&mut self, renderer: &mut dyn RenderSink, trigger: u32) {let src = EfbCopySrc::from_raw(self.bp_regs[BP_PE_COPY_SRC]);let dims = EfbCopyDims::from_raw(self.bp_regs[BP_PE_COPY_DIMS]);let src_x = src.left() as u32;@@ -528,9 +512,6 @@ impl GraphicsProcessor {let z_update = self.cur_zmode.update_enable();let depth_copy = self.cur_pe_control.pixel_format().is_depth_only();- if efb_copy_will_writeback(src_x, src_y, src_w, src_h, copy_format, depth_copy) {- self.pending_efb_writebacks += 1;- }renderer.exec(GxAction::CopyEfbToTexture {dest_addr,src_x,@@ -555,62 +536,9 @@ impl GraphicsProcessor {// next snapshot at this address re decodes once the deferred// RAM writeback lands.self.texture_hashes.retain(|k, _| k.ram_addr != dest_addr);-- self.drain_efb_writebacks(ram);- }- }-- #[cfg_attr(feature = "hotpath", hotpath::measure)]- pub fn drain_efb_writebacks(&mut self, ram: &mut RamViewMut<'_>) {- let Some(rx) = self.efb_writeback_rx.as_ref() else {- return;- };- while let Ok(wb) = rx.try_recv() {- Self::apply_efb_writeback(&mut self.pending_efb_writebacks, ram, wb);}}- #[cfg_attr(feature = "hotpath", hotpath::measure)]- pub fn wait_for_efb_writebacks(&mut self, renderer: &mut dyn RenderSink, ram: &mut RamViewMut<'_>) {- if self.pending_efb_writebacks == 0 {- return;- }- renderer.exec(GxAction::FlushEfbWritebacks);-- let Some(rx) = self.efb_writeback_rx.as_ref() else {- self.pending_efb_writebacks = 0;- return;- };-- while self.pending_efb_writebacks > 0 {- match rx.recv_timeout(EFB_WRITEBACK_WAIT_TIMEOUT) {- Ok(wb) => Self::apply_efb_writeback(&mut self.pending_efb_writebacks, ram, wb),- Err(err) => {- tracing::warn!(- ?err,- outstanding = self.pending_efb_writebacks,- "efb writeback wait timed out"- );- self.pending_efb_writebacks = 0;- return;- }- }- }- }-- #[inline]- fn apply_efb_writeback(pending: &mut u32, ram: &mut RamViewMut<'_>, wb: EfbWriteback) {- texture::write_strided_copy_to_ram(- ram,- wb.dest_addr,- &wb.bytes,- wb.row_bytes,- wb.row_count,- wb.dest_stride_bytes,- );- *pending = pending.saturating_sub(1);- }-fn recompute_scissor(&mut self) {let tl = SuScisRect::from_raw(self.bp_regs[BP_SU_SCIS_TL]);let br = SuScisRect::from_raw(self.bp_regs[BP_SU_SCIS_BR]);diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex df6a65c..031f4dc 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -98,9 +98,6 @@ pub enum GxAction {alpha_supported: bool,},- /// I onyl really added this cause of fuckass GC games acting up (Wario World).- FlushEfbWritebacks,-/// Composite all XFB copies from this frame into the output framebuffer./// Emitted once per vblank by `present_xfb()`. Each [`XfbPart`]/// identifies a copy by `id` and places it at `(offset_x, offset_y)`.@@ -142,18 +139,6 @@ pub enum GxAction {},}-/// Payload the renderer worker ships back when an EFB-to-texture readback-/// completes. The emu thread copies `bytes` into `Mmio::ram` at `dest_addr`-/// at the next safe drain point.-#[derive(Debug)]-pub struct EfbWriteback {- pub dest_addr: Address,- pub bytes: Vec<u8>,- pub row_bytes: usize,- pub row_count: usize,- pub dest_stride_bytes: usize,-}-/// Identifies one tile in a composited XFB frame. The `id` matches the/// `CopyXfb::id` that produced the source texture; `offset_x`/`offset_y`/// are the pixel coordinates in the output framebuffer.@@ -224,23 +209,13 @@ pub struct LightData {pub direction: [f32; 4],}-/// One-way sink for GX actions. The emulator pushes actions here; the-/// renderer consumes them (typically on a separate thread).+/// One-way sink for GX actions. The emulator pushes actions here.pub trait RenderSink: Send {- /// Submit a single action. Implementations should not block unless- /// back-pressure from the renderer requires it.+ /// Submit a single action.fn exec(&mut self, action: GxAction);- fn actions_sent_total(&self) -> u64 {- 0- }-- fn channel_len(&self) -> usize {- 0- }-- fn channel_capacity(&self) -> Option<usize> {- None+ fn flush_efb_copies(&mut self, ram: &mut crate::mmio::RamViewMut<'_>) {+ let _ = ram;}}diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex c083c84..f5fe767 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -349,13 +349,11 @@ fn run<const SYSTEM: SystemId>(let surface_format = wgpu::TextureFormat::Bgra8Unorm;- let (renderer, renderer_worker) =+ let (renderer, sink) =backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);emulator.gx.draw_box_recycle_rx = renderer.take_recycle_rx();- emulator.render_sink = Box::new(renderer.take_batching_sink());-- emulator.gx.efb_writeback_rx = renderer.take_writeback_rx();+ emulator.render_sink = Box::new(sink);let audio_stream = install_audio_sink(args, &mut emulator);@@ -454,10 +452,6 @@ fn run<const SYSTEM: SystemId>(tracing::error!(?err, "emu thread panicked");}- if let Err(err) = renderer_worker.shutdown_and_join() {- tracing::error!(?err, "gx-renderer thread panicked");- }-std::mem::forget(app);}