A GameCube/Wii emulator and debugger written in Rust.
overhaul gx pipeline, fix xf channels, lighting, texgen, etc. also added very basic SI gamepad support
Layle3a4b6a4449e7
diff --git a/Cargo.lock b/Cargo.lockindex 1694c6c..a2a838b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2708,6 +2708,7 @@ dependencies = ["gekko","image 0.1.0","pollster",+ "tracing-subscriber","wgpu","winit",]diff --git a/crates/backend-wgpu/src/gx.wgsl b/crates/backend-wgpu/src/gx.wgslindex 59fa388..c8780d8 100644--- a/crates/backend-wgpu/src/gx.wgsl+++ b/crates/backend-wgpu/src/gx.wgsl@@ -3,6 +3,7 @@ struct FrameUniforms {tev_color_reg1: vec4<f32>,tev_color_reg2: vec4<f32>,tev_color_reg3: vec4<f32>,+ tev_konst_colors: array<vec4<f32>, 16>,tev_color_env: array<vec4<u32>, 4>,tev_alpha_env: array<vec4<u32>, 4>,num_tev_stages: u32,@@ -65,7 +66,7 @@ fn extract_bits(val: u32, lo: u32, width: u32) -> u32 {}// TEV color input selector (TevColorIn, 4-bit, 16 variants)-fn tev_color_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>) -> vec3<f32> {+fn tev_color_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> vec3<f32> {switch sel {case 0u: { return regs[0].rgb; } // PrevColorcase 1u: { return vec3(regs[0].a); } // PrevAlpha@@ -81,14 +82,14 @@ fn tev_color_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: arracase 11u: { return vec3(ras_color.a); } // RasAlphacase 12u: { return vec3(1.0); } // Onecase 13u: { return vec3(0.5); } // Half- case 14u: { return vec3(0.0); } // TODO: const+ case 14u: { return konst_color.rgb; } // Konstcase 15u: { return vec3(0.0); } // Zerodefault: { return vec3(0.0); }}}// TEV alpha input selector (TevAlphaIn, 3-bit, 8 variants)-fn tev_alpha_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>) -> f32 {+fn tev_alpha_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: array<vec4<f32>, 4>, konst_color: vec4<f32>) -> f32 {switch sel {case 0u: { return regs[0].a; } // PrevAlphacase 1u: { return regs[1].a; } // Reg0Alpha@@ -96,7 +97,7 @@ fn tev_alpha_in(sel: u32, tex_color: vec4<f32>, ras_color: vec4<f32>, regs: arracase 3u: { return regs[3].a; } // Reg2Alphacase 4u: { return tex_color.a; } // TexAlphacase 5u: { return ras_color.a; } // RasAlpha- case 6u: { return 0.0; } // TODO: const+ case 6u: { return konst_color.a; } // Konstcase 7u: { return 0.0; } // Zerodefault: { return 0.0; }}@@ -227,10 +228,12 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {let c_scale = extract_bits(cenv, 20u, 2u);let c_dest = extract_bits(cenv, 22u, 2u);- let in_a = tev_color_in(c_a, tex_color, ras_color, regs);- let in_b = tev_color_in(c_b, tex_color, ras_color, regs);- let in_c = tev_color_in(c_c, tex_color, ras_color, regs);- let in_d = tev_color_in(c_d, tex_color, ras_color, regs);+ let konst_color = frame.tev_konst_colors[stage];++ let in_a = tev_color_in(c_a, tex_color, ras_color, regs, konst_color);+ let in_b = tev_color_in(c_b, tex_color, ras_color, regs, konst_color);+ let in_c = tev_color_in(c_c, tex_color, ras_color, regs, konst_color);+ let in_d = tev_color_in(c_d, tex_color, ras_color, regs, konst_color);let color_result = tev_combine_color(in_a, in_b, in_c, in_d, c_bias, c_sub, c_scale, c_clamp);// Write RGB to dest, preserve alpha@@ -252,10 +255,10 @@ fn fs_main(in: VsOut) -> @location(0) vec4<f32> {let a_scale = extract_bits(aenv, 20u, 2u);let a_dest = extract_bits(aenv, 22u, 2u);- let ain_a = tev_alpha_in(a_a, tex_color, ras_color, regs);- let ain_b = tev_alpha_in(a_b, tex_color, ras_color, regs);- let ain_c = tev_alpha_in(a_c, tex_color, ras_color, regs);- let ain_d = tev_alpha_in(a_d, tex_color, ras_color, regs);+ let ain_a = tev_alpha_in(a_a, tex_color, ras_color, regs, konst_color);+ let ain_b = tev_alpha_in(a_b, tex_color, ras_color, regs, konst_color);+ let ain_c = tev_alpha_in(a_c, tex_color, ras_color, regs, konst_color);+ let ain_d = tev_alpha_in(a_d, tex_color, ras_color, regs, konst_color);let alpha_result = tev_combine_alpha(ain_a, ain_b, ain_c, ain_d, a_bias, a_sub, a_scale, a_clamp);diff --git a/crates/backend-wgpu/src/helpers.rs b/crates/backend-wgpu/src/helpers.rsindex 38eecc3..07c9a37 100644--- a/crates/backend-wgpu/src/helpers.rs+++ b/crates/backend-wgpu/src/helpers.rs@@ -1,4 +1,4 @@-use gekko::flipper::gx::regs::{BlendFactor, CompareFunc, MagFilter, MinFilter, TevRegisterH, TevRegisterL, WrapMode};+use gekko::flipper::gx::regs::{BlendFactor, CompareFunc, MagFilter, MinFilter, WrapMode};pub fn map_wrap_mode(wrap: WrapMode) -> wgpu::AddressMode {match wrap {@@ -49,25 +49,3 @@ pub fn map_compare_func(f: CompareFunc) -> wgpu::CompareFunction {CompareFunc::Always => wgpu::CompareFunction::Always,}}--pub fn s11_to_f32(val: u16) -> f32 {- let signed = if val & 0x400 != 0 {- val as i32 - 0x800- } else {- val as i32- };- signed as f32 / 255.0-}--pub fn decode_tev_color_regs(lo: &[TevRegisterL; 4], hi: &[TevRegisterH; 4]) -> [[f32; 4]; 4] {- let mut out = [[0.0f32; 4]; 4];- for i in 0..4 {- out[i] = [- s11_to_f32(lo[i].r()),- s11_to_f32(hi[i].g()),- s11_to_f32(hi[i].b()),- s11_to_f32(lo[i].a()),- ];- }- out-}diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 8e6d705..b84b11a 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -18,7 +18,7 @@ impl From<&gekko::flipper::gx::draw::Vertex> for GpuVertex {Self {position: v.position,color: v.color0,- tex0: v.tex0.unwrap_or([0.0, 0.0]),+ tex0: v.texcoords[0].unwrap_or([0.0, 0.0]),}}}@@ -27,6 +27,7 @@ impl From<&gekko::flipper::gx::draw::Vertex> for GpuVertex {#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]struct FrameUniforms {tev_color_regs: [[f32; 4]; 4],+ tev_konst_colors: [[f32; 4]; 16],tev_color_env: [u32; 16],tev_alpha_env: [u32; 16],num_tev_stages: u32,@@ -58,9 +59,9 @@ struct PipelineKey {}impl PipelineKey {- fn from_draw_commands(commands: &DrawCommands) -> Self {- let blend = commands.bp_blend_mode;- let zmode = commands.bp_zmode;+ 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(),@@ -79,6 +80,7 @@ pub struct GxRenderer {pipeline_layout: wgpu::PipelineLayout,surface_format: wgpu::TextureFormat,bind_group_layout: wgpu::BindGroupLayout,+ #[allow(dead_code)]bind_group: wgpu::BindGroup,frame_uniform_buffer: wgpu::Buffer,draw_uniform_buffer: wgpu::Buffer,@@ -424,59 +426,59 @@ impl GxRenderer {return;}- let alpha_cmp = commands.bp_alpha_compare;- let frame_uniform = FrameUniforms {- tev_color_regs: helpers::decode_tev_color_regs(&commands.tev_color_regs_lo, &commands.tev_color_regs_hi),- tev_color_env: commands.tev_color_env.map(|e| e.raw()),- tev_alpha_env: commands.tev_alpha_env.map(|e| e.raw()),- num_tev_stages: commands.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,- _padding: [0; 2],- };-- // Get or create the pipeline for current blend/z state- let pipeline_key = PipelineKey::from_draw_commands(commands);- if !self.pipeline_cache.contains_key(&pipeline_key) {- let pipeline = self.create_pipeline(device, &pipeline_key);- self.pipeline_cache.insert(pipeline_key, pipeline);- }-- // Upload texture slot 0 if present, using cache to avoid redundant uploads- let sampler_key = if let Some(desc) = &commands.textures[0] {- let key = (desc.ram_addr, desc.width, desc.height, desc.format);- if !self.texture_cache.contains_key(&key) {- let (tex, view) = texture::upload_texture(device, queue, ram, desc);- self.texture_cache.insert(key, (tex, view));+ // Ensure all referenced textures are uploaded and pipelines/samplers created+ for dc in &commands.commands {+ for desc in dc.textures.iter().flatten() {+ let key = (desc.ram_addr, desc.width, desc.height, desc.format);+ if !self.texture_cache.contains_key(&key) {+ let (tex, view) = texture::upload_texture(device, queue, ram, desc);+ self.texture_cache.insert(key, (tex, view));+ }+ let sampler_key = (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);+ if !self.sampler_cache.contains_key(&sampler_key) {+ let s = 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()+ });+ self.sampler_cache.insert(sampler_key, s);+ }}- (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter)- } else {- (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear)- };+ 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);+ }+ }- // Get or create sampler for these modes- if !self.sampler_cache.contains_key(&sampler_key) {+ // Ensure fallback sampler exists+ let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);+ if !self.sampler_cache.contains_key(&fallback_sampler_key) {let s = 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),+ label: Some("gx_sampler_fallback"),..Default::default()});- self.sampler_cache.insert(sampler_key, s);+ self.sampler_cache.insert(fallback_sampler_key, s);}+self.scratch_vertices.clear();self.scratch_draws.clear();self.scratch_uniform_bytes.clear();- let stride = self.draw_uniform_stride as usize;+ let draw_stride = self.draw_uniform_stride as usize;let draw_size = std::mem::size_of::<DrawUniforms>();+ let frame_stride = align_up(+ std::mem::size_of::<FrameUniforms>() as u64,+ device.limits().min_uniform_buffer_offset_alignment as u64,+ ) as usize;+ let frame_size = std::mem::size_of::<FrameUniforms>();+ let mut frame_uniform_bytes: Vec<u8> = Vec::new();+ let mut draw_call_indices: Vec<usize> = Vec::new();- for dc in &commands.commands {+ for (dc_idx, dc) in commands.commands.iter().enumerate() {let prev_len = self.scratch_vertices.len();triangulate_into(dc, &mut self.scratch_vertices);let added = self.scratch_vertices.len() - prev_len;@@ -486,17 +488,40 @@ impl GxRenderer {let mvp = commands.projection * dc.modelview;let draw_uniform = DrawUniforms { mvp: mvp.0 };- let start = self.scratch_draws.len() * stride;- self.scratch_uniform_bytes.resize(start + stride, 0);- self.scratch_uniform_bytes[start..start + draw_size].copy_from_slice(bytemuck::bytes_of(&draw_uniform));+ let start = self.scratch_draws.len() * draw_stride;+ self.scratch_uniform_bytes.resize(start + draw_stride, 0);+ self.scratch_uniform_bytes[start..start + draw_size]+ .copy_from_slice(bytemuck::bytes_of(&draw_uniform));++ let alpha_cmp = dc.bp_alpha_compare;+ let frame_uniform = FrameUniforms {+ tev_color_regs: dc.tev_color_regs,+ tev_konst_colors: dc.tev_konst_colors,+ tev_color_env: dc.tev_color_env.map(|e| e.raw()),+ tev_alpha_env: dc.tev_alpha_env.map(|e| e.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,+ _padding: [0; 2],+ };+ let fstart = self.scratch_draws.len() * frame_stride;+ frame_uniform_bytes.resize(fstart + frame_stride, 0);+ frame_uniform_bytes[fstart..fstart + frame_size]+ .copy_from_slice(bytemuck::bytes_of(&frame_uniform));+self.scratch_draws.push((prev_len as u32, added as u32));+ draw_call_indices.push(dc_idx);}if self.scratch_draws.is_empty() {return;}- self.ensure_draw_capacity(device, self.scratch_draws.len());+ let num_draws = self.scratch_draws.len();+ self.ensure_draw_capacity(device, num_draws);if self.scratch_vertices.len() > self.vertex_capacity {self.vertex_capacity = self.scratch_vertices.len().next_power_of_two();@@ -508,51 +533,23 @@ impl GxRenderer {});}- let sampler = &self.sampler_cache[&sampler_key];- let tex_view = if commands.textures[0].is_some() {- let desc = commands.textures[0].as_ref().unwrap();- let key = (desc.ram_addr, desc.width, desc.height, desc.format);- &self.texture_cache[&key].1- } else {- &self.fallback_view- };+ let needed_frame_size = (num_draws * frame_stride) as u64;+ if needed_frame_size > self.frame_uniform_buffer.size() {+ self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("gx_frame_uniforms"),+ size: needed_frame_size,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+ }- queue.write_buffer(&self.frame_uniform_buffer, 0, bytemuck::bytes_of(&frame_uniform));+ queue.write_buffer(&self.frame_uniform_buffer, 0, &frame_uniform_bytes);queue.write_buffer(&self.draw_uniform_buffer, 0, &self.scratch_uniform_bytes);- queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&self.scratch_vertices));-- self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {- label: None,- layout: &self.bind_group_layout,- entries: &[- wgpu::BindGroupEntry {- binding: 0,- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {- buffer: &self.frame_uniform_buffer,- offset: 0,- size: wgpu::BufferSize::new(std::mem::size_of::<FrameUniforms>() as u64),- }),- },- wgpu::BindGroupEntry {- binding: 1,- resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {- buffer: &self.draw_uniform_buffer,- offset: 0,- size: wgpu::BufferSize::new(std::mem::size_of::<DrawUniforms>() as u64),- }),- },- wgpu::BindGroupEntry {- binding: 2,- resource: wgpu::BindingResource::TextureView(tex_view),- },- wgpu::BindGroupEntry {- binding: 3,- resource: wgpu::BindingResource::Sampler(sampler),- },- ],- });-- let pipeline = &self.pipeline_cache[&pipeline_key];+ queue.write_buffer(+ &self.vertex_buffer,+ 0,+ bytemuck::cast_slice(&self.scratch_vertices),+ );let mut encoder = device.create_command_encoder(&Default::default());{@@ -579,12 +576,68 @@ impl GxRenderer {timestamp_writes: None,multiview_mask: None,});- rpass.set_pipeline(pipeline);rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));- for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate() {+ for (index, (first_vertex, vertex_count)) in+ self.scratch_draws.iter().copied().enumerate()+ {+ let dc = &commands.commands[draw_call_indices[index]];+ let pipeline_key = PipelineKey::from_draw_call(dc);+ let pipeline = &self.pipeline_cache[&pipeline_key];+ rpass.set_pipeline(pipeline);++ let (tex_view, sampler) = if let Some(desc) = &dc.textures[0] {+ let tex_key = (desc.ram_addr, desc.width, desc.height, desc.format);+ let sampler_key =+ (desc.wrap_s, desc.wrap_t, desc.mag_filter, desc.min_filter);+ (+ &self.texture_cache[&tex_key].1,+ &self.sampler_cache[&sampler_key],+ )+ } else {+ (&self.fallback_view, &self.sampler_cache[&fallback_sampler_key])+ };++ let frame_offset =+ (index as u64 * frame_stride as u64) as wgpu::BufferAddress;let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;- rpass.set_bind_group(0, &self.bind_group, &[draw_offset]);++ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: None,+ layout: &self.bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: &self.frame_uniform_buffer,+ offset: frame_offset,+ size: wgpu::BufferSize::new(+ std::mem::size_of::<FrameUniforms>() as u64,+ ),+ }),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {+ buffer: &self.draw_uniform_buffer,+ offset: 0,+ size: wgpu::BufferSize::new(+ std::mem::size_of::<DrawUniforms>() as u64,+ ),+ }),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::TextureView(tex_view),+ },+ wgpu::BindGroupEntry {+ binding: 3,+ resource: wgpu::BindingResource::Sampler(sampler),+ },+ ],+ });++ rpass.set_bind_group(0, &bind_group, &[draw_offset]);rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);}}diff --git a/crates/backend-wgpu/src/texture.rs b/crates/backend-wgpu/src/texture.rsindex eedd6d7..71db599 100644--- a/crates/backend-wgpu/src/texture.rs+++ b/crates/backend-wgpu/src/texture.rs@@ -123,7 +123,7 @@ fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize};let intensity = expand_to_8bit(nibble as u16, 15);- put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, 255);+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, intensity);}}}@@ -156,7 +156,7 @@ fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize}let intensity = ram[byte_offset];- put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, 255);+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, intensity);}}}diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex 082eb55..d22bede 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -4,9 +4,11 @@ use winit::{application::ApplicationHandler,event::WindowEvent,event_loop::{ActiveEventLoop, EventLoop},+ keyboard::{KeyCode, PhysicalKey},window::{Window, WindowId},};+use gekko::flipper::si::pad::{self, PadStatus, STICK_CENTER};use gekko::gekko::Gekko;use image::Dol;@@ -40,8 +42,10 @@ impl ApplicationHandler for App {}fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {+ let mut egui_consumed = false;if let (Some(state), Some(window)) = (&mut self.state, &self.window) {- let _ = state.egui_winit.on_window_event(window, &event);+ let response = state.egui_winit.on_window_event(window, &event);+ egui_consumed = response.consumed;}match event {@@ -51,6 +55,12 @@ impl ApplicationHandler for App {state.resize(size.width, size.height);}}+ WindowEvent::KeyboardInput { event, .. } if !egui_consumed => {+ let pressed = event.state.is_pressed();+ if let PhysicalKey::Code(key) = event.physical_key {+ update_pad(self.emulator.primary_controller_mut(), key, pressed);+ }+ }WindowEvent::RedrawRequested => {if let (Some(state), Some(window)) = (&mut self.state, &self.window) {state.render(&mut self.emulator, &mut self.ui, window);@@ -79,7 +89,7 @@ fn main() {.map(|i| &args[i + 1]).or_else(|| args.get(1).filter(|a| !a.starts_with("--")));- let emulator = if let Some(ipl) = ipl_path {+ let mut emulator = if let Some(ipl) = ipl_path {let ipl_data = std::fs::read(ipl).expect("failed to read IPL");Gekko::with_ipl(&ipl_data, idle_skip)} else if let Some(rom) = rom_path {@@ -94,6 +104,11 @@ fn main() {std::process::exit(1);};+ emulator.add_primary_controller(PadStatus {+ connected: true,+ ..PadStatus::default()+ });+let event_loop = EventLoop::new().unwrap();let mut app = App {emulator,@@ -104,3 +119,46 @@ fn main() {};event_loop.run_app(&mut app).unwrap();}++fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {+ let set_button = |buttons: &mut u16, mask: u16, on: bool| {+ if on {+ *buttons |= mask;+ } else {+ *buttons &= !mask;+ }+ };++ match key {+ // Analog stick (digital, full deflection)+ KeyCode::ArrowUp => pad.stick_y = if pressed { 255 } else { STICK_CENTER },+ KeyCode::ArrowDown => pad.stick_y = if pressed { 0 } else { STICK_CENTER },+ KeyCode::ArrowLeft => pad.stick_x = if pressed { 0 } else { STICK_CENTER },+ KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },++ // Face buttons+ KeyCode::KeyX => set_button(&mut pad.buttons, pad::A, pressed),+ KeyCode::KeyZ => set_button(&mut pad.buttons, pad::B, pressed),+ KeyCode::KeyC => set_button(&mut pad.buttons, pad::X, pressed),+ KeyCode::KeyV => set_button(&mut pad.buttons, pad::Y, pressed),+ KeyCode::Enter => set_button(&mut pad.buttons, pad::START, pressed),++ // Triggers+ KeyCode::KeyA => {+ set_button(&mut pad.buttons, pad::L, pressed);+ pad.trigger_left = if pressed { 255 } else { 0 };+ }+ KeyCode::KeyS => {+ set_button(&mut pad.buttons, pad::R, pressed);+ pad.trigger_right = if pressed { 255 } else { 0 };+ }+ KeyCode::KeyD => set_button(&mut pad.buttons, pad::Z, pressed),++ // D-pad+ KeyCode::KeyI => set_button(&mut pad.buttons, pad::DPAD_UP, pressed),+ KeyCode::KeyK => set_button(&mut pad.buttons, pad::DPAD_DOWN, pressed),+ KeyCode::KeyJ => set_button(&mut pad.buttons, pad::DPAD_LEFT, pressed),+ KeyCode::KeyL => set_button(&mut pad.buttons, pad::DPAD_RIGHT, pressed),+ _ => {}+ }+}diff --git a/crates/debugger/src/windows/gx.rs b/crates/debugger/src/windows/gx.rsindex afe657b..475bfc0 100644--- a/crates/debugger/src/windows/gx.rs+++ b/crates/debugger/src/windows/gx.rs@@ -22,10 +22,6 @@ fn texture_preview(ui: &mut egui::Ui, tex: &TextureDescriptor, ram: &[u8]) {ui.label(format!("Mag: {:?} Min: {:?}", tex.mag_filter, tex.min_filter));}-fn mono_header(text: &str) -> RichText {- RichText::new(text).monospace().strong()-}-pub fn show_gx(ctx: &Context, open: &mut bool, gx: &Gx, mmio: &Mmio) {egui::Window::new("GX").open(open).show(ctx, |ui| {let dc = &gx.draw_commands;@@ -34,17 +30,11 @@ pub fn show_gx(ctx: &Context, open: &mut bool, gx: &Gx, mmio: &Mmio) {// Summaryui.horizontal(|ui| {ui.strong(format!("{} draw calls", dc.commands.len()));- ui.separator();- ui.strong(format!("{} TEV stages", dc.num_tev_stages));- ui.separator();- let n_tex = dc.textures.iter().filter(|t| t.is_some()).count();- ui.strong(format!("{n_tex} textures bound"));});ui.separator();// Transform- ui.collapsing("Transform", |ui| {- ui.label("Projection Matrix");+ ui.collapsing("Projection", |ui| {Grid::new("proj").num_columns(4).show(ui, |ui| {for row in 0..4 {for col in 0..4 {@@ -55,249 +45,138 @@ pub fn show_gx(ctx: &Context, open: &mut bool, gx: &Gx, mmio: &Mmio) {});});- // TEV Stages- ui.collapsing(format!("TEV Stages ({})", dc.num_tev_stages), |ui| {- for stage in 0..dc.num_tev_stages as usize {- let color = dc.tev_color_env[stage];- let alpha = dc.tev_alpha_env[stage];- let order = dc.tev_orders[stage / 2];- let (texmap, texcoord, chan, tex_en) = if stage % 2 == 0 {- (- order.texmap0(),- order.texcoord0(),- order.channel0(),- order.tex_enable0(),- )- } else {- (- order.texmap1(),- order.texcoord1(),- order.channel1(),- order.tex_enable1(),- )- };-- ui.collapsing(format!("Stage {stage}"), |ui| {- Grid::new(format!("tev_{stage}"))- .num_columns(2)- .striped(true)- .show(ui, |ui| {- // Texture / raster inputs- ui.label("Texture");- if tex_en {- let primary = if let Some(tex) = dc.textures[texmap as usize] {- format!(- "tex{texmap} / coord{texcoord} — {:?} {}x{}",- tex.format, tex.width, tex.height- )- } else {- format!("tex{texmap} / coord{texcoord} — (unbound)")- };- let resp = ui.label(primary);- if let Some(tex) = dc.textures[texmap as usize] {- resp.on_hover_ui(|ui| texture_preview(ui, &tex, &mmio.ram));- }- } else {- ui.monospace("disabled");- }- ui.end_row();-- ui.label("Raster Channel");- ui.monospace(format!("{chan:?}"));- ui.end_row();-- ui.label("Color A");- ui.monospace(format!("{}", color.a()));- ui.end_row();- ui.label("Color B");- ui.monospace(format!("{}", color.b()));- ui.end_row();- ui.label("Color C");- ui.monospace(format!("{}", color.c()));- ui.end_row();- ui.label("Color D");- ui.monospace(format!("{}", color.d()));- ui.end_row();- ui.label("Color Destination");- ui.monospace(format!("{}", color.dest())).on_hover_text(format!(- "bias={:?} scale={:?} sub={} clamp={}",- color.bias(),- color.scale(),- color.sub(),- color.clamp(),- ));- ui.end_row();-- ui.label("Alpha A");- ui.monospace(format!("{}", alpha.a()));- ui.end_row();- ui.label("Alpha B");- ui.monospace(format!("{}", alpha.b()));- ui.end_row();- ui.label("Alpha C");- ui.monospace(format!("{}", alpha.c()));- ui.end_row();- ui.label("Alpha D");- ui.monospace(format!("{}", alpha.d()));- ui.end_row();- ui.label("Alpha Destination");- ui.monospace(format!("{}", alpha.dest())).on_hover_text(format!(- "bias={:?} scale={:?} sub={} clamp={}",- alpha.bias(),- alpha.scale(),- alpha.sub(),- alpha.clamp(),- ));- ui.end_row();- });- });- }- });-- // Textures- let bound_count = dc.textures.iter().filter(|t| t.is_some()).count();- ui.collapsing(format!("Textures ({bound_count})"), |ui| {- if bound_count == 0 {- ui.label("none bound");- } else {- Grid::new("textures").num_columns(2).striped(true).show(ui, |ui| {- for (slot, tex_opt) in dc.textures.iter().enumerate() {- if let Some(tex) = tex_opt {- ui.label(format!("tex{slot}"));- ui.monospace(format!(- "{:?} {}x{} @ 0x{:08X}",- tex.format, tex.width, tex.height, tex.ram_addr- ))- .on_hover_ui(|ui| texture_preview(ui, tex, &mmio.ram));- ui.end_row();- }- }- });- }- });-- // PE- ui.collapsing("Output (PE)", |ui| {- Grid::new("output").num_columns(2).striped(true).show(ui, |ui| {- let bm = dc.bp_blend_mode;-- ui.label("Blend");- if bm.blend_enable() {- ui.monospace(format!(- "{:?} -> {:?}{}",- bm.src_factor(),- bm.dst_factor(),- if bm.subtract() { " (subtract)" } else { "" },- ))- .on_hover_text(format!(- "Color Write: {} Alpha Write: {} Dither: {}",- bm.color_update(),- bm.alpha_update(),- bm.dither_enable(),- ));- } else {- ui.label("disabled");- }- ui.end_row();-- if bm.logic_op_enable() {- ui.label("Logic Operation");- ui.monospace(format!("{:?}", bm.logic_op()));- ui.end_row();- }-- ui.label("Color Write");- ui.monospace(bm.color_update().to_string());- ui.end_row();-- ui.label("Alpha Write");- ui.monospace(bm.alpha_update().to_string());- ui.end_row();-- let zm = dc.bp_zmode;- ui.label("Depth Test");- if zm.enable() {- ui.monospace(format!("{:?} write={}", zm.func(), zm.update_enable(),));- } else {- ui.label("disabled");- }- ui.end_row();-- let ac = dc.bp_alpha_compare;- ui.label("Alpha Compare");- ui.monospace(format!(- "{:?}({}) {:?} {:?}({})",- ac.comp0(),- ac.ref0(),- ac.op(),- ac.comp1(),- ac.ref1(),- ));- ui.end_row();- });- });-- // TEV Registers- ui.collapsing("TEV Registers", |ui| {- Grid::new("tev_regs").num_columns(5).striped(true).show(ui, |ui| {- ui.label(mono_header("Reg "));- ui.label(mono_header(" R"));- ui.label(mono_header(" G"));- ui.label(mono_header(" B"));- ui.label(mono_header(" A"));- ui.end_row();-- for (i, name) in ["Prev", "Reg0", "Reg1", "Reg2"].iter().enumerate() {- let lo = dc.tev_color_regs_lo[i];- let hi = dc.tev_color_regs_hi[i];- ui.monospace(*name);- ui.monospace(format!("{:4}", lo.r()));- ui.monospace(format!("{:4}", hi.g()));- ui.monospace(format!("{:4}", hi.b()));- ui.monospace(format!("{:4}", lo.a()));- ui.end_row();- }- });- });-- // Draw Calls+ // Draw Calls (each with per-draw state)ui.collapsing(format!("Draw Calls ({})", dc.commands.len()), |ui| {ScrollArea::vertical().id_salt("draw_calls")- .max_height(300.0)+ .max_height(500.0).show(ui, |ui| {for (i, call) in dc.commands.iter().enumerate() {+ let has_tex = call.textures[0].is_some();let heading = RichText::new(format!(- "[{i:>3}] {:?} x {} vertices",+ "[{i:>3}] {:?} x {} verts tev={} {}",call.primitive,call.vertices.len(),+ call.num_tev_stages,+ if has_tex { "tex" } else { "no-tex" },)).monospace();ui.collapsing(heading, |ui| {- ui.label("Modelview matrix");- Grid::new(format!("mv_{i}")).num_columns(4).show(ui, |ui| {- for row in 0..4 {- for col in 0..4 {- ui.monospace(format!("{:+8.3}", call.modelview.0[col][row]));- }- ui.end_row();+ // Texture+ if let Some(tex) = &call.textures[0] {+ ui.collapsing("Texture", |ui| {+ ui.monospace(format!(+ "{:?} {}x{} @ 0x{:08X}",+ tex.format, tex.width, tex.height, tex.ram_addr+ ))+ .on_hover_ui(|ui| texture_preview(ui, tex, &mmio.ram));+ });+ }++ // TEV+ ui.collapsing(format!("TEV ({} stages)", call.num_tev_stages), |ui| {+ for stage in 0..call.num_tev_stages as usize {+ let color = call.tev_color_env[stage];+ let alpha = call.tev_alpha_env[stage];++ ui.collapsing(format!("Stage {stage}"), |ui| {+ Grid::new(format!("tev_{i}_{stage}"))+ .num_columns(2)+ .striped(true)+ .show(ui, |ui| {+ ui.label("Color A");+ ui.monospace(format!("{}", color.a()));+ ui.end_row();+ ui.label("Color B");+ ui.monospace(format!("{}", color.b()));+ ui.end_row();+ ui.label("Color C");+ ui.monospace(format!("{}", color.c()));+ ui.end_row();+ ui.label("Color D");+ ui.monospace(format!("{}", color.d()));+ ui.end_row();+ ui.label("Color Dest");+ ui.monospace(format!("{}", color.dest()));+ ui.end_row();++ ui.label("Alpha A");+ ui.monospace(format!("{}", alpha.a()));+ ui.end_row();+ ui.label("Alpha B");+ ui.monospace(format!("{}", alpha.b()));+ ui.end_row();+ ui.label("Alpha C");+ ui.monospace(format!("{}", alpha.c()));+ ui.end_row();+ ui.label("Alpha D");+ ui.monospace(format!("{}", alpha.d()));+ ui.end_row();+ ui.label("Alpha Dest");+ ui.monospace(format!("{}", alpha.dest()));+ ui.end_row();+ });+ });}});- ui.add_space(2.0);+ // Blend / Depth+ ui.collapsing("Output (PE)", |ui| {+ Grid::new(format!("pe_{i}"))+ .num_columns(2)+ .striped(true)+ .show(ui, |ui| {+ let bm = call.bp_blend_mode;+ ui.label("Blend");+ if bm.blend_enable() {+ ui.monospace(format!(+ "{:?} -> {:?}{}",+ bm.src_factor(),+ bm.dst_factor(),+ if bm.subtract() { " (sub)" } else { "" },+ ));+ } else {+ ui.label("disabled");+ }+ ui.end_row();++ let zm = call.bp_zmode;+ ui.label("Depth");+ if zm.enable() {+ ui.monospace(format!("{:?} write={}", zm.func(), zm.update_enable()));+ } else {+ ui.label("disabled");+ }+ ui.end_row();+ });+ });++ // Modelview+ ui.collapsing("Modelview", |ui| {+ Grid::new(format!("mv_{i}")).num_columns(4).show(ui, |ui| {+ for row in 0..4 {+ for col in 0..4 {+ ui.monospace(format!("{:+8.3}", call.modelview.0[col][row]));+ }+ ui.end_row();+ }+ });+ });++ // Verticeslet preview = call.vertices.len().min(4);for (vi, v) in call.vertices.iter().take(preview).enumerate() {ui.monospace(format!(- "v{vi} position ({:+.3}, {:+.3}, {:+.3})",+ "v{vi} pos ({:+.3}, {:+.3}, {:+.3})",v.position[0], v.position[1], v.position[2],));ui.monospace(format!(- " color ({:.2}, {:.2}, {:.2}, {:.2})",+ " col ({:.2}, {:.2}, {:.2}, {:.2})",v.color0[0], v.color0[1], v.color0[2], v.color0[3],));- if let Some(uv) = v.tex0 {- ui.monospace(format!(" texcoord ({:+.4}, {:+.4})", uv[0], uv[1],));+ if let Some(uv) = v.texcoords[0] {+ ui.monospace(format!(" uv ({:+.4}, {:+.4})", uv[0], uv[1]));}}if call.vertices.len() > preview {diff --git a/crates/gekko/src/flipper/gx.rs b/crates/gekko/src/flipper/gx.rsindex db2fb0d..422b7a5 100644--- a/crates/gekko/src/flipper/gx.rs+++ b/crates/gekko/src/flipper/gx.rs@@ -7,18 +7,21 @@ pub mod regs;use crate::{flipper::gx::{constants::{- ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_NRM, ARRAY_POS, ARRAY_STRIDE_REG, BP_GEN_MODE, BP_PE_ALPHA_COMPARE,- BP_PE_CMODE0, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT, BP_RAS1_TREF0,- BP_REG_SIZE, BP_TEV_COLOR_ENV_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, CP_REG_SIZE, VATA_REG,- VCD_HI_REG, VCD_LO_REG, XF_AMBIENT_COLOR0, XF_CHAN_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_MEM_SIZE,- XF_NRM_MTX_BASE, XF_POS_MTX_STRIDE, XF_PROJECTION_BASE, XF_PROJECTION_END,+ ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_NRM, ARRAY_POS, ARRAY_STRIDE_REG, ARRAY_TEX0, BP_GEN_MODE,+ BP_PE_ALPHA_COMPARE, BP_PE_CMODE0, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT,+ BP_RAS1_TREF0, BP_REG_SIZE, 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,+ CP_REG_SIZE, VATA_REG, VATB_REG, VATC_REG, VCD_HI_REG, VCD_LO_REG, XF_ALPHA_CTRL0, XF_AMBIENT_COLOR0,+ XF_COLOR_CTRL0, XF_DUAL_TEX_ENABLE, XF_DUALTEX_BASE, 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_MATRIX_INDEX_B, XF_MEM_SIZE, XF_NRM_MTX_BASE, XF_NUM_TEXGENS, XF_POS_MTX_STRIDE, XF_POST_MTX_BASE,+ XF_PROJECTION_BASE, XF_PROJECTION_END, XF_TEXGEN_BASE,},draw::DrawCommands,regs::{- AlphaCompare, AttnFn, BlendMode, ChanCtrl, GenMode, MatrixIndex0, TevAlphaEnv, TevColorEnv, TevRegType,- TevRegisterH, TevRegisterL, TxSetImage0, TxSetImage3, TxSetMode0, VatA, VcdHi, VcdLo, ZMode,+ AlphaCompare, AttnFn, BlendMode, ChanCtrl, DualTexGenReg, GenMode, MatrixIndex0, MatrixIndex1, TevAlphaEnv,+ TevColorEnv, TevRegType, TevRegisterH, TevRegisterL, TexGenReg, TxSetImage0, TxSetImage3, TxSetMode0, VatA,+ VatB, VatC, VcdHi, VcdLo, ZMode,},},gekko::Gekko,@@ -35,6 +38,21 @@ pub struct Gx {cp_regs: Vec<u32>,xf_mem: Vec<u32>,fifo: Vec<u8>,++ // Current GX state to snapshot into a DrawCall later+ cur_textures: [Option<draw::TextureDescriptor>; 8],+ cur_tev_color_env: [TevColorEnv; 16],+ cur_tev_alpha_env: [TevAlphaEnv; 16],+ cur_tev_color_regs_lo: [TevRegisterL; 4],+ cur_tev_color_regs_hi: [TevRegisterH; 4],+ cur_tev_const_regs_lo: [TevRegisterL; 4],+ cur_tev_const_regs_hi: [TevRegisterH; 4],+ cur_tev_orders: [regs::TevOrder; 8],+ cur_num_tev_stages: u8,+ cur_tev_konst_colors: [[f32; 4]; 16],+ cur_zmode: ZMode,+ cur_blend_mode: BlendMode,+ cur_alpha_compare: AlphaCompare,}impl Gx {@@ -46,6 +64,19 @@ impl Gx {xf_mem: vec![0; XF_MEM_SIZE],fifo: Vec::with_capacity(256),draw_commands: DrawCommands::default(),+ cur_textures: Default::default(),+ cur_tev_color_env: Default::default(),+ cur_tev_alpha_env: Default::default(),+ cur_tev_color_regs_lo: Default::default(),+ cur_tev_color_regs_hi: Default::default(),+ cur_tev_const_regs_lo: Default::default(),+ cur_tev_const_regs_hi: Default::default(),+ cur_tev_orders: Default::default(),+ cur_num_tev_stages: 0,+ cur_tev_konst_colors: [[0.0; 4]; 16],+ cur_zmode: Default::default(),+ cur_blend_mode: Default::default(),+ cur_alpha_compare: Default::default(),}}@@ -94,23 +125,27 @@ impl Gx {};let fmt = (cmd & 0b111) as usize;- let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG + fmt]);- let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG + fmt]);+ // VCD is global state (single register), VAT is per-format+ let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG]);+ let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG]);let vat_a = VatA::from_raw(self.cp_regs[VATA_REG + fmt]);+ let vat_b = VatB::from_raw(self.cp_regs[VATB_REG + fmt]);+ let vat_c = VatC::from_raw(self.cp_regs[VATC_REG + fmt]);++ let attr_stream_size = |attr: regs::AttributeType, direct_size: usize| -> usize {+ match attr {+ regs::AttributeType::Direct => direct_size,+ regs::AttributeType::Index8 => 1,+ regs::AttributeType::Index16 => 2,+ regs::AttributeType::None => 0,+ }+ };let pos_base = self.cp_regs[ARRAY_BASE_REG + ARRAY_POS] as usize;let pos_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_POS] as usize;let clr0_base = self.cp_regs[ARRAY_BASE_REG + ARRAY_CLR0] as usize;let clr0_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_CLR0] as usize;- let tex0_attr = vcd_hi.tex0();- let tex0_size = match tex0_attr {- regs::AttributeType::Direct => vat_a.tex0_data_size(),- regs::AttributeType::Index8 => 1,- regs::AttributeType::Index16 => 2,- regs::AttributeType::None => 0,- };-let pos_attr = vcd_lo.position();let nrm_attr = vcd_lo.normal();let clr0_attr = vcd_lo.color0();@@ -118,49 +153,120 @@ impl Gx {let nrm_data_size = vat_a.nrm_data_size();let clr0_data_size = vat_a.clr0_data_size();- let pos_stream_size = match pos_attr {- regs::AttributeType::Direct => pos_data_size,- regs::AttributeType::Index8 => 1,- regs::AttributeType::Index16 => 2,- regs::AttributeType::None => 0,- };- let nrm_stream_size = match nrm_attr {- regs::AttributeType::Direct => nrm_data_size,- regs::AttributeType::Index8 => 1,- regs::AttributeType::Index16 => 2,- regs::AttributeType::None => 0,- };- let clr0_stream_size = match clr0_attr {- regs::AttributeType::Direct => clr0_data_size,- regs::AttributeType::Index8 => 1,- regs::AttributeType::Index16 => 2,- regs::AttributeType::None => 0,- };+ let mtx_idx_size = vcd_lo.mtx_idx_count();+ let pos_stream_size = attr_stream_size(pos_attr, pos_data_size);+ let nrm_stream_size = vat_a.nrm_stream_size(nrm_attr);+ let clr0_stream_size = attr_stream_size(clr0_attr, clr0_data_size);+ let clr1_stream_size = attr_stream_size(vcd_lo.color1(), vat_a.clr1_data_size());++ // Build per-texcoord metadata arrays+ let tex_attrs = [+ vcd_hi.tex0(),+ vcd_hi.tex1(),+ vcd_hi.tex2(),+ vcd_hi.tex3(),+ vcd_hi.tex4(),+ vcd_hi.tex5(),+ vcd_hi.tex6(),+ vcd_hi.tex7(),+ ];+ let tex_data_sizes = [+ vat_a.tex0_data_size(),+ vat_b.tex1_data_size(),+ vat_b.tex2_data_size(),+ vat_b.tex3_data_size(),+ vat_b.tex4_data_size(),+ vat_c.tex5_data_size(),+ vat_c.tex6_data_size(),+ vat_c.tex7_data_size(),+ ];+ let tex_fmts = [+ vat_a.tex0_fmt(),+ vat_b.tex1_fmt(),+ vat_b.tex2_fmt(),+ vat_b.tex3_fmt(),+ vat_b.tex4_fmt(),+ vat_c.tex5_fmt(),+ vat_c.tex6_fmt(),+ vat_c.tex7_fmt(),+ ];+ let tex_shifts = [+ vat_a.tex0_shift(),+ vat_b.tex1_shift(),+ vat_b.tex2_shift(),+ vat_b.tex3_shift(),+ vat_c.tex4_shift(),+ vat_c.tex5_shift(),+ vat_c.tex6_shift(),+ vat_c.tex7_shift(),+ ];+ let tex_cnts = [+ vat_a.tex0_cnt(),+ vat_b.tex1_cnt(),+ vat_b.tex2_cnt(),+ vat_b.tex3_cnt(),+ vat_b.tex4_cnt(),+ vat_c.tex5_cnt(),+ vat_c.tex6_cnt(),+ vat_c.tex7_cnt(),+ ];+ let tex_stream_sizes: [usize; 8] = std::array::from_fn(|i| attr_stream_size(tex_attrs[i], tex_data_sizes[i]));+ let tex_bases: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_BASE_REG + ARRAY_TEX0 + i] as usize);+ let tex_strides: [usize; 8] = std::array::from_fn(|i| self.cp_regs[ARRAY_STRIDE_REG + ARRAY_TEX0 + i] as usize);let nrm_base_addr = self.cp_regs[ARRAY_BASE_REG + ARRAY_NRM] as usize;let nrm_stride = self.cp_regs[ARRAY_STRIDE_REG + ARRAY_NRM] as usize;- let vertex_stride = pos_stream_size + nrm_stream_size + clr0_stream_size + tex0_size;+ let vertex_stride = mtx_idx_size+ + pos_stream_size+ + nrm_stream_size+ + clr0_stream_size+ + clr1_stream_size+ + tex_stream_sizes.iter().sum::<usize>();++ if vertex_stride == 0 {+ tracing::warn!("draw call with zero vertex stride, skipping");+ return;+ }+let vertex_count = data.len() / vertex_stride;- // Read matrix indices and lighting state before the vertex loop+ // Per-vertex matrix index handling+ let has_pnmtxidx = vcd_lo.pos_nrm_mtx_idx();+ let tex_mtx_idx_size = mtx_idx_size - has_pnmtxidx as usize; // remaining mtx idx bytes after pnmtxidx++ // Default matrix index from register (used when per-vertex index is absent)let mtx_index_a = MatrixIndex0::from_raw(self.xf_mem[XF_MATRIX_INDEX_A]);- let pos_mtx_base = mtx_index_a.pos_mtx_idx() as usize * XF_POS_MTX_STRIDE;+ let default_pos_mtx_idx = mtx_index_a.pos_mtx_idx();- // Channel 0 lighting state- let chan_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_CHAN_CTRL0]);+ // Channel 0 lighting state (COLOR0 and ALPHA0 have separate controls)+ let color_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_COLOR_CTRL0]);+ let alpha_ctrl = ChanCtrl::from_raw(self.xf_mem[XF_ALPHA_CTRL0]);let ambient_reg = unpack_rgba(self.xf_mem[XF_AMBIENT_COLOR0]);let material_reg = unpack_rgba(self.xf_mem[XF_MATERIAL_COLOR0]);- // Normal matrix: hardware derives index from pos_mtx_idx (SDK Eq 5-6)- let nrm_mtx_idx = (mtx_index_a.pos_mtx_idx() as usize) % 32;- let nrm_mtx_base = XF_NRM_MTX_BASE + nrm_mtx_idx * 3;- let nrm_mtx: [f32; 9] = std::array::from_fn(|i| self.xf_f32(nrm_mtx_base + i));-let mut vertices: Vec<draw::Vertex> = Vec::with_capacity(vertex_count);let mut cur = Cursor::new(&data);for i in 0..vertex_count {+ // Read per-vertex position/normal matrix index, or use register default+ let pos_mtx_idx = if has_pnmtxidx {+ let mut buf = [0u8; 1];+ cur.read_exact(&mut buf).unwrap();+ buf[0] & 0x3F+ } else {+ default_pos_mtx_idx+ };++ // Skip remaining tex matrix index bytes (not yet used)+ cur.set_position(cur.position() + tex_mtx_idx_size as u64);++ // Derive per-vertex position and normal matrix bases+ let pos_mtx_base = pos_mtx_idx as usize * XF_POS_MTX_STRIDE;+ let nrm_mtx_idx = (pos_mtx_idx as usize) & 31;+ let nrm_mtx_base = XF_NRM_MTX_BASE + nrm_mtx_idx * 3;+ let nrm_mtx: [f32; 9] = std::array::from_fn(|i| self.xf_f32(nrm_mtx_base + i));+// Read positionlet position = if pos_attr == regs::AttributeType::Direct {let start = cur.position() as usize;@@ -179,6 +285,13 @@ impl Gx {Self::decode_normal(&data[start..start + nrm_data_size], &vat_a)} else if nrm_attr != regs::AttributeType::None {let nrm_index = read_index(&mut cur, nrm_attr);+ // When nrm_index3 && NBT, the stream contains 3 separate indices+ // (normal, binormal, tangent). Skip the extra 2 — only the normal+ // vector (first index) is needed for lighting.+ if vat_a.nrm_index3() && vat_a.nrm_cnt() == regs::NrmCount::Nbt {+ let idx_size = if nrm_attr == regs::AttributeType::Index8 { 1 } else { 2 };+ cur.set_position(cur.position() + (2 * idx_size) as u64);+ }let nrm_addr = nrm_base_addr + nrm_index * nrm_stride;Self::decode_normal(&mmio.ram[nrm_addr..nrm_addr + nrm_data_size], &vat_a)} else {@@ -198,23 +311,61 @@ impl Gx {Self::decode_color(&mmio.ram[clr0_addr..clr0_addr + clr0_data_size], &vat_a)};- // Read tex0- let tex0 = if tex0_attr == regs::AttributeType::Direct && vat_a.tex0_cnt() == regs::TexCount::St {- let mut s_buf = [0u8; 4];- let mut t_buf = [0u8; 4];- cur.read_exact(&mut s_buf).unwrap();- cur.read_exact(&mut t_buf).unwrap();- Some([f32::from_be_bytes(s_buf), f32::from_be_bytes(t_buf)])- } else {- cur.set_position(cur.position() + tex0_size as u64);- None- };+ // Skip color1 (not yet used for rendering)+ cur.set_position(cur.position() + clr1_stream_size as u64);++ // Read all texcoords (tex0-tex7)+ let mut raw_texcoords: [Option<[f32; 2]>; 8] = [None; 8];+ for tc in 0..8 {+ let tc_attr = tex_attrs[tc];+ let tc_data_size = tex_data_sizes[tc];+ if tc_attr == regs::AttributeType::None {+ continue;+ }+ raw_texcoords[tc] = Some(if tc_attr == regs::AttributeType::Direct {+ let start = cur.position() as usize;+ cur.set_position(cur.position() + tc_data_size as u64);+ Self::decode_texcoord(+ &data[start..start + tc_data_size],+ tex_fmts[tc],+ tex_shifts[tc],+ tex_cnts[tc],+ )+ } else {+ let tc_index = read_index(&mut cur, tc_attr);+ let tc_addr = tex_bases[tc] + tc_index * tex_strides[tc];+ Self::decode_texcoord(+ &mmio.ram[tc_addr..tc_addr + tc_data_size],+ tex_fmts[tc],+ tex_shifts[tc],+ tex_cnts[tc],+ )+ });+ }// Compute per-vertex lightinglet normal_view = Vec3::from(normal).transform(&nrm_mtx).normalize();let pos_view = self.xf_transform_3x4(pos_mtx_base, position);- let final_color =- self.compute_channel_lighting(&chan_ctrl, ambient_reg, material_reg, color0, normal_view, pos_view);+ let final_color = self.compute_channel_lighting(+ &color_ctrl,+ &alpha_ctrl,+ ambient_reg,+ material_reg,+ color0,+ normal_view,+ pos_view,+ );++ // Texture coordinate generation (XF texgen)+ 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));+ }+ // For texcoords beyond num_texgens, pass through raw values+ for tg_idx in num_texgens..8 {+ texcoords[tg_idx] = raw_texcoords[tg_idx];+ }tracing::debug!(vertex = i,@@ -226,33 +377,36 @@ impl Gx {vertices.push(draw::Vertex {position,color0: final_color,- tex0,+ texcoords,});}+ // Modelview uses the register-level default matrix (per-vertex transforms are+ // already applied during lighting via xf_transform_3x4 per vertex)+ let default_mtx_base = default_pos_mtx_idx as usize * XF_POS_MTX_STRIDE;let modelview = draw::Matrix4([[- self.xf_f32(pos_mtx_base),- self.xf_f32(pos_mtx_base + 4),- self.xf_f32(pos_mtx_base + 8),+ self.xf_f32(default_mtx_base),+ self.xf_f32(default_mtx_base + 4),+ self.xf_f32(default_mtx_base + 8),0.0,],[- self.xf_f32(pos_mtx_base + 1),- self.xf_f32(pos_mtx_base + 5),- self.xf_f32(pos_mtx_base + 9),+ self.xf_f32(default_mtx_base + 1),+ self.xf_f32(default_mtx_base + 5),+ self.xf_f32(default_mtx_base + 9),0.0,],[- self.xf_f32(pos_mtx_base + 2),- self.xf_f32(pos_mtx_base + 6),- self.xf_f32(pos_mtx_base + 10),+ self.xf_f32(default_mtx_base + 2),+ self.xf_f32(default_mtx_base + 6),+ self.xf_f32(default_mtx_base + 10),0.0,],[- self.xf_f32(pos_mtx_base + 3),- self.xf_f32(pos_mtx_base + 7),- self.xf_f32(pos_mtx_base + 11),+ self.xf_f32(default_mtx_base + 3),+ self.xf_f32(default_mtx_base + 7),+ self.xf_f32(default_mtx_base + 11),1.0,],]);@@ -260,15 +414,28 @@ impl Gx {tracing::debug!(primitive = format!("{:?}", primitive),vertices = format!("{:?}", vertices),- pos_mtx_idx = mtx_index_a.pos_mtx_idx(),+ pos_mtx_idx = default_pos_mtx_idx,modelview = format!("{:?}", modelview),projection = format!("{:?}", self.draw_commands.projection),"draw call created");++ // Resolve TEV color registers to f32 arrays for the snapshot+ let tev_color_regs = self.resolve_tev_color_regs();+self.draw_commands.commands.push(draw::DrawCall {primitive,vertices,modelview,+ textures: self.cur_textures,+ tev_color_env: self.cur_tev_color_env,+ tev_alpha_env: self.cur_tev_alpha_env,+ 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,});}@@ -408,77 +575,303 @@ impl Gx {result}+ fn decode_texcoord(data: &[u8], fmt: regs::ComponentFormat, shift: u8, cnt: regs::TexCount) -> [f32; 2] {+ let num = cnt.components();+ let divisor = (1u32 << shift) as f32;+ let mut result = [0.0f32; 2];+ let mut off = 0;++ for i in 0..num {+ result[i] = match fmt {+ regs::ComponentFormat::U8 => {+ let v = data[off] as f32 / divisor;+ off += 1;+ v+ }+ regs::ComponentFormat::S8 => {+ let v = data[off] as i8 as f32 / divisor;+ off += 1;+ v+ }+ regs::ComponentFormat::U16 => {+ let v = u16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;+ off += 2;+ v+ }+ regs::ComponentFormat::S16 => {+ let v = i16::from_be_bytes([data[off], data[off + 1]]) as f32 / divisor;+ off += 2;+ v+ }+ regs::ComponentFormat::F32 => {+ let v = f32::from_bits(u32::from_be_bytes([+ data[off],+ data[off + 1],+ data[off + 2],+ data[off + 3],+ ]));+ off += 4;+ v+ }+ };+ }+ result+ }+fn compute_channel_lighting(&self,- chan_ctrl: &ChanCtrl,+ color_ctrl: &ChanCtrl,+ alpha_ctrl: &ChanCtrl,ambient_reg: [f32; 4],material_reg: [f32; 4],vertex_color: [f32; 4],normal: Vec3,pos: Vec3,) -> [f32; 4] {- let mat_color = if chan_ctrl.mat_src() {- vertex_color+ let mat_rgb: [f32; 3] = if color_ctrl.mat_src() {+ [vertex_color[0], vertex_color[1], vertex_color[2]]} else {- material_reg+ [material_reg[0], material_reg[1], material_reg[2]]+ };+ let amb_rgb: [f32; 3] = if color_ctrl.amb_src() {+ [vertex_color[0], vertex_color[1], vertex_color[2]]+ } else {+ [ambient_reg[0], ambient_reg[1], ambient_reg[2]]};- let amb_color = if chan_ctrl.amb_src() { vertex_color } else { ambient_reg };- if !chan_ctrl.enable() {- return mat_color;+ let mat_a = if alpha_ctrl.mat_src() {+ vertex_color[3]+ } else {+ material_reg[3]+ };+ let amb_a = if alpha_ctrl.amb_src() {+ vertex_color[3]+ } else {+ ambient_reg[3]+ };++ // When lighting is disabled, return material color directly+ let color_lit_off = !color_ctrl.enable();+ let alpha_lit_off = !alpha_ctrl.enable();+ if color_lit_off && alpha_lit_off {+ return [mat_rgb[0], mat_rgb[1], mat_rgb[2], mat_a];}- let light_mask = chan_ctrl.light_mask();- let mut acc = amb_color;+ // Compute RGB lighting accumulator+ let mut rgb_out = mat_rgb;+ if !color_lit_off {+ let light_mask = color_ctrl.light_mask();+ let mut acc = amb_rgb;+ for light_id in 0..8u32 {+ if (light_mask >> light_id) & 1 == 0 {+ continue;+ }+ let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;+ let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);+ let factor = self.compute_light_factor(color_ctrl, base, normal, pos);+ acc[0] += light_color[0] * factor;+ acc[1] += light_color[1] * factor;+ acc[2] += light_color[2] * factor;+ }+ rgb_out = std::array::from_fn(|i| mat_rgb[i] * acc[i].clamp(0.0, 1.0));+ }- for light_id in 0..8u32 {- if (light_mask >> light_id) & 1 == 0 {- continue;+ // Compute Alpha lighting accumulator+ let mut a_out = mat_a;+ if !alpha_lit_off {+ let light_mask = alpha_ctrl.light_mask();+ let mut acc_a = amb_a;+ for light_id in 0..8u32 {+ if (light_mask >> light_id) & 1 == 0 {+ continue;+ }+ let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;+ let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);+ let factor = self.compute_light_factor(alpha_ctrl, base, normal, pos);+ acc_a += light_color[3] * factor;}+ a_out = mat_a * acc_a.clamp(0.0, 1.0);+ }- let base = XF_LIGHT_BASE + (light_id as usize) * XF_LIGHT_STRIDE;- let light_color = unpack_rgba(self.xf_mem[base + XF_LIGHT_COLOR]);- let cosatt = self.xf_vec3(base + XF_LIGHT_A0);- let distatt = self.xf_vec3(base + XF_LIGHT_K0);- let light_pos = self.xf_vec3(base + XF_LIGHT_PX);- let light_dir = self.xf_vec3(base + XF_LIGHT_NX);-- let to_light = light_pos - pos;- let to_light_dir = to_light.normalize();- let dot = normal.dot(to_light_dir);-- let diffuse = match chan_ctrl.diff_fn() {- regs::DiffuseFn::None => 1.0,- regs::DiffuseFn::Signed => dot,- regs::DiffuseFn::Clamp => dot.max(0.0),- };+ [rgb_out[0], rgb_out[1], rgb_out[2], a_out]+ }- let attn = match chan_ctrl.attn_fn() {- AttnFn::None => 1.0,- AttnFn::Spot => {- let cos_angle = light_dir.dot(to_light_dir);- let angle_attn = (cosatt.0 + cosatt.1 * cos_angle + cosatt.2 * cos_angle * cos_angle).max(0.0);- let dist = to_light.length();- saturating_div(angle_attn, distatt.0 + distatt.1 * dist + distatt.2 * dist * dist)- }- AttnFn::Spec => {- let cos_angle = normal.dot(to_light_dir);- let angle_attn = (cosatt.0 + cosatt.1 * cos_angle + cosatt.2 * cos_angle * cos_angle).max(0.0);- let cos_ha = normal.dot(light_dir.normalize()).max(0.0);- saturating_div(angle_attn, distatt.0 + distatt.1 * cos_ha + distatt.2 * cos_ha * cos_ha)+ fn compute_light_factor(&self, ctrl: &ChanCtrl, base: usize, normal: Vec3, pos: Vec3) -> f32 {+ let cosatt = self.xf_vec3(base + XF_LIGHT_A0);+ let distatt = self.xf_vec3(base + XF_LIGHT_K0);+ let light_pos = self.xf_vec3(base + XF_LIGHT_PX);+ let light_dir = self.xf_vec3(base + XF_LIGHT_NX);++ // ldir starts as light_pos - vertex_pos for all modes+ // In Spot mode, light_pos is a world position+ // In Spec mode, light_pos is repurposed as the half-angle direction vector+ let mut ldir = light_pos - pos;++ let attn = match ctrl.attn_fn() {+ AttnFn::None => {+ ldir = ldir.normalize();+ 1.0+ }+ AttnFn::Spot => {+ let dist = ldir.length();+ ldir = ldir.normalize();+ let cos_angle = light_dir.dot(ldir);+ let angle_attn = (cosatt.0 + cosatt.1 * cos_angle + cosatt.2 * cos_angle * cos_angle).max(0.0);+ saturating_div(angle_attn, distatt.0 + distatt.1 * dist + distatt.2 * dist * dist)+ }+ AttnFn::Spec => {+ ldir = ldir.normalize();+ let half_dot = ldir.dot(normal);+ if half_dot < 0.0 {+ return 0.0;}- };+ let s = normal.dot(light_dir).max(0.0);+ let att_len = Vec3(1.0, s, s * s);+ let da = if ctrl.diff_fn() != regs::DiffuseFn::None {+ distatt.normalize()+ } else {+ distatt+ };+ saturating_div(att_len.dot(cosatt).max(0.0), att_len.dot(da))+ }+ };- let factor = attn * diffuse;- acc[0] += light_color[0] * factor;- acc[1] += light_color[1] * factor;- acc[2] += light_color[2] * factor;- acc[3] += light_color[3] * factor;- }+ // Diffuse is computed from ldir dotted with normal+ let dif_attn = ldir.dot(normal);+ let diffuse = match ctrl.diff_fn() {+ regs::DiffuseFn::None => 1.0,+ regs::DiffuseFn::Signed => dif_attn,+ regs::DiffuseFn::Clamp => dif_attn.max(0.0),+ };- // Clamp illumination before material multiply- // Material multiplies clamped illumination- std::array::from_fn(|i| mat_color[i] * acc[i].clamp(0.0, 1.0))+ attn * diffuse+ }++ fn compute_texgen(+ &self,+ texgen_idx: usize,+ position: [f32; 3],+ normal: [f32; 3],+ raw_texcoords: &[Option<[f32; 2]>; 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]);++ // Select the source input vector based on texgen source_row+ let src = match tg.source_row() {+ regs::TexGenSrc::Pos => position,+ regs::TexGenSrc::Nrm => normal,+ regs::TexGenSrc::Tex0 => {+ let t = raw_texcoords[0].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex1 => {+ let t = raw_texcoords[1].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex2 => {+ let t = raw_texcoords[2].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex3 => {+ let t = raw_texcoords[3].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex4 => {+ let t = raw_texcoords[4].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex5 => {+ let t = raw_texcoords[5].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex6 => {+ let t = raw_texcoords[6].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ regs::TexGenSrc::Tex7 => {+ let t = raw_texcoords[7].unwrap_or([0.0, 0.0]);+ [t[0], t[1], 1.0]+ }+ // TODO: ???+ _ => [0.0, 0.0, 1.0],+ };++ // Form input vector based on input_form+ let input = match tg.input_form() {+ regs::TexGenInputForm::Ab11 => [src[0], src[1], 1.0, 1.0],+ 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;++ // Multiply input by texture matrix (2x4 or 3x4 depending on projection)+ let (s, t, q) = match tg.projection() {+ regs::TexGenProjection::St => {+ // 2x4 matrix -> (s, t)+ let s = self.xf_f32(tex_mtx_base) * input[0]+ + self.xf_f32(tex_mtx_base + 1) * input[1]+ + self.xf_f32(tex_mtx_base + 2) * input[2]+ + self.xf_f32(tex_mtx_base + 3) * input[3];+ let t = self.xf_f32(tex_mtx_base + 4) * input[0]+ + self.xf_f32(tex_mtx_base + 5) * input[1]+ + self.xf_f32(tex_mtx_base + 6) * input[2]+ + self.xf_f32(tex_mtx_base + 7) * input[3];+ (s, t, 1.0)+ }+ regs::TexGenProjection::Stq => {+ // 3x4 matrix -> (s, t, q)+ let s = self.xf_f32(tex_mtx_base) * input[0]+ + self.xf_f32(tex_mtx_base + 1) * input[1]+ + self.xf_f32(tex_mtx_base + 2) * input[2]+ + self.xf_f32(tex_mtx_base + 3) * input[3];+ let t = self.xf_f32(tex_mtx_base + 4) * input[0]+ + self.xf_f32(tex_mtx_base + 5) * input[1]+ + self.xf_f32(tex_mtx_base + 6) * input[2]+ + self.xf_f32(tex_mtx_base + 7) * input[3];+ let q = self.xf_f32(tex_mtx_base + 8) * input[0]+ + self.xf_f32(tex_mtx_base + 9) * input[1]+ + self.xf_f32(tex_mtx_base + 10) * input[2]+ + self.xf_f32(tex_mtx_base + 11) * input[3];+ (s, t, q)+ }+ };++ // Dual texgen post-transform (normalization + post-matrix multiply)+ let dual_tex_enabled = self.xf_mem[XF_DUAL_TEX_ENABLE] != 0;+ if dual_tex_enabled {+ let post_base = XF_POST_MTX_BASE + dt.post_mtx_idx() as usize * 4;+ // Normalize (s, t, q) only if dt.normalize() is set+ let (ns, nt, nq) = if dt.normalize() {+ let inv_q = if q.abs() > f32::EPSILON { 1.0 / q } else { 1.0 };+ (s * inv_q, t * inv_q, inv_q)+ } else {+ (s, t, q)+ };+ // Post-transform: 3x4 matrix multiply on (ns, nt, nq)+ let ps = self.xf_f32(post_base) * ns+ + self.xf_f32(post_base + 1) * nt+ + self.xf_f32(post_base + 2) * nq+ + self.xf_f32(post_base + 3);+ let pt = self.xf_f32(post_base + 4) * ns+ + self.xf_f32(post_base + 5) * nt+ + self.xf_f32(post_base + 6) * nq+ + self.xf_f32(post_base + 7);+ [ps, pt]+ } else if q.abs() < f32::EPSILON {+ // Weird quirk from Dolphin (VertexShaderGen.cpp), affects neheGX lesson 8+ [(s / 2.0).clamp(-1.0, 1.0), (t / 2.0).clamp(-1.0, 1.0)]+ } else {+ [s / q, t / q]+ }}fn xf_f32(&self, reg: usize) -> f32 {@@ -489,6 +882,120 @@ impl Gx {Vec3(self.xf_f32(reg), self.xf_f32(reg + 1), self.xf_f32(reg + 2))}+ fn s11_to_f32(val: u16) -> f32 {+ let signed = if val & 0x400 != 0 {+ val as i32 - 0x800+ } else {+ val as i32+ };+ signed as f32 / 255.0+ }++ /// Resolve TEV color registers (lo+hi) into [r,g,b,a] float arrays+ fn resolve_tev_color_regs(&self) -> [[f32; 4]; 4] {+ std::array::from_fn(|i| {+ let lo = self.cur_tev_color_regs_lo[i];+ let hi = self.cur_tev_color_regs_hi[i];+ [+ Self::s11_to_f32(lo.r()),+ Self::s11_to_f32(hi.g()),+ Self::s11_to_f32(hi.b()),+ Self::s11_to_f32(lo.a()),+ ]+ })+ }++ /// Resolve per-stage Konst colors from KSEL registers + Konst color registers+ fn resolve_konst_colors(&mut self) {+ let kregs: [[f32; 4]; 4] = std::array::from_fn(|i| {+ let lo = self.cur_tev_const_regs_lo[i];+ let hi = self.cur_tev_const_regs_hi[i];+ [+ Self::s11_to_f32(lo.r()),+ Self::s11_to_f32(hi.g()),+ Self::s11_to_f32(hi.b()),+ Self::s11_to_f32(lo.a()),+ ]+ });++ for stage in 0..16usize {+ let ksel_reg = self.bp_regs[BP_TEV_KSEL_0 + stage / 2];+ let (kcsel, kasel) = if stage % 2 == 0 {+ ((ksel_reg >> 4) & 0x1F, (ksel_reg >> 9) & 0x1F)+ } else {+ ((ksel_reg >> 14) & 0x1F, (ksel_reg >> 19) & 0x1F)+ };++ let rgb = Self::resolve_kcsel(kcsel, &kregs);+ let a = Self::resolve_kasel(kasel, &kregs);+ self.cur_tev_konst_colors[stage] = [rgb[0], rgb[1], rgb[2], a];+ }+ }++ fn resolve_kcsel(sel: u32, kregs: &[[f32; 4]; 4]) -> [f32; 3] {+ match sel {+ 0 => [1.0, 1.0, 1.0], // 1+ 1 => [0.875, 0.875, 0.875], // 7/8+ 2 => [0.75, 0.75, 0.75], // 3/4+ 3 => [0.625, 0.625, 0.625], // 5/8+ 4 => [0.5, 0.5, 0.5], // 1/2+ 5 => [0.375, 0.375, 0.375], // 3/8+ 6 => [0.25, 0.25, 0.25], // 1/4+ 7 => [0.125, 0.125, 0.125], // 1/8+ 12 => [kregs[0][0], kregs[0][1], kregs[0][2]], // K0.RGB+ 13 => [kregs[1][0], kregs[1][1], kregs[1][2]], // K1.RGB+ 14 => [kregs[2][0], kregs[2][1], kregs[2][2]], // K2.RGB+ 15 => [kregs[3][0], kregs[3][1], kregs[3][2]], // K3.RGB+ 16 => [kregs[0][0]; 3], // K0.RRR+ 17 => [kregs[1][0]; 3], // K1.RRR+ 18 => [kregs[2][0]; 3], // K2.RRR+ 19 => [kregs[3][0]; 3], // K3.RRR+ 20 => [kregs[0][1]; 3], // K0.GGG+ 21 => [kregs[1][1]; 3], // K1.GGG+ 22 => [kregs[2][1]; 3], // K2.GGG+ 23 => [kregs[3][1]; 3], // K3.GGG+ 24 => [kregs[0][2]; 3], // K0.BBB+ 25 => [kregs[1][2]; 3], // K1.BBB+ 26 => [kregs[2][2]; 3], // K2.BBB+ 27 => [kregs[3][2]; 3], // K3.BBB+ 28 => [kregs[0][3]; 3], // K0.AAA+ 29 => [kregs[1][3]; 3], // K1.AAA+ 30 => [kregs[2][3]; 3], // K2.AAA+ 31 => [kregs[3][3]; 3], // K3.AAA+ _ => [0.0, 0.0, 0.0],+ }+ }++ fn resolve_kasel(sel: u32, kregs: &[[f32; 4]; 4]) -> f32 {+ match sel {+ 0 => 1.0, // 1+ 1 => 0.875, // 7/8+ 2 => 0.75, // 3/4+ 3 => 0.625, // 5/8+ 4 => 0.5, // 1/2+ 5 => 0.375, // 3/8+ 6 => 0.25, // 1/4+ 7 => 0.125, // 1/8+ 16 => kregs[0][0], // K0.R+ 17 => kregs[1][0], // K1.R+ 18 => kregs[2][0], // K2.R+ 19 => kregs[3][0], // K3.R+ 20 => kregs[0][1], // K0.G+ 21 => kregs[1][1], // K1.G+ 22 => kregs[2][1], // K2.G+ 23 => kregs[3][1], // K3.G+ 24 => kregs[0][2], // K0.B+ 25 => kregs[1][2], // K1.B+ 26 => kregs[2][2], // K2.B+ 27 => kregs[3][2], // K3.B+ 28 => kregs[0][3], // K0.A+ 29 => kregs[1][3], // K1.A+ 30 => kregs[2][3], // K2.A+ 31 => kregs[3][3], // K3.A+ _ => 0.0,+ }+ }+fn xf_transform_3x4(&self, base: usize, v: [f32; 3]) -> Vec3 {Vec3(self.xf_f32(base) * v[0]@@ -587,7 +1094,7 @@ impl Gx {"texture descriptor updated");- self.draw_commands.textures[slot] = Some(draw::TextureDescriptor {+ self.cur_textures[slot] = Some(draw::TextureDescriptor {ram_addr,width: width as u32,height: height as u32,@@ -599,11 +1106,11 @@ impl Gx {});}- // Forward PE render state to draw commands+ // Forward PE render statematch idx {- BP_PE_ZMODE => self.draw_commands.bp_zmode = ZMode::from_raw(val),- BP_PE_CMODE0 => self.draw_commands.bp_blend_mode = BlendMode::from_raw(val),- BP_PE_ALPHA_COMPARE => self.draw_commands.bp_alpha_compare = AlphaCompare::from_raw(val),+ 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),_ => {}}@@ -625,7 +1132,7 @@ impl Gx {dest = format!("{:?}", env.dest()),"TEV color env");- self.draw_commands.tev_color_env[stage] = env;+ self.cur_tev_color_env[stage] = env;} else {let env = TevAlphaEnv::from_raw(val);tracing::debug!(@@ -640,13 +1147,13 @@ impl Gx {dest = format!("{:?}", env.dest()),"TEV alpha env");- self.draw_commands.tev_alpha_env[stage] = env;+ self.cur_tev_alpha_env[stage] = env;}}// TEV rasterizer order registers (RAS1_TREF0-7, 0x28-0x2F)if idx >= BP_RAS1_TREF0 && idx < BP_RAS1_TREF0 + BP_RAS1_TREF_COUNT {- self.draw_commands.tev_orders[idx - BP_RAS1_TREF0] = regs::TevOrder::from_raw(val);+ self.cur_tev_orders[idx - BP_RAS1_TREF0] = regs::TevOrder::from_raw(val);}// TEV color registers (0xE0-0xE7): pairs of lo/hi writes@@ -662,8 +1169,8 @@ impl Gx {"TEV register lo");match reg.reg_type() {- TevRegType::Color => self.draw_commands.tev_color_regs_lo[reg_idx] = reg,- TevRegType::Constant => self.draw_commands.tev_const_regs_lo[reg_idx] = reg,+ TevRegType::Color => self.cur_tev_color_regs_lo[reg_idx] = reg,+ TevRegType::Constant => self.cur_tev_const_regs_lo[reg_idx] = reg,}} else {let reg = TevRegisterH::from_raw(val);@@ -675,8 +1182,8 @@ impl Gx {"TEV register hi");match reg.reg_type() {- TevRegType::Color => self.draw_commands.tev_color_regs_hi[reg_idx] = reg,- TevRegType::Constant => self.draw_commands.tev_const_regs_hi[reg_idx] = reg,+ TevRegType::Color => self.cur_tev_color_regs_hi[reg_idx] = reg,+ TevRegType::Constant => self.cur_tev_const_regs_hi[reg_idx] = reg,}}}@@ -686,7 +1193,8 @@ impl Gx {let gen_mode = GenMode::from_raw(val);let stages = gen_mode.num_tev_stages() + 1;tracing::debug!(num_tev_stages = stages, "GEN_MODE");- self.draw_commands.num_tev_stages = stages;+ self.cur_num_tev_stages = stages;+ self.resolve_konst_colors();}// PE finishdiff --git a/crates/gekko/src/flipper/gx/constants.rs b/crates/gekko/src/flipper/gx/constants.rsindex 15a42ba..bd7bc24 100644--- a/crates/gekko/src/flipper/gx/constants.rs+++ b/crates/gekko/src/flipper/gx/constants.rs@@ -23,6 +23,8 @@ pub const XF_MEM_SIZE: usize = 0x1058;pub const VCD_LO_REG: usize = 0x50;pub const VCD_HI_REG: usize = 0x60;pub const VATA_REG: usize = 0x70;+pub const VATB_REG: usize = 0x80;+pub const VATC_REG: usize = 0x90;pub const ARRAY_BASE_REG: usize = 0xA0;pub const ARRAY_STRIDE_REG: usize = 0xB0;@@ -30,6 +32,7 @@ pub const ARRAY_POS: usize = 0;pub const ARRAY_NRM: usize = 1;pub const ARRAY_CLR0: usize = 2;pub const ARRAY_CLR1: usize = 3;+pub const ARRAY_TEX0: usize = 4;// XF memory addressespub const XF_MODELVIEW_BASE: usize = 0x0000;@@ -37,6 +40,7 @@ pub const XF_MODELVIEW_END: usize = 0x000B;pub const XF_PROJECTION_BASE: usize = 0x1020;pub const XF_PROJECTION_END: usize = 0x1026;pub const XF_MATRIX_INDEX_A: usize = 0x1018;+pub const XF_MATRIX_INDEX_B: usize = 0x1019;pub const XF_POS_MTX_STRIDE: usize = 4;// XF normal matrix (3x3)@@ -62,7 +66,18 @@ pub const XF_LIGHT_NZ: usize = 15;// XF channel configurationpub const XF_AMBIENT_COLOR0: usize = 0x100A;pub const XF_MATERIAL_COLOR0: usize = 0x100C;-pub const XF_CHAN_CTRL0: usize = 0x100E;+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+pub const XF_ALPHA_CTRL1: usize = 0x1011; // ALPHA1 channel control++// XF texture coordinate generation+pub const XF_TEXGEN_BASE: usize = 0x1040; // 0x1040-0x1047+pub const XF_DUALTEX_BASE: usize = 0x1050; // 0x1050-0x1057+pub const XF_NUM_TEXGENS: usize = 0x103F;+pub const XF_DUAL_TEX_ENABLE: usize = 0x1012; // TODO: only bit 0 used?+pub const XF_TEX_MTX_BASE: usize = 0x0078; // texture transform matrices (each 2x4 or 3x4)+pub const XF_POST_MTX_BASE: usize = 0x0500; // post-transform matrices (3x4, stride 4x3)// BP texture register base addresses (maps 0-3: base, maps 4-7: base + 0x20)pub const BP_TX_SETMODE0_I0: usize = 0x80; // TX_SETMODE0 maps 0-3@@ -94,3 +109,6 @@ pub 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)pub const BP_TEV_REGISTERL_0: usize = 0xE0;pub const BP_TEV_REGISTERH_0: usize = 0xE1;++// BP TEV KSEL (Konst Selection) registers+pub const BP_TEV_KSEL_0: usize = 0xF6; // 0xF6-0xFD, 8 registers covering 16 stagesdiff --git a/crates/gekko/src/flipper/gx/draw.rs b/crates/gekko/src/flipper/gx/draw.rsindex 1253c3e..eeb40fe 100644--- a/crates/gekko/src/flipper/gx/draw.rs+++ b/crates/gekko/src/flipper/gx/draw.rs@@ -1,6 +1,5 @@use super::regs::{- AlphaCompare, BlendMode, MagFilter, MinFilter, TevAlphaEnv, TevColorEnv, TevOrder, TevRegisterH, TevRegisterL,- WrapMode, ZMode,+ AlphaCompare, BlendMode, MagFilter, MinFilter, TevAlphaEnv, TevColorEnv, WrapMode, ZMode,};use chapa::BitEnum;@@ -39,7 +38,7 @@ impl Primitive {pub struct Vertex {pub position: [f32; 3],pub color0: [f32; 4],- pub tex0: Option<[f32; 2]>,+ pub texcoords: [Option<[f32; 2]>; 8],}#[derive(BitEnum, Debug, PartialEq, Eq, Hash)]@@ -73,6 +72,21 @@ pub struct DrawCall {pub primitive: Primitive,pub vertices: Vec<Vertex>,pub modelview: Matrix4,++ // Textures bound at draw time+ pub textures: [Option<TextureDescriptor>; 8],++ // 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,}#[derive(Debug, Clone, Copy)]@@ -104,22 +118,4 @@ impl std::ops::Mul for Matrix4 {pub struct DrawCommands {pub projection: Matrix4,pub commands: Vec<DrawCall>,- pub textures: [Option<TextureDescriptor>; 8],-- // TEV state- pub tev_color_env: [TevColorEnv; 16],- pub tev_alpha_env: [TevAlphaEnv; 16],-- // RGBA for each TEV register- pub tev_color_regs_lo: [TevRegisterL; 4],- pub tev_color_regs_hi: [TevRegisterH; 4],- pub tev_const_regs_lo: [TevRegisterL; 4],- pub tev_const_regs_hi: [TevRegisterH; 4],- pub tev_orders: [TevOrder; 8],- pub num_tev_stages: u8,-- // BP state- pub bp_zmode: ZMode,- pub bp_blend_mode: BlendMode,- pub bp_alpha_compare: AlphaCompare,}diff --git a/crates/gekko/src/flipper/gx/fifo.rs b/crates/gekko/src/flipper/gx/fifo.rsindex 35950b8..3880c2c 100644--- a/crates/gekko/src/flipper/gx/fifo.rs+++ b/crates/gekko/src/flipper/gx/fifo.rs@@ -1,8 +1,8 @@use super::constants::{BP_CMD, CALL_DL_CMD, CP_CMD, INV_VTX_CACHE_CMD, NOP_CMD, XF_CMD};use crate::flipper::gx::{Gx,- constants::{DRAW_COMMANDS_END, DRAW_COMMANDS_START, VATA_REG, VCD_HI_REG, VCD_LO_REG},- regs::{AttributeType, VatA, VcdHi, VcdLo},+ constants::{DRAW_COMMANDS_END, DRAW_COMMANDS_START, VATA_REG, VATB_REG, VATC_REG, VCD_HI_REG, VCD_LO_REG},+ regs::{AttributeType, VatA, VatB, VatC, VcdHi, VcdLo},};use std::io::{Cursor, Read};@@ -128,39 +128,35 @@ impl Gx {}fn vertex_stride(&self, vertex_format_index: usize) -> usize {- let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG + vertex_format_index]);- let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG + vertex_format_index]);+ // VCD is global state (single register), VAT is per-format+ let vcd_lo = VcdLo::from_raw(self.cp_regs[VCD_LO_REG]);+ let vcd_hi = VcdHi::from_raw(self.cp_regs[VCD_HI_REG]);let vat_a = VatA::from_raw(self.cp_regs[VATA_REG + vertex_format_index]);-- let tex0_size = match vcd_hi.tex0() {- AttributeType::Direct => vat_a.tex0_data_size(),- AttributeType::Index8 => 1,- AttributeType::Index16 => 2,- AttributeType::None => 0,- };-- let pos_size = match vcd_lo.position() {- AttributeType::Direct => vat_a.pos_data_size(),- AttributeType::Index8 => 1,- AttributeType::Index16 => 2,- AttributeType::None => 0,- };-- let nrm_size = match vcd_lo.normal() {- AttributeType::Direct => vat_a.nrm_data_size(),- AttributeType::Index8 => 1,- AttributeType::Index16 => 2,- AttributeType::None => 0,- };-- let clr0_size = match vcd_lo.color0() {- AttributeType::Direct => vat_a.clr0_data_size(),- AttributeType::Index8 => 1,- AttributeType::Index16 => 2,- AttributeType::None => 0,+ let vat_b = VatB::from_raw(self.cp_regs[VATB_REG + vertex_format_index]);+ let vat_c = VatC::from_raw(self.cp_regs[VATC_REG + vertex_format_index]);++ let attr_size = |attr: AttributeType, direct_size: usize| -> usize {+ match attr {+ AttributeType::Direct => direct_size,+ AttributeType::Index8 => 1,+ AttributeType::Index16 => 2,+ AttributeType::None => 0,+ }};- pos_size + nrm_size + clr0_size + tex0_size+ vcd_lo.mtx_idx_count()+ + attr_size(vcd_lo.position(), vat_a.pos_data_size())+ + vat_a.nrm_stream_size(vcd_lo.normal())+ + attr_size(vcd_lo.color0(), vat_a.clr0_data_size())+ + attr_size(vcd_lo.color1(), vat_a.clr1_data_size())+ + attr_size(vcd_hi.tex0(), vat_a.tex0_data_size())+ + attr_size(vcd_hi.tex1(), vat_b.tex1_data_size())+ + attr_size(vcd_hi.tex2(), vat_b.tex2_data_size())+ + attr_size(vcd_hi.tex3(), vat_b.tex3_data_size())+ + attr_size(vcd_hi.tex4(), vat_b.tex4_data_size())+ + attr_size(vcd_hi.tex5(), vat_c.tex5_data_size())+ + attr_size(vcd_hi.tex6(), vat_c.tex6_data_size())+ + attr_size(vcd_hi.tex7(), vat_c.tex7_data_size())}}diff --git a/crates/gekko/src/flipper/gx/regs.rs b/crates/gekko/src/flipper/gx/regs.rsindex c799c14..a372b42 100644--- a/crates/gekko/src/flipper/gx/regs.rs+++ b/crates/gekko/src/flipper/gx/regs.rs@@ -261,6 +261,12 @@ pub struct VatA {#[bits(14..=16)]pub clr0_fmt: ColorFormat,+ #[bits(17)]+ pub clr1_cnt: ColorCount,++ #[bits(18..=20)]+ pub clr1_fmt: ColorFormat,+#[bits(21)]pub tex0_cnt: TexCount,@@ -269,6 +275,12 @@ pub struct VatA {#[bits(25..=29)]pub tex0_shift: u8,++ #[bits(30)]+ pub byte_dequant: bool,++ #[bits(31)]+ pub nrm_index3: bool,}impl VatA {@@ -280,35 +292,224 @@ impl VatA {self.nrm_cnt().components() * self.nrm_fmt().size()}+ /// Number of bytes the normal attribute occupies in the FIFO stream.+ pub fn nrm_stream_size(&self, attr: AttributeType) -> usize {+ match attr {+ AttributeType::None => 0,+ AttributeType::Direct => self.nrm_data_size(),+ AttributeType::Index8 => {+ if self.nrm_index3() && self.nrm_cnt() == NrmCount::Nbt { 3 } else { 1 }+ }+ AttributeType::Index16 => {+ if self.nrm_index3() && self.nrm_cnt() == NrmCount::Nbt { 6 } else { 2 }+ }+ }+ }+pub fn clr0_data_size(&self) -> usize {self.clr0_fmt().data_size(self.clr0_cnt())}+ pub fn clr1_data_size(&self) -> usize {+ self.clr1_fmt().data_size(self.clr1_cnt())+ }+pub fn tex0_data_size(&self) -> usize {self.tex0_cnt().components() * self.tex0_fmt().size()}}+// CP 0x80-0x87 (one per vertex format)+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy)]+pub struct VatB {+ #[bits(0)]+ pub tex1_cnt: TexCount,++ #[bits(1..=3)]+ pub tex1_fmt: ComponentFormat,++ #[bits(4..=8)]+ pub tex1_shift: u8,++ #[bits(9)]+ pub tex2_cnt: TexCount,++ #[bits(10..=12)]+ pub tex2_fmt: ComponentFormat,++ #[bits(13..=17)]+ pub tex2_shift: u8,++ #[bits(18)]+ pub tex3_cnt: TexCount,++ #[bits(19..=21)]+ pub tex3_fmt: ComponentFormat,++ #[bits(22..=26)]+ pub tex3_shift: u8,++ #[bits(27)]+ pub tex4_cnt: TexCount,++ #[bits(28..=30)]+ pub tex4_fmt: ComponentFormat,+}++impl VatB {+ pub fn tex1_data_size(&self) -> usize {+ self.tex1_cnt().components() * self.tex1_fmt().size()+ }++ pub fn tex2_data_size(&self) -> usize {+ self.tex2_cnt().components() * self.tex2_fmt().size()+ }++ pub fn tex3_data_size(&self) -> usize {+ self.tex3_cnt().components() * self.tex3_fmt().size()+ }++ pub fn tex4_data_size(&self) -> usize {+ self.tex4_cnt().components() * self.tex4_fmt().size()+ }+}++// CP 0x90-0x97 (one per vertex format)+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy)]+pub struct VatC {+ #[bits(0..=4)]+ pub tex4_shift: u8,++ #[bits(5)]+ pub tex5_cnt: TexCount,++ #[bits(6..=8)]+ pub tex5_fmt: ComponentFormat,++ #[bits(9..=13)]+ pub tex5_shift: u8,++ #[bits(14)]+ pub tex6_cnt: TexCount,++ #[bits(15..=17)]+ pub tex6_fmt: ComponentFormat,++ #[bits(18..=22)]+ pub tex6_shift: u8,++ #[bits(23)]+ pub tex7_cnt: TexCount,++ #[bits(24..=26)]+ pub tex7_fmt: ComponentFormat,++ #[bits(27..=31)]+ pub tex7_shift: u8,+}++impl VatC {+ pub fn tex5_data_size(&self) -> usize {+ self.tex5_cnt().components() * self.tex5_fmt().size()+ }++ pub fn tex6_data_size(&self) -> usize {+ self.tex6_cnt().components() * self.tex6_fmt().size()+ }++ pub fn tex7_data_size(&self) -> usize {+ self.tex7_cnt().components() * self.tex7_fmt().size()+ }+}+// CP 0x60-0x67 (one per vertex format)#[chapa::bitfield(u32, order = lsb0)]#[derive(Debug, Clone, Copy)]pub struct VcdHi {#[bits(0..=1)]pub tex0: AttributeType,++ #[bits(2..=3)]+ pub tex1: AttributeType,++ #[bits(4..=5)]+ pub tex2: AttributeType,++ #[bits(6..=7)]+ pub tex3: AttributeType,++ #[bits(8..=9)]+ pub tex4: AttributeType,++ #[bits(10..=11)]+ pub tex5: AttributeType,++ #[bits(12..=13)]+ pub tex6: AttributeType,++ #[bits(14..=15)]+ pub tex7: AttributeType,}-// CP 0x50+// CP 0x50-0x57#[chapa::bitfield(u32, order = lsb0)]#[derive(Debug, Clone, Copy)]pub struct VcdLo {- #[bits(9..=10)]+ #[bits(0, alias = "pmidx")]+ pub pos_nrm_mtx_idx: bool,++ #[bits(1, alias = "t0midx")]+ pub tex0_mtx_idx: bool,++ #[bits(2, alias = "t1midx")]+ pub tex1_mtx_idx: bool,++ #[bits(3, alias = "t2midx")]+ pub tex2_mtx_idx: bool,++ #[bits(4, alias = "t3midx")]+ pub tex3_mtx_idx: bool,++ #[bits(5, alias = "t4midx")]+ pub tex4_mtx_idx: bool,++ #[bits(6, alias = "t5midx")]+ pub tex5_mtx_idx: bool,++ #[bits(7, alias = "t6midx")]+ pub tex6_mtx_idx: bool,++ #[bits(8, alias = "t7midx")]+ pub tex7_mtx_idx: bool,++ #[bits(9..=10, alias = "pos")]pub position: AttributeType,- #[bits(11..=12)]+ #[bits(11..=12, alias = "nrm")]pub normal: AttributeType,- #[bits(13..=14)]+ #[bits(13..=14, alias = "col0")]pub color0: AttributeType,++ #[bits(15..=16, alias = "col1")]+ pub color1: AttributeType,+}++impl VcdLo {+ /// Number of matrix index bytes in the vertex stream.+ pub fn mtx_idx_count(&self) -> usize {+ self.pos_nrm_mtx_idx() as usize+ + self.tex0_mtx_idx() as usize+ + self.tex1_mtx_idx() as usize+ + self.tex2_mtx_idx() as usize+ + self.tex3_mtx_idx() as usize+ + self.tex4_mtx_idx() as usize+ + self.tex5_mtx_idx() as usize+ + self.tex6_mtx_idx() as usize+ + self.tex7_mtx_idx() as usize+ }}#[chapa::bitfield(u32, order = lsb0)]@@ -640,7 +841,57 @@ pub struct MatrixIndex0 {pub pos_mtx_idx: u8,#[bits(6..=11)]- pub nrm_mtx_idx: u8,+ pub tex0_mtx_idx: u8,++ #[bits(12..=17)]+ pub tex1_mtx_idx: u8,++ #[bits(18..=23)]+ pub tex2_mtx_idx: u8,++ #[bits(24..=29)]+ pub tex3_mtx_idx: u8,+}++impl MatrixIndex0 {+ pub fn tex_mtx_idx(&self, n: usize) -> u8 {+ match n {+ 0 => self.tex0_mtx_idx(),+ 1 => self.tex1_mtx_idx(),+ 2 => self.tex2_mtx_idx(),+ 3 => self.tex3_mtx_idx(),+ _ => 0,+ }+ }+}++// XF 0x1019 Matrix Index B (tex4-7 matrix indices)+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Default)]+pub struct MatrixIndex1 {+ #[bits(0..=5)]+ pub tex4_mtx_idx: u8,++ #[bits(6..=11)]+ pub tex5_mtx_idx: u8,++ #[bits(12..=17)]+ pub tex6_mtx_idx: u8,++ #[bits(18..=23)]+ pub tex7_mtx_idx: u8,+}++impl MatrixIndex1 {+ pub fn tex_mtx_idx(&self, n: usize) -> u8 {+ match n {+ 4 => self.tex4_mtx_idx(),+ 5 => self.tex5_mtx_idx(),+ 6 => self.tex6_mtx_idx(),+ 7 => self.tex7_mtx_idx(),+ _ => 0,+ }+ }}// Diffuse lighting function@@ -703,3 +954,74 @@ impl ChanCtrl {}}}++// XF 0x1040-0x1047: Texture coordinate generation parameters+#[derive(Debug, PartialEq, BitEnum)]+pub enum TexGenProjection {+ St, // 2x4 matrix (s, t output)+ Stq, // 3x4 matrix (s, t, q output)+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum TexGenInputForm {+ Ab11, // (a, b, 1.0, 1.0)+ Abc1, // (a, b, c, 1.0)+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum TexGenType {+ Regular = 0,+ EmbossMap = 1,+ Color0 = 2,+ Color1 = 3,+}++#[derive(Debug, PartialEq, BitEnum)]+pub enum TexGenSrc {+ Pos = 0,+ Nrm = 1,+ Color = 2,+ BinNrm = 3,+ Tangent = 4,+ Tex0 = 5,+ Tex1 = 6,+ Tex2 = 7,+ Tex3 = 8,+ Tex4 = 9,+ Tex5 = 10,+ Tex6 = 11,+ Tex7 = 12,+}++#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy)]+pub struct TexGenReg {+ #[bits(1)]+ pub projection: TexGenProjection,++ #[bits(2, alias = "input_form")]+ pub texgen_input_form: TexGenInputForm,++ #[bits(4..=6)]+ pub texgen_type: TexGenType,++ #[bits(7..=11)]+ pub source_row: TexGenSrc,++ #[bits(12..=14)]+ pub emboss_source: u8,++ #[bits(15..=17)]+ pub emboss_light: u8,+}++// XF 0x1050-0x1057: Dual texture transform (post-transform)+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy)]+pub struct DualTexGenReg {+ #[bits(0..=5)]+ pub post_mtx_idx: u8,++ #[bits(6)]+ pub normalize: bool,+}diff --git a/crates/gekko/src/flipper/si.rs b/crates/gekko/src/flipper/si.rsindex 9de74f0..f0a6db8 100644--- a/crates/gekko/src/flipper/si.rs+++ b/crates/gekko/src/flipper/si.rs@@ -1,24 +1,49 @@+pub mod pad;pub mod regs;use crate::mmio::constants::SI_BASE;use crate::mmio::traits::{MmioAccess, MmioRegister};+use pad::{GC_CONTROLLER_ID, PadStatus};++const NUM_CHANNELS: usize = 4;++#[derive(Clone, Copy, Debug)]+pub struct SiChannel {+ pub out: u32,+ pub in_hi: u32,+ pub in_lo: u32,+}++impl Default for SiChannel {+ fn default() -> Self {+ Self {+ out: 0,+ in_hi: 0,+ in_lo: 0,+ }+ }+}pub struct Si {+ pub channels: [SiChannel; NUM_CHANNELS],pub poll: regs::SiPoll,pub comcsr: regs::SiComcsr,pub status: regs::SiStatusRegister,- pub ch0_in_buf_hi: regs::SiChannel0InBufHi,- pub io_buf: regs::SiIoBuf,+ pub exi_clock_count: u32,+ pub io_buffer: [u8; 128],+ pub pad_state: [PadStatus; NUM_CHANNELS],}impl Si {pub fn new() -> Self {Self {+ channels: [SiChannel::default(); NUM_CHANNELS],poll: regs::SiPoll::from_raw(0),comcsr: regs::SiComcsr::from_raw(0),status: regs::SiStatusRegister::from_raw(0),- ch0_in_buf_hi: regs::SiChannel0InBufHi::from_raw(0),- io_buf: regs::SiIoBuf::from_raw(0),+ exi_clock_count: 0,+ io_buffer: [0u8; 128],+ pad_state: [PadStatus::default(); NUM_CHANNELS],}}@@ -31,46 +56,266 @@ impl Si {regs::SiPoll,regs::SiComcsr,regs::SiStatusRegister,- regs::SiChannel0InBufHi,- regs::SiIoBuf,);+ pub fn mmio_read_u32(&mut self, offset: u32) -> u32 {+ match offset {+ // Channel registers: each channel occupies 0x0C bytes+ 0x00..=0x2F => self.read_channel_reg(offset),+ // EXI clock count+ 0x3C => self.exi_clock_count,+ // SI I/O buffer+ 0x80..=0xFC => {+ let i = (offset - 0x80) as usize;+ u32::from_be_bytes([+ self.io_buffer[i],+ self.io_buffer[i + 1],+ self.io_buffer[i + 2],+ self.io_buffer[i + 3],+ ])+ }+ // SIPOLL / SICOMCSR / SISR+ _ => self.read_raw(SI_BASE + offset, 4).unwrap_or_else(|| {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u32");+ 0+ }),+ }+ }++ pub fn mmio_read_u16(&mut self, offset: u32) -> u16 {+ match offset {+ 0x00..=0x2F | 0x3C..=0x3E | 0x80..=0xFE => {+ let aligned = offset & !3;+ let word = self.mmio_read_u32(aligned);+ if offset & 2 == 0 {+ (word >> 16) as u16+ } else {+ word as u16+ }+ }+ _ => self.read_raw(SI_BASE + offset, 2).unwrap_or_else(|| {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u16");+ 0+ }) as u16,+ }+ }+pub fn mmio_read_u8(&mut self, offset: u32) -> u8 {- self.read_raw(SI_BASE + offset, 1).unwrap_or_else(|| {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u8");- 0- }) as u8+ match offset {+ 0x00..=0x2F | 0x3C..=0x3F | 0x80..=0xFF => {+ let aligned = offset & !3;+ let word = self.mmio_read_u32(aligned);+ let byte_pos = offset & 3;+ ((word >> ((3 - byte_pos) * 8)) & 0xFF) as u8+ }+ _ => self.read_raw(SI_BASE + offset, 1).unwrap_or_else(|| {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u8");+ 0+ }) as u8,+ }+ }++ pub fn mmio_write_u32(&mut self, offset: u32, val: u32) {+ match offset {+ 0x00..=0x2F => self.write_channel_reg(offset, val),+ 0x3C => self.exi_clock_count = val,+ 0x80..=0xFC => {+ let i = (offset - 0x80) as usize;+ self.io_buffer[i..i + 4].copy_from_slice(&val.to_be_bytes());+ }+ _ => {+ if !self.write_raw(SI_BASE + offset, 4, val) {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u32");+ }+ }+ }+ }++ pub fn mmio_write_u16(&mut self, offset: u32, val: u16) {+ match offset {+ 0x00..=0x2F | 0x3C..=0x3E | 0x80..=0xFE => {+ let aligned = offset & !3;+ let mut word = self.read_channel_or_buf_u32_raw(aligned);+ if offset & 2 == 0 {+ word = (word & 0x0000_FFFF) | ((val as u32) << 16);+ } else {+ word = (word & 0xFFFF_0000) | (val as u32);+ }+ self.mmio_write_u32(aligned, word);+ }+ _ => {+ if !self.write_raw(SI_BASE + offset, 2, val as u32) {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u16");+ }+ }+ }}pub fn mmio_write_u8(&mut self, offset: u32, val: u8) {- if !self.write_raw(SI_BASE + offset, 1, val as u32) {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u8");+ match offset {+ 0x00..=0x2F | 0x3C..=0x3F | 0x80..=0xFF => {+ let aligned = offset & !3;+ let mut word = self.read_channel_or_buf_u32_raw(aligned);+ let byte_pos = offset & 3;+ let shift = (3 - byte_pos) * 8;+ word = (word & !(0xFF << shift)) | ((val as u32) << shift);+ self.mmio_write_u32(aligned, word);+ }+ _ => {+ if !self.write_raw(SI_BASE + offset, 1, val as u32) {+ tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u8");+ }+ }}}- pub fn mmio_read_u16(&mut self, offset: u32) -> u16 {- self.read_raw(SI_BASE + offset, 2).unwrap_or_else(|| {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u16");- 0- }) as u16+ fn read_channel_reg(&mut self, offset: u32) -> u32 {+ let ch = (offset / 0x0C) as usize;+ match offset % 0x0C {+ 0x00 => self.channels[ch].out,+ 0x04 => {+ self.clear_rdst(ch);+ self.channels[ch].in_hi+ }+ 0x08 => {+ self.clear_rdst(ch);+ self.channels[ch].in_lo+ }+ _ => 0,+ }}- pub fn mmio_write_u16(&mut self, offset: u32, val: u16) {- if !self.write_raw(SI_BASE + offset, 2, val as u32) {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u16");+ fn write_channel_reg(&mut self, offset: u32, val: u32) {+ let ch = (offset / 0x0C) as usize;+ match offset % 0x0C {+ 0x00 => self.channels[ch].out = val,+ 0x04 => self.channels[ch].in_hi = val,+ 0x08 => self.channels[ch].in_lo = val,+ _ => {}}}- pub fn mmio_read_u32(&mut self, offset: u32) -> u32 {- self.read_raw(SI_BASE + offset, 4).unwrap_or_else(|| {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI read_u32");- 0- })+ fn read_channel_or_buf_u32_raw(&self, offset: u32) -> u32 {+ match offset {+ 0x00..=0x2F => {+ let ch = (offset / 0x0C) as usize;+ match offset % 0x0C {+ 0x00 => self.channels[ch].out,+ 0x04 => self.channels[ch].in_hi,+ 0x08 => self.channels[ch].in_lo,+ _ => 0,+ }+ }+ 0x3C => self.exi_clock_count,+ 0x80..=0xFC => {+ let i = (offset - 0x80) as usize;+ u32::from_be_bytes([+ self.io_buffer[i],+ self.io_buffer[i + 1],+ self.io_buffer[i + 2],+ self.io_buffer[i + 3],+ ])+ }+ _ => 0,+ }}- pub fn mmio_write_u32(&mut self, offset: u32, val: u32) {- if !self.write_raw(SI_BASE + offset, 4, val) {- tracing::error!(offset = format!("{offset:08X}"), "unhandled SI write_u32");+ fn clear_rdst(&mut self, ch: usize) {+ match ch {+ 0 => self.status = self.status.with_rdst0(false),+ 1 => self.status = self.status.with_rdst1(false),+ 2 => self.status = self.status.with_rdst2(false),+ 3 => self.status = self.status.with_rdst3(false),+ _ => {}+ }+ }++ fn set_rdst(&mut self, ch: usize) {+ match ch {+ 0 => self.status = self.status.with_rdst0(true),+ 1 => self.status = self.status.with_rdst1(true),+ 2 => self.status = self.status.with_rdst2(true),+ 3 => self.status = self.status.with_rdst3(true),+ _ => {}+ }+ }++ pub fn update_polling(&mut self) {+ let enable = self.poll.enable();+ for ch in 0..NUM_CHANNELS {+ // EN0 is bit 7 of the 4-bit enable field, EN3 is bit 4+ let ch_enabled = (enable >> (3 - ch)) & 1 != 0;+ if ch_enabled && self.pad_state[ch].connected {+ self.channels[ch].in_hi = self.pad_state[ch].encode_hi();+ self.channels[ch].in_lo = self.pad_state[ch].encode_lo();+ self.set_rdst(ch);+ }+ }++ // Update RDST interrupt in COMCSR+ let any_rdst = self.status.rdst0()+ || self.status.rdst1()+ || self.status.rdst2()+ || self.status.rdst3();+ self.comcsr = self.comcsr.with_rdst_interrupt(any_rdst);+ }++ pub fn run_si_buffer(&mut self) {+ let channel = self.comcsr.channel() as usize;+ let cmd = self.io_buffer[0];++ let connected = self.pad_state[channel].connected;++ if connected {+ match cmd {+ // return 3-byte device ID+ 0x00 | 0xFF => {+ self.io_buffer[0] = (GC_CONTROLLER_ID) as u8;+ self.io_buffer[1] = (GC_CONTROLLER_ID >> 16) as u8;+ self.io_buffer[2] = (GC_CONTROLLER_ID >> 8) as u8;+ }+ // return current pad data (8 bytes)+ 0x40 => {+ let hi = self.pad_state[channel].encode_hi();+ let lo = self.pad_state[channel].encode_lo();+ self.io_buffer[0..4].copy_from_slice(&hi.to_be_bytes());+ self.io_buffer[4..8].copy_from_slice(&lo.to_be_bytes());+ }+ // return 10-byte origin data / recalibration payload+ 0x41 | 0x42 => {+ let origin = PadStatus::encode_origin();+ self.io_buffer[0..10].copy_from_slice(&origin);+ }+ _ => {+ tracing::warn!(cmd = format!("{cmd:02X}"), channel, "unknown SI buffer command");+ }+ }+ self.comcsr = self.comcsr.with_com_error(false);+ } else {+ self.comcsr = self.comcsr.with_com_error(true);+ }++ self.comcsr = self.comcsr.with_tstart(false).with_tc_interrupt(true);+ }++ pub fn send_channel_commands(&mut self) {+ let enable = self.poll.enable();+ for ch in 0..NUM_CHANNELS {+ let ch_enabled = (enable >> (3 - ch)) & 1 != 0;+ if !ch_enabled {+ continue;+ }++ if !self.pad_state[ch].connected {+ match ch {+ 0 => self.status = self.status.with_norep0(true),+ 1 => self.status = self.status.with_norep1(true),+ 2 => self.status = self.status.with_norep2(true),+ 3 => self.status = self.status.with_norep3(true),+ _ => {}+ }+ continue;+ }}}}diff --git a/crates/gekko/src/flipper/si/pad.rs b/crates/gekko/src/flipper/si/pad.rsnew file mode 100644index 0000000..8d6b489--- /dev/null+++ b/crates/gekko/src/flipper/si/pad.rs@@ -0,0 +1,75 @@+pub const DPAD_LEFT: u16 = 0x0001;+pub const DPAD_RIGHT: u16 = 0x0002;+pub const DPAD_DOWN: u16 = 0x0004;+pub const DPAD_UP: u16 = 0x0008;+pub const Z: u16 = 0x0010;+pub const R: u16 = 0x0020;+pub const L: u16 = 0x0040;+pub const A: u16 = 0x0100;+pub const B: u16 = 0x0200;+pub const X: u16 = 0x0400;+pub const Y: u16 = 0x0800;+pub const START: u16 = 0x1000;++pub const USE_ORIGIN: u16 = 0x0080;+pub const STICK_CENTER: u8 = 128;+pub const GC_CONTROLLER_ID: u32 = 0x0900_0000;++#[derive(Clone, Copy, Debug)]+pub struct PadStatus {+ pub buttons: u16,+ pub stick_x: u8,+ pub stick_y: u8,+ pub substick_x: u8,+ pub substick_y: u8,+ pub trigger_left: u8,+ pub trigger_right: u8,+ pub connected: bool,+}++impl Default for PadStatus {+ fn default() -> Self {+ Self {+ buttons: 0,+ stick_x: STICK_CENTER,+ stick_y: STICK_CENTER,+ substick_x: STICK_CENTER,+ substick_y: STICK_CENTER,+ trigger_left: 0,+ trigger_right: 0,+ connected: false,+ }+ }+}++impl PadStatus {+ // [buttons|USE_ORIGIN (16)] [stick_x (8)] [stick_y (8)]+ pub fn encode_hi(&self) -> u32 {+ let btns = (self.buttons | USE_ORIGIN) as u32;+ (btns << 16) | ((self.stick_x as u32) << 8) | (self.stick_y as u32)+ }++ // [substick_x (8)] [substick_y (8)] [trigger_l (8)] [trigger_r (8)]+ pub fn encode_lo(&self) -> u32 {+ ((self.substick_x as u32) << 24)+ | ((self.substick_y as u32) << 16)+ | ((self.trigger_left as u32) << 8)+ | (self.trigger_right as u32)+ }++ // recalibration payload+ pub fn encode_origin() -> [u8; 10] {+ [+ 0x00,+ 0x00,+ STICK_CENTER,+ STICK_CENTER,+ STICK_CENTER,+ STICK_CENTER,+ 0x00,+ 0x00,+ 0x00,+ 0x00,+ ]+ }+}diff --git a/crates/gekko/src/flipper/si/regs.rs b/crates/gekko/src/flipper/si/regs.rsindex ed25e40..feaa874 100644--- a/crates/gekko/src/flipper/si/regs.rs+++ b/crates/gekko/src/flipper/si/regs.rs@@ -83,7 +83,6 @@ impl MmioAccess<Si> for SiComcsr {if self.tc_interrupt() {csr = csr.with_tc_interrupt(false);}-if self.rdst_interrupt() {csr = csr.with_rdst_interrupt(false);}@@ -97,27 +96,96 @@ impl MmioAccess<Si> for SiComcsr {.with_in_length(self.in_length()).with_out_length(self.out_length()).with_channel_enable(self.channel_enable())- .with_channel_number(self.channel_number())- .with_tstart(self.tstart());+ .with_channel_number(self.channel_number());si.comcsr = csr;++ // Process SI buffer transfer when TSTART is written+ if self.tstart() {+ si.run_si_buffer();+ }}}// 0xCC006438 4 R/W SISR - SI Status Register-crate::mmio_register! {- SiStatusRegister: u32 @ 0xCC006438 => Si.status {}+ SiStatusRegister: u32 @ 0xCC006438 {+ // Channel 3+ #[bits(0)] pub unrun3: bool,+ #[bits(1)] pub ovrun3: bool,+ #[bits(2)] pub coll3: bool,+ #[bits(3)] pub norep3: bool,+ #[bits(4)] pub wrst3: bool,+ #[bits(5)] pub rdst3: bool,++ // Channel 2+ #[bits(8)] pub unrun2: bool,+ #[bits(9)] pub ovrun2: bool,+ #[bits(10)] pub coll2: bool,+ #[bits(11)] pub norep2: bool,+ #[bits(12)] pub wrst2: bool,+ #[bits(13)] pub rdst2: bool,++ // Channel 1+ #[bits(16)] pub unrun1: bool,+ #[bits(17)] pub ovrun1: bool,+ #[bits(18)] pub coll1: bool,+ #[bits(19)] pub norep1: bool,+ #[bits(20)] pub wrst1: bool,+ #[bits(21)] pub rdst1: bool,++ // Channel 0+ #[bits(24)] pub unrun0: bool,+ #[bits(25)] pub ovrun0: bool,+ #[bits(26)] pub coll0: bool,+ #[bits(27)] pub norep0: bool,+ #[bits(28)] pub wrst0: bool,+ #[bits(29)] pub rdst0: bool,++ #[bits(31)] pub wr: bool,+ }}-// 0xCC00643C 4 R/W SI Channel 0 Input Buffer High--crate::mmio_register! {- SiChannel0InBufHi: u32 @ 0xCC00643C => Si.ch0_in_buf_hi {}-}+impl MmioAccess<Si> for SiStatusRegister {+ fn read(si: &Si) -> Self {+ si.status+ }-// 0xCC006480 4 R/W SI I/O Buffer+ fn write(self, si: &mut Si) {+ let mut status = si.status;++ if self.norep0() { status = status.with_norep0(false); }+ if self.coll0() { status = status.with_coll0(false); }+ if self.ovrun0() { status = status.with_ovrun0(false); }+ if self.unrun0() { status = status.with_unrun0(false); }++ if self.norep1() { status = status.with_norep1(false); }+ if self.coll1() { status = status.with_coll1(false); }+ if self.ovrun1() { status = status.with_ovrun1(false); }+ if self.unrun1() { status = status.with_unrun1(false); }++ if self.norep2() { status = status.with_norep2(false); }+ if self.coll2() { status = status.with_coll2(false); }+ if self.ovrun2() { status = status.with_ovrun2(false); }+ if self.unrun2() { status = status.with_unrun2(false); }++ if self.norep3() { status = status.with_norep3(false); }+ if self.coll3() { status = status.with_coll3(false); }+ if self.ovrun3() { status = status.with_ovrun3(false); }+ if self.unrun3() { status = status.with_unrun3(false); }++ if self.wr() {+ si.status = status;+ si.send_channel_commands();+ status = si.status;+ status = status+ .with_wr(false)+ .with_wrst0(false)+ .with_wrst1(false)+ .with_wrst2(false)+ .with_wrst3(false);+ }-crate::mmio_register! {- SiIoBuf: u32 @ 0xCC006480 => Si.io_buf {}+ si.status = status;+ }}diff --git a/crates/gekko/src/gekko.rs b/crates/gekko/src/gekko.rsindex a27bd49..cc27e00 100644--- a/crates/gekko/src/gekko.rs+++ b/crates/gekko/src/gekko.rs@@ -1,7 +1,7 @@use crate::{cpu::{self, Cpu, IPL_RESET_VECTOR, semantics::Instruction},exi::{Exi, macronix::ExiMacronix},- flipper::{ai::Ai, cp::Cp, di::Di, dsp::Dsp, gx::Gx, mi::Mi, pe::Pe, pi::Pi, si::Si, vi::Vi},+ flipper::{ai::Ai, cp::Cp, di::Di, dsp::Dsp, gx::Gx, mi::Mi, pe::Pe, pi::Pi, si::{Si, pad}, vi::Vi},idle::{IDLE_LOOP_MAX_INSTRS, IdleCheck, IdleDetector},mmio::Mmio,scheduler::{CYCLES_PER_VSYNC, EventKind, Scheduler},@@ -130,6 +130,11 @@ impl Gekko {return;}+ // TODO: hack IPL state machine+ if self.cpu.pc == 0x81301284 {+ self.cpu.pc += 4;+ }+// Fetch and execute next instructionself.cpu.cia = self.cpu.pc;self.cpu.nia = self.cpu.cia.wrapping_add(4);@@ -160,6 +165,9 @@ impl Gekko {pub fn run_until_vsync(&mut self) {self.vsync_pending = false;+ // Update SI controller input at the start of each frame+ self.si.update_polling();+ self.check_si_interrupts();while !self.vsync_pending {self.step();}@@ -180,4 +188,12 @@ impl Gekko {let fmt = self.vi.dcr.video_format();(fmt.columns(), fmt.lines())}++ pub fn add_primary_controller(&mut self, input: pad::PadStatus) {+ self.si.pad_state[0] = input;+ }++ pub fn primary_controller_mut(&mut self) -> &mut pad::PadStatus {+ &mut self.si.pad_state[0]+ }}diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.tomlindex 81b8746..3ab762c 100644--- a/crates/tinyapp/Cargo.toml+++ b/crates/tinyapp/Cargo.toml@@ -15,3 +15,4 @@ egui-wgpu = "0.33"egui-winit = { version = "0.33", features = ["wayland", "x11"] }egui_plot = "0.34"bytemuck = { version = "1", features = ["derive"] }+tracing-subscriber = { version = "0.3", features = ["env-filter"] }diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex d910e5d..7020b90 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -1,5 +1,6 @@use egui::ViewportId;use egui_plot::{Line, Plot, PlotPoints};+use gekko::flipper::si::pad::{self, PadStatus, STICK_CENTER};use gekko::flipper::vi::regs::RefreshRate;use gekko::gekko::Gekko;use image::Dol;@@ -11,6 +12,7 @@ use winit::{application::ApplicationHandler,event::WindowEvent,event_loop::{ActiveEventLoop, EventLoop},+ keyboard::{KeyCode, PhysicalKey},window::{Window, WindowId},};@@ -455,6 +457,12 @@ impl ApplicationHandler for App {state.resize(size.width, size.height);}}+ WindowEvent::KeyboardInput { event, .. } => {+ let pressed = event.state.is_pressed();+ if let PhysicalKey::Code(key) = event.physical_key {+ update_pad(self.emulator.primary_controller_mut(), key, pressed);+ }+ }WindowEvent::RedrawRequested => {if let (Some(state), Some(window)) = (&mut self.state, &self.window) {state.render(&mut self.emulator, window);@@ -467,6 +475,14 @@ impl ApplicationHandler for App {}fn main() {+ tracing_subscriber::fmt()+ .without_time()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),+ )+ .init();+let args: Vec<String> = env::args().collect();let present_mode = std::env::args()@@ -482,7 +498,7 @@ fn main() {.map(|i| &args[i + 1]).or_else(|| args.get(1).filter(|a| !a.starts_with("--")));- let emulator = if let Some(ipl) = ipl_path {+ let mut emulator = if let Some(ipl) = ipl_path {let ipl_data = std::fs::read(ipl).expect("failed to read IPL");Gekko::with_ipl(&ipl_data, idle_skip)} else if let Some(rom) = rom_path {@@ -497,6 +513,12 @@ fn main() {std::process::exit(1);};+ // Channel 0 always has a controller connected+ emulator.add_primary_controller(PadStatus {+ connected: true,+ ..PadStatus::default()+ });+let event_loop = EventLoop::new().unwrap();let mut app = App {emulator,@@ -506,3 +528,47 @@ fn main() {};event_loop.run_app(&mut app).unwrap();}++fn update_pad(pad: &mut PadStatus, key: KeyCode, pressed: bool) {+ let set_button = |buttons: &mut u16, mask: u16, on: bool| {+ if on {+ *buttons |= mask;+ } else {+ *buttons &= !mask;+ }+ };++ match key {+ // Analog stick+ KeyCode::ArrowUp => pad.stick_y = if pressed { 255 } else { STICK_CENTER },+ KeyCode::ArrowDown => pad.stick_y = if pressed { 0 } else { STICK_CENTER },+ KeyCode::ArrowLeft => pad.stick_x = if pressed { 0 } else { STICK_CENTER },+ KeyCode::ArrowRight => pad.stick_x = if pressed { 255 } else { STICK_CENTER },++ // Face buttons+ KeyCode::KeyX => set_button(&mut pad.buttons, pad::A, pressed),+ KeyCode::KeyZ => set_button(&mut pad.buttons, pad::B, pressed),+ KeyCode::KeyC => set_button(&mut pad.buttons, pad::X, pressed),+ KeyCode::KeyV => set_button(&mut pad.buttons, pad::Y, pressed),+ KeyCode::Enter => set_button(&mut pad.buttons, pad::START, pressed),++ // Triggers+ KeyCode::KeyA => {+ set_button(&mut pad.buttons, pad::L, pressed);+ pad.trigger_left = if pressed { 255 } else { 0 };+ }+ KeyCode::KeyS => {+ set_button(&mut pad.buttons, pad::R, pressed);+ pad.trigger_right = if pressed { 255 } else { 0 };+ }+ KeyCode::KeyD => set_button(&mut pad.buttons, pad::Z, pressed),++ // D-pad+ KeyCode::KeyI => set_button(&mut pad.buttons, pad::DPAD_UP, pressed),+ KeyCode::KeyK => set_button(&mut pad.buttons, pad::DPAD_DOWN, pressed),+ KeyCode::KeyJ => set_button(&mut pad.buttons, pad::DPAD_LEFT, pressed),+ KeyCode::KeyL => set_button(&mut pad.buttons, pad::DPAD_RIGHT, pressed),++ _ => {}+ }+}