Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

first milestone of rewrite

Layle71e3304dfef2
diff --git a/Cargo.lock b/Cargo.lock
index 7bcc4b0..73ef766 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -232,9 +232,11 @@ name = "backend-wgpu"
version = "0.1.0"
dependencies = [
"bytemuck",
+ "crossbeam-channel",
"encase",
"gecko",
"glam",
+ "tracing",
"wesl",
"wgpu",
]
@@ -584,16 +586,6 @@ dependencies = [
"crossbeam-utils",
]
-[[package]]
-name = "console_error_panic_hook"
-version = "0.1.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
-dependencies = [
- "cfg-if",
- "wasm-bindgen",
-]
-
[[package]]
name = "const_panic"
version = "0.2.15"
@@ -751,38 +743,6 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
-[[package]]
-name = "dbglib"
-version = "0.1.0"
-dependencies = [
- "backend-wgpu",
- "disasm",
- "egui",
- "egui-phosphor",
- "gecko",
- "image 0.1.0",
-]
-
-[[package]]
-name = "debugger"
-version = "0.1.0"
-dependencies = [
- "backend-wgpu",
- "clap",
- "dbglib",
- "egui",
- "egui-phosphor",
- "egui-wgpu",
- "egui-winit",
- "gecko",
- "image 0.1.0",
- "pollster",
- "scripting",
- "tracing-subscriber",
- "wgpu",
- "winit",
-]
-
[[package]]
name = "derive_more"
version = "2.1.1"
@@ -924,15 +884,6 @@ dependencies = [
"unicode-segmentation",
]
-[[package]]
-name = "egui-phosphor"
-version = "0.11.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3b2838620355debaeb7fa3cc331a1d8ab77e6387d40e65686fa468c229dbf63"
-dependencies = [
- "egui",
-]
-
[[package]]
name = "egui-wgpu"
version = "0.33.3"
@@ -1178,9 +1129,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
-version = "0.11.1"
+version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73829a7b5c91198af28a99159b7ae4afbb252fb906159ff7f189f3a2ceaa3df2"
+checksum = "2d9237c6d82152100c691fb77ea18037b402bcc7257d2c876a4ffac81bc22a1c"
dependencies = [
"bytemuck",
]
@@ -1279,8 +1230,10 @@ dependencies = [
name = "gecko"
version = "0.1.0"
dependencies = [
+ "bytemuck",
"chapa",
"chipi-build",
+ "glam",
"image 0.1.0",
"tracing",
]
@@ -1334,6 +1287,7 @@ version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
dependencies = [
+ "bytemuck",
"encase",
]
@@ -3853,26 +3807,6 @@ dependencies = [
"pkg-config",
]
-[[package]]
-name = "web"
-version = "0.1.0"
-dependencies = [
- "backend-wgpu",
- "console_error_panic_hook",
- "dbglib",
- "egui",
- "egui-phosphor",
- "egui-wgpu",
- "egui-winit",
- "gecko",
- "image 0.1.0",
- "wasm-bindgen",
- "wasm-bindgen-futures",
- "web-sys",
- "wgpu",
- "winit",
-]
-
[[package]]
name = "web-sys"
version = "0.3.94"
@@ -4001,7 +3935,6 @@ dependencies = [
"thiserror 2.0.18",
"wgpu-core-deps-apple",
"wgpu-core-deps-emscripten",
- "wgpu-core-deps-wasm",
"wgpu-core-deps-windows-linux-android",
"wgpu-hal",
"wgpu-types",
@@ -4025,15 +3958,6 @@ dependencies = [
"wgpu-hal",
]
-[[package]]
-name = "wgpu-core-deps-wasm"
-version = "28.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12a2cf578ce8d7d50d0e63ddc2345c7dcb599f6eb90b888813406ea78b9b7010"
-dependencies = [
- "wgpu-hal",
-]
-
[[package]]
name = "wgpu-core-deps-windows-linux-android"
version = "28.0.0"
diff --git a/Cargo.toml b/Cargo.toml
index 76ad98c..408b303 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,14 +9,11 @@ members = [
"crates/image",
"crates/tinyapp",
"crates/backend-wgpu",
- "crates/dbglib",
- "crates/debugger",
"crates/scripting",
"crates/dspemu",
-
+
# Stuff we rarely use
"crates/dsptestrunner",
- "crates/web",
]
default-members = [
"crates/gctool",
@@ -27,12 +24,21 @@ default-members = [
"crates/image",
"crates/tinyapp",
"crates/backend-wgpu",
- "crates/dbglib",
- "crates/debugger",
"crates/scripting",
"crates/dspemu",
]
+# TODO: DO THESE BEFORE MASTER MERGE
+exclude = [
+ # Web targets WebGL; the new renderer uses wgpu features that GLES
+ # does not expose. Needs a separate fallback renderer.
+ "crates/web",
+
+ # Temporarily excluded. These need a egui/dbglib rewrite.
+ "crates/dbglib",
+ "crates/debugger",
+]
+
[patch.crates-io]
egui = { git = "https://github.com/ioncodes/egui.git" }
epaint = { git = "https://github.com/ioncodes/egui.git" }
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.toml
index cc3c056..9c13a3b 100644
--- a/crates/backend-wgpu/Cargo.toml
+++ b/crates/backend-wgpu/Cargo.toml
@@ -10,6 +10,8 @@ gecko = { path = "../gecko" }
wesl = "0.3.2"
encase = "0.12.0"
glam = { version = "0.32.1", features = ["encase"] }
+crossbeam-channel = "0.5.15"
+tracing = "0.1.44"
[build-dependencies]
wesl = "0.3.2"
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
new file mode 100644
index 0000000..7fcb204
--- /dev/null
+++ b/crates/backend-wgpu/src/action.rs
@@ -0,0 +1,515 @@
+use crate::pipeline::PipelineKey;
+use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GxRenderer, helpers, texture};
+use crate::{GpuVertex, align_up};
+use encase::{ShaderType as _, UniformBuffer};
+use gecko::flipper::gx::draw::TextureDescriptor;
+use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
+use gecko::host::{DrawData, GxAction};
+use glam::{Mat4, UVec4, Vec4};
+
+fn pack_u32_slice_to_uvec4x4(data: &[u32]) -> [UVec4; 4] {
+ let get = |i: usize| if i < data.len() { data[i] } else { 0 };
+ [
+ UVec4::new(get(0), get(1), get(2), get(3)),
+ UVec4::new(get(4), get(5), get(6), get(7)),
+ UVec4::new(get(8), get(9), get(10), get(11)),
+ UVec4::new(get(12), get(13), get(14), get(15)),
+ ]
+}
+
+impl GxRenderer {
+ fn current_pipeline_key(&self) -> PipelineKey {
+ let blend = self.current_blend_mode;
+ let zmode = self.current_zmode;
+ PipelineKey {
+ blend_enable: blend.blend_enable(),
+ src_factor: blend.src_factor(),
+ dst_factor: blend.dst_factor(),
+ subtract: blend.subtract(),
+ z_enable: zmode.enable(),
+ z_func: zmode.func(),
+ z_write: zmode.update_enable(),
+ color_update: blend.color_update(),
+ alpha_update: blend.alpha_update(),
+ }
+ }
+
+ /// Build a bind-group cache key from the current tracked textures.
+ fn current_bind_group_key(&self) -> BindGroupCacheKey {
+ let mut tex_keys = [None; 8];
+ let mut sampler_keys = [None; 8];
+ for slot in 0..8 {
+ if let Some(desc) = &self.current_textures[slot] {
+ tex_keys[slot] = Some((desc.ram_addr, desc.width, desc.height, desc.format));
+ sampler_keys[slot] = Some((desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter));
+ }
+ }
+ BindGroupCacheKey { tex_keys, sampler_keys }
+ }
+
+ /// Process a batch of [`GxAction`] values, rendering draw calls into the
+ /// internal EFB and handling EFB copies / XFB presentation.
+ pub fn render_actions(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, actions: &[GxAction], ram: &[u8]) {
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+
+ let draw_stride = self.draw_uniform_stride as usize;
+ let draw_encase_size = DrawUniforms::min_size().get() as usize;
+ let frame_stride = align_up(
+ FrameUniforms::min_size().get(),
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize;
+ let frame_encase_size = FrameUniforms::min_size().get() as usize;
+ let mut frame_uniform_bytes: Vec<u8> = Vec::new();
+
+ // Per-draw snapshots of pipeline key + bind group key (captured at draw time
+ // from the current tracked state).
+ let mut draw_pipeline_keys: Vec<PipelineKey> = Vec::new();
+ let mut draw_bg_keys: Vec<BindGroupCacheKey> = Vec::new();
+ // Per-draw viewport/scissor snapshots (captured from tracked state at draw time).
+ let mut draw_viewports: Vec<gecko::flipper::gx::draw::Viewport> = Vec::new();
+ let mut draw_scissors: Vec<gecko::flipper::gx::draw::Scissor> = Vec::new();
+
+ for action in actions {
+ match action {
+ GxAction::SetProjection { matrix, .. } => {
+ self.current_projection = Mat4::from_cols_array_2d(matrix);
+ }
+ GxAction::SetViewport(vp) => {
+ self.current_viewport = *vp;
+ }
+ GxAction::SetScissor(sc) => {
+ self.current_scissor = *sc;
+ }
+ GxAction::SetDepthMode(zm) => {
+ self.current_zmode = *zm;
+ }
+ GxAction::SetBlendMode(bm) => {
+ self.current_blend_mode = *bm;
+ }
+ GxAction::SetAlphaCompare(ac) => {
+ self.current_alpha_compare = *ac;
+ }
+ GxAction::SetTexture { slot, descriptor } => {
+ self.current_textures[*slot] = Some(*descriptor);
+ }
+
+ GxAction::Draw(draw) => {
+ // Copy tracked textures to avoid borrow conflict with &mut self.
+ let tex_snapshot = self.current_textures;
+ for desc in tex_snapshot.iter().flatten() {
+ self.ensure_texture(device, queue, ram, desc);
+ self.ensure_sampler(device, desc);
+ }
+
+ // Ensure pipeline for current tracked blend/depth state.
+ let pipeline_key = self.current_pipeline_key();
+ if !self.pipeline_cache.contains_key(&pipeline_key) {
+ let pipeline = self.create_pipeline(device, &pipeline_key);
+ self.pipeline_cache.insert(pipeline_key, pipeline);
+ }
+
+ // Triangulate.
+ let prev_len = self.scratch_vertices.len();
+ triangulate_draw_data(draw, &mut self.scratch_vertices);
+ let added = self.scratch_vertices.len() - prev_len;
+ if added == 0 {
+ continue;
+ }
+
+ // Build per-draw uniform (MVP) using tracked projection.
+ let modelview = Mat4::from_cols_array_2d(&draw.modelview);
+ let mvp = self.current_projection * modelview;
+ let draw_uniform = DrawUniforms { mvp };
+
+ 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),
+ 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,
+ 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.scratch_draws.len() * frame_stride;
+ frame_uniform_bytes.resize(fstart + frame_stride, 0);
+ let mut frame_buf =
+ UniformBuffer::new(&mut frame_uniform_bytes[fstart..fstart + frame_encase_size]);
+ frame_buf.write(&frame_uniform).unwrap();
+
+ // Snapshot tracked state for this draw.
+ draw_pipeline_keys.push(pipeline_key);
+ draw_bg_keys.push(self.current_bind_group_key());
+ draw_viewports.push(self.current_viewport);
+ draw_scissors.push(self.current_scissor);
+
+ self.scratch_draws.push((prev_len as u32, added as u32));
+ }
+
+ GxAction::CopyEfb(copy) => {
+ // Flush pending draws before the copy.
+ if !self.scratch_draws.is_empty() {
+ self.upload_buffers(device, queue, &frame_uniform_bytes);
+ self.execute_action_render_pass(
+ device,
+ queue,
+ &draw_pipeline_keys,
+ &draw_bg_keys,
+ &draw_viewports,
+ &draw_scissors,
+ );
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+ frame_uniform_bytes.clear();
+ draw_pipeline_keys.clear();
+ draw_bg_keys.clear();
+ draw_viewports.clear();
+ draw_scissors.clear();
+ }
+
+ self.execute_efb_copy(device, queue, copy);
+ }
+
+ GxAction::CopyXfb {
+ id,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear,
+ clear_color,
+ clear_z,
+ } => {
+ if !self.scratch_draws.is_empty() {
+ self.upload_buffers(device, queue, &frame_uniform_bytes);
+ self.execute_action_render_pass(
+ device,
+ queue,
+ &draw_pipeline_keys,
+ &draw_bg_keys,
+ &draw_viewports,
+ &draw_scissors,
+ );
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+ frame_uniform_bytes.clear();
+ draw_pipeline_keys.clear();
+ draw_bg_keys.clear();
+ draw_viewports.clear();
+ draw_scissors.clear();
+ }
+
+ self.execute_copy_xfb(
+ device,
+ queue,
+ *id,
+ *src_x,
+ *src_y,
+ *src_w,
+ *src_h,
+ *clear,
+ *clear_color,
+ *clear_z,
+ );
+ }
+
+ GxAction::PresentXfb { width, height, parts } => {
+ // Flush any trailing draws.
+ if !self.scratch_draws.is_empty() {
+ self.upload_buffers(device, queue, &frame_uniform_bytes);
+ self.execute_action_render_pass(
+ device,
+ queue,
+ &draw_pipeline_keys,
+ &draw_bg_keys,
+ &draw_viewports,
+ &draw_scissors,
+ );
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+ frame_uniform_bytes.clear();
+ draw_pipeline_keys.clear();
+ draw_bg_keys.clear();
+ draw_viewports.clear();
+ draw_scissors.clear();
+ }
+
+ self.execute_present_xfb(device, queue, *width, *height, parts);
+ }
+ }
+ }
+
+ // Flush remaining draws.
+ if !self.scratch_draws.is_empty() {
+ self.upload_buffers(device, queue, &frame_uniform_bytes);
+ self.execute_action_render_pass(
+ device,
+ queue,
+ &draw_pipeline_keys,
+ &draw_bg_keys,
+ &draw_viewports,
+ &draw_scissors,
+ );
+ }
+ }
+
+ /// Render pass for streamed action draws.
+ fn execute_action_render_pass(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ pipeline_keys: &[PipelineKey],
+ bg_keys: &[BindGroupCacheKey],
+ viewports: &[gecko::flipper::gx::draw::Viewport],
+ scissors: &[gecko::flipper::gx::draw::Scissor],
+ ) {
+ let target_width = crate::EFB_WIDTH;
+ let target_height = crate::EFB_HEIGHT;
+ let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
+ let frame_stride = align_up(
+ FrameUniforms::min_size().get(),
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize;
+
+ // Pre-build bind groups from tracked texture snapshots.
+ for bg_key in bg_keys {
+ self.bind_group_cache.entry(bg_key.clone()).or_insert_with(|| {
+ let mut tex_views: [&wgpu::TextureView; 8] = [&self.fallback_view; 8];
+ let mut tex_samplers: [&wgpu::Sampler; 8] = [&self.sampler_cache[&fallback_sampler_key]; 8];
+
+ for slot in 0..8 {
+ if let Some(tk) = &bg_key.tex_keys[slot] {
+ if let Some((_, view)) = self.texture_cache.get(tk) {
+ tex_views[slot] = view;
+ }
+ if let Some(sk) = &bg_key.sampler_keys[slot] {
+ if let Some(sampler) = self.sampler_cache.get(sk) {
+ tex_samplers[slot] = sampler;
+ }
+ }
+ }
+ }
+
+ let entries: [wgpu::BindGroupEntry; 18] = std::array::from_fn(|i| match i {
+ 0 => wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.frame_uniform_buffer,
+ offset: 0,
+ size: Some(FrameUniforms::min_size()),
+ }),
+ },
+ 1 => wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
+ buffer: &self.draw_uniform_buffer,
+ offset: 0,
+ size: Some(DrawUniforms::min_size()),
+ }),
+ },
+ 2..=9 => wgpu::BindGroupEntry {
+ binding: i as u32,
+ resource: wgpu::BindingResource::TextureView(tex_views[i - 2]),
+ },
+ _ => wgpu::BindGroupEntry {
+ binding: i as u32,
+ resource: wgpu::BindingResource::Sampler(tex_samplers[i - 10]),
+ },
+ });
+
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &self.bind_group_layout,
+ entries: &entries,
+ })
+ });
+ }
+
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let needs_initial_clear = self.efb_needs_clear;
+ self.efb_needs_clear = false;
+ let color_load = if needs_initial_clear {
+ wgpu::LoadOp::Clear(wgpu::Color::BLACK)
+ } else {
+ wgpu::LoadOp::Load
+ };
+ let depth_load = if needs_initial_clear {
+ wgpu::LoadOp::Clear(1.0)
+ } else {
+ wgpu::LoadOp::Load
+ };
+
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("gx_action_render_pass"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: &self.efb_msaa_view,
+ resolve_target: Some(&self.efb_view),
+ ops: wgpu::Operations {
+ load: color_load,
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
+ view: &self.efb_depth_view,
+ depth_ops: Some(wgpu::Operations {
+ load: depth_load,
+ store: wgpu::StoreOp::Store,
+ }),
+ stencil_ops: None,
+ }),
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+
+ for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate() {
+ let pipeline_key = &pipeline_keys[index];
+ let pipeline = &self.pipeline_cache[pipeline_key];
+ rpass.set_pipeline(pipeline);
+
+ let bg_key = &bg_keys[index];
+ let bind_group = &self.bind_group_cache[bg_key];
+
+ let frame_offset = (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]);
+
+ // TODO: verify?
+ let vp = &viewports[index];
+ let vp_w = vp.w.max(1.0);
+ let vp_h = vp.h.max(1.0);
+ rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);
+
+ let sc = &scissors[index];
+ let sc_w = sc.w.max(1).min(target_width.saturating_sub(sc.x));
+ let sc_h = sc.h.max(1).min(target_height.saturating_sub(sc.y));
+ rpass.set_scissor_rect(sc.x, sc.y, sc_w, sc_h);
+
+ rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);
+ }
+ }
+
+ queue.submit([encoder.finish()]);
+ }
+
+ fn ensure_texture(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ram: &[u8], desc: &TextureDescriptor) {
+ let key = (desc.ram_addr, desc.width, desc.height, desc.format);
+ self.texture_cache
+ .entry(key)
+ .or_insert_with(|| texture::upload_texture(device, queue, ram, desc));
+ }
+
+ fn ensure_sampler(&mut self, device: &wgpu::Device, desc: &TextureDescriptor) {
+ let key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
+ self.sampler_cache.entry(key).or_insert_with(|| {
+ device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("gx_sampler"),
+ address_mode_u: helpers::map_wrap_mode(key.0),
+ address_mode_v: helpers::map_wrap_mode(key.1),
+ mag_filter: helpers::map_mag_filter(key.2),
+ min_filter: helpers::map_min_filter(key.3),
+ ..Default::default()
+ })
+ });
+ }
+}
+
+/// Triangulate a [`DrawData`] into GPU vertices.
+fn triangulate_draw_data(draw: &DrawData, out: &mut Vec<GpuVertex>) {
+ use gecko::flipper::gx::draw::Primitive;
+
+ let verts = &draw.vertices;
+ let to_gpu = |v: &gecko::host::DrawVertex| -> GpuVertex {
+ GpuVertex {
+ position: v.position,
+ color: v.color0,
+ color1: v.color1,
+ normal: v.normal,
+ pos_view: v.pos_view,
+ tex0: v.texcoords[0],
+ tex1: v.texcoords[1],
+ tex2: v.texcoords[2],
+ tex3: v.texcoords[3],
+ tex4: v.texcoords[4],
+ tex5: v.texcoords[5],
+ tex6: v.texcoords[6],
+ tex7: v.texcoords[7],
+ }
+ };
+
+ match draw.primitive {
+ Primitive::Triangles => {
+ out.extend(verts.iter().map(to_gpu));
+ }
+ Primitive::Quads => {
+ for quad in verts.chunks(4) {
+ if quad.len() < 4 {
+ continue;
+ }
+ out.push(to_gpu(&quad[0]));
+ out.push(to_gpu(&quad[1]));
+ out.push(to_gpu(&quad[2]));
+ out.push(to_gpu(&quad[0]));
+ out.push(to_gpu(&quad[2]));
+ out.push(to_gpu(&quad[3]));
+ }
+ }
+ Primitive::TriangleStrip => {
+ for i in 2..verts.len() {
+ if i % 2 == 0 {
+ out.push(to_gpu(&verts[i - 2]));
+ out.push(to_gpu(&verts[i - 1]));
+ out.push(to_gpu(&verts[i]));
+ } else {
+ out.push(to_gpu(&verts[i - 1]));
+ out.push(to_gpu(&verts[i - 2]));
+ out.push(to_gpu(&verts[i]));
+ }
+ }
+ }
+ Primitive::TriangleFan => {
+ for i in 2..verts.len() {
+ out.push(to_gpu(&verts[0]));
+ out.push(to_gpu(&verts[i - 1]));
+ out.push(to_gpu(&verts[i]));
+ }
+ }
+ _ => {
+ tracing::error!(?draw.primitive, "triangulate: skipping unsupported primitive");
+ }
+ }
+}
diff --git a/crates/backend-wgpu/src/clear.rs b/crates/backend-wgpu/src/clear.rs
new file mode 100644
index 0000000..9f266b1
--- /dev/null
+++ b/crates/backend-wgpu/src/clear.rs
@@ -0,0 +1,185 @@
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct ClearUniforms {
+ color: [f32; 4],
+ depth: f32,
+ _pad: [f32; 3],
+}
+
+pub(crate) struct EfbClear {
+ pipeline: wgpu::RenderPipeline,
+ bind_group_layout: wgpu::BindGroupLayout,
+ uniform_buffer: wgpu::Buffer,
+ bind_group: wgpu::BindGroup,
+}
+
+impl EfbClear {
+ pub fn new(
+ device: &wgpu::Device,
+ color_format: wgpu::TextureFormat,
+ depth_format: wgpu::TextureFormat,
+ sample_count: u32,
+ ) -> Self {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("efb_clear_shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/clear.wgsl").into()),
+ });
+
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("efb_clear_bgl"),
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+
+ let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some("efb_clear_layout"),
+ bind_group_layouts: &[&bind_group_layout],
+ immediate_size: 0,
+ });
+
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("efb_clear_pipeline"),
+ layout: Some(&layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: color_format,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: Some(wgpu::DepthStencilState {
+ format: depth_format,
+ depth_write_enabled: true,
+ depth_compare: wgpu::CompareFunction::Always,
+ stencil: wgpu::StencilState::default(),
+ bias: wgpu::DepthBiasState::default(),
+ }),
+ multisample: wgpu::MultisampleState {
+ count: sample_count,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
+ multiview_mask: None,
+ cache: None,
+ });
+
+ let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("efb_clear_uniforms"),
+ size: std::mem::size_of::<ClearUniforms>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("efb_clear_bg"),
+ layout: &bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ }],
+ });
+
+ EfbClear {
+ pipeline,
+ bind_group_layout,
+ uniform_buffer,
+ bind_group,
+ }
+ }
+
+ /// Clear a rectangular region of `(color_view, depth_view)` to the given
+ /// color and depth. Areas outside the rect are preserved.
+ pub fn clear_region(
+ &self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ msaa_color_view: &wgpu::TextureView,
+ resolve_color_view: &wgpu::TextureView,
+ depth_view: &wgpu::TextureView,
+ target_width: u32,
+ target_height: u32,
+ x: u32,
+ y: u32,
+ w: u32,
+ h: u32,
+ color: [f32; 4],
+ depth: f32,
+ ) {
+ if w == 0 || h == 0 {
+ return;
+ }
+ let x = x.min(target_width);
+ let y = y.min(target_height);
+ let w = w.min(target_width.saturating_sub(x));
+ let h = h.min(target_height.saturating_sub(y));
+ if w == 0 || h == 0 {
+ return;
+ }
+
+ let uniforms = ClearUniforms {
+ color,
+ depth,
+ _pad: [0.0; 3],
+ };
+ queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&uniforms));
+
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("efb_clear_region"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: msaa_color_view,
+ resolve_target: Some(resolve_color_view),
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
+ view: depth_view,
+ depth_ops: Some(wgpu::Operations {
+ load: wgpu::LoadOp::Load,
+ store: wgpu::StoreOp::Store,
+ }),
+ stencil_ops: None,
+ }),
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+
+ rpass.set_pipeline(&self.pipeline);
+ rpass.set_bind_group(0, &self.bind_group, &[]);
+ rpass.set_scissor_rect(x, y, w, h);
+ rpass.draw(0..3, 0..1);
+ }
+ queue.submit([encoder.finish()]);
+ }
+
+ #[allow(dead_code)]
+ pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout {
+ &self.bind_group_layout
+ }
+}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 407bf3e..ff669f0 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -1,15 +1,40 @@
+mod action;
+mod clear;
mod helpers;
mod pipeline;
mod render;
+pub mod sink;
pub mod texture;
-mod triangulate;
use encase::ShaderType as _;
use gecko::flipper::gx::draw::TextureFormat;
-use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
+use gecko::flipper::gx::draw::{Scissor, TextureDescriptor, Viewport};
+use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, MagFilter, MinFilter, WrapMode, ZMode};
+use glam::Mat4;
use pipeline::PipelineKey;
use std::collections::HashMap;
-use triangulate::{GpuVertex, align_up};
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+pub(crate) struct GpuVertex {
+ pub position: [f32; 3],
+ pub color: [f32; 4],
+ pub color1: [f32; 4],
+ pub normal: [f32; 3],
+ pub pos_view: [f32; 3],
+ pub tex0: [f32; 2],
+ pub tex1: [f32; 2],
+ pub tex2: [f32; 2],
+ pub tex3: [f32; 2],
+ pub tex4: [f32; 2],
+ pub tex5: [f32; 2],
+ pub tex6: [f32; 2],
+ pub tex7: [f32; 2],
+}
+
+pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
+ (value + alignment - 1) & !(alignment - 1)
+}
type TexKey = (usize, u32, u32, TextureFormat);
type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter);
@@ -38,10 +63,14 @@ pub(crate) struct FrameUniforms {
light_distatt: [glam::Vec4; 8],
light_pos: [glam::Vec4; 8],
light_dir: [glam::Vec4; 8],
- color_ctrl: u32,
- alpha_ctrl: u32,
- ambient_color: glam::Vec4,
- material_color: glam::Vec4,
+ 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,
}
#[derive(encase::ShaderType)]
@@ -52,7 +81,8 @@ pub(crate) struct DrawUniforms {
const SHADER: &str = wesl::include_wesl!("gx_shader");
pub const EFB_WIDTH: u32 = 640;
-pub const EFB_HEIGHT: u32 = 480;
+pub const EFB_HEIGHT: u32 = 528;
+pub const EFB_SAMPLE_COUNT: u32 = 4;
pub struct GxRenderer {
pub(crate) pipeline_cache: HashMap<PipelineKey, wgpu::RenderPipeline>,
@@ -66,9 +96,13 @@ pub struct GxRenderer {
pub(crate) draw_uniform_capacity: usize,
pub(crate) vertex_buffer: wgpu::Buffer,
pub(crate) vertex_capacity: usize,
+ // EFB: resolved (1x) color used for CopyXfb reads + texture binding.
pub(crate) efb_texture: wgpu::Texture,
pub(crate) efb_view: wgpu::TextureView,
- pub(crate) efb_depth_texture: wgpu::Texture,
+ // EFB: multisampled (4x) color, actual render target for draws.
+ pub(crate) _efb_msaa_texture: wgpu::Texture,
+ pub(crate) efb_msaa_view: wgpu::TextureView,
+ // EFB: multisampled (4x) depth.
pub(crate) efb_depth_view: wgpu::TextureView,
pub(crate) efb_needs_clear: bool,
pub(crate) sampler_cache: HashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
@@ -78,14 +112,30 @@ pub struct GxRenderer {
pub(crate) scratch_draws: Vec<(u32, u32)>,
pub(crate) scratch_uniform_bytes: Vec<u8>,
pub(crate) bind_group_cache: HashMap<BindGroupCacheKey, wgpu::BindGroup>,
+ // Tracked GX state (updated by state-change actions)
+ pub(crate) current_projection: Mat4,
+ pub(crate) current_viewport: Viewport,
+ pub(crate) current_scissor: Scissor,
+ pub(crate) current_zmode: ZMode,
+ pub(crate) current_blend_mode: BlendMode,
+ pub(crate) current_alpha_compare: AlphaCompare,
+ pub(crate) current_textures: [Option<TextureDescriptor>; 8],
+ // Blit pipeline (EFB -> swapchain)
+ pub(crate) blit_pipeline: wgpu::RenderPipeline,
+ pub(crate) blit_bind_group_layout: wgpu::BindGroupLayout,
+ pub(crate) blit_sampler: wgpu::Sampler,
+ // XFB output texture: composited from per-copy snapshots by PresentXfb.
+ pub(crate) xfb_texture: wgpu::Texture,
+ pub(crate) xfb_view: wgpu::TextureView,
+ pub(crate) xfb_has_content: bool,
+ // Per-copy temporary textures stored by CopyXfb, composited by PresentXfb.
+ pub(crate) xfb_copies: HashMap<u32, (wgpu::Texture, wgpu::TextureView)>,
+ // Region-scoped EFB clear.
+ pub(crate) efb_clear: clear::EfbClear,
}
impl GxRenderer {
- pub fn new(
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- surface_format: wgpu::TextureFormat,
- ) -> Self {
+ 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 draw_uniform_stride = align_up(
@@ -185,7 +235,7 @@ impl GxRenderer {
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
@@ -213,9 +263,10 @@ impl GxRenderer {
mapped_at_creation: false,
});
- // Create fixed-size EFB
+ // Create fixed-size EFB with 4x MSAA.
+ // Resolved (1x) color: CopyXfb reads from here.
let efb_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("efb_color"),
+ label: Some("efb_color_resolved"),
size: wgpu::Extent3d {
width: EFB_WIDTH,
height: EFB_HEIGHT,
@@ -227,12 +278,29 @@ impl GxRenderer {
format: surface_format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC
- | wgpu::TextureUsages::COPY_DST
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let efb_view = efb_texture.create_view(&Default::default());
+ // Multisampled (4x) color: actual render target for draws.
+ let efb_msaa_texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("efb_color_msaa"),
+ size: wgpu::Extent3d {
+ width: EFB_WIDTH,
+ height: EFB_HEIGHT,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: EFB_SAMPLE_COUNT,
+ dimension: wgpu::TextureDimension::D2,
+ format: surface_format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ let efb_msaa_view = efb_msaa_texture.create_view(&Default::default());
+
+ // Multisampled (4x) depth.
let efb_depth_texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("efb_depth"),
size: wgpu::Extent3d {
@@ -241,7 +309,7 @@ impl GxRenderer {
depth_or_array_layers: 1,
},
mip_level_count: 1,
- sample_count: 1,
+ sample_count: EFB_SAMPLE_COUNT,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Depth24Plus,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
@@ -249,6 +317,99 @@ impl GxRenderer {
});
let efb_depth_view = efb_depth_texture.create_view(&Default::default());
+ // XFB accumulation texture. Holds the composited output of all
+ // CopyEfb(copy_to_xfb) ops for the current frame.
+ let xfb_texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("xfb_accum"),
+ size: wgpu::Extent3d {
+ width: EFB_WIDTH,
+ height: EFB_HEIGHT,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: surface_format,
+ usage: wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ let xfb_view = xfb_texture.create_view(&Default::default());
+
+ // Blit pipeline EFB -> swapchain shit
+ 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()),
+ });
+ let blit_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("efb_blit_bg_layout"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+ let blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&blit_bind_group_layout],
+ immediate_size: 0,
+ });
+ let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("efb_blit_pipeline"),
+ layout: Some(&blit_layout),
+ vertex: wgpu::VertexState {
+ module: &blit_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &blit_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: surface_format,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
+ let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("efb_blit_sampler"),
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+
+ let efb_clear = clear::EfbClear::new(
+ device,
+ surface_format,
+ wgpu::TextureFormat::Depth24Plus,
+ EFB_SAMPLE_COUNT,
+ );
+
GxRenderer {
pipeline_cache: HashMap::new(),
shader,
@@ -263,7 +424,8 @@ impl GxRenderer {
vertex_capacity: initial_capacity,
efb_texture,
efb_view,
- efb_depth_texture,
+ _efb_msaa_texture: efb_msaa_texture,
+ efb_msaa_view,
efb_depth_view,
efb_needs_clear: true,
sampler_cache: HashMap::from([(
@@ -276,7 +438,23 @@ impl GxRenderer {
scratch_draws: Vec::new(),
scratch_uniform_bytes: Vec::new(),
bind_group_cache: HashMap::new(),
+ current_projection: Mat4::IDENTITY,
+ current_viewport: Viewport::default(),
+ current_scissor: Scissor::default(),
+ current_zmode: ZMode::default(),
+ current_blend_mode: BlendMode::from_raw(0).with_color_update(true).with_alpha_update(true),
+ current_alpha_compare: AlphaCompare::from_raw(0)
+ .with_comp0(CompareFunc::Always)
+ .with_comp1(CompareFunc::Always),
+ current_textures: Default::default(),
+ blit_pipeline,
+ blit_bind_group_layout,
+ blit_sampler,
+ xfb_texture,
+ xfb_view,
+ xfb_has_content: false,
+ xfb_copies: HashMap::new(),
+ efb_clear,
}
}
-
}
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
index 149c472..0a4ae03 100644
--- a/crates/backend-wgpu/src/pipeline.rs
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -1,6 +1,5 @@
-use crate::triangulate::GpuVertex;
+use crate::GpuVertex;
use crate::{GxRenderer, helpers};
-use gecko::flipper::gx::draw::DrawCall;
use gecko::flipper::gx::regs::{BlendFactor, CompareFunc};
#[derive(Clone, Copy, Hash, PartialEq, Eq)]
@@ -16,24 +15,6 @@ pub(crate) struct PipelineKey {
pub alpha_update: bool,
}
-impl PipelineKey {
- pub fn from_draw_call(dc: &DrawCall) -> Self {
- let blend = dc.bp_blend_mode;
- let zmode = dc.bp_zmode;
- PipelineKey {
- blend_enable: blend.blend_enable(),
- src_factor: blend.src_factor(),
- dst_factor: blend.dst_factor(),
- subtract: blend.subtract(),
- z_enable: zmode.enable(),
- z_func: zmode.func(),
- z_write: zmode.update_enable(),
- color_update: blend.color_update(),
- alpha_update: blend.alpha_update(),
- }
- }
-}
-
impl GxRenderer {
pub(crate) fn create_pipeline(&self, device: &wgpu::Device, key: &PipelineKey) -> wgpu::RenderPipeline {
let vertex_layout = wgpu::VertexBufferLayout {
@@ -180,7 +161,11 @@ impl GxRenderer {
..Default::default()
},
depth_stencil,
- multisample: wgpu::MultisampleState::default(),
+ multisample: wgpu::MultisampleState {
+ count: crate::EFB_SAMPLE_COUNT,
+ mask: !0,
+ alpha_to_coverage_enabled: false,
+ },
multiview_mask: None,
cache: None,
})
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index 1721a2f..ceee07d 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,156 +1,11 @@
-use crate::BindGroupCacheKey;
-use crate::pipeline::PipelineKey;
-use crate::triangulate::{self, GpuVertex, align_up};
-use crate::{DrawUniforms, FrameUniforms, GxRenderer, helpers, texture};
-use encase::{ShaderType as _, UniformBuffer};
-use gecko::flipper::gx::draw::{DrawCommands, GxCommand};
-use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
-use glam::{Mat4, UVec4, Vec4};
+use crate::{FrameUniforms, GxRenderer};
+use crate::{GpuVertex, align_up};
+use encase::ShaderType as _;
+use gecko::flipper::gx::draw::EfbCopyCmd;
+use gecko::host::XfbPart;
impl GxRenderer {
- pub fn render(
- &mut self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- commands: &DrawCommands,
- ram: &mut [u8],
- target: &wgpu::TextureView,
- ) {
- if commands.commands.is_empty() {
- return;
- }
-
- self.prepare_resources(device, queue, commands, ram);
-
- // Render all draws into EFB in one pass, then process copies (readback to RAM + clear).
- // The caller displays from the XFB data written to RAM, not from the EFB directly.
- let (frame_uniform_bytes, draw_call_indices) = self.aggregate_draw_data(device, commands);
-
- if !self.scratch_draws.is_empty() {
- self.upload_buffers(device, queue, &frame_uniform_bytes);
- let num_draws = self.scratch_draws.len();
- self.execute_render_pass_range(device, queue, commands, &draw_call_indices, 0, num_draws);
- }
-
- // Blit EFB to screen
- self.blit_efb_to_target(device, queue, target);
-
- // Process copies (readback EFB to RAM as YUV422 + clear EFB for next frame)
- for cmd in &commands.commands {
- if let GxCommand::CopyEfb(copy) = cmd {
- self.execute_efb_copy(device, queue, copy, ram);
- }
- }
- }
-
- fn prepare_resources(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, commands: &DrawCommands, ram: &[u8]) {
- for cmd in &commands.commands {
- let GxCommand::Draw(dc) = cmd else { continue };
- for desc in dc.textures.iter().flatten() {
- let key = (desc.ram_addr, desc.width, desc.height, desc.format);
- self.texture_cache.entry(key).or_insert_with(|| {
- let (tex, view) = texture::upload_texture(device, queue, ram, desc);
- (tex, view)
- });
- let sampler_key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);
- self.sampler_cache.entry(sampler_key).or_insert_with(|| {
- device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("gx_sampler"),
- address_mode_u: helpers::map_wrap_mode(sampler_key.0),
- address_mode_v: helpers::map_wrap_mode(sampler_key.1),
- mag_filter: helpers::map_mag_filter(sampler_key.2),
- min_filter: helpers::map_min_filter(sampler_key.3),
- ..Default::default()
- })
- });
- }
- let pipeline_key = PipelineKey::from_draw_call(dc);
- if !self.pipeline_cache.contains_key(&pipeline_key) {
- let pipeline = self.create_pipeline(device, &pipeline_key);
- self.pipeline_cache.insert(pipeline_key, pipeline);
- }
- }
-
- let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
- self.sampler_cache.entry(fallback_sampler_key).or_insert_with(|| {
- device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("gx_sampler_fallback"),
- ..Default::default()
- })
- });
- }
-
- fn aggregate_draw_data(&mut self, device: &wgpu::Device, commands: &DrawCommands) -> (Vec<u8>, Vec<usize>) {
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
-
- let draw_stride = self.draw_uniform_stride as usize;
- let draw_encase_size = DrawUniforms::min_size().get() as usize;
- let frame_stride = align_up(
- FrameUniforms::min_size().get(),
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
- let frame_encase_size = FrameUniforms::min_size().get() as usize;
- let mut frame_uniform_bytes: Vec<u8> = Vec::new();
- let mut draw_call_indices: Vec<usize> = Vec::new();
-
- for (dc_idx, cmd) in commands.commands.iter().enumerate() {
- let GxCommand::Draw(dc) = cmd else { continue };
- let prev_len = self.scratch_vertices.len();
- triangulate::triangulate_into(dc, &mut self.scratch_vertices);
- let added = self.scratch_vertices.len() - prev_len;
- if added == 0 {
- continue;
- }
-
- let mvp = commands.projection * dc.modelview;
- let draw_uniform = DrawUniforms {
- mvp: Mat4::from_cols_array_2d(&mvp.0),
- };
-
- 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();
-
- let alpha_cmp = dc.bp_alpha_compare;
- let frame_uniform = FrameUniforms {
- tev_color_regs: dc.tev_color_regs.map(Vec4::from),
- tev_konst_colors: dc.tev_konst_colors.map(Vec4::from),
- tev_color_env: pack_u32x16_to_uvec4x4(&dc.tev_color_env.map(|e| e.raw())),
- tev_alpha_env: pack_u32x16_to_uvec4x4(&dc.tev_alpha_env.map(|e| e.raw())),
- tev_orders: pack_u32x16_to_uvec4x4(&dc.tev_orders.map(|o| o.raw())),
- num_tev_stages: dc.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,
- light_colors: dc.light_colors.map(Vec4::from),
- light_cosatt: dc.light_cosatt.map(Vec4::from),
- light_distatt: dc.light_distatt.map(Vec4::from),
- light_pos: dc.light_pos.map(Vec4::from),
- light_dir: dc.light_dir.map(Vec4::from),
- color_ctrl: dc.color_ctrl.raw(),
- alpha_ctrl: dc.alpha_ctrl.raw(),
- ambient_color: Vec4::from(dc.ambient_color),
- material_color: Vec4::from(dc.material_color),
- };
-
- let fstart = self.scratch_draws.len() * frame_stride;
- frame_uniform_bytes.resize(fstart + frame_stride, 0);
- let mut frame_buf = UniformBuffer::new(&mut frame_uniform_bytes[fstart..fstart + frame_encase_size]);
- frame_buf.write(&frame_uniform).unwrap();
-
- self.scratch_draws.push((prev_len as u32, added as u32));
- draw_call_indices.push(dc_idx);
- }
-
- (frame_uniform_bytes, draw_call_indices)
- }
-
- fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
+ pub(crate) fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
let num_draws = self.scratch_draws.len();
self.ensure_draw_capacity(device, num_draws);
@@ -184,298 +39,257 @@ impl GxRenderer {
queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.scratch_vertices));
}
- fn execute_render_pass_range(
+ pub(crate) fn execute_efb_copy(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, copy: &EfbCopyCmd) {
+ if copy.clear {
+ self.efb_clear.clear_region(
+ device,
+ queue,
+ &self.efb_msaa_view,
+ &self.efb_view,
+ &self.efb_depth_view,
+ crate::EFB_WIDTH,
+ crate::EFB_HEIGHT,
+ copy.src_x,
+ copy.src_y,
+ copy.src_w,
+ copy.src_h,
+ copy.clear_color,
+ copy.clear_z,
+ );
+ }
+ }
+
+ pub(crate) fn execute_copy_xfb(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
- commands: &DrawCommands,
- draw_call_indices: &[usize],
- scratch_start: usize,
- scratch_end: usize,
+ id: u32,
+ src_x: u32,
+ src_y: u32,
+ src_w: u32,
+ src_h: u32,
+ clear: bool,
+ clear_color: [f32; 4],
+ clear_z: f32,
) {
- let target_width = crate::EFB_WIDTH;
- let target_height = crate::EFB_HEIGHT;
- let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
- let frame_stride = align_up(
- FrameUniforms::min_size().get(),
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
-
- // Pre-build bind groups for each unique texture/sampler configuration.
- for &dc_idx in draw_call_indices {
- let GxCommand::Draw(dc) = &commands.commands[dc_idx] else { continue };
- let mut tex_keys: [Option<_>; 8] = [None; 8];
- let mut sampler_keys: [Option<_>; 8] = [None; 8];
-
- for slot in 0..8 {
- if let Some(desc) = &dc.textures[slot] {
- tex_keys[slot] = Some((desc.ram_addr, desc.width, desc.height, desc.format));
- sampler_keys[slot] = Some((desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter));
- }
- }
-
- let bg_key = BindGroupCacheKey { tex_keys, sampler_keys };
- self.bind_group_cache.entry(bg_key).or_insert_with(|| {
- let mut tex_views: [&wgpu::TextureView; 8] = [&self.fallback_view; 8];
- let mut tex_samplers: [&wgpu::Sampler; 8] = [&self.sampler_cache[&fallback_sampler_key]; 8];
-
- for slot in 0..8 {
- if let Some(tk) = &tex_keys[slot] {
- tex_views[slot] = &self.texture_cache[tk].1;
- tex_samplers[slot] = &self.sampler_cache[&sampler_keys[slot].unwrap()];
- }
- }
-
- let entries: [wgpu::BindGroupEntry; 18] = std::array::from_fn(|i| match i {
- 0 => wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.frame_uniform_buffer,
- offset: 0,
- size: Some(FrameUniforms::min_size()),
- }),
- },
- 1 => wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.draw_uniform_buffer,
- offset: 0,
- size: Some(DrawUniforms::min_size()),
- }),
- },
- 2..=9 => wgpu::BindGroupEntry {
- binding: i as u32,
- resource: wgpu::BindingResource::TextureView(tex_views[i - 2]),
- },
- _ => wgpu::BindGroupEntry {
- binding: i as u32,
- resource: wgpu::BindingResource::Sampler(tex_samplers[i - 10]),
- },
- });
-
- device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout: &self.bind_group_layout,
- entries: &entries,
- })
- });
+ let width = src_w.min(crate::EFB_WIDTH.saturating_sub(src_x));
+ let height = src_h.min(crate::EFB_HEIGHT.saturating_sub(src_y));
+ if width == 0 || height == 0 {
+ return;
}
- let mut encoder = device.create_command_encoder(&Default::default());
- {
- // TODO: lol?
- let needs_initial_clear = self.efb_needs_clear;
- self.efb_needs_clear = false;
- let color_load = if needs_initial_clear {
- wgpu::LoadOp::Clear(wgpu::Color::BLACK)
- } else {
- wgpu::LoadOp::Load
- };
- let depth_load = if needs_initial_clear {
- wgpu::LoadOp::Clear(1.0)
- } else {
- wgpu::LoadOp::Load
- };
-
- let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("gx_render_pass"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.efb_view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: color_load,
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
- view: &self.efb_depth_view,
- depth_ops: Some(wgpu::Operations {
- load: depth_load,
- store: wgpu::StoreOp::Store,
- }),
- stencil_ops: None,
- }),
- occlusion_query_set: None,
- timestamp_writes: None,
- multiview_mask: None,
+ // Create (or reuse) the temp texture for this copy id.
+ let entry = self.xfb_copies.entry(id).or_insert_with(|| {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("xfb_copy_tmp"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: self.surface_format,
+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
});
- rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
-
- for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate().skip(scratch_start).take(scratch_end - scratch_start) {
- let GxCommand::Draw(dc) = &commands.commands[draw_call_indices[index]] else {
- continue;
- };
- let pipeline_key = PipelineKey::from_draw_call(dc);
- let pipeline = &self.pipeline_cache[&pipeline_key];
- rpass.set_pipeline(pipeline);
-
- let mut tex_keys: [Option<_>; 8] = [None; 8];
- let mut sampler_keys: [Option<_>; 8] = [None; 8];
- for slot in 0..8 {
- if let Some(desc) = &dc.textures[slot] {
- tex_keys[slot] = Some((desc.ram_addr, desc.width, desc.height, desc.format));
- sampler_keys[slot] = Some((desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter));
- }
- }
-
- let bg_key = BindGroupCacheKey { tex_keys, sampler_keys };
- let bind_group = &self.bind_group_cache[&bg_key];
-
- let frame_offset = (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]);
-
- // Apply per-draw viewport and scissor, clamped to render target bounds
- let vp = &dc.viewport;
- let vp_x = vp.x.max(0.0);
- let vp_y = vp.y.max(0.0);
- let vp_w = vp.w.max(1.0).min(target_width as f32 - vp_x);
- let vp_h = vp.h.max(1.0).min(target_height as f32 - vp_y);
- rpass.set_viewport(vp_x, vp_y, vp_w, vp_h, vp.min_depth, vp.max_depth);
+ let view = tex.create_view(&Default::default());
+ (tex, view)
+ });
- let sc = &dc.scissor;
- let sc_w = sc.w.max(1).min(target_width.saturating_sub(sc.x));
- let sc_h = sc.h.max(1).min(target_height.saturating_sub(sc.y));
- rpass.set_scissor_rect(sc.x, sc.y, sc_w, sc_h);
+ // Recreate if size changed.
+ let existing_size = entry.0.size();
+ if existing_size.width != width || existing_size.height != height {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("xfb_copy_tmp"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: self.surface_format,
+ usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
- rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);
- }
+ let view = tex.create_view(&Default::default());
+ *entry = (tex, view);
}
+ let mut encoder = device.create_command_encoder(&Default::default());
+ encoder.copy_texture_to_texture(
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.efb_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: src_x,
+ y: src_y,
+ z: 0,
+ },
+ aspect: wgpu::TextureAspect::default(),
+ },
+ wgpu::TexelCopyTextureInfo {
+ texture: &entry.0,
+ mip_level: 0,
+ origin: wgpu::Origin3d::ZERO,
+ aspect: wgpu::TextureAspect::default(),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
queue.submit([encoder.finish()]);
+
+ // Region-scoped EFB clear after copy (if requested).
+ if clear {
+ self.efb_clear.clear_region(
+ device,
+ queue,
+ &self.efb_msaa_view,
+ &self.efb_view,
+ &self.efb_depth_view,
+ crate::EFB_WIDTH,
+ crate::EFB_HEIGHT,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear_color,
+ clear_z,
+ );
+ }
}
- fn execute_efb_copy(
+ pub(crate) fn execute_present_xfb(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
- copy: &gecko::flipper::gx::draw::EfbCopyCmd,
- ram: &mut [u8],
+ width: u32,
+ height: u32,
+ parts: &[XfbPart],
) {
- let x = copy.src_x.min(crate::EFB_WIDTH);
- let y = copy.src_y.min(crate::EFB_HEIGHT);
- let w = copy.src_w.min(crate::EFB_WIDTH.saturating_sub(x));
- let h = copy.src_h.min(crate::EFB_HEIGHT.saturating_sub(y));
+ let width = width.max(1);
+ let height = height.max(1);
+
+ // Resize the XFB output texture if the frame dimensions changed.
+ let cur = self.xfb_texture.size();
+ if cur.width != width || cur.height != height {
+ self.xfb_texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("xfb_accum"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: self.surface_format,
+ usage: wgpu::TextureUsages::COPY_DST
+ | wgpu::TextureUsages::TEXTURE_BINDING
+ | wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ self.xfb_view = self.xfb_texture.create_view(&Default::default());
+ }
- if w > 0 && h > 0 {
- let bytes_per_row = align_up(w as u64 * 4, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64) as u32;
- let buffer_size = bytes_per_row as u64 * h as u64;
+ let mut encoder = device.create_command_encoder(&Default::default());
- let staging = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("efb_copy_staging"),
- size: buffer_size,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- });
+ // Don't clear the XFB: let previous content persist so partial
+ // frames show the last valid content instead of a black flash.
+
+ let xfb_size = self.xfb_texture.size();
- let mut encoder = device.create_command_encoder(&Default::default());
- encoder.copy_texture_to_buffer(
+ for part in parts {
+ let Some((tex, _)) = self.xfb_copies.get(&part.id) else {
+ continue;
+ };
+ let src_size = tex.size();
+ let width = src_size.width.min(xfb_size.width.saturating_sub(part.offset_x));
+ let height = src_size.height.min(xfb_size.height.saturating_sub(part.offset_y));
+ if width == 0 || height == 0 {
+ continue;
+ }
+ encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
- texture: &self.efb_texture,
+ texture: tex,
mip_level: 0,
- origin: wgpu::Origin3d { x, y, z: 0 },
+ origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::default(),
},
- wgpu::TexelCopyBufferInfo {
- buffer: &staging,
- layout: wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(bytes_per_row),
- rows_per_image: Some(h),
+ wgpu::TexelCopyTextureInfo {
+ texture: &self.xfb_texture,
+ mip_level: 0,
+ origin: wgpu::Origin3d {
+ x: part.offset_x,
+ y: part.offset_y,
+ z: 0,
},
+ aspect: wgpu::TextureAspect::default(),
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
},
- wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
- queue.submit([encoder.finish()]);
-
- let slice = staging.slice(..);
- slice.map_async(wgpu::MapMode::Read, |_| {});
- let _ = device.poll(wgpu::PollType::wait_indefinitely());
-
- {
- let data = slice.get_mapped_range();
- if copy.copy_to_xfb {
- let is_bgra = matches!(
- self.surface_format,
- wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb
- );
- self::encode_xfb_yuv422(&data, bytes_per_row, w, h, ram, copy.dest_addr as usize, is_bgra);
- }
- // TODO: tiled texture encode for CopyTex
- drop(data);
- }
- staging.unmap();
}
- if copy.clear {
- // Clear the entire EFB with the game's clear color.
- // TODO: scoped clear (only the copied region) for proper multi-pass support.
- let mut encoder = device.create_command_encoder(&Default::default());
- {
- let _rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("efb_clear_after_copy"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.efb_view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color {
- r: copy.clear_color[0] as f64,
- g: copy.clear_color[1] as f64,
- b: copy.clear_color[2] as f64,
- a: copy.clear_color[3] as f64,
- }),
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
- view: &self.efb_depth_view,
- depth_ops: Some(wgpu::Operations {
- load: wgpu::LoadOp::Clear(copy.clear_z),
- store: wgpu::StoreOp::Store,
- }),
- stencil_ops: None,
- }),
- occlusion_query_set: None,
- timestamp_writes: None,
- multiview_mask: None,
- });
- }
- queue.submit([encoder.finish()]);
- }
+ queue.submit([encoder.finish()]);
+ self.xfb_has_content = true;
}
- fn blit_efb_to_target(
- &self,
- _device: &wgpu::Device,
- queue: &wgpu::Queue,
- target: &wgpu::TextureView,
- ) {
- let mut encoder = _device.create_command_encoder(&Default::default());
- let target_size = target.texture().size();
- let copy_w = crate::EFB_WIDTH.min(target_size.width);
- let copy_h = crate::EFB_HEIGHT.min(target_size.height);
+ /// Blit the composited XFB output to the swapchain target. Falls back
+ /// to the live EFB if no XFB content has been produced yet.
+ pub fn blit_to_target(&self, device: &wgpu::Device, queue: &wgpu::Queue, target: &wgpu::TextureView) {
+ let source_view = if self.xfb_has_content {
+ &self.xfb_view
+ } else {
+ &self.efb_view
+ };
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("efb_blit_bg"),
+ layout: &self.blit_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(source_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(&self.blit_sampler),
+ },
+ ],
+ });
- encoder.copy_texture_to_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.efb_texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::default(),
- },
- wgpu::TexelCopyTextureInfo {
- texture: target.texture(),
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::default(),
- },
- wgpu::Extent3d {
- width: copy_w,
- height: copy_h,
- depth_or_array_layers: 1,
- },
- );
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("efb_blit"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: None,
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_pipeline(&self.blit_pipeline);
+ rpass.set_bind_group(0, &bind_group, &[]);
+ rpass.draw(0..3, 0..1);
+ }
queue.submit([encoder.finish()]);
}
@@ -495,58 +309,3 @@ impl GxRenderer {
self.bind_group_cache.clear();
}
}
-
-fn pack_u32x16_to_uvec4x4(data: &[u32; 16]) -> [UVec4; 4] {
- [
- UVec4::new(data[0], data[1], data[2], data[3]),
- UVec4::new(data[4], data[5], data[6], data[7]),
- UVec4::new(data[8], data[9], data[10], data[11]),
- UVec4::new(data[12], data[13], data[14], data[15]),
- ]
-}
-
-/// Encode EFB readback pixels as YUV422 into guest RAM (XFB format).
-/// Pixel data may be RGBA or BGRA depending on the surface format.
-fn encode_xfb_yuv422(
- pixels: &[u8],
- bytes_per_row: u32,
- width: u32,
- height: u32,
- ram: &mut [u8],
- dest: usize,
- is_bgra: bool,
-) {
- let row_bytes = width as usize * 2;
- for y in 0..height as usize {
- let src_row = &pixels[y * bytes_per_row as usize..];
- let dst_row_off = dest + y * row_bytes;
- for px_pair in 0..(width as usize / 2) {
- let x = px_pair * 2;
- let s0 = x * 4;
- let s1 = (x + 1) * 4;
- let (r1, g1, b1) = if is_bgra {
- (src_row[s0 + 2] as i32, src_row[s0 + 1] as i32, src_row[s0] as i32)
- } else {
- (src_row[s0] as i32, src_row[s0 + 1] as i32, src_row[s0 + 2] as i32)
- };
- let (r2, g2, b2) = if is_bgra {
- (src_row[s1 + 2] as i32, src_row[s1 + 1] as i32, src_row[s1] as i32)
- } else {
- (src_row[s1] as i32, src_row[s1 + 1] as i32, src_row[s1 + 2] as i32)
- };
-
- let y1 = ((77 * r1 + 150 * g1 + 29 * b1) / 256).clamp(0, 255) as u8;
- let y2 = ((77 * r2 + 150 * g2 + 29 * b2) / 256).clamp(0, 255) as u8;
- let cb = ((112 * (b1 + b2) - 74 * (g1 + g2) - 38 * (r1 + r2)) / 512 + 128).clamp(0, 255) as u8;
- let cr = ((112 * (r1 + r2) - 94 * (g1 + g2) - 18 * (b1 + b2)) / 512 + 128).clamp(0, 255) as u8;
-
- let off = dst_row_off + px_pair * 4;
- if off + 3 < ram.len() {
- ram[off] = y1;
- ram[off + 1] = cb;
- ram[off + 2] = y2;
- ram[off + 3] = cr;
- }
- }
- }
-}
diff --git a/crates/backend-wgpu/src/shaders/clear.wgsl b/crates/backend-wgpu/src/shaders/clear.wgsl
new file mode 100644
index 0000000..309e174
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/clear.wgsl
@@ -0,0 +1,32 @@
+struct Uniforms {
+ color: vec4<f32>,
+ depth: f32,
+};
+
+@group(0) @binding(0)
+var<uniform> u: Uniforms;
+
+struct VsOut {
+ @builtin(position) position: vec4<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {
+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
+ var out: VsOut;
+ out.position = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
+ return out;
+}
+
+struct FsOut {
+ @location(0) color: vec4<f32>,
+ @builtin(frag_depth) depth: f32,
+};
+
+@fragment
+fn fs_main() -> FsOut {
+ var out: FsOut;
+ out.color = u.color;
+ out.depth = u.depth;
+ return out;
+}
diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.wesl
index fe6980c..96398a0 100644
--- a/crates/backend-wgpu/src/shaders/common.wesl
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -19,10 +19,14 @@ struct FrameUniforms {
light_distatt: array<vec4<f32>, 8>,
light_pos: array<vec4<f32>, 8>,
light_dir: array<vec4<f32>, 8>,
- color_ctrl: u32,
- alpha_ctrl: u32,
- ambient_color: vec4<f32>,
- material_color: vec4<f32>,
+ color_ctrl0: u32,
+ alpha_ctrl0: u32,
+ color_ctrl1: u32,
+ alpha_ctrl1: u32,
+ ambient_color0: vec4<f32>,
+ ambient_color1: vec4<f32>,
+ material_color0: vec4<f32>,
+ material_color1: vec4<f32>,
};
struct DrawUniforms {
diff --git a/crates/backend-wgpu/src/shaders/efb_blit.wgsl b/crates/backend-wgpu/src/shaders/efb_blit.wgsl
new file mode 100644
index 0000000..17f0df9
--- /dev/null
+++ b/crates/backend-wgpu/src/shaders/efb_blit.wgsl
@@ -0,0 +1,23 @@
+@group(0) @binding(0)
+var efb_tex: texture_2d<f32>;
+@group(0) @binding(1)
+var efb_samp: sampler;
+
+struct VsOut {
+ @builtin(position) position: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {
+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
+ var out: VsOut;
+ out.position = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
+ out.uv = vec2<f32>(uv.x, 1.0 - uv.y);
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ return textureSample(efb_tex, efb_samp, in.uv);
+}
diff --git a/crates/backend-wgpu/src/shaders/lighting.wesl b/crates/backend-wgpu/src/shaders/lighting.wesl
index 9735c9b..a19b046 100644
--- a/crates/backend-wgpu/src/shaders/lighting.wesl
+++ b/crates/backend-wgpu/src/shaders/lighting.wesl
@@ -44,20 +44,15 @@ fn compute_light_factor(ctrl: u32, light_idx: u32, normal: vec3<f32>, pos: vec3<
attn = safe_div(angle_attn, distatt.x + distatt.y * dist + distatt.z * dist * dist);
} else {
// AttnFn::Spec
- ldir = normalize(ldir);
- let half_dot = dot(ldir, normal);
- if half_dot < 0.0 {
+ let half_angle = normalize(light_pos);
+ let norm_dot_half = dot(normal, half_angle);
+ if norm_dot_half <= 0.0 {
return 0.0;
}
let s = max(dot(normal, light_dir), 0.0);
let att_len = vec3(1.0, s, s * s);
- var da: vec3<f32>;
- if diff_fn != 0u {
- da = normalize(distatt);
- } else {
- da = distatt;
- }
- attn = safe_div(max(dot(att_len, cosatt), 0.0), dot(att_len, da));
+ attn = safe_div(max(dot(att_len, cosatt), 0.0), dot(att_len, distatt));
+ ldir = half_angle;
}
let dif_attn = dot(ldir, normal);
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
index bb21cf5..9ad88e6 100644
--- a/crates/backend-wgpu/src/shaders/main.wesl
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -11,11 +11,15 @@ fn vs_main(in: VsIn) -> VsOut {
// Remap depth: GameCube/OpenGL uses [-1,1], wgpu uses [0,1]
out.clip_pos.z = out.clip_pos.z * 0.5 + out.clip_pos.w * 0.5;
out.color = compute_channel_lighting(
- frame.color_ctrl, frame.alpha_ctrl,
- frame.ambient_color, frame.material_color,
+ frame.color_ctrl0, frame.alpha_ctrl0,
+ frame.ambient_color0, frame.material_color0,
in.color, in.normal, in.pos_view,
);
- out.color1 = in.color1;
+ out.color1 = compute_channel_lighting(
+ frame.color_ctrl1, frame.alpha_ctrl1,
+ frame.ambient_color1, frame.material_color1,
+ in.color1, in.normal, in.pos_view,
+ );
out.uv0 = in.tex0;
out.uv1 = in.tex1;
out.uv2 = in.tex2;
diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rs
new file mode 100644
index 0000000..1f84dbf
--- /dev/null
+++ b/crates/backend-wgpu/src/sink.rs
@@ -0,0 +1,43 @@
+use crossbeam_channel::{Receiver, Sender, bounded};
+use gecko::host::{GxAction, RenderSink};
+
+/// Capacity of the action channel. Must be large enough to hold at least
+/// two full frames of actions without dropping. Complex scenes (IPL cube
+/// menu) can emit 4000+ draw calls per frame.
+const CHANNEL_CAPACITY: usize = 65536;
+
+pub struct Renderer {
+ tx: Sender<GxAction>,
+}
+
+pub struct ActionReceiver {
+ rx: Receiver<GxAction>,
+}
+
+pub fn channel() -> (Renderer, ActionReceiver) {
+ let (tx, rx) = bounded(CHANNEL_CAPACITY);
+ (Renderer { tx }, ActionReceiver { rx })
+}
+
+impl RenderSink for Renderer {
+ fn exec(&mut self, action: GxAction) {
+ // If the channel is full we drop the action rather than blocking the
+ // CPU thread. In practice, the main thread should drain fast enough.
+ let _ = self.tx.try_send(action);
+ }
+}
+
+impl ActionReceiver {
+ /// Drain all pending actions into the provided buffer.
+ pub fn drain(&self, buf: &mut Vec<GxAction>) {
+ while let Ok(action) = self.rx.try_recv() {
+ buf.push(action);
+ }
+ }
+
+ /// Returns `true` when the emulator-side sender has been dropped.
+ pub fn is_disconnected(&self) -> bool {
+ // try_recv returning Disconnected means all senders are gone.
+ matches!(self.rx.try_recv(), Err(crossbeam_channel::TryRecvError::Disconnected))
+ }
+}
diff --git a/crates/backend-wgpu/src/texture.rs b/crates/backend-wgpu/src/texture.rs
index 5f74fd1..936573a 100644
--- a/crates/backend-wgpu/src/texture.rs
+++ b/crates/backend-wgpu/src/texture.rs
@@ -38,7 +38,7 @@ pub fn upload_texture(
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
diff --git a/crates/backend-wgpu/src/triangulate.rs b/crates/backend-wgpu/src/triangulate.rs
deleted file mode 100644
index 11eecc2..0000000
--- a/crates/backend-wgpu/src/triangulate.rs
+++ /dev/null
@@ -1,88 +0,0 @@
-use gecko::flipper::gx::draw::{DrawCall, Primitive};
-
-#[repr(C)]
-#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
-pub(crate) struct GpuVertex {
- pub position: [f32; 3],
- pub color: [f32; 4],
- pub color1: [f32; 4],
- pub normal: [f32; 3],
- pub pos_view: [f32; 3],
- pub tex0: [f32; 2],
- pub tex1: [f32; 2],
- pub tex2: [f32; 2],
- pub tex3: [f32; 2],
- pub tex4: [f32; 2],
- pub tex5: [f32; 2],
- pub tex6: [f32; 2],
- pub tex7: [f32; 2],
-}
-
-impl From<&gecko::flipper::gx::draw::Vertex> for GpuVertex {
- fn from(v: &gecko::flipper::gx::draw::Vertex) -> Self {
- let tc = |i: usize| v.texcoords[i].unwrap_or([0.0, 0.0]);
- Self {
- position: v.position,
- color: v.color0,
- color1: v.color1,
- normal: v.normal,
- pos_view: v.pos_view,
- tex0: tc(0),
- tex1: tc(1),
- tex2: tc(2),
- tex3: tc(3),
- tex4: tc(4),
- tex5: tc(5),
- tex6: tc(6),
- tex7: tc(7),
- }
- }
-}
-
-pub(crate) fn triangulate_into(dc: &DrawCall, out: &mut Vec<GpuVertex>) {
- match dc.primitive {
- Primitive::Triangles => {
- out.extend(dc.vertices.iter().map(GpuVertex::from));
- }
- Primitive::Quads => {
- for quad in dc.vertices.chunks(4) {
- if quad.len() < 4 {
- continue;
- }
- out.push((&quad[0]).into());
- out.push((&quad[1]).into());
- out.push((&quad[2]).into());
- out.push((&quad[0]).into());
- out.push((&quad[2]).into());
- out.push((&quad[3]).into());
- }
- }
- Primitive::TriangleStrip => {
- for i in 2..dc.vertices.len() {
- if i % 2 == 0 {
- out.push((&dc.vertices[i - 2]).into());
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i]).into());
- } else {
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i - 2]).into());
- out.push((&dc.vertices[i]).into());
- }
- }
- }
- Primitive::TriangleFan => {
- for i in 2..dc.vertices.len() {
- out.push((&dc.vertices[0]).into());
- out.push((&dc.vertices[i - 1]).into());
- out.push((&dc.vertices[i]).into());
- }
- }
- _ => {
- eprintln!("triangulate: skipping unsupported primitive {:?}", dc.primitive);
- }
- }
-}
-
-pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
- (value + alignment - 1) & !(alignment - 1)
-}
diff --git a/crates/gecko/Cargo.toml b/crates/gecko/Cargo.toml
index 54afd58..4091203 100644
--- a/crates/gecko/Cargo.toml
+++ b/crates/gecko/Cargo.toml
@@ -15,3 +15,5 @@ chipi-build = "0.8.2"
chapa = "0.1.2"
tracing = { version = "0.1.44", features = ["release_max_level_off"] }
image = { path = "../image" }
+glam = { version = "0.32.1", features = ["bytemuck"] }
+bytemuck = { version = "1.25.0", features = ["derive"] }
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index b42e3dd..b8b0494 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -10,9 +10,10 @@ mod vertex;
mod xf;
use crate::flipper::gx::constants::{BP_REG_SIZE, CP_REG_SIZE, XF_MEM_SIZE};
-use crate::flipper::gx::draw::DrawCommands;
+use crate::flipper::gx::draw::Matrix4;
use crate::flipper::gx::regs::{AlphaCompare, BlendMode, TevAlphaEnv, TevColorEnv, TevRegisterH, TevRegisterL, ZMode};
use crate::gamecube::GameCube;
+use crate::host::{GxAction, RenderSink, XfbPart};
use crate::mmio::Mmio;
use fifo::FifoCmd;
@@ -21,13 +22,13 @@ pub struct GraphicsProcessor {
pub raise_token_interrupt: bool,
pub pending_token: u16,
pub token_dirty: bool,
- pub draw_commands: DrawCommands,
+ pub projection: Matrix4,
pub bp_regs: Vec<u32>,
pub cp_regs: Vec<u32>,
pub xf_mem: Vec<u32>,
pub fifo: Vec<u8>,
- // Current GX state to snapshot into a DrawCall later
+ // Current GX state to snapshot into a Draw action later
pub cur_textures: [Option<draw::TextureDescriptor>; 8],
pub cur_tev_color_env: [TevColorEnv; 16],
pub cur_tev_alpha_env: [TevAlphaEnv; 16],
@@ -43,6 +44,21 @@ pub struct GraphicsProcessor {
pub cur_alpha_compare: AlphaCompare,
pub cur_viewport: draw::Viewport,
pub cur_scissor: draw::Scissor,
+ // BP_SU_SCIS_OFFSET: applied to both the scissor rect and the viewport
+ // origin. Games use this to do tiled rendering without changing their
+ // projection or logical viewport.
+ pub cur_scissor_offset_x: i32,
+ pub cur_scissor_offset_y: i32,
+ // XFB copies accumulated since the last vblank. `present_xfb()` drains
+ // this at each field boundary to emit a PresentXfb action.
+ pub xfb_copies: Vec<XfbCopy>,
+}
+
+/// A single EFB-to-XFB copy, stored until `present_xfb` computes the layout.
+pub struct XfbCopy {
+ pub dest_addr: u32,
+ pub dest_stride: u32,
+ pub src_h: u32,
}
impl GraphicsProcessor {
@@ -56,7 +72,7 @@ impl GraphicsProcessor {
cp_regs: vec![0; CP_REG_SIZE],
xf_mem: vec![0; XF_MEM_SIZE],
fifo: Vec::with_capacity(256),
- draw_commands: DrawCommands::default(),
+ projection: Matrix4::default(),
cur_textures: Default::default(),
cur_tev_color_env: Default::default(),
cur_tev_alpha_env: Default::default(),
@@ -72,48 +88,119 @@ impl GraphicsProcessor {
cur_alpha_compare: Default::default(),
cur_viewport: Default::default(),
cur_scissor: Default::default(),
+ cur_scissor_offset_x: 0,
+ cur_scissor_offset_y: 0,
+ xfb_copies: Vec::new(),
}
}
- pub fn mmio_write_u8(&mut self, mmio: &mut Mmio, val: u8) {
+ pub fn mmio_write_u8(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink, val: u8) {
self.push_u8(val);
- self.drain_fifo(mmio);
+ self.drain_fifo(mmio, renderer);
}
- pub fn mmio_write_u16(&mut self, mmio: &mut Mmio, val: u16) {
+ pub fn mmio_write_u16(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink, val: u16) {
self.push_u16(val);
- self.drain_fifo(mmio);
+ self.drain_fifo(mmio, renderer);
}
- pub fn mmio_write_u32(&mut self, mmio: &mut Mmio, val: u32) {
+ pub fn mmio_write_u32(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink, val: u32) {
self.push_u32(val);
- self.drain_fifo(mmio);
+ self.drain_fifo(mmio, renderer);
}
- fn drain_fifo(&mut self, mmio: &mut Mmio) {
+ fn drain_fifo(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink) {
for cmd in self.drain() {
match cmd {
FifoCmd::Cp(data) => self.load_cp(&data),
- FifoCmd::Xf(data) => self.load_xf(&data),
- FifoCmd::Bp(data) => self.load_bp(&data),
+ FifoCmd::Xf(data) => self.load_xf(renderer, &data),
+ FifoCmd::Bp(data) => self.load_bp(renderer, &data),
FifoCmd::CallDisplayList { phys_addr, nbytes } => {
let addr = (phys_addr & 0x3FFFFFFF) as usize;
let len = nbytes as usize;
- self.execute_display_list(mmio, &mmio.ram[addr..addr + len].to_vec());
+ self.execute_display_list(mmio, renderer, &mmio.ram[addr..addr + len].to_vec());
}
- FifoCmd::DrawCall(cmd, data) => self.create_draw_call(mmio, cmd, data),
+ FifoCmd::DrawCall(cmd, data) => self.create_draw_call(mmio, renderer, cmd, data),
}
}
}
- fn execute_display_list(&mut self, mmio: &mut Mmio, data: &[u8]) {
+ fn execute_display_list(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink, data: &[u8]) {
let saved = std::mem::take(&mut self.fifo);
self.fifo = data.to_vec();
- self.drain_fifo(mmio);
+ self.drain_fifo(mmio, renderer);
self.fifo = saved;
}
}
+pub fn present_xfb(gc: &mut GameCube) {
+ if gc.gx.xfb_copies.is_empty() {
+ return;
+ }
+
+ let (frame_w, frame_h) = gc.vi.frame_dimensions();
+ let vi_base = gc.vi.xfb_addr();
+
+ // All copies in a frame share the same stride.
+ let stride = gc.gx.xfb_copies[0].dest_stride as u32;
+ let bytes_per_row = stride as u64 * 32;
+ if bytes_per_row == 0 {
+ gc.gx.xfb_copies.clear();
+ return;
+ }
+ let xfb_bytes = bytes_per_row * frame_h as u64;
+ let stride_in_pixels = (bytes_per_row / 2) as u32;
+
+ let build_parts = |base_addr: u32| -> Vec<XfbPart> {
+ let mut parts = Vec::with_capacity(gc.gx.xfb_copies.len());
+ for (id, copy) in gc.gx.xfb_copies.iter().enumerate() {
+ if copy.dest_addr < base_addr {
+ continue;
+ }
+ let delta_bytes = (copy.dest_addr - base_addr) as u64;
+ if delta_bytes >= xfb_bytes {
+ continue;
+ }
+ let delta_pixels = (delta_bytes / 2) as u32;
+ let offset_x = delta_pixels % stride_in_pixels;
+ let offset_y = delta_pixels / stride_in_pixels;
+ // Real XFB copies always land at row boundaries (offset_x == 0).
+ // A non-zero offset_x means this copy belongs to a different
+ // buffer that happens to sit nearby in memory, reject it? TODO
+ if offset_x != 0 || offset_y >= frame_h as u32 {
+ continue;
+ }
+ parts.push(XfbPart {
+ id: id as u32,
+ offset_x,
+ offset_y,
+ });
+ }
+ parts
+ };
+
+ let min_base = gc.gx.xfb_copies.iter().map(|c| c.dest_addr).min().unwrap_or(0);
+
+ let parts = if vi_base != 0 {
+ let p = build_parts(vi_base);
+ if !p.is_empty() { p } else { build_parts(min_base) }
+ } else {
+ build_parts(min_base)
+ };
+
+ if parts.is_empty() {
+ gc.gx.xfb_copies.clear();
+ return;
+ }
+
+ gc.render_sink.exec(GxAction::PresentXfb {
+ width: frame_w,
+ height: frame_h,
+ parts,
+ });
+ gc.gx.xfb_copies.clear();
+}
+
impl GameCube {
/// Check if the GX stub detected a finish or token command and signal PE
pub fn check_gx_pe_interrupts(&mut self) {
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 069b6f6..bc558d5 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -1,9 +1,8 @@
use super::constants::{
BP_GEN_MODE, BP_PE_ALPHA_COMPARE, BP_PE_CMODE0, BP_PE_COPY_CLEAR_AR, BP_PE_COPY_CLEAR_GB, BP_PE_COPY_CLEAR_Z,
BP_PE_COPY_CMD, BP_PE_COPY_DIMS, BP_PE_COPY_DST, BP_PE_COPY_DST_STRIDE, BP_PE_COPY_SRC, BP_PE_DONE,
- BP_PE_DONE_FINISH_BIT, BP_PE_TOKEN, BP_PE_TOKEN_INT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT, BP_RAS1_TREF0,
- BP_SU_SCIS_BR, BP_SU_SCIS_OFFSET, BP_SU_SCIS_TL, BP_TEV_COLOR_ENV_0, BP_TEV_KSEL_0, BP_TEV_REGISTERL_0,
- BP_TX_SETIMAGE0_I0,
+ BP_PE_DONE_FINISH_BIT, BP_PE_TOKEN, BP_PE_TOKEN_INT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT, BP_RAS1_TREF0, BP_SU_SCIS_BR,
+ BP_SU_SCIS_OFFSET, BP_SU_SCIS_TL, BP_TEV_COLOR_ENV_0, BP_TEV_KSEL_0, BP_TEV_REGISTERL_0, BP_TX_SETIMAGE0_I0,
BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, EFB_HEIGHT,
EFB_WIDTH,
};
@@ -12,9 +11,10 @@ use super::regs::{
TxSetImage0, TxSetImage3, TxSetMode0, ZMode,
};
use super::{GraphicsProcessor, draw};
+use crate::host::{GxAction, RenderSink};
impl GraphicsProcessor {
- pub fn load_bp(&mut self, data: &[u8]) {
+ pub fn load_bp(&mut self, renderer: &mut dyn RenderSink, data: &[u8]) {
let idx = data[0] as usize;
let val = u32::from_be_bytes([0, data[1], data[2], data[3]]);
self.bp_regs[idx] = val;
@@ -36,14 +36,23 @@ impl GraphicsProcessor {
};
if let Some(slot) = texture_slot {
- self.snapshot_texture(slot, val);
+ self.snapshot_texture(renderer, slot, val);
}
// Forward PE render state
match idx {
- BP_PE_ZMODE => self.cur_zmode = ZMode::from_raw(val),
- BP_PE_CMODE0 => self.cur_blend_mode = BlendMode::from_raw(val),
- BP_PE_ALPHA_COMPARE => self.cur_alpha_compare = AlphaCompare::from_raw(val),
+ BP_PE_ZMODE => {
+ self.cur_zmode = ZMode::from_raw(val);
+ renderer.exec(GxAction::SetDepthMode(self.cur_zmode));
+ }
+ BP_PE_CMODE0 => {
+ self.cur_blend_mode = BlendMode::from_raw(val);
+ renderer.exec(GxAction::SetBlendMode(self.cur_blend_mode));
+ }
+ BP_PE_ALPHA_COMPARE => {
+ self.cur_alpha_compare = AlphaCompare::from_raw(val);
+ renderer.exec(GxAction::SetAlphaCompare(self.cur_alpha_compare));
+ }
_ => {}
}
@@ -101,18 +110,27 @@ impl GraphicsProcessor {
self.raise_token_interrupt = true;
}
- // Scissor registers (BP 0x20, 0x21, 0x59)
- if idx == BP_SU_SCIS_TL || idx == BP_SU_SCIS_BR || idx == BP_SU_SCIS_OFFSET {
+ // Scissor registers (BP 0x20 = TL, 0x21 = BR, 0x59 = OFFSET).
+ // An offset change also affects the effective viewport, so we refresh
+ // both when the offset register is written.
+ if idx == BP_SU_SCIS_TL || idx == BP_SU_SCIS_BR {
self.recompute_scissor();
+ renderer.exec(GxAction::SetScissor(self.cur_scissor));
+ } else if idx == BP_SU_SCIS_OFFSET {
+ self.recompute_scissor_offset();
+ self.recompute_scissor();
+ self.rebuild_viewport();
+ renderer.exec(GxAction::SetScissor(self.cur_scissor));
+ renderer.exec(GxAction::SetViewport(self.cur_viewport));
}
// EFB copy trigger (BP 0x52)
if idx == BP_PE_COPY_CMD {
- self.efb_copy(val);
+ self.efb_copy(renderer, val);
}
}
- fn snapshot_texture(&mut self, slot: usize, image3_val: u32) {
+ fn snapshot_texture(&mut self, renderer: &mut dyn RenderSink, slot: usize, image3_val: u32) {
let image0_reg = if slot < 4 {
BP_TX_SETIMAGE0_I0 + slot
} else {
@@ -154,6 +172,11 @@ impl GraphicsProcessor {
mag_filter: mode0.mag_filter(),
min_filter: mode0.min_filter(),
});
+
+ renderer.exec(GxAction::SetTexture {
+ slot,
+ descriptor: self.cur_textures[slot].unwrap(),
+ });
}
fn load_tev_env(&mut self, idx: usize, val: u32) {
@@ -222,20 +245,28 @@ impl GraphicsProcessor {
}
}
- fn efb_copy(&mut self, trigger: u32) {
- // Decode source rect from BP 0x49/0x4A
+ fn efb_copy(&mut self, renderer: &mut dyn RenderSink, trigger: u32) {
+ // Decode source rect from BP 0x49/0x4A.
+ // BPMEM_EFB_TL (0x49): x in bits 0..10, y in bits 10..20.
+ // BPMEM_EFB_BR (0x4A): width-1 in bits 0..10, height-1 in bits 10..20.
let src_reg = self.bp_regs[BP_PE_COPY_SRC];
let dims_reg = self.bp_regs[BP_PE_COPY_DIMS];
- let src_x = (src_reg >> 10) & 0x3FF;
- let src_y = src_reg & 0x3FF;
- let src_w = ((dims_reg >> 10) & 0x3FF) + 1;
- let src_h = (dims_reg & 0x3FF) + 1;
+ let src_x = src_reg & 0x3FF;
+ let src_y = (src_reg >> 10) & 0x3FF;
+ let src_w = (dims_reg & 0x3FF) + 1;
+ let src_h = ((dims_reg >> 10) & 0x3FF) + 1;
// Destination address (BP 0x4B, shifted left by 5)
let dest_addr = (self.bp_regs[BP_PE_COPY_DST] & 0x00FFFFFF) << 5;
let dest_stride = self.bp_regs[BP_PE_COPY_DST_STRIDE] & 0x3FF;
- // Trigger word bits
+ // Trigger word bits (PE_COPY_EXECUTE, BP 0x52):
+ // bit 0-1: clamp
+ // bit 9: half (1/2 vertical scale)
+ // bit 10: scale_invert
+ // bit 11: clear EFB after copy
+ // bit 12-13: frame-to-field (interlacing)
+ // bit 14: copy-to-xfb (0 = copy-to-texture)
let copy_to_xfb = (trigger >> 14) & 1 != 0;
let clear = (trigger >> 11) & 1 != 0;
let half = (trigger >> 9) & 1 != 0;
@@ -264,20 +295,42 @@ impl GraphicsProcessor {
"EFB copy triggered"
);
- // Snapshot all copy state at enqueue time
- self.draw_commands.commands.push(draw::GxCommand::CopyEfb(draw::EfbCopyCmd {
- src_x,
- src_y,
- src_w,
- src_h,
- dest_addr,
- dest_stride,
- copy_to_xfb,
- clear,
- clear_color: [r, g, b, a],
- clear_z,
- half,
- }));
+ if copy_to_xfb {
+ // XFB copy: queue the copy for present_xfb() to compose at vblank,
+ // and tell the renderer to snapshot the EFB region now.
+ let id = self.xfb_copies.len() as u32;
+ self.xfb_copies.push(super::XfbCopy {
+ dest_addr,
+ dest_stride,
+ src_h,
+ });
+ renderer.exec(GxAction::CopyXfb {
+ id,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear,
+ clear_color: [r, g, b, a],
+ clear_z,
+ });
+ } else {
+ // Texture copy (non-XFB).
+ let efb_cmd = draw::EfbCopyCmd {
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ dest_addr,
+ dest_stride,
+ copy_to_xfb: false,
+ clear,
+ clear_color: [r, g, b, a],
+ clear_z,
+ half,
+ };
+ renderer.exec(GxAction::CopyEfb(efb_cmd));
+ }
}
fn recompute_scissor(&mut self) {
@@ -289,10 +342,18 @@ impl GraphicsProcessor {
let br_y = (br & 0x7FF) as i32 - 342 + 1; // BR is inclusive
let br_x = ((br >> 12) & 0x7FF) as i32 - 342 + 1;
- let x = tl_x.max(0) as u32;
- let y = tl_y.max(0) as u32;
- let x2 = (br_x.max(0) as u32).min(EFB_WIDTH);
- let y2 = (br_y.max(0) as u32).min(EFB_HEIGHT);
+ // BP_SU_SCIS_OFFSET shifts the scissor (and viewport) origin in the
+ // EFB. Games use it for tiled rendering: the logical scissor stays
+ // the same, but the offset moves where that rectangle lands.
+ let eff_tl_x = tl_x - self.cur_scissor_offset_x;
+ let eff_tl_y = tl_y - self.cur_scissor_offset_y;
+ let eff_br_x = br_x - self.cur_scissor_offset_x;
+ let eff_br_y = br_y - self.cur_scissor_offset_y;
+
+ let x = eff_tl_x.max(0) as u32;
+ let y = eff_tl_y.max(0) as u32;
+ let x2 = (eff_br_x.max(0) as u32).min(EFB_WIDTH);
+ let y2 = (eff_br_y.max(0) as u32).min(EFB_HEIGHT);
self.cur_scissor = draw::Scissor {
x,
@@ -301,4 +362,15 @@ impl GraphicsProcessor {
h: y2.saturating_sub(y),
};
}
+
+ fn recompute_scissor_offset(&mut self) {
+ // BP_SU_SCIS_OFFSET layout:
+ // bits 0..10: (x + 342) / 2
+ // bits 10..20: (y + 342) / 2
+ let raw = self.bp_regs[BP_SU_SCIS_OFFSET];
+ let raw_x = (raw & 0x3FF) as i32;
+ let raw_y = ((raw >> 10) & 0x3FF) as i32;
+ self.cur_scissor_offset_x = raw_x * 2 - 342;
+ self.cur_scissor_offset_y = raw_y * 2 - 342;
+ }
}
diff --git a/crates/gecko/src/flipper/gx/constants.rs b/crates/gecko/src/flipper/gx/constants.rs
index 6f2d7f8..2a90dae 100644
--- a/crates/gecko/src/flipper/gx/constants.rs
+++ b/crates/gecko/src/flipper/gx/constants.rs
@@ -65,7 +65,9 @@ pub const XF_LIGHT_NZ: usize = 15;
// XF channel configuration
pub const XF_AMBIENT_COLOR0: usize = 0x100A;
+pub const XF_AMBIENT_COLOR1: usize = 0x100B;
pub const XF_MATERIAL_COLOR0: usize = 0x100C;
+pub const XF_MATERIAL_COLOR1: usize = 0x100D;
pub const XF_COLOR_CTRL0: usize = 0x100E; // COLOR0 channel control
pub const XF_COLOR_CTRL1: usize = 0x100F; // COLOR1 channel control
pub const XF_ALPHA_CTRL0: usize = 0x1010; // ALPHA0 channel control
@@ -143,7 +145,7 @@ pub const BP_PE_COPY_CMD: usize = 0x52;
// EFB dimensions
pub const EFB_WIDTH: u32 = 640;
-pub const EFB_HEIGHT: u32 = 480;
+pub const EFB_HEIGHT: u32 = 528;
// Depth max for 24-bit Z
pub const DEPTH_24_BIT_MAX: f32 = 16777215.0; // (1 << 24) - 1
diff --git a/crates/gecko/src/flipper/gx/draw.rs b/crates/gecko/src/flipper/gx/draw.rs
index 675985a..a32da68 100644
--- a/crates/gecko/src/flipper/gx/draw.rs
+++ b/crates/gecko/src/flipper/gx/draw.rs
@@ -1,9 +1,7 @@
-use super::regs::{
- AlphaCompare, BlendMode, ChanCtrl, MagFilter, MinFilter, TevAlphaEnv, TevColorEnv, TevStageOrder, WrapMode, ZMode,
-};
+use super::regs::{MagFilter, MinFilter, WrapMode};
use chapa::BitEnum;
-#[derive(Debug)]
+#[derive(Debug, Clone, Copy)]
pub enum Primitive {
Quads,
Triangles,
@@ -113,46 +111,20 @@ impl Default for Scissor {
}
}
-pub struct DrawCall {
- pub primitive: Primitive,
- pub vertices: Vec<Vertex>,
- pub modelview: Matrix4,
- pub viewport: Viewport,
- pub scissor: Scissor,
-
- // Textures bound at draw time
- pub textures: [Option<TextureDescriptor>; 8],
-
- // Per-TEV-stage order (resolved from paired TevOrder registers)
- pub tev_orders: [TevStageOrder; 16],
-
- // TEV state snapshot
- pub tev_color_env: [TevColorEnv; 16],
- pub tev_alpha_env: [TevAlphaEnv; 16],
- pub tev_color_regs: [[f32; 4]; 4],
- pub tev_konst_colors: [[f32; 4]; 16],
- pub num_tev_stages: u8,
-
- // BP state snapshot
- pub bp_zmode: ZMode,
- pub bp_blend_mode: BlendMode,
- pub bp_alpha_compare: AlphaCompare,
-
- // Lighting state snapshot (XF)
- pub light_colors: [[f32; 4]; 8],
- pub light_cosatt: [[f32; 4]; 8],
- pub light_distatt: [[f32; 4]; 8],
- pub light_pos: [[f32; 4]; 8],
- pub light_dir: [[f32; 4]; 8],
- pub color_ctrl: ChanCtrl,
- pub alpha_ctrl: ChanCtrl,
- pub ambient_color: [f32; 4],
- pub material_color: [f32; 4],
-}
-
#[derive(Debug, Clone, Copy)]
pub struct Matrix4(pub [[f32; 4]; 4]);
+impl Matrix4 {
+ /// Flatten the 4x4 column-major matrix into a 16-element array.
+ pub fn to_col_array(&self) -> [f32; 16] {
+ let m = &self.0;
+ [
+ m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3],
+ m[3][0], m[3][1], m[3][2], m[3][3],
+ ]
+ }
+}
+
impl Default for Matrix4 {
fn default() -> Self {
Matrix4([[0.0; 4]; 4])
@@ -175,11 +147,7 @@ impl std::ops::Mul for Matrix4 {
}
}
-pub enum GxCommand {
- Draw(DrawCall),
- CopyEfb(EfbCopyCmd),
-}
-
+#[derive(Debug, Clone)]
pub struct EfbCopyCmd {
pub src_x: u32,
pub src_y: u32,
@@ -193,45 +161,3 @@ pub struct EfbCopyCmd {
pub clear_z: f32,
pub half: bool,
}
-
-#[derive(Default)]
-pub struct DrawCommands {
- pub projection: Matrix4,
- pub commands: Vec<GxCommand>,
- vertex_pool: Vec<Vec<Vertex>>,
-}
-
-impl DrawCommands {
- pub fn recycle(&mut self) {
- for cmd in self.commands.drain(..) {
- if let GxCommand::Draw(dc) = cmd {
- let mut buf = dc.vertices;
- buf.clear();
- self.vertex_pool.push(buf);
- }
- }
- }
-
- /// Extract draw data for cross-thread rendering.
- ///
- /// Moves the accumulated `commands` into a new `DrawCommands` (along with
- /// a copy(!) of the current projection matrix) while preserving the
- /// projection matrix and vertex-buffer pool on `self` so the emulator can
- /// reuse them for the next frame.
- pub fn take_for_render(&mut self) -> DrawCommands {
- DrawCommands {
- projection: self.projection,
- commands: std::mem::take(&mut self.commands),
- vertex_pool: Vec::new(),
- }
- }
-
- pub fn take_vertex_buf(&mut self, capacity: usize) -> Vec<Vertex> {
- if let Some(mut buf) = self.vertex_pool.pop() {
- buf.reserve(capacity.saturating_sub(buf.capacity()));
- buf
- } else {
- Vec::with_capacity(capacity)
- }
- }
-}
diff --git a/crates/gecko/src/flipper/gx/texgen.rs b/crates/gecko/src/flipper/gx/texgen.rs
index b2968bf..06cf954 100644
--- a/crates/gecko/src/flipper/gx/texgen.rs
+++ b/crates/gecko/src/flipper/gx/texgen.rs
@@ -1,9 +1,6 @@
use super::GraphicsProcessor;
-use super::constants::{
- XF_DUAL_TEX_ENABLE, XF_DUALTEX_BASE, XF_MATRIX_INDEX_A, XF_MATRIX_INDEX_B, XF_POS_MTX_STRIDE, XF_POST_MTX_BASE,
- XF_TEXGEN_BASE,
-};
-use super::regs::{DualTexGenReg, MatrixIndex0, MatrixIndex1, TexGenReg};
+use super::constants::{XF_DUAL_TEX_ENABLE, XF_DUALTEX_BASE, XF_POS_MTX_STRIDE, XF_POST_MTX_BASE, XF_TEXGEN_BASE};
+use super::regs::{DualTexGenReg, TexGenReg};
impl GraphicsProcessor {
pub fn compute_texgen(
@@ -12,6 +9,7 @@ impl GraphicsProcessor {
position: [f32; 3],
normal: [f32; 3],
raw_texcoords: &[Option<[f32; 2]>; 8],
+ tex_mtx_indices: &[u8; 8],
) -> [f32; 2] {
let tg = TexGenReg::from_raw(self.xf_mem[XF_TEXGEN_BASE + texgen_idx]);
let dt = DualTexGenReg::from_raw(self.xf_mem[XF_DUALTEX_BASE + texgen_idx]);
@@ -25,15 +23,8 @@ impl GraphicsProcessor {
super::regs::TexGenInputForm::Abc1 => [src[0], src[1], src[2], 1.0],
};
- // Texture matrix base from MatrixIndex register
- let tex_mtx_idx = if texgen_idx < 4 {
- let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
- mtx_index_a.tex_mtx_idx(texgen_idx) as usize
- } else {
- let mtx_index_b = MatrixIndex1::from_raw(self.xf_mem[XF_MATRIX_INDEX_B]);
- mtx_index_b.tex_mtx_idx(texgen_idx) as usize
- };
- let tex_mtx_base = tex_mtx_idx * XF_POS_MTX_STRIDE;
+ // Texture matrix base from per-vertex index
+ let tex_mtx_base = tex_mtx_indices[texgen_idx] as usize * XF_POS_MTX_STRIDE;
// Multiply input by texture matrix (2x4 or 3x4 depending on projection)
let (s, t, q) = self.apply_tex_matrix(&tg, tex_mtx_base, &input);
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index 565c0a7..cfcfb63 100644
--- a/crates/gecko/src/flipper/gx/vertex.rs
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -1,12 +1,16 @@
use super::constants::{
ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_CLR1, ARRAY_NRM, ARRAY_POS, ARRAY_STRIDE_REG, ARRAY_TEX0, VATA_REG, VATB_REG,
- VATC_REG, VCD_HI_REG, VCD_LO_REG, XF_ALPHA_CTRL0, XF_AMBIENT_COLOR0, XF_COLOR_CTRL0, XF_LIGHT_A0, XF_LIGHT_BASE,
- XF_LIGHT_COLOR, XF_LIGHT_K0, XF_LIGHT_NX, XF_LIGHT_PX, XF_LIGHT_STRIDE, XF_MATERIAL_COLOR0, XF_MATRIX_INDEX_A,
- XF_NRM_MTX_BASE, XF_NUM_TEXGENS, XF_POS_MTX_STRIDE,
+ VATC_REG, VCD_HI_REG, VCD_LO_REG, XF_ALPHA_CTRL0, XF_ALPHA_CTRL1, XF_AMBIENT_COLOR0, XF_AMBIENT_COLOR1,
+ XF_COLOR_CTRL0, XF_COLOR_CTRL1, XF_LIGHT_A0, XF_LIGHT_BASE, XF_LIGHT_COLOR, XF_LIGHT_K0, XF_LIGHT_NX, XF_LIGHT_PX,
+ XF_LIGHT_STRIDE, XF_MATERIAL_COLOR0, XF_MATERIAL_COLOR1, XF_MATRIX_INDEX_A, XF_MATRIX_INDEX_B, XF_NRM_MTX_BASE,
+ XF_NUM_TEXGENS, XF_POS_MTX_STRIDE,
};
use super::math::{Vec3, unpack_rgba};
-use super::regs::{self, AttributeType, ComponentFormat, MatrixIndex0, TexCount, VatA, VatB, VatC, VcdHi, VcdLo};
+use super::regs::{
+ self, AttributeType, ComponentFormat, MatrixIndex0, MatrixIndex1, TexCount, VatA, VatB, VatC, VcdHi, VcdLo,
+};
use super::{GraphicsProcessor, draw};
+use crate::host::{DrawData, DrawVertex, GxAction, LightData, RenderSink};
use crate::mmio::Mmio;
use std::io::{Cursor, Read};
@@ -28,8 +32,9 @@ struct VertexFormat {
tex_strides: [usize; 8],
vertex_stride: usize,
has_pnmtxidx: bool,
- tex_mtx_idx_size: usize,
+ has_tex_mtx_idx: [bool; 8],
default_pos_mtx_idx: u8,
+ default_tex_mtx_idx: [u8; 8],
pos_attr: AttributeType,
nrm_attr: AttributeType,
clr0_attr: AttributeType,
@@ -43,7 +48,7 @@ struct VertexFormat {
}
impl GraphicsProcessor {
- pub fn create_draw_call(&mut self, mmio: &mut Mmio, cmd: u8, data: Vec<u8>) {
+ pub fn create_draw_call(&mut self, mmio: &mut Mmio, renderer: &mut dyn RenderSink, cmd: u8, data: Vec<u8>) {
let Some(primitive) = draw::Primitive::from_cmd(cmd) else {
tracing::error!(cmd, "goofy draw command");
return;
@@ -58,7 +63,7 @@ impl GraphicsProcessor {
let vertex_count = data.len() / vf.vertex_stride;
- let mut vertices = self.draw_commands.take_vertex_buf(vertex_count);
+ let mut vertices: Vec<draw::Vertex> = Vec::with_capacity(vertex_count);
let mut cur = Cursor::new(&data);
for i in 0..vertex_count {
@@ -73,38 +78,74 @@ impl GraphicsProcessor {
vertices = format!("{:?}", vertices),
pos_mtx_idx = vf.default_pos_mtx_idx,
modelview = format!("{:?}", modelview),
- projection = format!("{:?}", self.draw_commands.projection),
+ projection = format!("{:?}", self.projection),
"draw call created"
);
// Resolve TEV color registers to f32 arrays for the snapshot
let tev_color_regs = self.resolve_tev_color_regs();
+ let tev_orders = self.resolve_tev_orders();
+
+ // Snapshot light data for the action stream
+ let light_colors = self.snapshot_light_field(XF_LIGHT_COLOR);
+ let light_cosatt = self.snapshot_light_field(XF_LIGHT_A0);
+ let light_distatt = self.snapshot_light_field(XF_LIGHT_K0);
+ let light_pos = self.snapshot_light_field(XF_LIGHT_PX);
+ let light_dir = self.snapshot_light_field(XF_LIGHT_NX);
+
+ let color_ctrl = [
+ regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]),
+ regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL1]),
+ ];
+ let alpha_ctrl = [
+ regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]),
+ regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL1]),
+ ];
+ let ambient_color = [
+ unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]),
+ unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR1]),
+ ];
+ let material_color = [
+ unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]),
+ unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR1]),
+ ];
- self.draw_commands.commands.push(draw::GxCommand::Draw(draw::DrawCall {
+ // Emit action to the render sink
+ let draw_vertices: Vec<DrawVertex> = vertices
+ .iter()
+ .map(|v| DrawVertex {
+ position: v.position,
+ normal: v.normal,
+ color0: v.color0,
+ color1: v.color1,
+ pos_view: v.pos_view,
+ texcoords: std::array::from_fn(|i| v.texcoords[i].unwrap_or([0.0, 0.0])),
+ })
+ .collect();
+
+ let lights: [LightData; 8] = std::array::from_fn(|i| LightData {
+ color: light_colors[i],
+ cosatt: light_cosatt[i],
+ distatt: light_distatt[i],
+ position: light_pos[i],
+ direction: light_dir[i],
+ });
+
+ renderer.exec(GxAction::Draw(DrawData {
primitive,
- vertices,
- modelview,
- viewport: self.cur_viewport,
- scissor: self.cur_scissor,
- textures: self.cur_textures,
- tev_orders: self.resolve_tev_orders(),
- tev_color_env: self.cur_tev_color_env,
- tev_alpha_env: self.cur_tev_alpha_env,
+ vertices: draw_vertices,
+ modelview: modelview.0,
+ tev_color_env: self.cur_tev_color_env.iter().map(|e| e.raw()).collect(),
+ tev_alpha_env: self.cur_tev_alpha_env.iter().map(|e| e.raw()).collect(),
+ tev_orders: tev_orders.iter().map(|o| o.raw()).collect(),
tev_color_regs,
tev_konst_colors: self.cur_tev_konst_colors,
num_tev_stages: self.cur_num_tev_stages,
- bp_zmode: self.cur_zmode,
- bp_blend_mode: self.cur_blend_mode,
- bp_alpha_compare: self.cur_alpha_compare,
- light_colors: self.snapshot_light_field(XF_LIGHT_COLOR),
- light_cosatt: self.snapshot_light_field(XF_LIGHT_A0),
- light_distatt: self.snapshot_light_field(XF_LIGHT_K0),
- light_pos: self.snapshot_light_field(XF_LIGHT_PX),
- light_dir: self.snapshot_light_field(XF_LIGHT_NX),
- color_ctrl: regs::ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]),
- alpha_ctrl: regs::ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]),
- ambient_color: unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]),
- material_color: unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]),
+ color_ctrl,
+ alpha_ctrl,
+ ambient_color,
+ material_color,
+ lights,
}));
}
@@ -195,10 +236,30 @@ impl GraphicsProcessor {
let tex_strides: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_STRIDE_REG + ARRAY_TEX0 + i] as usize);
let has_pnmtxidx = vcd_lo.pos_nrm_mtx_idx();
- let tex_mtx_idx_size = mtx_idx_size - has_pnmtxidx as usize;
+ let has_tex_mtx_idx = [
+ vcd_lo.tex0_mtx_idx(),
+ vcd_lo.tex1_mtx_idx(),
+ vcd_lo.tex2_mtx_idx(),
+ vcd_lo.tex3_mtx_idx(),
+ vcd_lo.tex4_mtx_idx(),
+ vcd_lo.tex5_mtx_idx(),
+ vcd_lo.tex6_mtx_idx(),
+ vcd_lo.tex7_mtx_idx(),
+ ];
let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);
+ let mtx_index_b = MatrixIndex1::from_raw(self.xf_mem[XF_MATRIX_INDEX_B]);
let default_pos_mtx_idx = mtx_index_a.pos_mtx_idx();
+ let default_tex_mtx_idx = [
+ mtx_index_a.tex_mtx_idx(0),
+ mtx_index_a.tex_mtx_idx(1),
+ mtx_index_a.tex_mtx_idx(2),
+ mtx_index_a.tex_mtx_idx(3),
+ mtx_index_b.tex_mtx_idx(4),
+ mtx_index_b.tex_mtx_idx(5),
+ mtx_index_b.tex_mtx_idx(6),
+ mtx_index_b.tex_mtx_idx(7),
+ ];
let vertex_stride = mtx_idx_size
+ pos_stream_size
@@ -227,8 +288,9 @@ impl GraphicsProcessor {
tex_strides,
vertex_stride,
has_pnmtxidx,
- tex_mtx_idx_size,
+ has_tex_mtx_idx,
default_pos_mtx_idx,
+ default_tex_mtx_idx,
pos_attr,
nrm_attr,
clr0_attr,
@@ -256,8 +318,15 @@ impl GraphicsProcessor {
vf.default_pos_mtx_idx
};
- // Skip remaining tex matrix index bytes (not yet used)
- cur.set_position(cur.position() + vf.tex_mtx_idx_size as u64);
+ // Read per-vertex texture matrix indices, or use register defaults
+ let mut tex_mtx_idx = vf.default_tex_mtx_idx;
+ for i in 0..8 {
+ if vf.has_tex_mtx_idx[i] {
+ let mut buf = [0u8; 1];
+ cur.read_exact(&mut buf).unwrap();
+ tex_mtx_idx[i] = buf[0];
+ }
+ }
// Derive per-vertex position and normal matrix bases
let pos_mtx_base = pos_mtx_idx as usize * XF_POS_MTX_STRIDE;
@@ -302,11 +371,19 @@ impl GraphicsProcessor {
} else if vf.clr0_attr == AttributeType::Direct {
let start = cur.position() as usize;
cur.set_position(cur.position() + vf.clr0_data_size as u64);
- decode_color(&data[start..start + vf.clr0_data_size], vf.vat_a.clr0_fmt(), vf.vat_a.clr0_cnt())
+ decode_color(
+ &data[start..start + vf.clr0_data_size],
+ vf.vat_a.clr0_fmt(),
+ vf.vat_a.clr0_cnt(),
+ )
} else {
let clr0_index = read_index(cur, vf.clr0_attr);
let clr0_addr = vf.clr0_base + clr0_index * vf.clr0_stride;
- decode_color(&ram[clr0_addr..clr0_addr + vf.clr0_data_size], vf.vat_a.clr0_fmt(), vf.vat_a.clr0_cnt())
+ decode_color(
+ &ram[clr0_addr..clr0_addr + vf.clr0_data_size],
+ vf.vat_a.clr0_fmt(),
+ vf.vat_a.clr0_cnt(),
+ )
};
// Read color1
@@ -315,11 +392,19 @@ impl GraphicsProcessor {
} else if vf.clr1_attr == AttributeType::Direct {
let start = cur.position() as usize;
cur.set_position(cur.position() + vf.clr1_data_size as u64);
- decode_color(&data[start..start + vf.clr1_data_size], vf.vat_a.clr1_fmt(), vf.vat_a.clr1_cnt())
+ decode_color(
+ &data[start..start + vf.clr1_data_size],
+ vf.vat_a.clr1_fmt(),
+ vf.vat_a.clr1_cnt(),
+ )
} else {
let clr1_index = read_index(cur, vf.clr1_attr);
let clr1_addr = vf.clr1_base + clr1_index * vf.clr1_stride;
- decode_color(&ram[clr1_addr..clr1_addr + vf.clr1_data_size], vf.vat_a.clr1_fmt(), vf.vat_a.clr1_cnt())
+ decode_color(
+ &ram[clr1_addr..clr1_addr + vf.clr1_data_size],
+ vf.vat_a.clr1_fmt(),
+ vf.vat_a.clr1_cnt(),
+ )
};
// Read all texcoords (tex0-tex7)
@@ -359,7 +444,7 @@ impl GraphicsProcessor {
let num_texgens = (self.xf_mem[XF_NUM_TEXGENS] as usize).min(8);
let mut texcoords: [Option<[f32; 2]>; 8] = [None; 8];
for tg_idx in 0..num_texgens {
- texcoords[tg_idx] = Some(self.compute_texgen(tg_idx, position, normal, &raw_texcoords));
+ texcoords[tg_idx] = Some(self.compute_texgen(tg_idx, position, normal, &raw_texcoords, &tex_mtx_idx));
}
// For texcoords beyond num_texgens, pass through raw values
for tg_idx in num_texgens..8 {
@@ -421,7 +506,12 @@ impl GraphicsProcessor {
unpack_rgba(self.xf_mem[base])
} else {
// Float vec3, w = 0
- [f32::from_bits(self.xf_mem[base]), f32::from_bits(self.xf_mem[base + 1]), f32::from_bits(self.xf_mem[base + 2]), 0.0]
+ [
+ f32::from_bits(self.xf_mem[base]),
+ f32::from_bits(self.xf_mem[base + 1]),
+ f32::from_bits(self.xf_mem[base + 2]),
+ 0.0,
+ ]
}
})
}
@@ -514,7 +604,7 @@ fn decode_color(data: &[u8], fmt: regs::ColorFormat, cnt: regs::ColorCount) -> [
let r = ((raw >> 12) & 0xF) as f32 / 15.0;
let g = ((raw >> 8) & 0xF) as f32 / 15.0;
let b = ((raw >> 4) & 0xF) as f32 / 15.0;
- let a = (raw & 0xF) as f32 / 15.0;
+ let a = if has_alpha { (raw & 0xF) as f32 / 15.0 } else { 1.0 };
[r, g, b, a]
}
regs::ColorFormat::Rgba6 => {
@@ -522,7 +612,7 @@ fn decode_color(data: &[u8], fmt: regs::ColorFormat, cnt: regs::ColorCount) -> [
let r = ((raw >> 18) & 0x3F) as f32 / 63.0;
let g = ((raw >> 12) & 0x3F) as f32 / 63.0;
let b = ((raw >> 6) & 0x3F) as f32 / 63.0;
- let a = (raw & 0x3F) as f32 / 63.0;
+ let a = if has_alpha { (raw & 0x3F) as f32 / 63.0 } else { 1.0 };
[r, g, b, a]
}
regs::ColorFormat::Rgba8 => {
@@ -541,25 +631,29 @@ fn decode_normal(data: &[u8], vat: &VatA) -> [f32; 3] {
let mut result = [0.0f32; 3];
let mut off = 0;
+ // Hardware uses fixed-point: 6 fractional bits for byte types, 14 for word types.
+ const SHIFT_BYTE: f32 = (1u32 << 6) as f32; // 64.0
+ const SHIFT_WORD: f32 = (1u32 << 14) as f32; // 16384.0
+
for i in 0..cnt {
result[i] = match fmt {
ComponentFormat::U8 => {
- let v = data[off] as f32 / 255.0;
+ let v = data[off] as f32 / SHIFT_BYTE;
off += 1;
v
}
ComponentFormat::S8 => {
- let v = data[off] as i8 as f32 / 127.0;
+ let v = data[off] as i8 as f32 / SHIFT_BYTE;
off += 1;
v
}
ComponentFormat::U16 => {
- let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / 65535.0;
+ let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / SHIFT_WORD;
off += 2;
v
}
ComponentFormat::S16 => {
- let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / 32767.0;
+ let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / SHIFT_WORD;
off += 2;
v
}
diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rs
index 8ed588e..a21eca1 100644
--- a/crates/gecko/src/flipper/gx/xf.rs
+++ b/crates/gecko/src/flipper/gx/xf.rs
@@ -4,6 +4,7 @@ use super::constants::{
};
use super::math::Vec3;
use super::{GraphicsProcessor, draw};
+use crate::host::{GxAction, RenderSink};
impl GraphicsProcessor {
pub fn xf_transform_3x4(&self, base: usize, v: [f32; 3]) -> Vec3 {
@@ -38,6 +39,12 @@ impl GraphicsProcessor {
let x = offset_x - 342.0 - scale_x;
let y = offset_y - 342.0 + scale_y; // +scale_y because scale_y is negative
+ // Apply BP_SU_SCIS_OFFSET: it shifts both the scissor rect and the
+ // viewport origin in the EFB, so games can tile-render without
+ // touching their projection matrix.
+ let x = x - self.cur_scissor_offset_x as f32;
+ let y = y - self.cur_scissor_offset_y as f32;
+
let far = offset_z / DEPTH_24_BIT_MAX;
let near = far - scale_z / DEPTH_24_BIT_MAX;
@@ -60,7 +67,7 @@ impl GraphicsProcessor {
let pm6 = f32::from_bits(self.xf_mem[XF_PROJECTION_BASE + 5]);
let proj_type = self.xf_mem[XF_PROJECTION_END];
- self.draw_commands.projection = if proj_type == 0 {
+ self.projection = if proj_type == 0 {
// Perspective
draw::Matrix4([
[pm1, 0.0, 0.0, 0.0],
@@ -91,7 +98,7 @@ impl GraphicsProcessor {
);
}
- pub fn load_xf(&mut self, data: &[u8]) {
+ pub fn load_xf(&mut self, renderer: &mut dyn RenderSink, data: &[u8]) {
let length = u16::from_be_bytes([data[0], data[1]]) as usize;
let addr = u16::from_be_bytes([data[2], data[3]]) as usize;
let n = length + 1;
@@ -113,14 +120,18 @@ impl GraphicsProcessor {
}
// Rebuild projection if the write touched its address range
- // (modelview is resolved lazily at draw call time from the current position matrix slot)
if addr <= XF_PROJECTION_END && end > XF_PROJECTION_BASE {
self.rebuild_projection();
+ renderer.exec(GxAction::SetProjection {
+ matrix: self.projection.0,
+ is_perspective: self.xf_mem[XF_PROJECTION_END] == 0,
+ });
}
// Rebuild viewport if the write touched its address range
if addr <= XF_VIEWPORT_END && end > XF_VIEWPORT_BASE {
self.rebuild_viewport();
+ renderer.exec(GxAction::SetViewport(self.cur_viewport));
}
}
}
diff --git a/crates/gecko/src/flipper/vi.rs b/crates/gecko/src/flipper/vi.rs
index 5278b00..b56f351 100644
--- a/crates/gecko/src/flipper/vi.rs
+++ b/crates/gecko/src/flipper/vi.rs
@@ -190,6 +190,21 @@ impl VideoInterface {
self.half_line_count >= self.half_lines_per_odd_field()
}
+ pub fn frame_dimensions(&self) -> (u32, u32) {
+ let hsw_raw = self.hsw.raw();
+ let width = (((hsw_raw >> 8) & 0x7F) * 16) as u32;
+ let active_lines = self.vtr.active_video() as u32;
+ let interlaced = self.dcr.interlaced();
+ let height = if active_lines == 0 {
+ 480
+ } else if interlaced {
+ active_lines.saturating_mul(2)
+ } else {
+ active_lines
+ };
+ (if width == 0 { 640 } else { width }, height)
+ }
+
pub fn xfb_addr(&self) -> u32 {
if self.dcr.interlaced() && self.in_even_field() {
if self.bfbl.page_offset() {
@@ -256,8 +271,18 @@ pub fn ensure_half_line_scheduled(gc: &mut GameCube) {
if ticks_per_hl > 0 {
gc.vi.half_line_scheduled = true;
gc.scheduler.schedule_in(ticks_per_hl, |gc| {
+ let prev_hl = gc.vi.half_line_count;
gc.vi.on_half_line(gc.scheduler.cycles);
gc.vi.half_line_scheduled = false;
+
+ let curr_hl = gc.vi.half_line_count;
+ let total_hl = gc.vi.total_half_lines();
+ let odd_field_start = 0u32;
+ let even_field_start = gc.vi.half_lines_per_odd_field();
+ if total_hl > 0 && (curr_hl == odd_field_start || curr_hl == even_field_start) && curr_hl != prev_hl {
+ crate::flipper::gx::present_xfb(gc);
+ }
+
self::ensure_half_line_scheduled(gc);
self::refresh_interrupts(gc);
});
diff --git a/crates/gecko/src/gamecube.rs b/crates/gecko/src/gamecube.rs
index 4c5508a..2d7915e 100644
--- a/crates/gecko/src/gamecube.rs
+++ b/crates/gecko/src/gamecube.rs
@@ -14,6 +14,7 @@ use crate::flipper::si::{SerialInterface, pad};
use crate::flipper::vi::VideoInterface;
#[cfg(feature = "hooks")]
use crate::hooks::{HookFilters, HookFlags, HookState, Host};
+use crate::host::{EmptyRenderSink, RenderSink};
#[cfg(feature = "idle-skip")]
use crate::idle::{IDLE_LOOP_MAX_INSTRS, IdleCheck, IdleDetector};
use crate::mmio::Mmio;
@@ -36,6 +37,10 @@ pub struct GameCube {
pub si: SerialInterface,
pub ai: AudioInterface,
pub mi: MemoryInterface,
+
+ /// GX dispatches actions here.
+ pub render_sink: Box<dyn RenderSink>,
+
#[cfg(feature = "idle-skip")]
idle: IdleDetector,
@@ -86,6 +91,9 @@ impl GameCube {
si: SerialInterface::new(),
ai: AudioInterface::new(),
mi: MemoryInterface::new(),
+
+ render_sink: Box::new(EmptyRenderSink),
+
#[cfg(feature = "idle-skip")]
idle: IdleDetector::new(),
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
new file mode 100644
index 0000000..ff3af83
--- /dev/null
+++ b/crates/gecko/src/host.rs
@@ -0,0 +1,125 @@
+use crate::flipper::gx::draw::{EfbCopyCmd, Primitive, Scissor, TextureDescriptor, Viewport};
+use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, ZMode};
+
+#[derive(Debug)]
+pub enum GxAction {
+ // XF
+ SetProjection {
+ matrix: [[f32; 4]; 4],
+ is_perspective: bool,
+ },
+ SetViewport(Viewport),
+
+ // BP
+ SetScissor(Scissor),
+ SetDepthMode(ZMode),
+ SetBlendMode(BlendMode),
+ SetAlphaCompare(AlphaCompare),
+ SetTexture {
+ slot: usize,
+ descriptor: TextureDescriptor,
+ },
+
+ /// 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),
+
+ /// Trigger an EFB copy.
+ CopyEfb(EfbCopyCmd),
+
+ /// Copy the EFB source region to a temporary texture identified by `id`.
+ /// The renderer stores this until the next [`PresentXfb`] composites it
+ /// into the output framebuffer.
+ CopyXfb {
+ id: u32,
+ src_x: u32,
+ src_y: u32,
+ src_w: u32,
+ src_h: u32,
+ clear: bool,
+ clear_color: [f32; 4],
+ clear_z: f32,
+ },
+
+ /// 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)`.
+ PresentXfb {
+ width: u32,
+ height: u32,
+ parts: Vec<XfbPart>,
+ },
+}
+
+/// 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.
+#[derive(Debug, Clone, Copy)]
+pub struct XfbPart {
+ pub id: u32,
+ pub offset_x: u32,
+ pub offset_y: u32,
+}
+
+/// 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)]
+pub struct DrawData {
+ pub primitive: Primitive,
+ pub vertices: Vec<DrawVertex>,
+ pub modelview: [[f32; 4]; 4],
+ // TEV combiner state
+ pub tev_color_env: Vec<u32>,
+ pub tev_alpha_env: Vec<u32>,
+ pub tev_orders: Vec<u32>,
+ pub tev_color_regs: [[f32; 4]; 4],
+ pub tev_konst_colors: [[f32; 4]; 16],
+ pub num_tev_stages: u8,
+ // Lighting state (2 channels: COLOR0/ALPHA0 and COLOR1/ALPHA1)
+ pub color_ctrl: [ChanCtrl; 2],
+ pub alpha_ctrl: [ChanCtrl; 2],
+ pub ambient_color: [[f32; 4]; 2],
+ pub material_color: [[f32; 4]; 2],
+ pub lights: [LightData; 8],
+}
+
+/// Per-vertex data after decode, ready for the renderer.
+#[derive(Debug, Clone, Default)]
+#[repr(C)]
+pub struct DrawVertex {
+ pub position: [f32; 3],
+ pub normal: [f32; 3],
+ pub color0: [f32; 4],
+ pub color1: [f32; 4],
+ pub pos_view: [f32; 3],
+ pub texcoords: [[f32; 2]; 8],
+}
+
+/// Per-light snapshot for the draw call.
+#[derive(Debug, Clone, Default)]
+pub struct LightData {
+ pub color: [f32; 4],
+ pub cosatt: [f32; 4],
+ pub distatt: [f32; 4],
+ pub position: [f32; 4],
+ pub direction: [f32; 4],
+}
+
+/// One-way sink for GX actions. The emulator pushes actions here; the
+/// renderer consumes them (typically on a separate thread).
+pub trait RenderSink: Send {
+ /// Submit a single action. Implementations should not block unless
+ /// back-pressure from the renderer requires it.
+ fn exec(&mut self, action: GxAction);
+}
+
+/// 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;
+
+impl RenderSink for EmptyRenderSink {
+ fn exec(&mut self, _: GxAction) {}
+}
diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rs
index bc82b7f..5dedb07 100644
--- a/crates/gecko/src/lib.rs
+++ b/crates/gecko/src/lib.rs
@@ -2,6 +2,7 @@ pub mod cpu;
pub mod dvd;
pub mod flipper;
pub mod gamecube;
+pub mod host;
pub mod idle;
pub mod mmio;
pub mod scheduler;
diff --git a/crates/gecko/src/mmio/bus.rs b/crates/gecko/src/mmio/bus.rs
index 3dcd189..7df84e4 100644
--- a/crates/gecko/src/mmio/bus.rs
+++ b/crates/gecko/src/mmio/bus.rs
@@ -297,7 +297,7 @@ impl GameCube {
self.mmio.ram[wptr] = val;
self.pi.advance_fifo_wptr(1);
if self.cp.control.gp_link_enable() {
- self.gx.mmio_write_u8(&mut self.mmio, val);
+ self.gx.mmio_write_u8(&mut self.mmio, self.render_sink.as_mut(), val);
self.check_gx_pe_interrupts();
}
}
@@ -344,7 +344,7 @@ impl GameCube {
self.mmio.ram[wptr..wptr + 2].copy_from_slice(&bytes);
self.pi.advance_fifo_wptr(2);
if self.cp.control.gp_link_enable() {
- self.gx.mmio_write_u16(&mut self.mmio, val);
+ self.gx.mmio_write_u16(&mut self.mmio, self.render_sink.as_mut(), val);
self.check_gx_pe_interrupts();
}
}
@@ -391,7 +391,7 @@ impl GameCube {
self.mmio.ram[wptr..wptr + 4].copy_from_slice(&bytes);
self.pi.advance_fifo_wptr(4);
if self.cp.control.gp_link_enable() {
- self.gx.mmio_write_u32(&mut self.mmio, val);
+ self.gx.mmio_write_u32(&mut self.mmio, self.render_sink.as_mut(), val);
self.check_gx_pe_interrupts();
}
}
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index 6543ac3..da0c612 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -4,32 +4,25 @@ use std::time::Instant;
use crossbeam_channel::Receiver;
use egui::ViewportId;
-use egui_plot::{Line, Plot, PlotPoints};
-use gecko::flipper::gx::draw::DrawCommands;
use gecko::flipper::si::pad::PadStatus;
+use gecko::host::GxAction;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
use winit::keyboard::PhysicalKey;
use winit::window::{Window, WindowId};
-use crate::thread::{FrameData, FrameMessage};
+use crate::thread::FrameMessage;
use crate::update_pad;
-const SHADER: &str = include_str!("xfb.wgsl");
-
pub struct State {
surface: wgpu::Surface<'static>,
surface_config: wgpu::SurfaceConfiguration,
device: wgpu::Device,
queue: wgpu::Queue,
- pipeline: wgpu::RenderPipeline,
- bind_group_layout: wgpu::BindGroupLayout,
- texture: wgpu::Texture,
- bind_group: wgpu::BindGroup,
- tex_width: u32,
- tex_height: u32,
gx_renderer: backend_wgpu::GxRenderer,
+ action_rx: backend_wgpu::sink::ActionReceiver,
+ action_buf: Vec<GxAction>,
// egui overlay
egui_ctx: egui::Context,
egui_renderer: egui_wgpu::Renderer,
@@ -41,9 +34,11 @@ pub struct State {
}
impl State {
- pub fn new(window: Arc<Window>, frame_size: (u32, u32), present_mode: wgpu::PresentMode) -> Self {
- let (w, h) = frame_size;
-
+ pub fn new(
+ window: Arc<Window>,
+ present_mode: wgpu::PresentMode,
+ action_rx: backend_wgpu::sink::ActionReceiver,
+ ) -> Self {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
backends: wgpu::Backends::all(),
..Default::default()
@@ -63,16 +58,11 @@ impl State {
let size = window.inner_size();
let surface_caps = surface.get_capabilities(&adapter);
- let surface_format = surface_caps
- .formats
- .iter()
- .find(|f| f.is_srgb())
- .copied()
- .unwrap_or(surface_caps.formats[0]);
+ let gx_renderer = backend_wgpu::GxRenderer::new(&device, &queue, wgpu::TextureFormat::Bgra8Unorm);
let surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
- format: surface_format,
+ format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width.max(1),
height: size.height.max(1),
present_mode,
@@ -82,70 +72,12 @@ impl State {
};
surface.configure(&device, &surface_config);
- let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: None,
- entries: &[
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Texture {
- multisampled: false,
- view_dimension: wgpu::TextureViewDimension::D2,
- sample_type: wgpu::TextureSampleType::Float { filterable: true },
- },
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
- count: None,
- },
- ],
- });
-
- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: None,
- source: wgpu::ShaderSource::Wgsl(SHADER.into()),
- });
-
- let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: None,
- bind_group_layouts: &[&bind_group_layout],
- immediate_size: 0,
- });
-
- let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: None,
- layout: Some(&pipeline_layout),
- vertex: wgpu::VertexState {
- module: &shader,
- entry_point: Some("vs_main"),
- buffers: &[],
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: surface_format,
- blend: None,
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState::default(),
- depth_stencil: None,
- multisample: wgpu::MultisampleState::default(),
- multiview_mask: None,
- cache: None,
- });
-
- let (texture, bind_group) = create_xfb_texture(&device, &bind_group_layout, w, h);
- let gx_renderer = backend_wgpu::GxRenderer::new(&device, &queue, surface_format);
-
let egui_ctx = egui::Context::default();
- let egui_renderer = egui_wgpu::Renderer::new(&device, surface_format, egui_wgpu::RendererOptions::default());
+ let egui_renderer = egui_wgpu::Renderer::new(
+ &device,
+ wgpu::TextureFormat::Bgra8Unorm,
+ egui_wgpu::RendererOptions::default(),
+ );
let egui_winit = egui_winit::State::new(egui_ctx.clone(), ViewportId::ROOT, window.as_ref(), None, None, None);
State {
@@ -153,13 +85,9 @@ impl State {
surface_config,
device,
queue,
- pipeline,
- bind_group_layout,
- texture,
- bind_group,
- tex_width: w,
- tex_height: h,
gx_renderer,
+ action_rx,
+ action_buf: Vec::new(),
egui_ctx,
egui_renderer,
egui_winit,
@@ -185,10 +113,7 @@ impl State {
msg = Some(newer); // drain
}
- let mut msg = match msg {
- Some(m) => m,
- None => return,
- };
+ let Some(msg) = msg else { return };
// FPS bookkeeping
let delta = self.last_frame.elapsed().as_secs_f64();
@@ -211,16 +136,20 @@ impl State {
};
let view = frame.texture.create_view(&Default::default());
- // Render emulator output
- match &mut msg.data {
- FrameData::Gx { commands, ram } => {
- self.render_gx(commands, ram, &view);
- }
- FrameData::Xfb { pixels } => {
- self.render_xfb(pixels, msg.width, msg.height, &view);
- }
+ let ram = msg.ram;
+ self.action_buf.clear();
+ self.action_rx.drain(&mut self.action_buf);
+
+ // Drive the GX renderer with any queued actions (draws into its EFB
+ // and updates the snapshot on CopyEfb).
+ if !self.action_buf.is_empty() {
+ self.gx_renderer
+ .render_actions(&self.device, &self.queue, &self.action_buf, &ram);
}
+ // Blit the latest EFB snapshot to the swapchain.
+ self.gx_renderer.blit_to_target(&self.device, &self.queue, &view);
+
// egui overlay
let raw_input = self.egui_winit.take_egui_input(window);
let fps_points: Vec<[f64; 2]> = self.fps_history.iter().copied().collect();
@@ -236,7 +165,7 @@ impl State {
.frame(frame)
.show(&ctx, |ui| {
ui.label(egui::RichText::new(format!("{fps:.1} FPS {native_pct:.1}%")).monospace());
- Plot::new("fps_plot")
+ egui_plot::Plot::new("fps_plot")
.height(60.0)
.width(180.0)
.show_axes(false)
@@ -246,7 +175,7 @@ impl State {
.allow_scroll(false)
.show(ui, |plot_ui| {
plot_ui.line(
- Line::new("fps", PlotPoints::from(fps_points.clone()))
+ egui_plot::Line::new("fps", egui_plot::PlotPoints::from(fps_points.clone()))
.color(egui::Color32::from_rgb(100, 200, 100)),
);
});
@@ -301,117 +230,6 @@ impl State {
frame.present();
}
-
- fn render_gx(&mut self, commands: &DrawCommands, ram: &mut [u8], view: &wgpu::TextureView) {
- self.gx_renderer
- .render(&self.device, &self.queue, commands, ram, view);
- }
-
- fn render_xfb(&mut self, pixels: &[u32], w: u32, h: u32, view: &wgpu::TextureView) {
- if (w, h) != (self.tex_width, self.tex_height) {
- let (texture, bind_group) = create_xfb_texture(&self.device, &self.bind_group_layout, w, h);
- self.texture = texture;
- self.bind_group = bind_group;
- self.tex_width = w;
- self.tex_height = h;
- }
-
- let rgba: Vec<u8> = pixels
- .iter()
- .flat_map(|&p| [(p >> 16) as u8, (p >> 8) as u8, p as u8, 0xFF])
- .collect();
-
- self.queue.write_texture(
- wgpu::TexelCopyTextureInfo {
- texture: &self.texture,
- mip_level: 0,
- origin: wgpu::Origin3d::ZERO,
- aspect: wgpu::TextureAspect::All,
- },
- &rgba,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(w * 4),
- rows_per_image: Some(h),
- },
- wgpu::Extent3d {
- width: w,
- height: h,
- depth_or_array_layers: 1,
- },
- );
-
- let mut encoder = self.device.create_command_encoder(&Default::default());
- {
- let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: None,
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: None,
- occlusion_query_set: None,
- timestamp_writes: None,
- multiview_mask: None,
- });
- rpass.set_pipeline(&self.pipeline);
- rpass.set_bind_group(0, &self.bind_group, &[]);
- rpass.draw(0..3, 0..1);
- }
-
- self.queue.submit([encoder.finish()]);
- }
-}
-
-fn create_xfb_texture(
- device: &wgpu::Device,
- layout: &wgpu::BindGroupLayout,
- w: u32,
- h: u32,
-) -> (wgpu::Texture, wgpu::BindGroup) {
- let texture = device.create_texture(&wgpu::TextureDescriptor {
- label: None,
- size: wgpu::Extent3d {
- width: w.max(1),
- height: h.max(1),
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
-
- let view = texture.create_view(&Default::default());
- let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
- mag_filter: wgpu::FilterMode::Nearest,
- min_filter: wgpu::FilterMode::Nearest,
- ..Default::default()
- });
-
- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: None,
- layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(&view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&sampler),
- },
- ],
- });
-
- (texture, bind_group)
}
// ---------------------------------------------------------------------------
@@ -420,11 +238,11 @@ fn create_xfb_texture(
pub struct App {
pub frame_rx: Receiver<FrameMessage>,
+ pub action_rx: Option<backend_wgpu::sink::ActionReceiver>,
pub input: Arc<Mutex<PadStatus>>,
pub window: Option<Arc<Window>>,
pub state: Option<State>,
pub present_mode: wgpu::PresentMode,
- pub initial_frame_size: (u32, u32),
}
impl ApplicationHandler for App {
@@ -435,7 +253,8 @@ impl ApplicationHandler for App {
.unwrap(),
);
- let state = State::new(window.clone(), self.initial_frame_size, self.present_mode);
+ let action_rx = self.action_rx.take().expect("action_rx consumed twice");
+ let state = State::new(window.clone(), self.present_mode, action_rx);
window.request_redraw();
self.window = Some(window);
self.state = Some(state);
@@ -476,4 +295,3 @@ impl ApplicationHandler for App {
}
}
}
-
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index e33e76e..4ab2e63 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -101,10 +101,10 @@ fn main() {
..PadStatus::default()
});
- let initial_frame_size = {
- let (w, h) = emulator.frame_size();
- (w as u32, h as u32)
- };
+ // Create the action-stream channel and install the renderer sink on the
+ // emulator so GX actions flow through automatically.
+ let (renderer, action_rx) = backend_wgpu::sink::channel();
+ emulator.render_sink = Box::new(renderer);
let input = Arc::new(Mutex::new(*emulator.primary_controller_mut()));
@@ -120,11 +120,11 @@ fn main() {
.expect("failed to spawn emulator thread");
let mut app = app::App {
frame_rx,
+ action_rx: Some(action_rx),
input,
window: None,
state: None,
present_mode,
- initial_frame_size,
};
event_loop.run_app(&mut app).unwrap();
}
diff --git a/crates/tinyapp/src/thread.rs b/crates/tinyapp/src/thread.rs
index b006d74..ceec883 100644
--- a/crates/tinyapp/src/thread.rs
+++ b/crates/tinyapp/src/thread.rs
@@ -1,20 +1,15 @@
use crossbeam_channel::Sender;
use gecko::{
- flipper::{gx::draw::DrawCommands, si::pad::PadStatus, vi::regs::RefreshRate},
+ flipper::{si::pad::PadStatus, vi::regs::RefreshRate},
gamecube::GameCube,
};
use std::sync::{Arc, Mutex};
use winit::event_loop::EventLoopProxy;
-pub enum FrameData {
- Gx { commands: DrawCommands, ram: Vec<u8> },
- Xfb { pixels: Vec<u32> },
-}
-
pub struct FrameMessage {
- pub data: FrameData,
- pub width: u32,
- pub height: u32,
+ /// Guest RAM snapshot so the renderer can upload textures referenced by
+ /// the actions in the channel.
+ pub ram: Vec<u8>,
pub native_hz: f64,
}
@@ -33,25 +28,9 @@ pub fn emu_thread(
RefreshRate::Hz50 => 50.0,
};
- let (w, h) = emulator.frame_size();
- let (width, height) = (w as u32, h as u32);
-
- let data = if !emulator.gx.draw_commands.commands.is_empty() {
- FrameData::Gx {
- commands: emulator.gx.draw_commands.take_for_render(),
- ram: emulator.mmio.ram.clone(),
- }
- } else {
- FrameData::Xfb {
- pixels: emulator.render_xfb(),
- }
- };
-
if frame_tx
.send(FrameMessage {
- data,
- width,
- height,
+ ram: emulator.mmio.ram.clone(),
native_hz,
})
.is_err()
diff --git a/crates/tinyapp/src/xfb.wgsl b/crates/tinyapp/src/xfb.wgsl
deleted file mode 100644
index 697ce0e..0000000
--- a/crates/tinyapp/src/xfb.wgsl
+++ /dev/null
@@ -1,30 +0,0 @@
-struct VsOut {
- @builtin(position) pos: vec4<f32>,
- @location(0) uv: vec2<f32>,
-}
-
-@vertex
-fn vs_main(@builtin(vertex_index) i: u32) -> VsOut {
- var pos = array<vec2<f32>, 3>(
- vec2<f32>(-1.0, 1.0),
- vec2<f32>( 3.0, 1.0),
- vec2<f32>(-1.0, -3.0),
- );
- var uv = array<vec2<f32>, 3>(
- vec2<f32>(0.0, 0.0),
- vec2<f32>(2.0, 0.0),
- vec2<f32>(0.0, 2.0),
- );
- var out: VsOut;
- out.pos = vec4<f32>(pos[i], 0.0, 1.0);
- out.uv = uv[i];
- return out;
-}
-
-@group(0) @binding(0) var xfb_tex: texture_2d<f32>;
-@group(0) @binding(1) var xfb_sam: sampler;
-
-@fragment
-fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- return textureSample(xfb_tex, xfb_sam, in.uv);
-}
diff --git a/crates/tinybench/src/main.rs b/crates/tinybench/src/main.rs
index d6d2e72..03387f8 100644
--- a/crates/tinybench/src/main.rs
+++ b/crates/tinybench/src/main.rs
@@ -71,7 +71,6 @@ fn run_bench(emulator: &mut GameCube, args: &Args) {
let frame_start = Instant::now();
emulator.run_until_vsync();
- emulator.gx.draw_commands.recycle();
let frame_time = frame_start.elapsed().as_secs_f64();
frame_count += 1;