A GameCube/Wii emulator and debugger written in Rust.
it kinda works?
Layle19b7c4826b87
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex 3e0a263..8c45fcc 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -231,10 +231,9 @@ impl GxRenderer {self.pipeline_cache.insert(full_key, pipeline);}- let first_vertex = self.scratch_vertices.len() as u32;+ let first_vertex = draw.base_vertex;let first_index = self.scratch_indices.len() as u32;- let (vertex_count, index_count) =- triangulate_draw_data(draw, &mut self.scratch_vertices, &mut self.scratch_indices);+ let (vertex_count, index_count) = emit_draw_indices(draw, &mut self.scratch_indices);if vertex_count == 0 {tracing::warn!("draw call produced zero vertices, skipping");return;@@ -606,6 +605,11 @@ impl GxRenderer {}rpass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);++ let mut last_pipeline_ptr: *const wgpu::RenderPipeline = std::ptr::null();+ let mut last_viewport: Option<(f32, f32, f32, f32, f32, f32)> = None;+ let mut last_scissor: Option<(u32, u32, u32, u32)> = None;+for (index, (first_vertex, vertex_count, first_index, index_count)) inself.scratch_draws.iter().copied().enumerate(){@@ -619,7 +623,12 @@ impl GxRenderer {}let full_key = &self.draw_pipeline_keys[index];let pipeline = &self.pipeline_cache[full_key];- rpass.set_pipeline(pipeline);+ let pipeline_ptr = pipeline as *const wgpu::RenderPipeline;+ if pipeline_ptr != last_pipeline_ptr {+ rpass.set_pipeline(pipeline);+ last_pipeline_ptr = pipeline_ptr;+ }+#[cfg(feature = "renderdoc-capture")]{let pipeline_marker = format!(@@ -650,8 +659,13 @@ impl GxRenderer {let max_dim = target_width.max(target_height) as f32;let vp_w = vp.w.clamp(1.0, max_dim);let vp_h = vp.h.clamp(1.0, max_dim);+if vp.x.is_finite() && vp.y.is_finite() && vp_w.is_finite() && vp_h.is_finite() {- rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);+ let vp_tuple = (vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);+ if last_viewport != Some(vp_tuple) {+ rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);+ last_viewport = Some(vp_tuple);+ }} else {tracing::warn!(x = vp.x,@@ -667,7 +681,12 @@ impl GxRenderer {let sc_y = sc.y.min(target_height);let sc_w = sc.w.min(target_width - sc_x);let sc_h = sc.h.min(target_height - sc_y);- rpass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h);+ let sc_tuple = (sc_x, sc_y, sc_w, sc_h);+ if last_scissor != Some(sc_tuple) {+ rpass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h);+ last_scissor = Some(sc_tuple);+ }+#[cfg(feature = "renderdoc-capture")]{let raster_marker = format!(@@ -682,10 +701,12 @@ impl GxRenderer {} else {rpass.draw_indexed(first_index..first_index + index_count, first_vertex as i32, 0..1);}+#[cfg(feature = "renderdoc-capture")]rpass.pop_debug_group();}}+#[cfg(feature = "renderdoc-capture")]encoder.pop_debug_group();@@ -707,35 +728,30 @@ impl GxRenderer {}}-fn triangulate_draw_data(draw: &DrawData, verts_out: &mut Vec<GpuVertex>, indices_out: &mut Vec<u32>) -> (u32, u32) {+/// Emit indices for a draw whose vertices already live in the renderer's+/// `scratch_vertices` at `[base_vertex .. base_vertex + n]`. Indices are+/// written into `indices_out` as offsets relative to `base_vertex`, since+/// `draw_indexed` is called with `base_vertex` as `first_vertex`. Returns+/// `(vertex_count, index_count)`.+fn emit_draw_indices(draw: &DrawData, indices_out: &mut Vec<u32>) -> (u32, u32) {use gecko::flipper::gx::draw::Primitive;- let verts: &[GpuVertex] = &draw.vertices;- let n = verts.len() as u32;+ let n = draw.vertex_count;match draw.primitive {- Primitive::Triangles => {- verts_out.extend_from_slice(verts);- (n, 0)- }+ Primitive::Triangles => (n, 0),Primitive::Quads => {- verts_out.extend_from_slice(verts);-let chunks = n / 4;for q in 0..chunks {let base = q * 4;indices_out.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);}-(n, chunks * 6)}Primitive::TriangleStrip => {if n < 3 {return (0, 0);}-- verts_out.extend_from_slice(verts);-let tris = n - 2;for i in 0..tris {if i & 1 == 0 {@@ -744,15 +760,12 @@ fn triangulate_draw_data(draw: &DrawData, verts_out: &mut Vec<GpuVertex>, indiceindices_out.extend_from_slice(&[i + 1, i, i + 2]);}}-(n, tris * 3)}Primitive::TriangleFan => {if n < 3 {return (0, 0);}-- verts_out.extend_from_slice(verts);let tris = n - 2;for i in 0..tris {indices_out.extend_from_slice(&[0, i + 1, i + 2]);@@ -760,7 +773,7 @@ fn triangulate_draw_data(draw: &DrawData, verts_out: &mut Vec<GpuVertex>, indice(n, tris * 3)}_ => {- tracing::error!(?draw.primitive, "triangulate: skipping unsupported primitive");+ tracing::error!(?draw.primitive, "emit_draw_indices: skipping unsupported primitive");(0, 0)}}diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex 72d4f5e..3ded8a8 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -89,9 +89,10 @@ impl GxRenderer {let needed_frame_size = frame_uniform_bytes.len() as u64;if needed_frame_size > self.frame_uniform_buffer.size() {+ let new_size = needed_frame_size.next_power_of_two().max(needed_frame_size);self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {label: Some("gx_frame_uniforms"),- size: needed_frame_size,+ size: new_size,usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,mapped_at_creation: false,});diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rsindex 7bff815..5264181 100644--- a/crates/backend-wgpu/src/sink.rs+++ b/crates/backend-wgpu/src/sink.rs@@ -1,27 +1,11 @@use crate::GxRenderer;-use crossbeam_channel::{Receiver, Sender, bounded};-#[cfg(feature = "hotpath")]-macro_rules! instrument_channel {- ($e:expr, $label:expr) => {- hotpath::channel!($e, label = $label)- };-}-#[cfg(not(feature = "hotpath"))]-macro_rules! instrument_channel {- ($e:expr, $label:expr) => {- $e- };-}--use gecko::host::{DrawData, GxAction, RenderSink};+use gecko::host::{DrawVertex, GxAction, RenderSink};use std::sync::{Arc, Mutex, OnceLock};use std::time::Instant;pub type FrameReadyCallback = Box<dyn Fn(Instant) + Send + Sync>;-const RECYCLE_CAPACITY: usize = 8192;-/// Holds the XFB output texture view that the emu thread updates and the/// windowing thread reads for blitting.pub struct Shared {@@ -43,32 +27,28 @@ pub struct InlineSink {queue: wgpu::Queue,shared: Arc<Shared>,frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,- boxes_tx: Sender<Box<DrawData>>,}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);+ if let GxAction::PresentXfb { .. } = action {+ 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());}- _ => {}}}fn flush_efb_copies(&mut self, ram: &mut gecko::mmio::RamViewMut<'_>) {self.gx.drain_pending_writebacks(&self.device, &self.queue, ram);}++ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {+ &mut self.gx.scratch_vertices+ }}impl Drop for InlineSink {@@ -94,7 +74,6 @@ pub struct Renderer {blit_sampler: wgpu::Sampler,target_aspect: TargetAspect,frame_ready_cb: Arc<OnceLock<FrameReadyCallback>>,- recycle_rx: Arc<Mutex<Option<Receiver<Box<DrawData>>>>>,#[cfg(feature = "renderdoc-capture")]renderdoc: Arc<Mutex<crate::renderdoc_capture::RenderDocCapture>>,}@@ -180,9 +159,6 @@ impl Renderer {..Default::default()});- let (boxes_tx, recycle_rx) =- instrument_channel!(bounded::<Box<DrawData>>(RECYCLE_CAPACITY), "draw_data_recycle");-let frame_ready_cb: Arc<OnceLock<FrameReadyCallback>> = Arc::new(OnceLock::new());let sink = InlineSink {@@ -191,7 +167,6 @@ impl Renderer {queue,shared: shared.clone(),frame_ready_cb: frame_ready_cb.clone(),- boxes_tx,};let renderer = Renderer {@@ -202,7 +177,6 @@ impl Renderer {blit_sampler,target_aspect,frame_ready_cb,- recycle_rx: Arc::new(Mutex::new(Some(recycle_rx))),#[cfg(feature = "renderdoc-capture")]renderdoc: Arc::new(Mutex::new(crate::renderdoc_capture::RenderDocCapture::new())),};@@ -259,10 +233,6 @@ impl Renderer {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}diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex 3472408..14d2cdb 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -57,13 +57,6 @@ impl EmulatorVariant {}}- 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,- Self::Wii(e) => e.gx.draw_box_recycle_rx = rx,- }- }-fn load_dsp_irom(&mut self, data: &[u8]) {match self {Self::Gc(e) => e.dsp.load_irom(data),@@ -521,7 +514,6 @@ fn main() {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(sink));let ui = DebuggerUi {diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex cc88bd6..c94a902 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, GxAction, LightData, TextureKey, XfbPart};+use crate::host::{DrawVertex, GxAction, LightData, TextureKey, XfbPart};use crate::system::{System, SystemId};use rustc_hash::FxHashMap;@@ -95,8 +95,6 @@ pub struct GraphicsProcessor {// sends. Keyed by the same `TextureKey` sent to the renderer in// [`GxAction::LoadTexture`].pub texture_hashes: FxHashMap<TextureKey, u64>,- pub draw_box_pool: Vec<Box<DrawData>>,- pub draw_box_recycle_rx: Option<crossbeam_channel::Receiver<Box<DrawData>>>,}/// A single EFB-to-XFB copy, stored until `present_xfb` computes the layout.@@ -179,15 +177,6 @@ impl GraphicsProcessor {#[cfg(feature = "gx-stats")]stats: GxStats::default(),texture_hashes: FxHashMap::default(),- draw_box_pool: {- const POOL_PREALLOC: usize = 1024;- let mut v: Vec<Box<crate::host::DrawData>> = Vec::with_capacity(POOL_PREALLOC);- for _ in 0..POOL_PREALLOC {- v.push(Box::new(crate::host::DrawData::default()));- }- v- },- draw_box_recycle_rx: None,}}}diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rsindex c0ca401..2a23ddd 100644--- a/crates/gecko/src/flipper/gx/vertex.rs+++ b/crates/gecko/src/flipper/gx/vertex.rs@@ -2,7 +2,7 @@ use super::constants::*;use super::math::{Vec3, unpack_rgba};use super::regs::{self, *};use super::{GraphicsProcessor, draw};-use crate::host::{DrawVertex, GxAction, RenderSink};+use crate::host::{DrawData, DrawVertex, GxAction, RenderSink};use crate::mmio::{Mmio, RamView};use crate::system::SystemId;use std::io::{Cursor, Read};@@ -77,12 +77,7 @@ impl GraphicsProcessor {self.stats.draws_by_primitive[(primitive as usize) & 0x7] += 1;}- if let Some(rx) = &self.draw_box_recycle_rx {- while let Ok(b) = rx.try_recv() {- self.draw_box_pool.push(b);- }- }- let mut boxed = self.draw_box_pool.pop().unwrap_or_default();+ let mut boxed: Box<DrawData> = Box::default();self.draw_vertices_scratch.clear();if self.draw_vertices_scratch.capacity() < vertex_count {@@ -103,8 +98,11 @@ impl GraphicsProcessor {self.konst_dirty = false;}- boxed.vertices.clear();- boxed.vertices.append(&mut self.draw_vertices_scratch);+ let renderer_scratch = renderer.vertex_scratch();+ let base_vertex = renderer_scratch.len() as u32;+ renderer_scratch.append(&mut self.draw_vertices_scratch);+ boxed.base_vertex = base_vertex;+ boxed.vertex_count = vertex_count as u32;// Flatten the three indirect matrices to 6 rows. Row 2M is row// 0 of matrix M, row 2M+1 is row 1. The .w lane carries thediff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 031f4dc..d30af3a 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -149,13 +149,17 @@ pub struct XfbPart {pub offset_y: u32,}-/// Per-draw data: primitive type, decoded vertices, modelview transform,+/// Per-draw data: primitive type, vertex range, modelview transform,/// and TEV/lighting configuration (snapshotted at draw time since TEV is-/// built up incrementally via BP writes).+/// built up incrementally via BP writes). Vertices live in the renderer's+/// scratch buffer (see [`RenderSink::vertex_scratch`]); `base_vertex` is+/// the index into that buffer where this draw's vertices start and+/// `vertex_count` is how many of them belong to this draw.#[derive(Debug, Default)]pub struct DrawData {pub primitive: Primitive,- pub vertices: Vec<DrawVertex>,+ pub base_vertex: u32,+ pub vertex_count: u32,pub modelview: [[f32; 4]; 4],// TEV combiner statepub tev_color_env: [u32; 16],@@ -214,6 +218,13 @@ pub trait RenderSink: Send {/// Submit a single action.fn exec(&mut self, action: GxAction);+ /// Mutable handle to the sink's vertex scratch buffer. Callers append+ /// per-draw vertices here before issuing [`GxAction::Draw`] and store the+ /// pre-append length as [`DrawData::base_vertex`]. Real renderers+ /// (e.g. wgpu) keep this buffer alive across draws and upload it in one+ /// shot at flush time; headless sinks can use a throwaway local.+ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex>;+fn flush_efb_copies(&mut self, ram: &mut crate::mmio::RamViewMut<'_>) {let _ = ram;}@@ -221,12 +232,19 @@ pub trait RenderSink: Send {/// Swallows every action. Used by headless runners (tinybench, tinytracer)/// and as the default when no renderer is installed.-#[derive(Debug, Clone, Copy)]-pub struct EmptyRenderSink;+#[derive(Debug, Default)]+pub struct EmptyRenderSink {+ scratch: Vec<DrawVertex>,+}impl RenderSink for EmptyRenderSink {fn exec(&mut self, _action: GxAction) {#[cfg(feature = "rendersink-blackbox")]std::hint::black_box(&_action);+ self.scratch.clear();+ }++ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {+ &mut self.scratch}}diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex 57eed04..b665500 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -105,7 +105,7 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {starlet: Starlet::new(),hollywood: Hollywood::new(),- render_sink: Box::new(EmptyRenderSink),+ render_sink: Box::new(EmptyRenderSink::default()),audio_sink: Box::new(EmptyAudioSink),#[cfg(feature = "hooks")]diff --git a/crates/mcp/src/boot.rs b/crates/mcp/src/boot.rsindex 3ded10a..a0d8e01 100644--- a/crates/mcp/src/boot.rs+++ b/crates/mcp/src/boot.rs@@ -26,6 +26,7 @@ fn make_sink(device,queue,introspect,+ scratch: Vec::new(),})}diff --git a/crates/mcp/src/sink.rs b/crates/mcp/src/sink.rsindex e4a2af2..87ead58 100644--- a/crates/mcp/src/sink.rs+++ b/crates/mcp/src/sink.rs@@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex};use backend_wgpu::GxRenderer;use gecko::flipper::gx::draw::TextureFormat;-use gecko::host::{GxAction, RenderSink, TextureKey};+use gecko::host::{DrawVertex, GxAction, RenderSink, TextureKey};pub struct TextureRecord {pub width: u32,@@ -27,6 +27,10 @@ pub struct McpSink {pub device: wgpu::Device,pub queue: wgpu::Queue,pub introspect: Arc<Mutex<Introspection>>,+ /// Side scratch for vertices emitted by gecko since the trait method+ /// can't return `&mut` into the `Mutex<GxRenderer>`. Synced into the+ /// underlying renderer's `scratch_vertices` on every `exec`.+ pub scratch: Vec<DrawVertex>,}impl RenderSink for McpSink {@@ -72,6 +76,10 @@ impl RenderSink for McpSink {self.gx.lock().unwrap()- .process_action(&self.device, &self.queue, &action);+ .process_action_with_external_scratch(&self.device, &self.queue, &action, &mut self.scratch);+ }++ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {+ &mut self.scratch}}diff --git a/crates/screenshotter/src/main.rs b/crates/screenshotter/src/main.rsindex d3b5e98..ce9d21e 100644--- a/crates/screenshotter/src/main.rs+++ b/crates/screenshotter/src/main.rs@@ -17,6 +17,7 @@ struct SyncSink {gx: Arc<Mutex<GxRenderer>>,device: wgpu::Device,queue: wgpu::Queue,+ scratch: Vec<gecko::host::DrawVertex>,}impl RenderSink for SyncSink {@@ -24,7 +25,11 @@ impl RenderSink for SyncSink {self.gx.lock().unwrap()- .process_action(&self.device, &self.queue, &action);+ .process_action_with_external_scratch(&self.device, &self.queue, &action, &mut self.scratch);+ }++ fn vertex_scratch(&mut self) -> &mut Vec<gecko::host::DrawVertex> {+ &mut self.scratch}}@@ -224,6 +229,7 @@ fn run_one(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::Texgx: gx.clone(),device: device.clone(),queue: queue.clone(),+ scratch: Vec::new(),});gamecube.insert_dvd(image);diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex f5fe767..17fb11f 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -352,7 +352,6 @@ fn run<const SYSTEM: SystemId>(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(sink);let audio_stream = install_audio_sink(args, &mut emulator);diff --git a/crates/web/Cargo.lock b/crates/web/Cargo.lockindex 5691b39..26f8430 100644--- a/crates/web/Cargo.lock+++ b/crates/web/Cargo.lock@@ -617,6 +617,7 @@ dependencies = ["cranelift-native","libc","log",+ "memmap2 0.2.3","region","target-lexicon","wasmtime-internal-jit-icache-coherence",@@ -1747,6 +1748,15 @@ version = "2.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"+[[package]]+name = "memmap2"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4"+dependencies = [+ "libc",+]+[[package]]name = "memmap2"version = "0.9.10"@@ -2614,7 +2624,7 @@ checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec"dependencies = ["ab_glyph","log",- "memmap2",+ "memmap2 0.9.10","smithay-client-toolkit","tiny-skia",]@@ -2748,7 +2758,7 @@ dependencies = ["cursor-icon","libc","log",- "memmap2",+ "memmap2 0.9.10","rustix 0.38.44","thiserror 1.0.69","wayland-backend",@@ -3807,7 +3817,7 @@ dependencies = ["dpi","js-sys","libc",- "memmap2",+ "memmap2 0.9.10","ndk","objc2 0.5.2","objc2-app-kit",diff --git a/crates/web/src/lib.rs b/crates/web/src/lib.rsindex 5dd3170..656f7c7 100644--- a/crates/web/src/lib.rs+++ b/crates/web/src/lib.rs@@ -8,7 +8,7 @@ use gecko::HostInput;use gecko::flipper::si::pad::{self, PadStatus, STICK_CENTER, STICK_MAX, STICK_MIN, TRIGGER_MAX, TRIGGER_MIN};use gecko::flipper::vi::regs::RefreshRate;use gecko::gamecube::GameCube;-use gecko::host::{GxAction, RenderSink};+use gecko::host::{DrawVertex, GxAction, RenderSink};use image::Dol;use wasm_bindgen::prelude::*;use winit::application::ApplicationHandler;@@ -46,16 +46,50 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {}";-type ActionQueue = Arc<Mutex<Vec<GxAction>>>;+/// Shared between [`WebSink`] (running on the emulator side) and the main+/// thread that drains the queue. The `epoch` is bumped each time the main+/// thread drains; the sink uses it to know when to reset its mirrored+/// vertex scratch.+struct WebSinkShared {+ actions: Vec<GxAction>,+ scratch: Vec<DrawVertex>,+ epoch: u64,+}++type WebSinkQueue = Arc<Mutex<WebSinkShared>>;/// RenderSink that queues actions for synchronous processing on the main thread.struct WebSink {- queue: ActionQueue,+ shared: WebSinkQueue,+ /// Mirror of `shared.scratch`, written by the gecko side via+ /// [`RenderSink::vertex_scratch`]. Synced into `shared.scratch` on every+ /// `exec`. Cleared when the main thread bumps `shared.epoch`.+ scratch: Vec<DrawVertex>,+ last_epoch: u64,}impl RenderSink for WebSink {fn exec(&mut self, action: GxAction) {- self.queue.lock().unwrap().push(action);+ let mut s = self.shared.lock().unwrap();+ if s.epoch != self.last_epoch {+ self.scratch.clear();+ self.last_epoch = s.epoch;+ }+ if self.scratch.len() > s.scratch.len() {+ let start = s.scratch.len();+ s.scratch.extend_from_slice(&self.scratch[start..]);+ }+ s.actions.push(action);+ }++ fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {+ let s = self.shared.lock().unwrap();+ if s.epoch != self.last_epoch {+ self.scratch.clear();+ self.last_epoch = s.epoch;+ }+ drop(s);+ &mut self.scratch}}@@ -245,7 +279,7 @@ impl State {fn render(&mut self,emulator: &mut GameCube,- action_queue: &ActionQueue,+ action_queue: &WebSinkQueue,#[cfg(feature = "debug")] debug_state: &mut debug_ui::DebugState,window: &Window,) {@@ -270,8 +304,15 @@ impl State {#[cfg(not(feature = "debug"))]emulator.run_until_vsync();- // Drain and process all queued GxActions.- let actions: Vec<GxAction> = action_queue.lock().unwrap().drain(..).collect();+ // Drain queued GxActions and the matching vertex scratch.+ let (actions, scratch): (Vec<GxAction>, Vec<DrawVertex>) = {+ let mut s = action_queue.lock().unwrap();+ s.epoch = s.epoch.wrapping_add(1);+ (std::mem::take(&mut s.actions), std::mem::take(&mut s.scratch))+ };+ // Make the drained scratch the renderer's vertex buffer for this drain so+ // each `Draw` action's `base_vertex` indexes into it correctly.+ let _old = self.gx_renderer.replace_vertex_scratch(scratch);for action in &actions {self.gx_renderer.process_action(&self.device, &self.queue, action);}@@ -402,7 +443,7 @@ type SharedState = Rc<RefCell<Option<State>>>;struct App {emulator: GameCube,input: HostInput,- action_queue: ActionQueue,+ action_queue: WebSinkQueue,window: Option<Arc<Window>>,state: SharedState,#[cfg(feature = "debug")]@@ -496,9 +537,15 @@ pub fn start_emulator(rom_data: &[u8], filename: String, dsp_irom: Option<Vec<u8emulator.apply_host_input(&input);// Install the WebSink as the emulator's render sink.- let action_queue: ActionQueue = Arc::new(Mutex::new(Vec::new()));+ let action_queue: WebSinkQueue = Arc::new(Mutex::new(WebSinkShared {+ actions: Vec::new(),+ scratch: Vec::new(),+ epoch: 0,+ }));emulator.render_sink = Box::new(WebSink {- queue: action_queue.clone(),+ shared: action_queue.clone(),+ scratch: Vec::new(),+ last_epoch: 0,});let event_loop = EventLoop::new().unwrap();