Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

wonky backend optimizations

Layle56e8c6833484
diff --git a/Cargo.lock b/Cargo.lock
index 8fa35ba..0c4c829 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -270,7 +270,6 @@ version = "0.1.0"
dependencies = [
"bytemuck",
"crossbeam-channel",
- "encase",
"gecko",
"glam",
"png",
@@ -655,15 +654,6 @@ dependencies = [
"crossbeam-utils",
]
-[[package]]
-name = "const_panic"
-version = "0.2.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e262cdaac42494e3ae34c43969f9cdeb7da178bdb4b66fa6a1ea2edb4c8ae652"
-dependencies = [
- "typewit",
-]
-
[[package]]
name = "convert_case"
version = "0.10.0"
@@ -1285,37 +1275,6 @@ dependencies = [
"log",
]
-[[package]]
-name = "encase"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6e3e0ff2ee0b7aa97428308dd9e1e42369cb22f5fb8dc1c55546637443a60f1e"
-dependencies = [
- "const_panic",
- "encase_derive",
- "thiserror 2.0.18",
-]
-
-[[package]]
-name = "encase_derive"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a4d90c5d7d527c6cb8a3b114efd26a6304d9ab772656e73d8f4e32b1f3d601a2"
-dependencies = [
- "encase_derive_impl",
-]
-
-[[package]]
-name = "encase_derive_impl"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8bad72d8308f7a382de2391ec978ddd736e0103846b965d7e2a63a75768af30"
-dependencies = [
- "proc-macro2",
- "quote",
- "syn",
-]
-
[[package]]
name = "env_home"
version = "0.1.0"
@@ -1649,7 +1608,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
dependencies = [
"bytemuck",
- "encase",
]
[[package]]
@@ -4159,12 +4117,6 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
-[[package]]
-name = "typewit"
-version = "1.14.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8c1ae7cc0fdb8b842d65d127cb981574b0d2b249b74d1c7a2986863dc134f71"
-
[[package]]
name = "unicode-ident"
version = "1.0.24"
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.toml
index d3e9166..c0b5cac 100644
--- a/crates/backend-wgpu/Cargo.toml
+++ b/crates/backend-wgpu/Cargo.toml
@@ -12,8 +12,7 @@ wgpu = "28.0.0"
bytemuck = { version = "1.25.0", features = ["derive"] }
gecko = { path = "../gecko" }
wesl = "0.3.2"
-encase = "0.12.0"
-glam = { version = "0.32.1", features = ["encase"] }
+glam = { version = "0.32.1", features = ["bytemuck"] }
crossbeam-channel = "0.5.15"
tracing = "0.1.44"
rustc-hash = "2.1.2"
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 1bc4760..57ddc0c 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,6 +1,8 @@
use crate::pipeline::PipelineKey;
-use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GpuVertex, GxRenderer, SamplerKey, helpers};
-use encase::{ShaderType as _, UniformBuffer};
+use crate::{
+ BindGroupCacheKey, DRAW_UNIFORMS_SIZE, DrawUniforms, FRAME_UNIFORMS_SIZE, FrameUniforms, GpuVertex, GxRenderer,
+ SamplerKey, helpers,
+};
use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
use gecko::host::{DrawData, GxAction};
use glam::{Mat4, UVec4, Vec4};
@@ -46,9 +48,9 @@ impl GxRenderer {
/// lazily when a non-draw action arrives.
pub fn process_action(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, action: &GxAction) {
let draw_stride = self.draw_uniform_stride as usize;
- let draw_encase_size = DrawUniforms::min_size().get() as usize;
+ let draw_struct_size = DRAW_UNIFORMS_SIZE.get() as usize;
let frame_stride = self.frame_stride;
- let frame_encase_size = self.frame_encase_size;
+ let frame_struct_size = FRAME_UNIFORMS_SIZE.get() as usize;
match action {
GxAction::SetProjection { matrix, .. } => {
@@ -183,57 +185,67 @@ impl GxRenderer {
let start = self.scratch_draws.len() * draw_stride;
self.scratch_uniform_bytes.resize(start + draw_stride, 0);
- let mut draw_buf = UniformBuffer::new(&mut self.scratch_uniform_bytes[start..start + draw_encase_size]);
- draw_buf.write(&draw_uniform).unwrap();
-
- // Build per-draw frame uniform (TEV + lighting from DrawData,
- // alpha compare from tracked state).
- let alpha_cmp = self.current_alpha_compare;
- let frame_uniform = FrameUniforms {
- tev_color_regs: draw.tev_color_regs.map(Vec4::from),
- tev_konst_colors: draw.tev_konst_colors.map(Vec4::from),
- tev_color_env: pack_u32_slice_to_uvec4x4(&draw.tev_color_env),
- tev_alpha_env: pack_u32_slice_to_uvec4x4(&draw.tev_alpha_env),
- tev_orders: pack_u32_slice_to_uvec4x4(&draw.tev_orders),
- tev_ksel: pack_u32_slice_to_uvec4x4(&draw.tev_ksel),
- num_tev_stages: draw.num_tev_stages as u32,
- alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
- alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
- alpha_comp0: alpha_cmp.comp0() as u32,
- alpha_comp1: alpha_cmp.comp1() as u32,
- alpha_op: alpha_cmp.op() as u32,
- indirect_matrices: draw.indirect_matrices.map(glam::IVec4::from),
- indirect_scales: draw.indirect_scales.map(glam::UVec4::from),
- indirect_refs: draw.indirect_refs,
- num_indirect_stages: draw.num_indirect_stages as u32,
- bump_imask: draw.bump_imask,
- tev_indirect: pack_u32_slice_to_uvec4x4(&draw.tev_indirect),
- light_colors: draw.lights.each_ref().map(|l| Vec4::from(l.color)),
- light_cosatt: draw.lights.each_ref().map(|l| Vec4::from(l.cosatt)),
- light_distatt: draw.lights.each_ref().map(|l| Vec4::from(l.distatt)),
- light_pos: draw.lights.each_ref().map(|l| Vec4::from(l.position)),
- light_dir: draw.lights.each_ref().map(|l| Vec4::from(l.direction)),
- color_ctrl0: draw.color_ctrl[0].raw(),
- alpha_ctrl0: draw.alpha_ctrl[0].raw(),
- color_ctrl1: draw.color_ctrl[1].raw(),
- alpha_ctrl1: draw.alpha_ctrl[1].raw(),
- ambient_color0: Vec4::from(draw.ambient_color[0]),
- ambient_color1: Vec4::from(draw.ambient_color[1]),
- material_color0: Vec4::from(draw.material_color[0]),
- material_color1: Vec4::from(draw.material_color[1]),
+ self.scratch_uniform_bytes[start..start + draw_struct_size]
+ .copy_from_slice(bytemuck::bytes_of(&draw_uniform));
+
+ // Build a fresh FrameUniforms slot only when the producer
+ // signaled state changed since the last draw or this is the
+ // first draw of the flush.
+ let frame_idx = if draw.frame_dirty || self.last_frame_uniform_index.is_none() {
+ let alpha_cmp = self.current_alpha_compare;
+ let frame_uniform = FrameUniforms {
+ tev_color_regs: draw.tev_color_regs.map(Vec4::from),
+ tev_konst_colors: draw.tev_konst_colors.map(Vec4::from),
+ tev_color_env: pack_u32_slice_to_uvec4x4(&draw.tev_color_env),
+ tev_alpha_env: pack_u32_slice_to_uvec4x4(&draw.tev_alpha_env),
+ tev_orders: pack_u32_slice_to_uvec4x4(&draw.tev_orders),
+ tev_ksel: pack_u32_slice_to_uvec4x4(&draw.tev_ksel),
+ num_tev_stages: draw.num_tev_stages as u32,
+ alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
+ alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
+ alpha_comp0: alpha_cmp.comp0() as u32,
+ alpha_comp1: alpha_cmp.comp1() as u32,
+ alpha_op: alpha_cmp.op() as u32,
+ _pad0: [0; 2],
+ indirect_matrices: draw.indirect_matrices.map(glam::IVec4::from),
+ indirect_scales: draw.indirect_scales.map(glam::UVec4::from),
+ indirect_refs: draw.indirect_refs,
+ num_indirect_stages: draw.num_indirect_stages as u32,
+ bump_imask: draw.bump_imask,
+ _pad1: 0,
+ tev_indirect: pack_u32_slice_to_uvec4x4(&draw.tev_indirect),
+ light_colors: draw.lights.each_ref().map(|l| Vec4::from(l.color)),
+ light_cosatt: draw.lights.each_ref().map(|l| Vec4::from(l.cosatt)),
+ light_distatt: draw.lights.each_ref().map(|l| Vec4::from(l.distatt)),
+ light_pos: draw.lights.each_ref().map(|l| Vec4::from(l.position)),
+ light_dir: draw.lights.each_ref().map(|l| Vec4::from(l.direction)),
+ color_ctrl0: draw.color_ctrl[0].raw(),
+ alpha_ctrl0: draw.alpha_ctrl[0].raw(),
+ color_ctrl1: draw.color_ctrl[1].raw(),
+ alpha_ctrl1: draw.alpha_ctrl[1].raw(),
+ ambient_color0: Vec4::from(draw.ambient_color[0]),
+ ambient_color1: Vec4::from(draw.ambient_color[1]),
+ material_color0: Vec4::from(draw.material_color[0]),
+ material_color1: Vec4::from(draw.material_color[1]),
+ };
+
+ let fstart = self.frame_uniform_bytes.len();
+ self.frame_uniform_bytes.resize(fstart + frame_stride, 0);
+ self.frame_uniform_bytes[fstart..fstart + frame_struct_size]
+ .copy_from_slice(bytemuck::bytes_of(&frame_uniform));
+ let idx = (fstart / frame_stride) as u32;
+ self.last_frame_uniform_index = Some(idx);
+ idx
+ } else {
+ self.last_frame_uniform_index.unwrap()
};
- let fstart = self.scratch_draws.len() * frame_stride;
- self.frame_uniform_bytes.resize(fstart + frame_stride, 0);
- let mut frame_buf =
- UniformBuffer::new(&mut self.frame_uniform_bytes[fstart..fstart + frame_encase_size]);
- frame_buf.write(&frame_uniform).unwrap();
-
// Snapshot tracked state for this draw.
self.draw_pipeline_keys.push(pipeline_key);
self.draw_bg_keys.push(self.current_bind_group_key());
self.draw_viewports.push(self.current_viewport);
self.draw_scissors.push(self.current_scissor);
+ self.draw_frame_indices.push(frame_idx);
#[cfg(feature = "renderdoc-capture")]
self.draw_primitives.push(draw.primitive);
@@ -377,6 +389,8 @@ impl GxRenderer {
self.draw_bg_keys.clear();
self.draw_viewports.clear();
self.draw_scissors.clear();
+ self.draw_frame_indices.clear();
+ self.last_frame_uniform_index = None;
#[cfg(feature = "renderdoc-capture")]
self.draw_primitives.clear();
}
@@ -420,7 +434,7 @@ impl GxRenderer {
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &self.frame_uniform_buffer,
offset: 0,
- size: Some(FrameUniforms::min_size()),
+ size: Some(FRAME_UNIFORMS_SIZE),
}),
},
1 => wgpu::BindGroupEntry {
@@ -428,7 +442,7 @@ impl GxRenderer {
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer: &self.draw_uniform_buffer,
offset: 0,
- size: Some(DrawUniforms::min_size()),
+ size: Some(DRAW_UNIFORMS_SIZE),
}),
},
2..=9 => wgpu::BindGroupEntry {
@@ -548,7 +562,7 @@ impl GxRenderer {
let bg_key = &self.draw_bg_keys[index];
let bind_group = &self.bind_group_cache[bg_key];
- let frame_offset = (index * frame_stride) as u32;
+ let frame_offset = self.draw_frame_indices[index] * frame_stride as u32;
let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;
rpass.set_bind_group(0, bind_group, &[frame_offset, draw_offset]);
#[cfg(feature = "renderdoc-capture")]
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index c112d13..9b96c96 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -10,7 +10,6 @@ mod render;
mod renderdoc_capture;
pub mod sink;
-use encase::ShaderType as _;
use gecko::common::Address;
#[cfg(feature = "renderdoc-capture")]
use gecko::flipper::gx::draw::Primitive;
@@ -22,6 +21,7 @@ use gecko::host::TextureKey;
use glam::Mat4;
use pipeline::PipelineKey;
use rustc_hash::FxHashMap;
+use std::num::NonZeroU64;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
@@ -53,52 +53,67 @@ pub(crate) struct BindGroupCacheKey {
sampler_keys: [Option<SamplerKey>; 8],
}
-#[derive(encase::ShaderType)]
+#[repr(C)]
+#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct FrameUniforms {
- tev_color_regs: [glam::Vec4; 4],
- tev_konst_colors: [glam::Vec4; 16],
- tev_color_env: [glam::UVec4; 4],
- tev_alpha_env: [glam::UVec4; 4],
- tev_orders: [glam::UVec4; 4],
- tev_ksel: [glam::UVec4; 4],
- num_tev_stages: u32,
- alpha_ref0: f32,
- alpha_ref1: f32,
- alpha_comp0: u32,
- alpha_comp1: u32,
- alpha_op: u32,
+ pub tev_color_regs: [glam::Vec4; 4],
+ pub tev_konst_colors: [glam::Vec4; 16],
+ pub tev_color_env: [glam::UVec4; 4],
+ pub tev_alpha_env: [glam::UVec4; 4],
+ pub tev_orders: [glam::UVec4; 4],
+ pub tev_ksel: [glam::UVec4; 4],
+ pub num_tev_stages: u32,
+ pub alpha_ref0: f32,
+ pub alpha_ref1: f32,
+ pub alpha_comp0: u32,
+ pub alpha_comp1: u32,
+ pub alpha_op: u32,
+ pub _pad0: [u32; 2],
// Indirect texturing state. `indirect_matrices` stores the 6 rows of
// the three 2x3 matrices.
- indirect_matrices: [glam::IVec4; 6],
+ pub indirect_matrices: [glam::IVec4; 6],
// Two packed RAS1_SS registers holding four 4-bit divisor exponents
// each. Stage i reads from `indirect_scales[i / 2]`.
- indirect_scales: [glam::UVec4; 2],
+ pub indirect_scales: [glam::UVec4; 2],
// Packed RAS1_IREF. Four 3+3 bit (texmap, texcoord) pairs.
- indirect_refs: u32,
- num_indirect_stages: u32,
- bump_imask: u32,
+ pub indirect_refs: u32,
+ pub num_indirect_stages: u32,
+ pub bump_imask: u32,
+ pub _pad1: u32,
// Per-TEV-stage IND_CMD, packed four per UVec4.
- tev_indirect: [glam::UVec4; 4],
- light_colors: [glam::Vec4; 8],
- light_cosatt: [glam::Vec4; 8],
- light_distatt: [glam::Vec4; 8],
- light_pos: [glam::Vec4; 8],
- light_dir: [glam::Vec4; 8],
- color_ctrl0: u32,
- alpha_ctrl0: u32,
- color_ctrl1: u32,
- alpha_ctrl1: u32,
- ambient_color0: glam::Vec4,
- ambient_color1: glam::Vec4,
- material_color0: glam::Vec4,
- material_color1: glam::Vec4,
+ pub tev_indirect: [glam::UVec4; 4],
+ pub light_colors: [glam::Vec4; 8],
+ pub light_cosatt: [glam::Vec4; 8],
+ pub light_distatt: [glam::Vec4; 8],
+ pub light_pos: [glam::Vec4; 8],
+ pub light_dir: [glam::Vec4; 8],
+ pub color_ctrl0: u32,
+ pub alpha_ctrl0: u32,
+ pub color_ctrl1: u32,
+ pub alpha_ctrl1: u32,
+ pub ambient_color0: glam::Vec4,
+ pub ambient_color1: glam::Vec4,
+ pub material_color0: glam::Vec4,
+ pub material_color1: glam::Vec4,
}
-#[derive(encase::ShaderType)]
+pub(crate) const FRAME_UNIFORMS_SIZE: NonZeroU64 = match NonZeroU64::new(std::mem::size_of::<FrameUniforms>() as u64) {
+ Some(v) => v,
+ None => panic!("FrameUniforms must be non-zero sized"),
+};
+const _: () = assert!(std::mem::size_of::<FrameUniforms>() == 1536);
+
+#[repr(C)]
+#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct DrawUniforms {
- mvp: glam::Mat4,
+ pub mvp: glam::Mat4,
}
+pub(crate) const DRAW_UNIFORMS_SIZE: NonZeroU64 = match NonZeroU64::new(std::mem::size_of::<DrawUniforms>() as u64) {
+ Some(v) => v,
+ None => panic!("DrawUniforms must be non-zero sized"),
+};
+
const SHADER: &str = wesl::include_wesl!("gx_shader");
pub const EFB_WIDTH: u32 = 640;
@@ -152,10 +167,17 @@ pub struct GxRenderer {
pub(crate) draw_bg_keys: Vec<BindGroupCacheKey>,
pub(crate) draw_viewports: Vec<Viewport>,
pub(crate) draw_scissors: Vec<Scissor>,
+ /// Per-draw index into the FrameUniforms array. Multiple consecutive
+ /// draws that share TEV/lighting/alpha/indirect state point at the same
+ /// slot via dynamic offset; only state-changing draws push a fresh slot
+ /// (driven by `DrawData::frame_dirty` from the producer).
+ pub(crate) draw_frame_indices: Vec<u32>,
+ /// Index of the most recently appended FrameUniforms slot, reused when
+ /// `frame_dirty` is false. Reset to `None` at each `flush_pending_draws`.
+ pub(crate) last_frame_uniform_index: Option<u32>,
#[cfg(feature = "renderdoc-capture")]
pub(crate) draw_primitives: Vec<Primitive>,
pub(crate) frame_stride: usize,
- pub(crate) frame_encase_size: usize,
// Tracked GX state (updated by state-change actions)
pub(crate) current_projection: Mat4,
pub(crate) current_viewport: Viewport,
@@ -192,8 +214,8 @@ pub struct GxRenderer {
impl GxRenderer {
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, surface_format: wgpu::TextureFormat) -> Self {
- let frame_uniform_size = FrameUniforms::min_size().get();
- let draw_uniform_size = DrawUniforms::min_size().get();
+ let frame_uniform_size = FRAME_UNIFORMS_SIZE.get();
+ let draw_uniform_size = DRAW_UNIFORMS_SIZE.get();
let draw_uniform_stride = align_up(
draw_uniform_size,
device.limits().min_uniform_buffer_offset_alignment as u64,
@@ -220,7 +242,7 @@ impl GxRenderer {
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true,
- min_binding_size: Some(FrameUniforms::min_size()),
+ min_binding_size: Some(FRAME_UNIFORMS_SIZE),
},
count: None,
},
@@ -230,7 +252,7 @@ impl GxRenderer {
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true,
- min_binding_size: Some(DrawUniforms::min_size()),
+ min_binding_size: Some(DRAW_UNIFORMS_SIZE),
},
count: None,
},
@@ -643,13 +665,14 @@ impl GxRenderer {
draw_bg_keys: Vec::new(),
draw_viewports: Vec::new(),
draw_scissors: Vec::new(),
+ draw_frame_indices: Vec::new(),
+ last_frame_uniform_index: None,
#[cfg(feature = "renderdoc-capture")]
draw_primitives: Vec::new(),
frame_stride: align_up(
- FrameUniforms::min_size().get(),
+ FRAME_UNIFORMS_SIZE.get(),
device.limits().min_uniform_buffer_offset_alignment as u64,
) as usize,
- frame_encase_size: FrameUniforms::min_size().get() as usize,
current_projection: Mat4::IDENTITY,
current_viewport: Viewport::default(),
current_scissor: Scissor::default(),
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index b80ea6e..73c8de7 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,5 +1,6 @@
-use crate::{FrameUniforms, GpuVertex, GxRenderer, align_up};
-use encase::ShaderType as _;
+#[cfg(feature = "efb-writeback")]
+use crate::align_up;
+use crate::{GpuVertex, GxRenderer};
use gecko::common::Address;
#[cfg(feature = "efb-writeback")]
use gecko::flipper::gx::texture;
@@ -16,6 +17,19 @@ pub(crate) struct XfbCopyUniforms {
filter_mode: u32,
}
+/// Upload `bytes` into `buffer` at offset 0 via `write_buffer_with`, which
+/// hands us a writable view into wgpu's staging memory and skips the extra
+/// copy `write_buffer` would do. No-op when `bytes` is empty.
+fn write_buffer(queue: &wgpu::Queue, buffer: &wgpu::Buffer, bytes: &[u8]) {
+ let Some(size) = std::num::NonZeroU64::new(bytes.len() as u64) else {
+ return;
+ };
+ let mut view = queue
+ .write_buffer_with(buffer, 0, size)
+ .expect("buffer too small for write_buffer_with");
+ view.copy_from_slice(bytes);
+}
+
impl GxRenderer {
pub(crate) fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
let num_draws = self.scratch_draws.len();
@@ -31,11 +45,7 @@ impl GxRenderer {
});
}
- let frame_stride = align_up(
- FrameUniforms::min_size().get(),
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
- let needed_frame_size = (num_draws * frame_stride) as u64;
+ let needed_frame_size = frame_uniform_bytes.len() as u64;
if needed_frame_size > self.frame_uniform_buffer.size() {
self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("gx_frame_uniforms"),
@@ -46,9 +56,9 @@ impl GxRenderer {
self.bind_group_cache.clear();
}
- queue.write_buffer(&self.frame_uniform_buffer, 0, frame_uniform_bytes);
- queue.write_buffer(&self.draw_uniform_buffer, 0, &self.scratch_uniform_bytes);
- queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.scratch_vertices));
+ write_buffer(queue, &self.frame_uniform_buffer, frame_uniform_bytes);
+ write_buffer(queue, &self.draw_uniform_buffer, &self.scratch_uniform_bytes);
+ write_buffer(queue, &self.vertex_buffer, bytemuck::cast_slice(&self.scratch_vertices));
}
pub(crate) fn execute_copy_xfb(
diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rs
index 4685f55..949cb92 100644
--- a/crates/backend-wgpu/src/sink.rs
+++ b/crates/backend-wgpu/src/sink.rs
@@ -2,13 +2,16 @@ use crate::GxRenderer;
use crossbeam_channel::{Receiver, Sender, bounded};
#[cfg(feature = "efb-writeback")]
use gecko::host::EfbWriteback;
-use gecko::host::{GxAction, RenderSink};
+use gecko::host::{DrawData, GxAction, RenderSink};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
#[cfg(feature = "renderdoc-capture")]
use std::time::Duration;
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.
@@ -26,7 +29,7 @@ pub enum TargetAspect {
}
enum WorkerMsg {
- Action(GxAction),
+ ActionBatch(Vec<GxAction>),
#[cfg(feature = "renderdoc-capture")]
BeginEmulatedFrame {
ack: Sender<()>,
@@ -43,13 +46,25 @@ enum WorkerMsg {
TriggerCapture,
}
-fn worker(mut gx: GxRenderer, device: wgpu::Device, queue: wgpu::Queue, shared: Arc<Shared>, rx: Receiver<WorkerMsg>) {
+struct Recyclers {
+ boxes: Sender<Box<DrawData>>,
+ batches: Sender<Vec<GxAction>>,
+}
+
+fn worker(
+ mut gx: GxRenderer,
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ shared: Arc<Shared>,
+ rx: Receiver<WorkerMsg>,
+ recyclers: Recyclers,
+) {
#[cfg(feature = "renderdoc-capture")]
let mut renderdoc = crate::renderdoc_capture::RenderDocCapture::new();
while let Ok(msg) = rx.recv() {
- let action = match msg {
- WorkerMsg::Action(action) => action,
+ let mut batch = match msg {
+ WorkerMsg::ActionBatch(batch) => batch,
#[cfg(feature = "renderdoc-capture")]
WorkerMsg::BeginEmulatedFrame { ack } => {
renderdoc.begin_emulated_frame();
@@ -85,14 +100,26 @@ fn worker(mut gx: GxRenderer, device: wgpu::Device, queue: wgpu::Queue, shared:
}
};
- gx.process_action(&device, &queue, &action);
-
- // After a PresentXfb, update the shared output so the main thread
- // picks up the latest composited frame on its next blit.
- if matches!(action, GxAction::PresentXfb { .. }) {
- let mut output = shared.output.lock().unwrap();
- *output = gx.xfb_view.clone();
+ for action in batch.drain(..) {
+ gx.process_action(&device, &queue, &action);
+
+ match action {
+ GxAction::PresentXfb { .. } => {
+ let mut output = shared.output.lock().unwrap();
+ *output = gx.xfb_view.clone();
+ }
+ GxAction::Draw(mut boxed) => {
+ boxed.vertices.clear();
+ let _ = recyclers.boxes.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);
}
}
@@ -122,6 +149,8 @@ pub struct Renderer {
/// `efb-writeback` is enabled.
#[cfg(feature = "efb-writeback")]
writeback_rx: Arc<Mutex<Option<Receiver<EfbWriteback>>>>,
+ recycle_rx: Arc<Mutex<Option<Receiver<Box<DrawData>>>>>,
+ batch_recycle_rx: Arc<Mutex<Option<Receiver<Vec<GxAction>>>>>,
}
impl Renderer {
@@ -220,6 +249,12 @@ impl Renderer {
});
let (tx, rx) = bounded(CHANNEL_CAPACITY);
+ let (boxes_tx, recycle_rx) = bounded::<Box<DrawData>>(RECYCLE_CAPACITY);
+ let (batches_tx, batch_recycle_rx) = bounded::<Vec<GxAction>>(BATCH_RECYCLE_CAPACITY);
+ let recyclers = Recyclers {
+ boxes: boxes_tx,
+ batches: batches_tx,
+ };
// Spawn the worker.
let worker_shared = shared.clone();
@@ -227,7 +262,7 @@ impl Renderer {
let worker_queue = queue.clone();
std::thread::Builder::new()
.name("gx-renderer".into())
- .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx))
+ .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx, recyclers))
.expect("failed to spawn renderer worker");
Renderer {
@@ -241,6 +276,8 @@ impl Renderer {
actions_sent: Arc::new(AtomicU64::new(0)),
#[cfg(feature = "efb-writeback")]
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))),
}
}
@@ -253,6 +290,10 @@ impl Renderer {
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
}
@@ -349,10 +390,68 @@ impl Renderer {
}
}
-impl RenderSink for 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();
+ }
+}
+
+impl RenderSink for BatchingSink {
fn exec(&mut self, action: GxAction) {
- self.actions_sent.fetch_add(1, Ordering::Relaxed);
- let _ = self.tx.send(WorkerMsg::Action(action));
+ let force_flush = matches!(action, GxAction::PresentXfb { .. } | GxAction::CopyEfbToTexture { .. });
+
+ self.batch.push(action);
+
+ if force_flush || self.batch.len() >= BATCH_SIZE {
+ self.flush();
+ }
}
fn actions_sent_total(&self) -> u64 {
@@ -364,7 +463,7 @@ impl RenderSink for Renderer {
}
fn channel_capacity(&self) -> Option<usize> {
- self.tx.capacity()
+ Some(self.channel_capacity)
}
}
diff --git a/crates/debugger/Cargo.toml b/crates/debugger/Cargo.toml
index 86b0190..7ede60b 100644
--- a/crates/debugger/Cargo.toml
+++ b/crates/debugger/Cargo.toml
@@ -5,7 +5,7 @@ edition = "2024"
[features]
scripting-mut-traps = ["gecko/hooks-mut-traps", "scripting/hooks-mut-traps"]
-efb-writeback = ["backend-wgpu/efb-writeback", "dep:crossbeam-channel"]
+efb-writeback = ["backend-wgpu/efb-writeback"]
renderdoc-capture = ["backend-wgpu/renderdoc-capture"]
[dependencies]
@@ -14,7 +14,7 @@ scripting = { path = "../scripting" }
image = { path = "../image", features = ["symbols"] }
dbglib = { path = "../dbglib" }
backend-wgpu = { path = "../backend-wgpu" }
-crossbeam-channel = { version = "0.5.15", optional = true }
+crossbeam-channel = "0.5.15"
wgpu = "28.0.0"
winit = "0.30.13"
pollster = "0.4.0"
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rs
index 7370f84..a7543d3 100644
--- a/crates/debugger/src/main.rs
+++ b/crates/debugger/src/main.rs
@@ -59,6 +59,13 @@ 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),
@@ -423,7 +430,8 @@ fn main() {
let target_aspect = resolve_aspect(&args.aspect, matches!(emulator, EmulatorVariant::Wii(_)));
let renderer = backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);
- emulator.install_render_sink(Box::new(renderer.clone()));
+ emulator.install_recycle_rx(renderer.take_recycle_rx());
+ emulator.install_render_sink(Box::new(renderer.take_batching_sink()));
#[cfg(feature = "efb-writeback")]
{
diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.toml
index f768387..279c8a2 100644
--- a/crates/gecko/Cargo.toml
+++ b/crates/gecko/Cargo.toml
@@ -12,7 +12,7 @@ hooks-mut-traps = ["hooks"]
# it in the GX copy format, and ships the bytes over a channel to the emu
# thread which copies them into `Mmio::ram` synchronously. Expensive (GPU
# stall, encode, RAM copy).
-efb-writeback = ["dep:crossbeam-channel"]
+efb-writeback = []
# Enable the WAV file audio sink
audio-wav-dump = ["dep:hound"]
# Cranelift JIT for Gekko
@@ -29,6 +29,8 @@ vtx-jit-validate = ["jit", "gx-stats"]
fps-counter = []
gx-stats = []
profile = ["dep:backtrace", "dep:windows-sys"]
+# Enables std::hint::black_box inside `EmptyRenderSink::exec`
+rendersink-blackbox = []
[build-dependencies]
chipi-build = "0.9.1"
@@ -41,7 +43,7 @@ disasm = { path = "../disasm" }
glam = { version = "0.32.1", features = ["bytemuck"] }
bytemuck = { version = "1.25.0", features = ["derive"] }
twox-hash = "2.1.2"
-crossbeam-channel = { version = "0.5.15", optional = true }
+crossbeam-channel = "0.5.15"
hound = { version = "3.5.1", optional = true }
multiversion = "0.8.0"
rustc-hash = "2.1.2"
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index 820c8fe..a59f9b5 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -19,7 +19,7 @@ use crate::flipper::gx::regs::{
};
#[cfg(feature = "efb-writeback")]
use crate::host::EfbWriteback;
-use crate::host::{DrawVertex, GxAction, LightData, TextureKey, XfbPart};
+use crate::host::{DrawData, DrawVertex, GxAction, LightData, TextureKey, XfbPart};
use crate::system::{System, SystemId};
use rustc_hash::FxHashMap;
@@ -83,6 +83,7 @@ pub struct GraphicsProcessor {
pub jit_vtx_validator: jit::validate::VertexJitValidator,
pub lighting_dirty: bool,
pub konst_dirty: bool,
+ pub frame_state_dirty: bool,
pub cached_color_ctrl: [ChanCtrl; 2],
pub cached_alpha_ctrl: [ChanCtrl; 2],
pub cached_ambient_color: [[f32; 4]; 2],
@@ -102,6 +103,8 @@ pub struct GraphicsProcessor {
// sees fresh RAM. Only present when the `efb-writeback` feature is on.
#[cfg(feature = "efb-writeback")]
pub efb_writeback_rx: Option<crossbeam_channel::Receiver<EfbWriteback>>,
+ 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.
@@ -174,6 +177,7 @@ impl GraphicsProcessor {
jit_vtx_validator: jit::validate::VertexJitValidator::new(),
lighting_dirty: true,
konst_dirty: true,
+ frame_state_dirty: true,
cached_color_ctrl: [ChanCtrl::default(); 2],
cached_alpha_ctrl: [ChanCtrl::default(); 2],
cached_ambient_color: [[0.0; 4]; 2],
@@ -184,6 +188,8 @@ impl GraphicsProcessor {
texture_hashes: FxHashMap::default(),
#[cfg(feature = "efb-writeback")]
efb_writeback_rx: None,
+ draw_box_pool: Vec::with_capacity(64),
+ draw_box_recycle_rx: None,
}
}
}
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 47f1be6..7b2a5de 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -82,6 +82,7 @@ impl GraphicsProcessor {
}
BP_PE_ALPHA_COMPARE => {
self.cur_alpha_compare = AlphaCompare::from_raw(val);
+ self.frame_state_dirty = true;
renderer.exec(GxAction::SetAlphaCompare(self.cur_alpha_compare));
}
_ => {}
@@ -91,16 +92,19 @@ impl GraphicsProcessor {
// Even addresses = color env, odd = alpha env
if idx >= BP_TEV_COLOR_ENV_0 && idx < BP_TEV_COLOR_ENV_0 + 32 {
self.load_tev_env(idx, val);
+ self.frame_state_dirty = true;
}
// TEV rasterizer order registers (RAS1_TREF0-7, 0x28-0x2F)
if idx >= BP_RAS1_TREF0 && idx < BP_RAS1_TREF0 + BP_RAS1_TREF_COUNT {
self.cur_tev_orders[idx - BP_RAS1_TREF0] = TevOrder::from_raw(val);
+ self.frame_state_dirty = true;
}
// TEV color registers (0xE0-0xE7): pairs of lo/hi writes
if idx >= BP_TEV_REGISTERL_0 && idx <= BP_TEV_REGISTERL_0 + 7 {
self.load_tev_register(idx, val);
+ self.frame_state_dirty = true;
}
// GEN_MODE, extract num TEV stages + cull mode + num indirect stages
@@ -116,55 +120,60 @@ impl GraphicsProcessor {
self.cur_num_tev_stages = stages;
self.cur_num_indirect_stages = indirect_stages;
self.konst_dirty = true;
+ self.frame_state_dirty = true;
renderer.exec(GxAction::SetCullMode(gen_mode.cull_mode()));
}
- // Indirect-matrix rows at 0x06..=0x0E. Each write lands in one
- // of the A, B, or C rows of one of three matrices.
- match idx {
- BP_IND_MTX_A0 => self.cur_indirect_matrices[0].a = val,
- BP_IND_MTX_B0 => self.cur_indirect_matrices[0].b = val,
- BP_IND_MTX_C0 => self.cur_indirect_matrices[0].c = val,
- BP_IND_MTX_A1 => self.cur_indirect_matrices[1].a = val,
- BP_IND_MTX_B1 => self.cur_indirect_matrices[1].b = val,
- BP_IND_MTX_C1 => self.cur_indirect_matrices[1].c = val,
- BP_IND_MTX_A2 => self.cur_indirect_matrices[2].a = val,
- BP_IND_MTX_B2 => self.cur_indirect_matrices[2].b = val,
- BP_IND_MTX_C2 => self.cur_indirect_matrices[2].c = val,
- _ => {}
+ // Indirect-matrix rows at 0x06..=0x0E
+ if (BP_IND_MTX_A0..=BP_IND_MTX_C2).contains(&idx) {
+ let off = idx - BP_IND_MTX_A0;
+ let mtx = &mut self.cur_indirect_matrices[off / 3];
+ match off % 3 {
+ 0 => mtx.a = val,
+ 1 => mtx.b = val,
+ _ => mtx.c = val,
+ }
+ self.frame_state_dirty = true;
}
// TODO: BumpIMask is captured for measure but never read on the
// GPU side. AFAICT it's unused. Dolphin agrees.
if idx == BP_BUMP_IMASK {
self.cur_bump_imask = val;
+ self.frame_state_dirty = true;
}
// Per TEV stage indirect commands at 0x10..=0x1F.
if idx >= BP_IND_CMD_0 && idx < BP_IND_CMD_0 + BP_IND_CMD_COUNT {
self.cur_tev_indirect[idx - BP_IND_CMD_0] = TevIndirect::from_raw(val);
+ self.frame_state_dirty = true;
}
// Indirect texcoord scale pair. SS0 covers indirect stages 0-1,
// SS1 covers 2-3.
if idx == BP_RAS1_SS0 {
self.cur_indirect_scales[0] = Ras1Ss::from_raw(val);
+ self.frame_state_dirty = true;
} else if idx == BP_RAS1_SS1 {
self.cur_indirect_scales[1] = Ras1Ss::from_raw(val);
+ self.frame_state_dirty = true;
}
if idx == BP_RAS1_IREF {
self.cur_indirect_refs = Ras1IRef::from_raw(val);
+ self.frame_state_dirty = true;
}
// TEV KSEL (constant color selection) registers: recalculate konst colors
if idx >= BP_TEV_KSEL_0 && idx <= BP_TEV_KSEL_0 + 7 {
self.konst_dirty = true;
+ self.frame_state_dirty = true;
}
// TEV color register writes also affect konst colors
if idx >= BP_TEV_REGISTERL_0 && idx <= BP_TEV_REGISTERL_0 + 7 {
self.konst_dirty = true;
+ self.frame_state_dirty = true;
}
// PE finish
diff --git a/crates/gecko/src/flipper/gx/draw.rs b/crates/gecko/src/flipper/gx/draw.rs
index 8ef67b0..325638e 100644
--- a/crates/gecko/src/flipper/gx/draw.rs
+++ b/crates/gecko/src/flipper/gx/draw.rs
@@ -1,9 +1,10 @@
use super::regs::*;
use chapa::BitEnum;
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone, Copy, Default)]
pub enum Primitive {
Quads,
+ #[default]
Triangles,
TriangleStrip,
TriangleFan,
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index 76af5c7..b096936 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::{DrawData, DrawVertex, GxAction, RenderSink};
+use crate::host::{DrawVertex, GxAction, RenderSink};
use crate::mmio::{Mmio, RamView};
use crate::system::SystemId;
use std::io::{Cursor, Read};
@@ -76,6 +76,14 @@ 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();
+ std::mem::swap(&mut boxed.vertices, &mut self.draw_vertices_scratch);
+
self.draw_vertices_scratch.clear();
self.draw_vertices_scratch.reserve(vertex_count);
@@ -124,29 +132,30 @@ impl GraphicsProcessor {
],
];
- renderer.exec(GxAction::Draw(DrawData {
- primitive,
- vertices: draw_vertices,
- modelview: modelview.0,
- tev_color_env: std::array::from_fn(|i| self.cur_tev_color_env[i].raw()),
- tev_alpha_env: std::array::from_fn(|i| self.cur_tev_alpha_env[i].raw()),
- tev_orders: std::array::from_fn(|i| tev_orders[i].raw()),
- tev_ksel: std::array::from_fn(|i| self.bp_regs[BP_TEV_KSEL_0 + i]),
- tev_color_regs,
- tev_konst_colors: self.cur_tev_konst_colors,
- num_tev_stages: self.cur_num_tev_stages,
- indirect_matrices,
- indirect_scales,
- indirect_refs: self.cur_indirect_refs.raw(),
- num_indirect_stages: self.cur_num_indirect_stages,
- bump_imask: self.cur_bump_imask,
- tev_indirect: std::array::from_fn(|i| self.cur_tev_indirect[i].raw()),
- color_ctrl: self.cached_color_ctrl,
- alpha_ctrl: self.cached_alpha_ctrl,
- ambient_color: self.cached_ambient_color,
- material_color: self.cached_material_color,
- lights: self.cached_lights,
- }));
+ boxed.primitive = primitive;
+ boxed.vertices = draw_vertices;
+ boxed.modelview = modelview.0;
+ boxed.tev_color_env = std::array::from_fn(|i| self.cur_tev_color_env[i].raw());
+ boxed.tev_alpha_env = std::array::from_fn(|i| self.cur_tev_alpha_env[i].raw());
+ boxed.tev_orders = std::array::from_fn(|i| tev_orders[i].raw());
+ boxed.tev_ksel = std::array::from_fn(|i| self.bp_regs[BP_TEV_KSEL_0 + i]);
+ boxed.tev_color_regs = tev_color_regs;
+ boxed.tev_konst_colors = self.cur_tev_konst_colors;
+ boxed.num_tev_stages = self.cur_num_tev_stages;
+ boxed.indirect_matrices = indirect_matrices;
+ boxed.indirect_scales = indirect_scales;
+ boxed.indirect_refs = self.cur_indirect_refs.raw();
+ boxed.num_indirect_stages = self.cur_num_indirect_stages;
+ boxed.bump_imask = self.cur_bump_imask;
+ boxed.tev_indirect = std::array::from_fn(|i| self.cur_tev_indirect[i].raw());
+ boxed.color_ctrl = self.cached_color_ctrl;
+ boxed.alpha_ctrl = self.cached_alpha_ctrl;
+ boxed.ambient_color = self.cached_ambient_color;
+ boxed.material_color = self.cached_material_color;
+ boxed.lights = self.cached_lights;
+ boxed.frame_dirty = self.frame_state_dirty;
+ self.frame_state_dirty = false;
+ renderer.exec(GxAction::Draw(boxed));
#[cfg(feature = "gx-stats")]
{
diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rs
index 21c2fb4..9054f42 100644
--- a/crates/gecko/src/flipper/gx/xf.rs
+++ b/crates/gecko/src/flipper/gx/xf.rs
@@ -143,6 +143,7 @@ impl GraphicsProcessor {
|| self::ranges_overlap(addr, end, XF_CHAN_CFG_BEGIN, XF_CHAN_CFG_END)
{
self.lighting_dirty = true;
+ self.frame_state_dirty = true;
}
}
@@ -198,6 +199,7 @@ impl GraphicsProcessor {
|| self::ranges_overlap(dst_addr, end, XF_CHAN_CFG_BEGIN, XF_CHAN_CFG_END)
{
self.lighting_dirty = true;
+ self.frame_state_dirty = true;
}
}
}
diff --git a/crates/gecko/src/gekko/jit/handlers.rs b/crates/gecko/src/gekko/jit/handlers.rs
index 9e27968..2249350 100644
--- a/crates/gecko/src/gekko/jit/handlers.rs
+++ b/crates/gecko/src/gekko/jit/handlers.rs
@@ -4,8 +4,8 @@ use cranelift_frontend::FunctionBuilder;
use crate::gekko::instruction::Instruction;
use crate::gekko::jit::translator::{
- self, AddmeSubfmeKind, AddzeSubfzeKind, CYCLES_PER_INSTR, ImmLogical, JitTranslator, LocalFuncs, LogicalFullOp,
- LogicalOp, MemSize, ShiftKind, TermEmit, vmctx_flags,
+ self, AddmeSubfmeKind, AddzeSubfzeKind, ImmLogical, JitTranslator, LocalFuncs, LogicalFullOp, LogicalOp, MemSize,
+ ShiftKind, TermEmit, vmctx_flags,
};
use crate::gekko::jit::{abi, lut};
use crate::system::SystemId;
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index 0b15592..67e0438 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -76,7 +76,7 @@ pub enum GxAction {
/// Issue a draw call. The renderer uses its tracked state (projection,
/// viewport, scissor, depth, blend, alpha, textures) plus the per-draw
/// TEV/lighting snapshot carried here.
- Draw(DrawData),
+ Draw(Box<DrawData>),
/// Copy the EFB source region to a temporary texture identified by `id`.
/// The renderer stores this until the next [`PresentXfb`] composites it
@@ -167,7 +167,7 @@ pub struct XfbPart {
/// Per-draw data: primitive type, decoded vertices, modelview transform,
/// and TEV/lighting configuration (snapshotted at draw time since TEV is
/// built up incrementally via BP writes).
-#[derive(Debug)]
+#[derive(Debug, Default)]
pub struct DrawData {
pub primitive: Primitive,
pub vertices: Vec<DrawVertex>,
@@ -196,6 +196,7 @@ pub struct DrawData {
pub ambient_color: [[f32; 4]; 2],
pub material_color: [[f32; 4]; 2],
pub lights: [LightData; 8],
+ pub frame_dirty: bool,
}
/// Per-vertex data after decode, ready for the renderer.
@@ -246,5 +247,8 @@ pub trait RenderSink: Send {
pub struct EmptyRenderSink;
impl RenderSink for EmptyRenderSink {
- fn exec(&mut self, _: GxAction) {}
+ fn exec(&mut self, _action: GxAction) {
+ #[cfg(feature = "rendersink-blackbox")]
+ std::hint::black_box(&_action);
+ }
}
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index fb431bf..2876587 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -302,7 +302,8 @@ fn run<const SYSTEM: SystemId>(
let renderer = backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format, target_aspect);
- emulator.render_sink = Box::new(renderer.clone());
+ emulator.gx.draw_box_recycle_rx = renderer.take_recycle_rx();
+ emulator.render_sink = Box::new(renderer.take_batching_sink());
#[cfg(feature = "efb-writeback")]
{
diff --git a/crates/tinybench/Cargo.toml b/crates/tinybench/Cargo.toml
index 7d2a7ac..72c22d3 100644
--- a/crates/tinybench/Cargo.toml
+++ b/crates/tinybench/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[features]
-default = []
+default = ["gecko/rendersink-blackbox"]
jit-stats = ["gecko/jit-stats"]
[dependencies]
diff --git a/crates/tinybench/src/bin/wii_bench.rs b/crates/tinybench/src/bin/wii_bench.rs
index 9b29e4f..de5b667 100644
--- a/crates/tinybench/src/bin/wii_bench.rs
+++ b/crates/tinybench/src/bin/wii_bench.rs
@@ -154,9 +154,7 @@ fn run_bench(emulator: &mut Wii, args: &Args) {
}
}
- let measure_dur = measure_start
- .map(|s| s.elapsed().as_secs_f64())
- .unwrap_or(0.0);
+ let measure_dur = measure_start.map(|s| s.elapsed().as_secs_f64()).unwrap_or(0.0);
let avg_fps = if measure_dur > 0.0 {
measured_frames as f64 / measure_dur
} else {