A GameCube/Wii emulator and debugger written in Rust.
resnapshot paletted textures on TX_SETTLUT and LOAD_TLUT1, more renderdoc and debugger capabilities, indirect texturing pipeline
Layle57837b1a1019
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex 3435eaa..62ff103 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -74,9 +74,10 @@ impl GxRenderer {id,width,height,+ fmt,rgba,} => {- let texture_label = format!("gx_tex addr={:#010x} size={}x{}", *id, *width, *height);+ let texture_label = format!("gx_tex addr={:#010x} fmt={:?} size={}x{}", *id, *fmt, *width, *height);let tex = device.create_texture(&wgpu::TextureDescriptor {label: Some(&texture_label),size: wgpu::Extent3d {@@ -88,7 +89,9 @@ impl GxRenderer {sample_count: 1,dimension: wgpu::TextureDimension::D2,format: wgpu::TextureFormat::Rgba8Unorm,- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,+ usage: wgpu::TextureUsages::TEXTURE_BINDING+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::COPY_SRC,view_formats: &[],});queue.write_texture(@@ -119,7 +122,22 @@ impl GxRenderer {self.return_to_pool(old_tex, old_view);}- self.texture_cache.insert(*id, (tex, view));+ self.texture_cache.insert(*id, (*fmt, tex, view));+ }+ GxAction::InvalidateCaches => {+ self.flush_pending_draws(device, queue);+ self.texture_cache.clear();+ let drained: Vec<_> = self.efb_copy_cache.drain().map(|(_, v)| v).collect();+ for (tex, view) in drained {+ self.return_to_pool(tex, view);+ }+ self.bind_group_cache.clear();+ self.pipeline_cache.clear();+ }+ #[cfg(not(target_arch = "wasm32"))]+ GxAction::DumpTextures { dir } => {+ self.flush_pending_draws(device, queue);+ self.dump_textures(device, queue, dir);}GxAction::SetTexture {slot,@@ -179,6 +197,12 @@ impl GxRenderer {alpha_comp0: alpha_cmp.comp0() as u32,alpha_comp1: alpha_cmp.comp1() as u32,alpha_op: alpha_cmp.op() as u32,+ indirect_matrices: draw.indirect_matrices.map(glam::IVec4::from),+ indirect_scales: draw.indirect_scales.map(glam::UVec4::from),+ indirect_refs: draw.indirect_refs,+ num_indirect_stages: draw.num_indirect_stages as u32,+ bump_imask: draw.bump_imask,+ tev_indirect: pack_u32_slice_to_uvec4x4(&draw.tev_indirect),light_colors: draw.lights.each_ref().map(|l| Vec4::from(l.color)),light_cosatt: draw.lights.each_ref().map(|l| Vec4::from(l.cosatt)),light_distatt: draw.lights.each_ref().map(|l| Vec4::from(l.distatt)),@@ -364,7 +388,12 @@ impl GxRenderer {if let Some(tid) = &bg_key.tex_keys[slot] {// The EFB-copy cache wins over the RAM-decoded// `texture_cache`.- if let Some((_, view)) = self.efb_copy_cache.get(tid).or_else(|| self.texture_cache.get(tid)) {+ let view = self+ .efb_copy_cache+ .get(tid)+ .map(|(_, v)| v)+ .or_else(|| self.texture_cache.get(tid).map(|(_, _, v)| v));+ if let Some(view) = view {tex_views[slot] = view;}diff --git a/crates/backend-wgpu/src/dump.rs b/crates/backend-wgpu/src/dump.rsnew file mode 100644index 0000000..4b3208c--- /dev/null+++ b/crates/backend-wgpu/src/dump.rs@@ -0,0 +1,104 @@+use std::path::{Path, PathBuf};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use crate::GxRenderer;+use crate::align_up;+use crate::capture::{self, CapturedFrame};++impl GxRenderer {+ pub(crate) fn dump_textures(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, dir: &Path) {+ let millis = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_millis())+ .unwrap_or(0);++ if let Err(err) = std::fs::create_dir_all(dir) {+ tracing::error!(dir = %dir.display(), ?err, "dump_textures: failed to create dir");+ return;+ }++ let mut saved = 0usize;+ for (addr, (fmt, tex, _)) in self.texture_cache.iter() {+ let size = tex.size();+ let width = size.width;+ let height = size.height;+ if width == 0 || height == 0 {+ continue;+ }++ if tex.format() != wgpu::TextureFormat::Rgba8Unorm {+ tracing::warn!(+ addr = *addr,+ wgpu_fmt = ?tex.format(),+ "dump_textures: skipping non-Rgba8Unorm texture"+ );+ continue;+ }++ let bytes_per_row = align_up(width as u64 * 4, 256);+ let staging_size = bytes_per_row * height as u64;+ let staging = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("dump_texture_staging"),+ size: staging_size,+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,+ mapped_at_creation: false,+ });++ let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {+ label: Some("dump_texture_encoder"),+ });+ encoder.copy_texture_to_buffer(+ wgpu::TexelCopyTextureInfo {+ texture: tex,+ mip_level: 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 as u32),+ rows_per_image: Some(height),+ },+ },+ wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ );+ queue.submit([encoder.finish()]);++ let slice = staging.slice(..staging_size);+ slice.map_async(wgpu::MapMode::Read, |_| {});+ if let Err(err) = device.poll(wgpu::PollType::Wait {+ submission_index: None,+ timeout: Some(Duration::from_secs(5)),+ }) {+ tracing::warn!(addr = *addr, ?err, "dump_textures: device poll failed");+ continue;+ }++ let mut rgba = vec![0u8; (width * height * 4) as usize];+ {+ let mapped = slice.get_mapped_range();+ let row_bytes = (width * 4) as usize;+ let src_row_bytes = bytes_per_row as usize;+ for y in 0..height as usize {+ let src_row = &mapped[y * src_row_bytes..y * src_row_bytes + row_bytes];+ let dst_row = &mut rgba[y * row_bytes..y * row_bytes + row_bytes];+ dst_row.copy_from_slice(src_row);+ }+ }+ staging.unmap();++ let filename = format!("{millis}_{:08X}_{:?}_{}x{}.png", *addr, *fmt, width, height);+ let path: PathBuf = dir.join(filename);+ capture::save_png_async(path, CapturedFrame { width, height, rgba }, false);+ saved += 1;+ }++ tracing::info!(count = saved, dir = %dir.display(), "dumped textures");+ }+}diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 56f117a..bd5b9f8 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -1,6 +1,8 @@mod action;pub mod capture;mod clear;+#[cfg(not(target_arch = "wasm32"))]+mod dump;mod helpers;mod pipeline;mod render;@@ -8,7 +10,7 @@ pub mod sink;use encase::ShaderType as _;use gecko::common::Address;-use gecko::flipper::gx::draw::{Scissor, Viewport};+use gecko::flipper::gx::draw::{Scissor, TextureFormat, Viewport};use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, MagFilter, MinFilter, WrapMode, ZMode};#[cfg(feature = "efb-writeback")]use gecko::host::EfbWriteback;@@ -59,6 +61,18 @@ pub(crate) struct FrameUniforms {alpha_comp0: u32,alpha_comp1: u32,alpha_op: u32,+ // Indirect texturing state. `indirect_matrices` stores the 6 rows of+ // the three 2x3 matrices.+ indirect_matrices: [glam::IVec4; 6],+ // Two packed RAS1_SS registers holding four 4-bit divisor exponents+ // each. Stage i reads from `indirect_scales[i / 2]`.+ indirect_scales: [glam::UVec4; 2],+ // Packed RAS1_IREF. Four 3+3 bit (texmap, texcoord) pairs.+ indirect_refs: u32,+ num_indirect_stages: u32,+ bump_imask: u32,+ // Per-TEV-stage IND_CMD, packed four per UVec4.+ tev_indirect: [glam::UVec4; 4],light_colors: [glam::Vec4; 8],light_cosatt: [glam::Vec4; 8],light_distatt: [glam::Vec4; 8],@@ -107,7 +121,7 @@ pub struct GxRenderer {pub(crate) efb_depth_view: wgpu::TextureView,pub(crate) efb_needs_clear: bool,pub(crate) sampler_cache: FxHashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,- pub(crate) texture_cache: FxHashMap<Address, (wgpu::Texture, wgpu::TextureView)>,+ pub(crate) texture_cache: FxHashMap<Address, (TextureFormat, wgpu::Texture, wgpu::TextureView)>,// GPU textures holding EFB copy results, checked before `texture_cache` on every texture bind.pub(crate) efb_copy_cache: FxHashMap<Address, (wgpu::Texture, wgpu::TextureView)>,// Retired EFB-copy textures grouped by size, popped by the next copy to skip reallocating.diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.weslindex 9d5db0c..cdecd6f 100644--- a/crates/backend-wgpu/src/shaders/common.wesl+++ b/crates/backend-wgpu/src/shaders/common.wesl@@ -13,6 +13,13 @@ struct FrameUniforms {alpha_comp0: u32,alpha_comp1: u32,alpha_op: u32,+ // Indirect memes+ indirect_matrices: array<vec4<i32>, 6>,+ indirect_scales: array<vec4<u32>, 2>,+ indirect_refs: u32,+ num_indirect_stages: u32,+ bump_imask: u32,+ tev_indirect: array<vec4<u32>, 4>,// XF lighting statelight_colors: array<vec4<f32>, 8>,light_cosatt: array<vec4<f32>, 8>,diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.weslindex 5899824..19b685d 100644--- a/crates/backend-wgpu/src/shaders/main.wesl+++ b/crates/backend-wgpu/src/shaders/main.wesl@@ -1,5 +1,6 @@import super::common::{FrameUniforms, DrawUniforms, VsIn, VsOut, frame, draw, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};import super::tev_helpers::{read_packed, extract_bits, select_texcoord, stq_to_uv, sample_texmap, tev_color_in, tev_alpha_in};+import super::tev_indirect::{IndirectSamples, IndirectResult, sample_indirect_textures, apply_indirect, texmap_size};import super::tev_combiners::{tev_combine_color, tev_combine_alpha};import super::alpha_test::{alpha_compare, alpha_combine};import super::lighting::compute_channel_lighting;@@ -46,6 +47,9 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {var last_color_dest = 0u;var last_alpha_dest = 0u;+ let presampled = sample_indirect_textures(in);+ var running_uv = vec2<f32>(0.0, 0.0);+for (var stage = 0u; stage < 16u; stage++) {if stage >= num_stages {break;@@ -59,6 +63,16 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {let tex_enabled = ((order >> 6u) & 1u) != 0u;let ras_channel = (order >> 7u) & 7u;+ // Run the stage's indirect pipeline first. It yields the final+ // direct-texmap UV, the fixpoint chaining value, and any bump+ // alpha produced. When the stage doesn't use indirect this+ // returns the raw direct UV and zero bump alpha.+ let stq = select_texcoord(in, texcoord_idx);+ let direct_uv = stq_to_uv(stq);+ let direct_size = texmap_size(texmap_idx);+ let indirect = apply_indirect(stage, direct_uv, direct_size, presampled, running_uv);+ running_uv = indirect.uv;+// Select raster color based on channel:// 0=Color0, 1=Color1, 2=Alpha0, 3=Alpha1, 4=Color0A0, 5=Color1A1, 6=Zero, 7=Bumpvar ras_color: vec4<f32>;@@ -70,14 +84,12 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {case 4u: { ras_color = color0; } // Color0A0case 5u: { ras_color = in.color1; } // Color1A1case 6u: { ras_color = vec4(0.0, 0.0, 0.0, 0.0); } // Zero- default: { ras_color = vec4(0.0, 0.0, 0.0, 0.0); } // Bump (TODO: not implemented)+ default: { ras_color = vec4(indirect.bump_alpha); } // Bump}var tex_color: vec4<f32>;if tex_enabled {- let stq = select_texcoord(in, texcoord_idx);- let uv = stq_to_uv(stq);- tex_color = sample_texmap(texmap_idx, uv);+ tex_color = sample_texmap(texmap_idx, indirect.uv);} else {tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);}diff --git a/crates/backend-wgpu/src/shaders/tev_indirect.wesl b/crates/backend-wgpu/src/shaders/tev_indirect.weslnew file mode 100644index 0000000..e39fd65--- /dev/null+++ b/crates/backend-wgpu/src/shaders/tev_indirect.wesl@@ -0,0 +1,192 @@+import super::common::{VsOut, FrameUniforms, frame, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};+import super::tev_helpers::{select_texcoord, stq_to_uv, sample_texmap, read_packed};++fn texmap_size(texmap: u32) -> vec2<f32> {+ switch texmap {+ case 0u: { return vec2<f32>(textureDimensions(tex0)); }+ case 1u: { return vec2<f32>(textureDimensions(tex1)); }+ case 2u: { return vec2<f32>(textureDimensions(tex2)); }+ case 3u: { return vec2<f32>(textureDimensions(tex3)); }+ case 4u: { return vec2<f32>(textureDimensions(tex4)); }+ case 5u: { return vec2<f32>(textureDimensions(tex5)); }+ case 6u: { return vec2<f32>(textureDimensions(tex6)); }+ default: { return vec2<f32>(textureDimensions(tex7)); }+ }+}++fn ind_quantize_and_bias(+ sample: vec3<f32>,+ format: u32,+ bias_s: u32,+ bias_t: u32,+ bias_u: u32,+) -> vec3<f32> {+ let bias_mask = vec3<f32>(f32(bias_s), f32(bias_t), f32(bias_u));+ switch format {+ case 0u: {+ let byte = floor(sample * 255.0);+ return byte - 128.0 * bias_mask;+ }+ case 1u: {+ let byte = floor(sample * 31.0);+ return byte + bias_mask;+ }+ case 2u: {+ let byte = floor(sample * 15.0);+ return byte + bias_mask;+ }+ default: {+ let byte = floor(sample * 7.0);+ return byte + bias_mask;+ }+ }+}++fn ind_bump_alpha_byte(sample_byte_u8: u32, format: u32) -> u32 {+ var shift: u32 = 0u;+ switch format {+ case 0u: { shift = 0u; }+ case 1u: { shift = 5u; }+ case 2u: { shift = 4u; }+ default: { shift = 3u; }+ }+ return (sample_byte_u8 << shift) & 0xF8u;+}++fn ind_wrap_texels(mode: u32) -> f32 {+ return 256.0 / exp2(f32(mode - 1u));+}++fn ind_wrap_axis(uv_coord: f32, mode: u32, tex_size: f32) -> f32 {+ if mode == 0u {+ return uv_coord;+ }+ if mode >= 6u {+ return 0.0;+ }+ let period = ind_wrap_texels(mode) / tex_size;+ return fract(uv_coord / period) * period;+}++struct IndirectSamples {+ samples: array<vec3<f32>, 4>,+}++fn sample_indirect_textures(in: VsOut) -> IndirectSamples {+ var result: IndirectSamples;+ result.samples[0] = vec3<f32>(0.0);+ result.samples[1] = vec3<f32>(0.0);+ result.samples[2] = vec3<f32>(0.0);+ result.samples[3] = vec3<f32>(0.0);++ let num_stages = frame.num_indirect_stages;+ for (var i = 0u; i < 4u; i = i + 1u) {+ if i >= num_stages {+ break;+ }++ let shift = i * 6u;+ let texmap = (frame.indirect_refs >> shift) & 7u;+ let texcoord = (frame.indirect_refs >> (shift + 3u)) & 7u;+ let scale_pair = frame.indirect_scales[i / 2u];+ let scale_s: u32 = select(scale_pair.x, scale_pair.z, (i & 1u) == 1u);+ let scale_t: u32 = select(scale_pair.y, scale_pair.w, (i & 1u) == 1u);++ let stq = select_texcoord(in, texcoord);+ let direct_uv = stq_to_uv(stq);+ let sample_uv = vec2<f32>(+ direct_uv.x * exp2(-f32(scale_s)),+ direct_uv.y * exp2(-f32(scale_t)),+ );+ let sample = sample_texmap(texmap, sample_uv);++ result.samples[i] = sample.abg;+ }+ return result;+}++struct IndirectResult {+ uv: vec2<f32>,+ bump_alpha: f32,+}++fn apply_indirect(+ stage: u32,+ direct_uv: vec2<f32>,+ direct_tex_size: vec2<f32>,+ presampled: IndirectSamples,+ previous_uv: vec2<f32>,+) -> IndirectResult {+ var result: IndirectResult;+ result.uv = direct_uv;+ result.bump_alpha = 0.0;++ let cmd = read_packed(frame.tev_indirect, stage);+ let source_stage = cmd & 3u;+ let format = (cmd >> 2u) & 3u;+ let bias_s = (cmd >> 4u) & 1u;+ let bias_t = (cmd >> 5u) & 1u;+ let bias_u = (cmd >> 6u) & 1u;+ let bump_source = (cmd >> 7u) & 3u;+ let matrix_index = (cmd >> 9u) & 3u;+ let matrix_mode = (cmd >> 11u) & 3u;+ let wrap_s = (cmd >> 13u) & 7u;+ let wrap_t = (cmd >> 16u) & 7u;+ let add_previous = ((cmd >> 20u) & 1u) != 0u;+ // TODO: bit 19?++ let sample = presampled.samples[source_stage];++ if bump_source != 0u {+ var raw_byte: f32 = 0.0;+ switch bump_source {+ case 1u: { raw_byte = sample.x; }+ case 2u: { raw_byte = sample.y; }+ case 3u: { raw_byte = sample.z; }+ default: {}+ }+ let byte_u8 = u32(floor(raw_byte * 255.0));+ result.bump_alpha = f32(ind_bump_alpha_byte(byte_u8, format)) / 255.0;+ }++ let has_offset = matrix_index != 0u || wrap_s != 0u || wrap_t != 0u || add_previous;+ if !has_offset {+ return result;+ }++ let quantized = ind_quantize_and_bias(sample, format, bias_s, bias_t, bias_u);++ var offset_uv = vec2<f32>(0.0);+ if matrix_index != 0u {+ let idx = matrix_index - 1u;+ let row0 = vec3<f32>(frame.indirect_matrices[idx * 2u].xyz) * (1.0 / 1024.0);+ let row1 = vec3<f32>(frame.indirect_matrices[idx * 2u + 1u].xyz) * (1.0 / 1024.0);+ let scale_exp = frame.indirect_matrices[idx * 2u].w;+ let inv_scale = exp2(-f32(scale_exp));+ switch matrix_mode {+ case 0u: {+ offset_uv = vec2<f32>(dot(row0, quantized), dot(row1, quantized))+ * inv_scale+ / direct_tex_size;+ }+ case 1u: {+ offset_uv = direct_uv * (quantized.x * (1.0 / 256.0) * inv_scale);+ }+ case 2u: {+ offset_uv = direct_uv * (quantized.y * (1.0 / 256.0) * inv_scale);+ }+ default: {}+ }+ }++ let wrapped = vec2<f32>(+ ind_wrap_axis(direct_uv.x, wrap_s, direct_tex_size.x),+ ind_wrap_axis(direct_uv.y, wrap_t, direct_tex_size.y),+ );+ var final_uv = wrapped + offset_uv;+ if add_previous {+ final_uv = final_uv + previous_uv;+ }+ result.uv = final_uv;+ return result;+}diff --git a/crates/dbglib/src/windows/gx.rs b/crates/dbglib/src/windows/gx.rsindex fc943e4..656f2de 100644--- a/crates/dbglib/src/windows/gx.rs+++ b/crates/dbglib/src/windows/gx.rs@@ -21,9 +21,30 @@ fn texture_preview(ui: &mut egui::Ui, tex: &TextureDescriptor, ram: &[u8], paletui.label(format!("Mag: {:?} Min: {:?}", tex.mag_filter, tex.min_filter));}-pub fn show_gx(ctx: &Context, open: &mut bool, gx: &GraphicsProcessor, mmio: &Mmio) {+pub fn show_gx(+ ctx: &Context,+ open: &mut bool,+ gx: &GraphicsProcessor,+ mmio: &Mmio,+ invalidate_caches: &mut bool,+ dump_textures: &mut bool,+) {egui::Window::new("GX").open(open).show(ctx, |ui| {ScrollArea::vertical().show(ui, |ui| {+ ui.horizontal(|ui| {+ if ui.button("Invalidate Caches").clicked() {+ *invalidate_caches = true;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if ui.button("Dump Textures").clicked() {+ *dump_textures = true;+ }+ #[cfg(target_arch = "wasm32")]+ let _ = dump_textures;+ ui.label(format!("{} cached", gx.texture_hashes.len()));+ });+ ui.separator();+// Projection matrixui.collapsing("Projection", |ui| {Grid::new("proj").num_columns(4).show(ui, |ui| {diff --git a/crates/debugger/src/debugger.rs b/crates/debugger/src/debugger.rsindex f2fe272..3a75834 100644--- a/crates/debugger/src/debugger.rs+++ b/crates/debugger/src/debugger.rs@@ -30,6 +30,8 @@ pub struct DebuggerUi {pub lua_source: String,pub lua_log: Vec<String>,pub lua_load_pending: bool,+ pub gx_invalidate_requested: bool,+ pub gx_dump_requested: bool,}impl Default for DebuggerUi {@@ -56,6 +58,8 @@ impl Default for DebuggerUi {lua_source: DEFAULT_LUA_SCRIPT.to_string(),lua_log: Vec::new(),lua_load_pending: false,+ gx_invalidate_requested: false,+ gx_dump_requested: false,}}}diff --git a/crates/debugger/src/render.rs b/crates/debugger/src/render.rsindex aeb9e8f..6c66618 100644--- a/crates/debugger/src/render.rs+++ b/crates/debugger/src/render.rs@@ -257,7 +257,14 @@ impl RenderState {}}if debugger_ui.show_gx_state {- dbglib::windows::gx::show_gx(&ctx, &mut debugger_ui.show_gx_state, gx, mmio);+ dbglib::windows::gx::show_gx(+ &ctx,+ &mut debugger_ui.show_gx_state,+ gx,+ mmio,+ &mut debugger_ui.gx_invalidate_requested,+ &mut debugger_ui.gx_dump_requested,+ );}if debugger_ui.show_mmio {dbglib::windows::mmio::show_mmio(@@ -305,6 +312,17 @@ impl RenderState {}});+ if std::mem::take(&mut debugger_ui.gx_invalidate_requested) {+ emulator.gx.texture_hashes.clear();+ emulator.render_sink.exec(gecko::host::GxAction::InvalidateCaches);+ }+ #[cfg(not(target_arch = "wasm32"))]+ if std::mem::take(&mut debugger_ui.gx_dump_requested) {+ emulator.render_sink.exec(gecko::host::GxAction::DumpTextures {+ dir: std::path::PathBuf::from("textures"),+ });+ }+self.egui_winit.handle_platform_output(window, full_output.platform_output);diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex ca70d9e..96b5711 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -50,6 +50,13 @@ pub struct GraphicsProcessor {pub cur_tev_orders: [regs::TevOrder; 8],pub cur_num_tev_stages: u8,pub cur_tev_konst_colors: [[f32; 4]; 16],+ // Indirect texturing state. Brain damage.+ pub cur_indirect_matrices: [regs::IndMtx; 3],+ pub cur_indirect_scales: [regs::Ras1Ss; 2],+ pub cur_indirect_refs: regs::Ras1IRef,+ pub cur_tev_indirect: [regs::TevIndirect; 16],+ pub cur_num_indirect_stages: u8,+ pub cur_bump_imask: u32,pub cur_zmode: ZMode,pub cur_pe_control: regs::PeControl,pub cur_blend_mode: BlendMode,@@ -107,6 +114,12 @@ impl GraphicsProcessor {cur_tev_orders: Default::default(),cur_num_tev_stages: 0,cur_tev_konst_colors: [[0.0; 4]; 16],+ cur_indirect_matrices: Default::default(),+ cur_indirect_scales: Default::default(),+ cur_indirect_refs: Default::default(),+ cur_tev_indirect: Default::default(),+ cur_num_indirect_stages: 0,+ cur_bump_imask: 0,cur_zmode: Default::default(),cur_pe_control: Default::default(),cur_blend_mode: BlendMode::from_raw(0).with_color_update(true).with_alpha_update(true),diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex c694bd3..b929b6f 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -1,17 +1,5 @@-use super::constants::{- BP_GEN_MODE, BP_LOAD_TLUT0, BP_LOAD_TLUT1, 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_COPY_YSCALE, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_TOKEN, BP_PE_TOKEN_INT, BP_PE_ZCOMPARE,- 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, BP_TX_SETTLUT_I0, BP_TX_SETTLUT_I4, EFB_HEIGHT,- EFB_WIDTH, TLUT_ENTRIES_PER_UNIT, TLUT_LOAD_ENTRIES_PER_UNIT,-};-use super::regs::{- AlphaCompare, BlendMode, DispCopyYScale, EfbCopyDims, EfbCopyDst, EfbCopyDstStride, EfbCopySrc, GenMode, PeClearAr,- PeClearGb, PeClearZ, PeControl, PeCopyCmd, SuScisOffset, SuScisRect, TevAlphaEnv, TevColorEnv, TevOrder,- TevRegType, TevRegisterH, TevRegisterL, TxSetImage0, TxSetImage3, TxSetMode0, ZMode,-};+use super::constants::*;+use super::regs::*;use super::{GraphicsProcessor, draw, texture};use crate::common::Address;use crate::host::{GxAction, RenderSink};@@ -46,17 +34,32 @@ impl GraphicsProcessor {// TX_SETTLUT: per-texture-slot binding of the palette (tmem offset +// palette pixel format). Layout mirrors TX_SETIMAGE*: slots 0-3 at- // BP_TX_SETTLUT_I0, slots 4-7 at BP_TX_SETTLUT_I4.- if idx >= BP_TX_SETTLUT_I0 && idx < BP_TX_SETTLUT_I0 + 4 {- self.cur_tluts[idx - BP_TX_SETTLUT_I0] = draw::TlutRef::from_raw(val);+ // BP_TX_SETTLUT_I0, slots 4-7 at BP_TX_SETTLUT_I4. Rebinding a TLUT+ // invalidates the cached decode of any paletted texture on that slot,+ // since both palette format and tmem offset feed the decoded pixels.+ let tlut_slot = if idx >= BP_TX_SETTLUT_I0 && idx < BP_TX_SETTLUT_I0 + 4 {+ Some(idx - BP_TX_SETTLUT_I0)} else if idx >= BP_TX_SETTLUT_I4 && idx < BP_TX_SETTLUT_I4 + 4 {- self.cur_tluts[idx - BP_TX_SETTLUT_I4 + 4] = draw::TlutRef::from_raw(val);+ Some(idx - BP_TX_SETTLUT_I4 + 4)+ } else {+ None+ };+ if let Some(slot) = tlut_slot {+ self.cur_tluts[slot] = draw::TlutRef::from_raw(val);+ self.resnapshot_paletted_slot(renderer, ram, slot);}// LOADTLUT: writing TLUT1 triggers a copy from main RAM (address in- // TLUT0, stored pre-shifted by 5) into our palette TMEM.+ // TLUT0, stored pre-shifted by 5) into our palette TMEM. Any paletted+ // texture already bound is now looking at fresh palette bytes, so we+ // must redecode it. We don't know which slots' TLUT regions overlap+ // the load, so rescan all bound paletted slots (saw this in Dolphin @+ // TMEM::InvalidateAll on LOADTLUT1).if idx == BP_LOAD_TLUT1 {self.load_tlut(ram, val);+ for slot in 0..self.cur_textures.len() {+ self.resnapshot_paletted_slot(renderer, ram, slot);+ }}// Forward PE render state@@ -95,16 +98,60 @@ impl GraphicsProcessor {self.load_tev_register(idx, val);}- // GEN_MODE, extract num TEV stages + cull mode+ // GEN_MODE, extract num TEV stages + cull mode + num indirect stagesif idx == BP_GEN_MODE {let gen_mode = GenMode::from_raw(val);let stages = gen_mode.num_tev_stages() + 1;- tracing::debug!(num_tev_stages = stages, "GEN_MODE");+ let indirect_stages = gen_mode.num_ind_stages();+ tracing::debug!(+ num_tev_stages = stages,+ num_indirect_stages = indirect_stages,+ "GEN_MODE"+ );self.cur_num_tev_stages = stages;+ self.cur_num_indirect_stages = indirect_stages;self.resolve_konst_colors();renderer.exec(GxAction::SetCullMode(gen_mode.cull_mode()));}+ // Indirect-matrix rows at 0x06..=0x0E. Each write lands in one+ // of the A, B, or C rows of one of three matrices.+ match idx {+ BP_IND_MTX_A0 => self.cur_indirect_matrices[0].a = val,+ BP_IND_MTX_B0 => self.cur_indirect_matrices[0].b = val,+ BP_IND_MTX_C0 => self.cur_indirect_matrices[0].c = val,+ BP_IND_MTX_A1 => self.cur_indirect_matrices[1].a = val,+ BP_IND_MTX_B1 => self.cur_indirect_matrices[1].b = val,+ BP_IND_MTX_C1 => self.cur_indirect_matrices[1].c = val,+ BP_IND_MTX_A2 => self.cur_indirect_matrices[2].a = val,+ BP_IND_MTX_B2 => self.cur_indirect_matrices[2].b = val,+ BP_IND_MTX_C2 => self.cur_indirect_matrices[2].c = val,+ _ => {}+ }++ // TODO: BumpIMask is captured for measure but never read on the+ // GPU side. AFAICT it's unused. Dolphin agrees.+ if idx == BP_BUMP_IMASK {+ self.cur_bump_imask = val;+ }++ // Per TEV stage indirect commands at 0x10..=0x1F.+ if idx >= BP_IND_CMD_0 && idx < BP_IND_CMD_0 + BP_IND_CMD_COUNT {+ self.cur_tev_indirect[idx - BP_IND_CMD_0] = TevIndirect::from_raw(val);+ }++ // Indirect texcoord scale pair. SS0 covers indirect stages 0-1,+ // SS1 covers 2-3.+ if idx == BP_RAS1_SS0 {+ self.cur_indirect_scales[0] = Ras1Ss::from_raw(val);+ } else if idx == BP_RAS1_SS1 {+ self.cur_indirect_scales[1] = Ras1Ss::from_raw(val);+ }++ if idx == BP_RAS1_IREF {+ self.cur_indirect_refs = Ras1IRef::from_raw(val);+ }+// TEV KSEL (constant color selection) registers: recalculate konst colorsif idx >= BP_TEV_KSEL_0 && idx <= BP_TEV_KSEL_0 + 7 {self.resolve_konst_colors();@@ -216,6 +263,7 @@ impl GraphicsProcessor {id: ram_addr as Address,width,height,+ fmt: format,rgba: texture::decode_to_rgba(ram, &desc, palette, tlut.format),});}@@ -241,6 +289,25 @@ impl GraphicsProcessor {});}+ /// If the slot currently binds a paletted texture, rerun the snapshot+ /// pipeline so `texture_data_changed` rehashes the (now possibly fresh)+ /// palette bytes + TLUT format and decodes a new RGBA if anything moved.+ fn resnapshot_paletted_slot(&mut self, renderer: &mut dyn RenderSink, ram: &[u8], slot: usize) {+ let Some(desc) = self.cur_textures[slot] else {+ return;+ };+ if !desc.format.is_paletted() {+ return;+ }+ let image3_reg = if slot < 4 {+ BP_TX_SETIMAGE3_I0 + slot+ } else {+ BP_TX_SETIMAGE3_I4 + (slot - 4)+ };+ let image3_val = self.bp_regs[image3_reg];+ self.snapshot_texture(renderer, ram, slot, image3_val);+ }+fn load_tev_env(&mut self, idx: usize, val: u32) {let stage = (idx - BP_TEV_COLOR_ENV_0) / 2;if idx % 2 == 0 {diff --git a/crates/gecko/src/flipper/gx/constants.rs b/crates/gecko/src/flipper/gx/constants.rsindex 6fda03d..7267dd9 100644--- a/crates/gecko/src/flipper/gx/constants.rs+++ b/crates/gecko/src/flipper/gx/constants.rs@@ -131,6 +131,26 @@ pub const BP_PE_TOKEN_INT: usize = 0x48;pub const BP_GEN_MODE: usize = 0x00;pub const BP_RAS1_TREF0: usize = 0x28; // ..0x2F, order registerspub const BP_RAS1_TREF_COUNT: usize = 8;++// BP indirect texture registers+pub const BP_IND_MTX_A0: usize = 0x06;+pub const BP_IND_MTX_B0: usize = 0x07;+pub const BP_IND_MTX_C0: usize = 0x08;+pub const BP_IND_MTX_A1: usize = 0x09;+pub const BP_IND_MTX_B1: usize = 0x0A;+pub const BP_IND_MTX_C1: usize = 0x0B;+pub const BP_IND_MTX_A2: usize = 0x0C;+pub const BP_IND_MTX_B2: usize = 0x0D;+pub const BP_IND_MTX_C2: usize = 0x0E;+pub const BP_BUMP_IMASK: usize = 0x0F;+// 16 per-TEV-stage indirect command registers at 0x10..=0x1F+pub const BP_IND_CMD_0: usize = 0x10;+pub const BP_IND_CMD_COUNT: usize = 16;+// Two 4x4-bit TEXSCALE registers, covering indirect stages 0-1 and 2-3+pub const BP_RAS1_SS0: usize = 0x25;+pub const BP_RAS1_SS1: usize = 0x26;+// Indirect texture reference: maps 4 indirect stages to texmap + texcoord+pub const BP_RAS1_IREF: usize = 0x27;pub const BP_TEV_COLOR_ENV_0: usize = 0xC0; // stage N color = 0xC0 + N*2pub const BP_TEV_ALPHA_ENV_0: usize = 0xC1; // stage N alpha = 0xC1 + N*2// lo = 0xE0 + N*2 (R,A), hi = 0xE1 + N*2 (G,B)diff --git a/crates/gecko/src/flipper/gx/draw.rs b/crates/gecko/src/flipper/gx/draw.rsindex 44654f4..bc8347b 100644--- a/crates/gecko/src/flipper/gx/draw.rs+++ b/crates/gecko/src/flipper/gx/draw.rs@@ -1,4 +1,4 @@-use super::regs::{MagFilter, MinFilter, WrapMode};+use super::regs::*;use chapa::BitEnum;#[derive(Debug, Clone, Copy)]diff --git a/crates/gecko/src/flipper/gx/fifo.rs b/crates/gecko/src/flipper/gx/fifo.rsindex 08afd59..415ed4f 100644--- a/crates/gecko/src/flipper/gx/fifo.rs+++ b/crates/gecko/src/flipper/gx/fifo.rs@@ -1,12 +1,6 @@-use super::constants::{- ARRAY_LIGHT, ARRAY_NRM_MTX, ARRAY_POS_NRM_MTX, ARRAY_POST_MTX, BP_CMD, CALL_DL_CMD, CP_CMD, INV_VTX_CACHE_CMD,- LOAD_INDX_A_CMD, LOAD_INDX_B_CMD, LOAD_INDX_C_CMD, LOAD_INDX_D_CMD, NOP_CMD, XF_CMD,-};+use super::constants::*;+use super::regs::*;use crate::flipper::gx::GraphicsProcessor;-use crate::flipper::gx::constants::{- DRAW_COMMANDS_END, DRAW_COMMANDS_START, VATA_REG, VATB_REG, VATC_REG, VCD_HI_REG, VCD_LO_REG,-};-use crate::flipper::gx::regs::{AttributeType, VatA, VatB, VatC, VcdHi, VcdLo};use std::io::{Cursor, Read};impl GraphicsProcessor {diff --git a/crates/gecko/src/flipper/gx/regs.rs b/crates/gecko/src/flipper/gx/regs.rsindex 716be7b..f815d20 100644--- a/crates/gecko/src/flipper/gx/regs.rs+++ b/crates/gecko/src/flipper/gx/regs.rs@@ -891,6 +891,159 @@ pub struct GenMode {pub num_tev_stages: u8, // num stages - 1#[bits(14..=15)]pub cull_mode: CullMode,+ #[bits(16..=18)]+ pub num_ind_stages: u8,+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum IndTexFormat {+ Itf8 = 0,+ Itf5 = 1,+ Itf4 = 2,+ Itf3 = 3,+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum IndTexBumpAlpha {+ Off = 0,+ S = 1,+ T = 2,+ U = 3,+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum IndMtxIndex {+ Off = 0,+ Mtx0 = 1,+ Mtx1 = 2,+ Mtx2 = 3,+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum IndMtxId {+ Indirect = 0,+ S = 1,+ T = 2,+ Invalid = 3, // libogc?+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum IndTexWrap {+ Off = 0,+ W256 = 1,+ W128 = 2,+ W64 = 3,+ W32 = 4,+ W16 = 5,+ W0 = 6,+ W0Alt = 7,+}++// BP 0x10+N indirect TEV command, one per TEV stage.+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Default)]+pub struct TevIndirect {+ #[bits(0..=1)]+ pub bt: u8, // which indirect stage supplies the coord+ #[bits(2..=3)]+ pub fmt: IndTexFormat,+ #[bits(4)]+ pub bias_s: bool,+ #[bits(5)]+ pub bias_t: bool,+ #[bits(6)]+ pub bias_u: bool,+ #[bits(7..=8)]+ pub bs: IndTexBumpAlpha,+ #[bits(9..=10)]+ pub matrix_index: IndMtxIndex,+ #[bits(11..=12)]+ pub matrix_id: IndMtxId,+ #[bits(13..=15)]+ pub sw: IndTexWrap,+ #[bits(16..=18)]+ pub tw: IndTexWrap,+ #[bits(19)]+ pub lb_utclod: bool,+ #[bits(20)]+ pub fb_addprev: bool,+}++// BP 0x25/0x26 RAS1_SS0/SS1+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Default)]+pub struct Ras1Ss {+ #[bits(0..=3)]+ pub ss0: u8,+ #[bits(4..=7)]+ pub ts0: u8,+ #[bits(8..=11)]+ pub ss1: u8,+ #[bits(12..=15)]+ pub ts1: u8,+}++// BP 0x27 RAS1_IREF+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Default)]+pub struct Ras1IRef {+ #[bits(0..=2)]+ pub bi0: u8,+ #[bits(3..=5)]+ pub bc0: u8,+ #[bits(6..=8)]+ pub bi1: u8,+ #[bits(9..=11)]+ pub bc1: u8,+ #[bits(12..=14)]+ pub bi2: u8,+ #[bits(15..=17)]+ pub bc2: u8,+ #[bits(18..=20)]+ pub bi3: u8,+ #[bits(21..=23)]+ pub bc3: u8,+}++// BP 0x06..=0x0E IND_MTX_{A,B,C}{0,1,2}. Three 32-bit rows together+// describe one 2x3 indirect matrix plus a 5-bit shared scale exponent.+// Elements are 11-bit signed. The combined scale is formed by+// (A[22:24] << 0) | (B[22:24] << 2) | (C[22:23] << 4) per libogc.+#[derive(Debug, Clone, Copy, Default)]+pub struct IndMtx {+ pub a: u32,+ pub b: u32,+ pub c: u32,+}++fn sign_extend_11(val: u32) -> i32 {+ let v = (val & 0x7FF) as i32;+ if v & 0x400 != 0 { v - 0x800 } else { v }+}++impl IndMtx {+ pub fn row0(&self) -> [i32; 3] {+ [sign_extend_11(self.a), sign_extend_11(self.b), sign_extend_11(self.c)]+ }++ pub fn row1(&self) -> [i32; 3] {+ [+ sign_extend_11(self.a >> 11),+ sign_extend_11(self.b >> 11),+ sign_extend_11(self.c >> 11),+ ]+ }++ pub fn scale(&self) -> u8 {+ let s0 = ((self.a >> 22) & 0x3) as u8;+ let s1 = ((self.b >> 22) & 0x3) as u8;+ let s2 = ((self.c >> 22) & 0x1) as u8;+ s0 | (s1 << 2) | (s2 << 4)+ }++ pub fn scale_exponent(&self) -> i32 {+ 17 - self.scale() as i32+ }}#[derive(BitEnum, Debug, PartialEq, Eq, Hash)]diff --git a/crates/gecko/src/flipper/gx/texgen.rs b/crates/gecko/src/flipper/gx/texgen.rsindex 9ad957e..9e7052a 100644--- a/crates/gecko/src/flipper/gx/texgen.rs+++ b/crates/gecko/src/flipper/gx/texgen.rs@@ -1,6 +1,6 @@use super::GraphicsProcessor;-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};+use super::constants::*;+use super::regs::*;impl GraphicsProcessor {pub fn compute_texgen(diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rsindex f4c0a67..d0dad7a 100644--- a/crates/gecko/src/flipper/gx/vertex.rs+++ b/crates/gecko/src/flipper/gx/vertex.rs@@ -1,14 +1,6 @@-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_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::constants::*;use super::math::{Vec3, unpack_rgba};-use super::regs::{- self, AttributeType, ComponentFormat, MatrixIndex0, MatrixIndex1, TexCount, VatA, VatB, VatC, VcdHi, VcdLo,-};+use super::regs::{self, *};use super::{GraphicsProcessor, draw};use crate::host::{DrawData, DrawVertex, GxAction, LightData, RenderSink};use crate::mmio::Mmio;@@ -131,6 +123,35 @@ impl GraphicsProcessor {direction: light_dir[i],});+ // Flatten the three indirect matrices to 6 rows. Row 2M is row+ // 0 of matrix M, row 2M+1 is row 1. The .w lane carries the+ // shared scale exponent (positive means right-shift, negative+ // means left-shift of the mat-mul result).+ let mut indirect_matrices = [[0i32; 4]; 6];+ for m in 0..3 {+ let mtx = &self.cur_indirect_matrices[m];+ let exp = mtx.scale_exponent();+ let r0 = mtx.row0();+ let r1 = mtx.row1();+ indirect_matrices[2 * m] = [r0[0], r0[1], r0[2], exp];+ indirect_matrices[2 * m + 1] = [r1[0], r1[1], r1[2], exp];+ }++ let indirect_scales = [+ [+ self.cur_indirect_scales[0].ss0() as u32,+ self.cur_indirect_scales[0].ts0() as u32,+ self.cur_indirect_scales[0].ss1() as u32,+ self.cur_indirect_scales[0].ts1() as u32,+ ],+ [+ self.cur_indirect_scales[1].ss0() as u32,+ self.cur_indirect_scales[1].ts0() as u32,+ self.cur_indirect_scales[1].ss1() as u32,+ self.cur_indirect_scales[1].ts1() as u32,+ ],+ ];+renderer.exec(GxAction::Draw(DrawData {primitive,vertices: draw_vertices,@@ -141,6 +162,12 @@ impl GraphicsProcessor {tev_color_regs,tev_konst_colors: self.cur_tev_konst_colors,num_tev_stages: self.cur_num_tev_stages,+ indirect_matrices,+ indirect_scales,+ indirect_refs: self.cur_indirect_refs.raw(),+ num_indirect_stages: self.cur_num_indirect_stages,+ bump_imask: self.cur_bump_imask,+ tev_indirect: self.cur_tev_indirect.iter().map(|c| c.raw()).collect(),color_ctrl,alpha_ctrl,ambient_color,diff --git a/crates/gecko/src/flipper/gx/xf.rs b/crates/gecko/src/flipper/gx/xf.rsindex 986038c..c4f9e87 100644--- a/crates/gecko/src/flipper/gx/xf.rs+++ b/crates/gecko/src/flipper/gx/xf.rs@@ -1,8 +1,4 @@-use super::constants::{- ARRAY_BASE_REG, ARRAY_STRIDE_REG, DEPTH_24_BIT_MAX, XF_PROJECTION_BASE, XF_PROJECTION_END, XF_VIEWPORT_BASE,- XF_VIEWPORT_END, XF_VIEWPORT_OFFSET_X, XF_VIEWPORT_OFFSET_Y, XF_VIEWPORT_OFFSET_Z, XF_VIEWPORT_SCALE_X,- XF_VIEWPORT_SCALE_Y, XF_VIEWPORT_SCALE_Z,-};+use super::constants::*;use super::math::Vec3;use super::{GraphicsProcessor, draw};use crate::host::{GxAction, RenderSink};diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 892c454..aeb31cb 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -1,6 +1,8 @@use crate::common::Address;-use crate::flipper::gx::draw::{Primitive, Scissor, Viewport};+use crate::flipper::gx::draw::{Primitive, Scissor, TextureFormat, Viewport};use crate::flipper::gx::regs::{AlphaCompare, BlendMode, ChanCtrl, CullMode, MagFilter, MinFilter, WrapMode, ZMode};+#[cfg(not(target_arch = "wasm32"))]+use std::path::PathBuf;#[derive(Debug)]pub enum GxAction {@@ -24,9 +26,21 @@ pub enum GxAction {id: Address,width: u32,height: u32,+ fmt: TextureFormat,rgba: Vec<u8>,},+ /// Debug action: Drop every cached pipeline, bind group, and texture on+ /// the renderer side. Used by the GX debug window to force fresh decodes.+ InvalidateCaches,++ /// Debug action: Dump every currently cached texture to `dir` as a PNG,+ /// filename including the GX format. Native only.+ #[cfg(not(target_arch = "wasm32"))]+ DumpTextures {+ dir: PathBuf,+ },+/// Bind a previously loaded texture to a TEV texture slot.SetTexture {slot: usize,@@ -143,6 +157,16 @@ pub struct DrawData {pub tev_color_regs: [[f32; 4]; 4],pub tev_konst_colors: [[f32; 4]; 16],pub num_tev_stages: u8,+ // Indirect texturing state. `indirect_matrices` is 6 rows (2 per+ // matrix, matrix N at rows 2*N and 2*N+1) with .xyz holding the+ // 11-bit signed elements and .w holding `17 - scale_exponent`.+ // `tev_indirect` holds the raw IND_CMD per TEV stage (16 entries).+ pub indirect_matrices: [[i32; 4]; 6],+ pub indirect_scales: [[u32; 4]; 2],+ pub indirect_refs: u32,+ pub num_indirect_stages: u8,+ pub bump_imask: u32,+ pub tev_indirect: Vec<u32>,// Lighting state (2 channels: COLOR0/ALPHA0 and COLOR1/ALPHA1)pub color_ctrl: [ChanCtrl; 2],pub alpha_ctrl: [ChanCtrl; 2],diff --git a/crates/web/Cargo.lock b/crates/web/Cargo.lockindex 4a72369..b60ccc2 100644--- a/crates/web/Cargo.lock+++ b/crates/web/Cargo.lock@@ -24,6 +24,12 @@ version = "0.21.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf203f9d3bd8f29f98833d1fbef628df18f759248a547e7e01cfbf63cda36a99"+[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"+[[package]]name = "ahash"version = "0.8.12"@@ -160,6 +166,7 @@ dependencies = ["encase","gecko","glam",+ "png","rustc-hash 2.1.2","tracing","wesl",@@ -475,6 +482,15 @@ dependencies = ["libc",]+[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]+[[package]]name = "crossbeam-channel"version = "0.5.15"@@ -784,6 +800,15 @@ dependencies = ["num-traits",]+[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]+[[package]]name = "fearless_simd"version = "0.3.0"@@ -805,6 +830,16 @@ version = "0.5.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"+[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]+[[package]]name = "fnv"version = "1.0.7"@@ -1560,6 +1595,16 @@ dependencies = ["paste",]+[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]+[[package]]name = "multiversion"version = "0.8.0"@@ -2052,6 +2097,19 @@ version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"+[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.11.1",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide",+]+[[package]]name = "polling"version = "3.11.0"@@ -2426,6 +2484,12 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"+[[package]]name = "simd_cesu8"version = "1.1.1"diff --git a/crates/web/src/debug_ui.rs b/crates/web/src/debug_ui.rsindex 8f8c036..6feabc9 100644--- a/crates/web/src/debug_ui.rs+++ b/crates/web/src/debug_ui.rs@@ -20,6 +20,8 @@ pub struct DebugState {pub run_until_addr_input: String,pub breakpoint_addr_input: String,pub dvd_cover_open: Option<bool>,+ pub gx_invalidate_requested: bool,+ pub gx_dump_requested: bool,}impl Default for DebugState {@@ -44,6 +46,8 @@ impl Default for DebugState {run_until_addr_input: String::new(),breakpoint_addr_input: String::new(),dvd_cover_open: None,+ gx_invalidate_requested: false,+ gx_dump_requested: false,}}}@@ -57,6 +61,14 @@ impl DebugState {emulator.close_cover();}}++ if std::mem::take(&mut self.gx_invalidate_requested) {+ emulator.gx.texture_hashes.clear();+ emulator.render_sink.exec(gecko::host::GxAction::InvalidateCaches);+ }++ // Dump action is for desktop only.+ self.gx_dump_requested = false;self.debugger.tick(emulator);}@@ -126,7 +138,14 @@ impl DebugState {self.debugger.set_state(state);}if self.show_gx_state {- dbglib::windows::gx::show_gx(ctx, &mut self.show_gx_state, &emulator.gx, &emulator.mmio);+ dbglib::windows::gx::show_gx(+ ctx,+ &mut self.show_gx_state,+ &emulator.gx,+ &emulator.mmio,+ &mut self.gx_invalidate_requested,+ &mut self.gx_dump_requested,+ );}if self.show_mmio {dbglib::windows::mmio::show_mmio(