A GameCube/Wii emulator and debugger written in Rust.
all my homies hate efb copies
Layle3d81456eb857
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rsindex 9e36a3d..b6ad77d 100644--- a/crates/backend-wgpu/src/action.rs+++ b/crates/backend-wgpu/src/action.rs@@ -205,9 +205,15 @@ impl GxRenderer {src_y,src_w,src_h,+ dst_h,+ gamma,clear,clear_color,clear_z,+ color_update,+ alpha_update,+ z_update,+ alpha_supported,} => {self.flush_pending_draws(device, queue);self.execute_copy_xfb(@@ -218,9 +224,15 @@ impl GxRenderer {*src_y,*src_w,*src_h,+ *dst_h,+ *gamma,*clear,*clear_color,*clear_z,+ *color_update,+ *alpha_update,+ *z_update,+ *alpha_supported,);}@@ -237,21 +249,16 @@ impl GxRenderer {src_h,copy_format: _copy_format,mipmap: _mipmap,- stride: _,+ stride: _stride,clear,clear_color,clear_z,color_update,- alpha_update: _,- z_update: _,+ alpha_update,+ z_update,+ alpha_supported,+ depth_copy: _depth_copy,} => {- // Dolphin (`BPFunctions::ClearScreen`) clears per-channel- // using the current blend/depth write masks; if a channel- // is not write-enabled it is not cleared. Our- // `clear_region` wipes color+depth together.- // TODO: split `clear_region` into color- and depth-only- // variants and gate on each mask independently.- let effective_clear = *clear && *color_update;self.flush_pending_draws(device, queue);// With `efb-writeback`: read the EFB back, encode it in@@ -268,17 +275,23 @@ impl GxRenderer {*src_h,*_copy_format,*_mipmap,- effective_clear,+ *_stride,+ *_depth_copy,+ *clear,*clear_color,*clear_z,+ *color_update,+ *alpha_update,+ *z_update,+ *alpha_supported,);// Default path: no readback, no encode, no RAM touch. Texture// invalidation happens on the emu side via a `texture_hashes`// drop. We only need to honor the post-copy clear here.#[cfg(not(feature = "efb-writeback"))]- if effective_clear {- self.efb_clear.clear_region(+ if *clear {+ self.efb_clear.clear_region_masked(device,queue,&self.efb_msaa_view,@@ -292,6 +305,9 @@ impl GxRenderer {*src_h,*clear_color,*clear_z,+ *color_update,+ *alpha_update && *alpha_supported,+ *z_update,);}}@@ -397,8 +413,16 @@ impl GxRenderer {let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {label: Some("gx_action_render_pass"),color_attachments: &[Some(wgpu::RenderPassColorAttachment {- view: &self.efb_msaa_view,- resolve_target: Some(&self.efb_view),+ view: if crate::EFB_SAMPLE_COUNT == 1 {+ &self.efb_view+ } else {+ &self.efb_msaa_view+ },+ resolve_target: if crate::EFB_SAMPLE_COUNT == 1 {+ None+ } else {+ Some(&self.efb_view)+ },ops: wgpu::Operations {load: color_load,store: wgpu::StoreOp::Store,diff --git a/crates/backend-wgpu/src/clear.rs b/crates/backend-wgpu/src/clear.rsindex 487553d..824af46 100644--- a/crates/backend-wgpu/src/clear.rs+++ b/crates/backend-wgpu/src/clear.rs@@ -7,12 +7,67 @@ struct ClearUniforms {}pub(crate) struct EfbClear {- pipeline: wgpu::RenderPipeline,- bind_group_layout: wgpu::BindGroupLayout,+ pipeline_all_depth: wgpu::RenderPipeline,+ pipeline_rgb_depth: wgpu::RenderPipeline,+ pipeline_alpha_depth: wgpu::RenderPipeline,+ pipeline_none_depth: wgpu::RenderPipeline,+ pipeline_all: wgpu::RenderPipeline,+ pipeline_rgb: wgpu::RenderPipeline,+ pipeline_alpha: wgpu::RenderPipeline,uniform_buffer: wgpu::Buffer,bind_group: wgpu::BindGroup,}+fn create_clear_pipeline(+ device: &wgpu::Device,+ shader: &wgpu::ShaderModule,+ layout: &wgpu::PipelineLayout,+ color_format: wgpu::TextureFormat,+ depth_format: wgpu::TextureFormat,+ sample_count: u32,+ color_write_mask: wgpu::ColorWrites,+ depth_write_enabled: bool,+) -> wgpu::RenderPipeline {+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("efb_clear_pipeline"),+ layout: Some(layout),+ vertex: wgpu::VertexState {+ module: shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: color_format,+ blend: None,+ write_mask: color_write_mask,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ ..Default::default()+ },+ depth_stencil: Some(wgpu::DepthStencilState {+ format: depth_format,+ depth_write_enabled,+ depth_compare: wgpu::CompareFunction::Always,+ stencil: wgpu::StencilState::default(),+ bias: wgpu::DepthBiasState::default(),+ }),+ multisample: wgpu::MultisampleState {+ count: sample_count,+ mask: !0,+ alpha_to_coverage_enabled: false,+ },+ multiview_mask: None,+ cache: None,+ })+}+impl EfbClear {pub fn new(device: &wgpu::Device,@@ -45,44 +100,77 @@ impl EfbClear {immediate_size: 0,});- let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {- label: Some("efb_clear_pipeline"),- layout: Some(&layout),- vertex: wgpu::VertexState {- module: &shader,- entry_point: Some("vs_main"),- buffers: &[],- compilation_options: Default::default(),- },- fragment: Some(wgpu::FragmentState {- module: &shader,- entry_point: Some("fs_main"),- targets: &[Some(wgpu::ColorTargetState {- format: color_format,- blend: None,- write_mask: wgpu::ColorWrites::ALL,- })],- compilation_options: Default::default(),- }),- primitive: wgpu::PrimitiveState {- topology: wgpu::PrimitiveTopology::TriangleList,- ..Default::default()- },- depth_stencil: Some(wgpu::DepthStencilState {- format: depth_format,- depth_write_enabled: true,- depth_compare: wgpu::CompareFunction::Always,- stencil: wgpu::StencilState::default(),- bias: wgpu::DepthBiasState::default(),- }),- multisample: wgpu::MultisampleState {- count: sample_count,- mask: !0,- alpha_to_coverage_enabled: false,- },- multiview_mask: None,- cache: None,- });+ let rgb = wgpu::ColorWrites::RED | wgpu::ColorWrites::GREEN | wgpu::ColorWrites::BLUE;+ let pipeline_all_depth = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ wgpu::ColorWrites::ALL,+ true,+ );+ let pipeline_rgb_depth = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ rgb,+ true,+ );+ let pipeline_alpha_depth = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ wgpu::ColorWrites::ALPHA,+ true,+ );+ let pipeline_none_depth = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ wgpu::ColorWrites::empty(),+ true,+ );+ let pipeline_all = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ wgpu::ColorWrites::ALL,+ false,+ );+ let pipeline_rgb = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ rgb,+ false,+ );+ let pipeline_alpha = create_clear_pipeline(+ device,+ &shader,+ &layout,+ color_format,+ depth_format,+ sample_count,+ wgpu::ColorWrites::ALPHA,+ false,+ );let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {label: Some("efb_clear_uniforms"),@@ -101,16 +189,20 @@ impl EfbClear {});EfbClear {- pipeline,- bind_group_layout,+ pipeline_all_depth,+ pipeline_rgb_depth,+ pipeline_alpha_depth,+ pipeline_none_depth,+ pipeline_all,+ pipeline_rgb,+ pipeline_alpha,uniform_buffer,bind_group,}}- /// Clear a rectangular region of `(color_view, depth_view)` to the given- /// color and depth. Areas outside the rect are preserved.- pub fn clear_region(+ /// Clear a rectangular region with independent RGB, alpha, and depth masks.+ pub fn clear_region_masked(&self,device: &wgpu::Device,queue: &wgpu::Queue,@@ -125,7 +217,13 @@ impl EfbClear {h: u32,color: [f32; 4],depth: f32,+ color_update: bool,+ alpha_update: bool,+ z_update: bool,) {+ if !color_update && !alpha_update && !z_update {+ return;+ }if w == 0 || h == 0 {tracing::warn!(x, y, w, h, "clear: zero-area clear region, skipping");return;@@ -139,6 +237,18 @@ impl EfbClear {return;}+ // im gonna vomit+ let pipeline = match (color_update, alpha_update, z_update) {+ (true, true, true) => &self.pipeline_all_depth,+ (true, false, true) => &self.pipeline_rgb_depth,+ (false, true, true) => &self.pipeline_alpha_depth,+ (false, false, true) => &self.pipeline_none_depth,+ (true, true, false) => &self.pipeline_all,+ (true, false, false) => &self.pipeline_rgb,+ (false, true, false) => &self.pipeline_alpha,+ (false, false, false) => unreachable!(),+ };+let uniforms = ClearUniforms {color,depth,@@ -151,8 +261,16 @@ impl EfbClear {let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {label: Some("efb_clear_region"),color_attachments: &[Some(wgpu::RenderPassColorAttachment {- view: msaa_color_view,- resolve_target: Some(resolve_color_view),+ view: if crate::EFB_SAMPLE_COUNT == 1 {+ resolve_color_view+ } else {+ msaa_color_view+ },+ resolve_target: if crate::EFB_SAMPLE_COUNT == 1 {+ None+ } else {+ Some(resolve_color_view)+ },ops: wgpu::Operations {load: wgpu::LoadOp::Load,store: wgpu::StoreOp::Store,@@ -172,16 +290,11 @@ impl EfbClear {multiview_mask: None,});- rpass.set_pipeline(&self.pipeline);+ rpass.set_pipeline(pipeline);rpass.set_bind_group(0, &self.bind_group, &[]);rpass.set_scissor_rect(x, y, w, h);rpass.draw(0..3, 0..1);}queue.submit([encoder.finish()]);}-- #[allow(dead_code)]- pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout {- &self.bind_group_layout- }}diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rsindex 7d0b611..ec6b9d5 100644--- a/crates/backend-wgpu/src/lib.rs+++ b/crates/backend-wgpu/src/lib.rs@@ -137,6 +137,10 @@ pub struct GxRenderer {pub(crate) xfb_has_content: bool,// Per-copy temporary textures stored by CopyXfb, composited by PresentXfb.pub(crate) xfb_copies: FxHashMap<u32, (wgpu::Texture, wgpu::TextureView)>,+ pub(crate) xfb_copy_pipeline: wgpu::RenderPipeline,+ pub(crate) xfb_copy_bind_group_layout: wgpu::BindGroupLayout,+ pub(crate) xfb_copy_sampler: wgpu::Sampler,+ pub(crate) xfb_copy_uniform_buffer: wgpu::Buffer,// Region-scoped EFB clear.pub(crate) efb_clear: clear::EfbClear,// EFB-to-texture readback. Only allocated with `efb-writeback`.@@ -164,6 +168,10 @@ impl GxRenderer {label: Some("gx_shader"),source: wgpu::ShaderSource::Wgsl(SHADER.into()),});+ let xfb_copy_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {+ label: Some("xfb_copy_shader"),+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/xfb_copy.wgsl").into()),+ });// Bindings: 0=FrameUniforms, 1=DrawUniforms, 2-9=textures 0-7, 10-17=samplers 0-7let mut layout_entries = vec![@@ -353,6 +361,91 @@ impl GxRenderer {});let xfb_view = xfb_texture.create_view(&Default::default());+ let xfb_copy_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {+ label: Some("xfb_copy_bgl"),+ entries: &[+ wgpu::BindGroupLayoutEntry {+ binding: 0,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Buffer {+ ty: wgpu::BufferBindingType::Uniform,+ has_dynamic_offset: false,+ min_binding_size: None,+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 1,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Texture {+ multisampled: false,+ view_dimension: wgpu::TextureViewDimension::D2,+ sample_type: wgpu::TextureSampleType::Float { filterable: true },+ },+ count: None,+ },+ wgpu::BindGroupLayoutEntry {+ binding: 2,+ visibility: wgpu::ShaderStages::FRAGMENT,+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),+ count: None,+ },+ ],+ });+ let xfb_copy_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {+ label: Some("xfb_copy_layout"),+ bind_group_layouts: &[&xfb_copy_bind_group_layout],+ immediate_size: 0,+ });+ let xfb_copy_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {+ label: Some("xfb_copy_pipeline"),+ layout: Some(&xfb_copy_pipeline_layout),+ vertex: wgpu::VertexState {+ module: &xfb_copy_shader,+ entry_point: Some("vs_main"),+ buffers: &[],+ compilation_options: Default::default(),+ },+ fragment: Some(wgpu::FragmentState {+ module: &xfb_copy_shader,+ entry_point: Some("fs_main"),+ targets: &[Some(wgpu::ColorTargetState {+ format: surface_format,+ blend: None,+ write_mask: wgpu::ColorWrites::ALL,+ })],+ compilation_options: Default::default(),+ }),+ primitive: wgpu::PrimitiveState {+ topology: wgpu::PrimitiveTopology::TriangleList,+ ..Default::default()+ },+ depth_stencil: None,+ multisample: wgpu::MultisampleState {+ count: 1,+ mask: !0,+ alpha_to_coverage_enabled: false,+ },+ multiview_mask: None,+ cache: None,+ });+ let xfb_copy_sampler = device.create_sampler(&wgpu::SamplerDescriptor {+ label: Some("xfb_copy_sampler"),+ address_mode_u: wgpu::AddressMode::ClampToEdge,+ address_mode_v: wgpu::AddressMode::ClampToEdge,+ address_mode_w: wgpu::AddressMode::ClampToEdge,+ mag_filter: wgpu::FilterMode::Linear,+ min_filter: wgpu::FilterMode::Linear,+ mipmap_filter: wgpu::MipmapFilterMode::Nearest,+ ..Default::default()+ });+ let xfb_copy_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {+ label: Some("xfb_copy_uniforms"),+ size: std::mem::size_of::<render::XfbCopyUniforms>() as u64,+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,+ mapped_at_creation: false,+ });+let efb_clear = clear::EfbClear::new(device,surface_format,@@ -417,6 +510,10 @@ impl GxRenderer {xfb_view,xfb_has_content: false,xfb_copies: FxHashMap::default(),+ xfb_copy_pipeline,+ xfb_copy_bind_group_layout,+ xfb_copy_sampler,+ xfb_copy_uniform_buffer,efb_clear,#[cfg(feature = "efb-writeback")]efb_readback_staging: None,diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rsindex 396020d..4aac952 100644--- a/crates/backend-wgpu/src/render.rs+++ b/crates/backend-wgpu/src/render.rs@@ -9,6 +9,15 @@ use gecko::flipper::gx::texture;use gecko::host::EfbWriteback;use gecko::host::XfbPart;+#[repr(C)]+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]+pub(crate) struct XfbCopyUniforms {+ src_rect: [f32; 4],+ dst_size: [f32; 2],+ gamma: f32,+ filter_mode: u32,+}+impl GxRenderer {pub(crate) fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {let num_draws = self.scratch_draws.len();@@ -53,12 +62,19 @@ impl GxRenderer {src_y: u32,src_w: u32,src_h: u32,+ dst_h: u32,+ gamma: f32,clear: bool,clear_color: [f32; 4],clear_z: f32,+ color_update: bool,+ alpha_update: bool,+ z_update: bool,+ alpha_supported: bool,) {let width = src_w.min(crate::EFB_WIDTH.saturating_sub(src_x));let height = src_h.min(crate::EFB_HEIGHT.saturating_sub(src_y));+ let dst_h = dst_h.max(1);if width == 0 || height == 0 {tracing::warn!(src_x,@@ -75,14 +91,16 @@ impl GxRenderer {label: Some("xfb_copy_tmp"),size: wgpu::Extent3d {width,- height,+ height: dst_h,depth_or_array_layers: 1,},mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,format: self.surface_format,- usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,+ usage: wgpu::TextureUsages::COPY_SRC+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::RENDER_ATTACHMENT,view_formats: &[],});let view = tex.create_view(&Default::default());@@ -91,19 +109,21 @@ impl GxRenderer {// Recreate if size changed.let existing_size = entry.0.size();- if existing_size.width != width || existing_size.height != height {+ if existing_size.width != width || existing_size.height != dst_h {let tex = device.create_texture(&wgpu::TextureDescriptor {label: Some("xfb_copy_tmp"),size: wgpu::Extent3d {width,- height,+ height: dst_h,depth_or_array_layers: 1,},mip_level_count: 1,sample_count: 1,dimension: wgpu::TextureDimension::D2,format: self.surface_format,- usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,+ usage: wgpu::TextureUsages::COPY_SRC+ | wgpu::TextureUsages::COPY_DST+ | wgpu::TextureUsages::RENDER_ATTACHMENT,view_formats: &[],});@@ -112,34 +132,91 @@ impl GxRenderer {}let mut encoder = device.create_command_encoder(&Default::default());- encoder.copy_texture_to_texture(- wgpu::TexelCopyTextureInfo {- texture: &self.efb_texture,- mip_level: 0,- origin: wgpu::Origin3d {- x: src_x,- y: src_y,- z: 0,+ let needs_shader_copy = dst_h != height || (gamma - 1.0).abs() > f32::EPSILON;+ if needs_shader_copy {+ let uniforms = XfbCopyUniforms {+ src_rect: [src_x as f32, src_y as f32, width as f32, height as f32],+ dst_size: [width as f32, dst_h as f32],+ gamma,+ filter_mode: 0,+ };+ queue.write_buffer(&self.xfb_copy_uniform_buffer, 0, bytemuck::bytes_of(&uniforms));++ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ label: Some("xfb_copy_bg"),+ layout: &self.xfb_copy_bind_group_layout,+ entries: &[+ wgpu::BindGroupEntry {+ binding: 0,+ resource: self.xfb_copy_uniform_buffer.as_entire_binding(),+ },+ wgpu::BindGroupEntry {+ binding: 1,+ resource: wgpu::BindingResource::TextureView(&self.efb_view),+ },+ wgpu::BindGroupEntry {+ binding: 2,+ resource: wgpu::BindingResource::Sampler(&self.xfb_copy_sampler),+ },+ ],+ });++ {+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {+ label: Some("xfb_copy"),+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {+ view: &entry.1,+ resolve_target: None,+ ops: wgpu::Operations {+ load: wgpu::LoadOp::Load,+ store: wgpu::StoreOp::Store,+ },+ depth_slice: None,+ })],+ depth_stencil_attachment: None,+ occlusion_query_set: None,+ timestamp_writes: None,+ multiview_mask: None,+ });+ rpass.set_pipeline(&self.xfb_copy_pipeline);+ rpass.set_bind_group(0, &bind_group, &[]);+ rpass.draw(0..3, 0..1);+ }+ } else {+ // Keep exact 1:1 XFB copies on the raw copy path. Running them+ // through the shader would sample with filtering and can soften+ // the image even when no scaling or gamma is requested.+ // TODO: We could just call it a trade-off and just have it all go+ // through? It looks a bit fuzzy, has it's own charm.+ encoder.copy_texture_to_texture(+ wgpu::TexelCopyTextureInfo {+ texture: &self.efb_texture,+ mip_level: 0,+ origin: wgpu::Origin3d {+ x: src_x,+ y: src_y,+ z: 0,+ },+ aspect: wgpu::TextureAspect::default(),},- aspect: wgpu::TextureAspect::default(),- },- wgpu::TexelCopyTextureInfo {- texture: &entry.0,- mip_level: 0,- origin: wgpu::Origin3d::ZERO,- aspect: wgpu::TextureAspect::default(),- },- wgpu::Extent3d {- width,- height,- depth_or_array_layers: 1,- },- );+ wgpu::TexelCopyTextureInfo {+ texture: &entry.0,+ mip_level: 0,+ origin: wgpu::Origin3d::ZERO,+ aspect: wgpu::TextureAspect::default(),+ },+ wgpu::Extent3d {+ width,+ height,+ depth_or_array_layers: 1,+ },+ );+ }queue.submit([encoder.finish()]);// Region-scoped EFB clear after copy (if requested).if clear {- self.efb_clear.clear_region(+ self.efb_clear.clear_region_masked(device,queue,&self.efb_msaa_view,@@ -153,6 +230,9 @@ impl GxRenderer {src_h,clear_color,clear_z,+ color_update,+ alpha_update && alpha_supported,+ z_update,);}}@@ -243,9 +323,8 @@ impl GxRenderer {/// optional 2x downsample, encode into the requested GX texture format,/// and ship the bytes back to the emu thread via the writeback channel.///- /// `effective_clear` is the already-gated clear flag (see the- /// `CopyEfbToTexture` arm in `action.rs`); this function does not look- /// at the per-channel write masks itself.+ /// The clear flag and per-channel update masks are applied after the+ /// copy, matching GX copy-clear ordering.////// Only compiled with `efb-writeback`. The default no-feature path/// handles CopyEfbToTexture inline in `action.rs` with just a clear.@@ -261,9 +340,15 @@ impl GxRenderer {src_h: u32,copy_format: u8,mipmap: bool,- effective_clear: bool,+ stride: u32,+ depth_copy: bool,+ clear: bool,clear_color: [f32; 4],clear_z: f32,+ color_update: bool,+ alpha_update: bool,+ z_update: bool,+ alpha_supported: bool,) {// Clamp the source to EFB bounds (mirrors execute_copy_xfb).let width = src_w.min(crate::EFB_WIDTH.saturating_sub(src_x));@@ -281,13 +366,18 @@ impl GxRenderer {// Early-out for formats we don't encode: skip the expensive readback// but still honor the clear.- let Some(copy_format_enum) = texture::CopyFormat::from_u8(copy_format) else {+ let copy_format_option = if depth_copy {+ texture::CopyFormat::from_u8_depth(copy_format)+ } else {+ texture::CopyFormat::from_u8_color(copy_format)+ };+ let Some(copy_format_enum) = copy_format_option else {tracing::warn!(copy_format = format!("{copy_format:#x}"),"efb_to_texture: unsupported copy format, skipping readback");- if effective_clear {- self.efb_clear.clear_region(+ if clear {+ self.efb_clear.clear_region_masked(device,queue,&self.efb_msaa_view,@@ -301,11 +391,42 @@ impl GxRenderer {src_h,clear_color,clear_z,+ color_update,+ alpha_update && alpha_supported,+ z_update,);}return;};+ if depth_copy {+ tracing::warn!(+ copy_format = format!("{copy_format:#x}"),+ "efb_to_texture: depth readback is not implemented yet, skipping readback"+ );+ if clear {+ self.efb_clear.clear_region_masked(+ device,+ queue,+ &self.efb_msaa_view,+ &self.efb_view,+ &self.efb_depth_view,+ crate::EFB_WIDTH,+ crate::EFB_HEIGHT,+ src_x,+ src_y,+ src_w,+ src_h,+ clear_color,+ clear_z,+ color_update,+ alpha_update && alpha_supported,+ z_update,+ );+ }+ return;+ }+// wgpu requires 256-byte row alignment for texture<->buffer copies.let bytes_per_row = align_up(width as u64 * 4, 256);let staging_size = bytes_per_row * height as u64;@@ -404,18 +525,24 @@ impl GxRenderer {// Encode and ship back.let encoded = texture::encode_from_rgba(&encode_src, encode_w as usize, encode_h as usize, copy_format_enum);+ let row_bytes = texture::encoded_row_bytes(encode_w, copy_format_enum);+ let row_count = texture::encoded_row_count(encode_h, copy_format_enum);+ let dest_stride_bytes = stride as usize;if let Some(tx) = &self.efb_writeback_tx {if let Err(err) = tx.try_send(EfbWriteback {dest_addr,bytes: encoded,+ row_bytes,+ row_count,+ dest_stride_bytes,}) {tracing::warn!(?err, "efb_to_texture: writeback channel send failed");}}- if effective_clear {- self.efb_clear.clear_region(+ if clear {+ self.efb_clear.clear_region_masked(device,queue,&self.efb_msaa_view,@@ -429,6 +556,9 @@ impl GxRenderer {src_h,clear_color,clear_z,+ color_update,+ alpha_update && alpha_supported,+ z_update,);}}diff --git a/crates/backend-wgpu/src/shaders/xfb_copy.wgsl b/crates/backend-wgpu/src/shaders/xfb_copy.wgslnew file mode 100644index 0000000..a01f270--- /dev/null+++ b/crates/backend-wgpu/src/shaders/xfb_copy.wgsl@@ -0,0 +1,42 @@+struct Uniforms {+ src_rect: vec4<f32>,+ dst_size: vec2<f32>,+ gamma: f32,+ filter_mode: u32,+};++@group(0) @binding(0)+var<uniform> u: Uniforms;++@group(0) @binding(1)+var efb_tex: texture_2d<f32>;++@group(0) @binding(2)+var efb_sampler: sampler;++struct VsOut {+ @builtin(position) position: vec4<f32>,+};++@vertex+fn vs_main(@builtin(vertex_index) vi: u32) -> VsOut {+ let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));+ var out: VsOut;+ out.position = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);+ return out;+}++@fragment+fn fs_main(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {+ let tex_size = vec2<f32>(textureDimensions(efb_tex));+ let dst_size = max(u.dst_size, vec2<f32>(1.0, 1.0));+ let src_pixel = u.src_rect.xy + (position.xy / dst_size) * u.src_rect.zw;+ let uv = (src_pixel + vec2<f32>(0.5, 0.5)) / tex_size;++ var color = textureSample(efb_tex, efb_sampler, uv);+ if (abs(u.gamma - 1.0) > 0.001) {+ color = vec4<f32>(pow(max(color.rgb, vec3<f32>(0.0, 0.0, 0.0)), vec3<f32>(u.gamma)), color.a);+ }++ return color;+}diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rsindex b7ce65f..3197abf 100644--- a/crates/gecko/src/flipper/gx.rs+++ b/crates/gecko/src/flipper/gx.rs@@ -44,6 +44,7 @@ pub struct GraphicsProcessor {pub cur_num_tev_stages: u8,pub cur_tev_konst_colors: [[f32; 4]; 16],pub cur_zmode: ZMode,+ pub cur_pe_control: regs::PeControl,pub cur_blend_mode: BlendMode,pub cur_alpha_compare: AlphaCompare,pub cur_viewport: draw::Viewport,@@ -98,6 +99,7 @@ impl GraphicsProcessor {cur_num_tev_stages: 0,cur_tev_konst_colors: [[0.0; 4]; 16],cur_zmode: Default::default(),+ cur_pe_control: Default::default(),cur_blend_mode: BlendMode::from_raw(0).with_color_update(true).with_alpha_update(true),cur_alpha_compare: Default::default(),cur_viewport: Default::default(),@@ -167,8 +169,7 @@ pub fn present_xfb(gc: &mut GameCube) {let vi_base = gc.vi.xfb_addr();// All copies in a frame share the same stride.- let stride = gc.gx.xfb_copies[0].dest_stride as u32;- let bytes_per_row = stride as u64 * 32;+ let bytes_per_row = gc.gx.xfb_copies[0].dest_stride as u64;if bytes_per_row == 0 {tracing::warn!("present_xfb: zero bytes_per_row, dropping XFB copies");gc.gx.xfb_copies.clear();diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rsindex 7e8a20c..3cb42f4 100644--- a/crates/gecko/src/flipper/gx/bp.rs+++ b/crates/gecko/src/flipper/gx/bp.rs@@ -1,15 +1,15 @@use super::constants::{BP_GEN_MODE, BP_PE_ALPHA_COMPARE, BP_PE_CMODE0, BP_PE_COPY_CLEAR_AR, BP_PE_COPY_CLEAR_GB, BP_PE_COPY_CLEAR_Z,- BP_PE_COPY_CMD, BP_PE_COPY_DIMS, BP_PE_COPY_DST, BP_PE_COPY_DST_STRIDE, BP_PE_COPY_SRC, BP_PE_DONE,- BP_PE_DONE_FINISH_BIT, BP_PE_TOKEN, BP_PE_TOKEN_INT, BP_PE_ZMODE, BP_RAS1_TREF_COUNT, BP_RAS1_TREF0, BP_SU_SCIS_BR,- BP_SU_SCIS_OFFSET, BP_SU_SCIS_TL, BP_TEV_COLOR_ENV_0, BP_TEV_KSEL_0, BP_TEV_REGISTERL_0, BP_TX_SETIMAGE0_I0,- BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, EFB_HEIGHT,- EFB_WIDTH,+ BP_PE_COPY_CMD, BP_PE_COPY_DIMS, BP_PE_COPY_DST, BP_PE_COPY_DST_STRIDE, BP_PE_COPY_SRC, BP_PE_COPY_YSCALE,+ BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_PE_TOKEN, BP_PE_TOKEN_INT, BP_PE_ZCOMPARE, BP_PE_ZMODE, BP_RAS1_TREF_COUNT,+ BP_RAS1_TREF0, BP_SU_SCIS_BR, BP_SU_SCIS_OFFSET, BP_SU_SCIS_TL, BP_TEV_COLOR_ENV_0, BP_TEV_KSEL_0,+ BP_TEV_REGISTERL_0, BP_TX_SETIMAGE0_I0, BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4,+ BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, EFB_HEIGHT, EFB_WIDTH,};use super::regs::{- AlphaCompare, BlendMode, EfbCopyDims, EfbCopyDst, EfbCopyDstStride, EfbCopySrc, GenMode, PeClearAr, PeClearGb,- PeClearZ, PeCopyCmd, SuScisOffset, SuScisRect, TevAlphaEnv, TevColorEnv, TevOrder, TevRegType, TevRegisterH,- TevRegisterL, TxSetImage0, TxSetImage3, TxSetMode0, ZMode,+ AlphaCompare, BlendMode, DispCopyYScale, EfbCopyDims, EfbCopyDst, EfbCopyDstStride, EfbCopySrc, GenMode, PeClearAr,+ PeClearGb, PeClearZ, PeControl, PeCopyCmd, SuScisOffset, SuScisRect, TevAlphaEnv, TevColorEnv, TevOrder,+ TevRegType, TevRegisterH, TevRegisterL, TxSetImage0, TxSetImage3, TxSetMode0, ZMode,};use super::{GraphicsProcessor, draw, texture};use crate::common::Address;@@ -53,6 +53,9 @@ impl GraphicsProcessor {self.cur_blend_mode = BlendMode::from_raw(val);renderer.exec(GxAction::SetBlendMode(self.cur_blend_mode));}+ BP_PE_ZCOMPARE => {+ self.cur_pe_control = PeControl::from_raw(val);+ }BP_PE_ALPHA_COMPARE => {self.cur_alpha_compare = AlphaCompare::from_raw(val);renderer.exec(GxAction::SetAlphaCompare(self.cur_alpha_compare));@@ -285,7 +288,7 @@ impl GraphicsProcessor {let src_h = dims.height_minus1() as u32 + 1;let dest_addr = EfbCopyDst::from_raw(self.bp_regs[BP_PE_COPY_DST]).addr();- let dest_stride = EfbCopyDstStride::from_raw(self.bp_regs[BP_PE_COPY_DST_STRIDE]).stride() as u32;+ let dest_stride = EfbCopyDstStride::from_raw(self.bp_regs[BP_PE_COPY_DST_STRIDE]).stride_bytes();let cmd = PeCopyCmd::from_raw(trigger);let copy_to_xfb = cmd.copy_to_xfb();@@ -314,6 +317,24 @@ impl GraphicsProcessor {);if copy_to_xfb {+ let yscale_reg = DispCopyYScale::from_raw(self.bp_regs[BP_PE_COPY_YSCALE]).scale() as f32;+ let y_scale = if cmd.scale_invert() {+ if yscale_reg == 0.0 { 1.0 } else { 256.0 / yscale_reg }+ } else {+ yscale_reg / 256.0+ };+ let y_scale = if y_scale.is_finite() && y_scale > 0.0 {+ y_scale+ } else {+ 1.0+ };+ let dst_h = (1.0 + dims.height_minus1() as f32 * y_scale).floor().max(1.0) as u32;+ let gamma = match cmd.gamma() {+ 0 => 1.0,+ 1 => 1.7,+ 2 | 3 => 2.2,+ _ => 1.0,+ };// XFB copy: queue the copy for present_xfb() to compose at vblank,// and tell the renderer to snapshot the EFB region now.let id = self.xfb_copies.len() as u32;@@ -328,9 +349,15 @@ impl GraphicsProcessor {src_y,src_w,src_h,+ dst_h,+ gamma,clear,clear_color: [r, g, b, a],clear_z,+ color_update: self.cur_blend_mode.color_update(),+ alpha_update: self.cur_blend_mode.alpha_update(),+ z_update: self.cur_zmode.update_enable(),+ alpha_supported: self.cur_pe_control.pixel_format().has_alpha(),});} else {let copy_format = cmd.copy_format();@@ -356,6 +383,8 @@ impl GraphicsProcessor {color_update,alpha_update,z_update,+ alpha_supported: self.cur_pe_control.pixel_format().has_alpha(),+ depth_copy: self.cur_pe_control.pixel_format().is_depth_only(),});// Default path (feature off): the renderer doesn't do a readback@@ -376,17 +405,14 @@ impl GraphicsProcessor {if let Some(rx) = &self.efb_writeback_rx {match rx.recv_timeout(Duration::from_secs(2)) {Ok(wb) => {- let start = wb.dest_addr as usize;- let end = start + wb.bytes.len();- if end <= ram.len() {- ram[start..end].copy_from_slice(&wb.bytes);- } else {- tracing::warn!(- addr = format!("{:#010X}", wb.dest_addr),- len = wb.bytes.len(),- "efb writeback OOB, dropping"- );- }+ texture::write_strided_copy_to_ram(+ ram,+ wb.dest_addr,+ &wb.bytes,+ wb.row_bytes,+ wb.row_count,+ wb.dest_stride_bytes,+ );}Err(err) => {tracing::warn!(?err, "efb writeback recv timed out");diff --git a/crates/gecko/src/flipper/gx/constants.rs b/crates/gecko/src/flipper/gx/constants.rsindex ef9bdea..8c56ee1 100644--- a/crates/gecko/src/flipper/gx/constants.rs+++ b/crates/gecko/src/flipper/gx/constants.rs@@ -106,6 +106,7 @@ pub const BP_TX_SETIMAGE3_I4: usize = 0xB4; // TX_SETIMAGE3 maps 4-7 (IMAGE_BASE// BP PE (Pixel Engine) registerspub const BP_PE_ZMODE: usize = 0x40;pub const BP_PE_CMODE0: usize = 0x41; // blend mode+pub const BP_PE_ZCOMPARE: usize = 0x43;pub const BP_PE_ALPHA_COMPARE: usize = 0xF3;pub const BP_PE_DONE: usize = 0x45;pub const BP_PE_DONE_FINISH_BIT: u32 = 0x02;diff --git a/crates/gecko/src/flipper/gx/regs.rs b/crates/gecko/src/flipper/gx/regs.rsindex f079dd0..716be7b 100644--- a/crates/gecko/src/flipper/gx/regs.rs+++ b/crates/gecko/src/flipper/gx/regs.rs@@ -102,6 +102,41 @@ pub struct BlendMode {pub logic_op: LogicOp,}+#[derive(Debug, PartialEq, BitEnum, Hash, Eq)]+pub enum PixelFormat {+ Rgb8Z24 = 0,+ Rgba6Z24 = 1,+ Rgb565Z16 = 2,+ Z24 = 3,+ Y8 = 4,+ U8 = 5,+ V8 = 6,+ Yuv420 = 7,+}++impl PixelFormat {+ pub fn has_alpha(self) -> bool {+ matches!(self, PixelFormat::Rgba6Z24)+ }++ pub fn is_depth_only(self) -> bool {+ matches!(self, PixelFormat::Z24)+ }+}++#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Default)]+pub struct PeControl {+ #[bits(0..=2)]+ pub pixel_format: PixelFormat,++ #[bits(3..=5)]+ pub depth_format: u8,++ #[bits(6)]+ pub early_ztest: bool,+}+// BP 0xF3 Alpha compare#[chapa::bitfield(u32, order = lsb0)]#[derive(Debug, Clone, Copy, Default)]@@ -1104,6 +1139,20 @@ pub struct EfbCopyDstStride {pub stride: u16,}+impl EfbCopyDstStride {+ pub fn stride_bytes(&self) -> u32 {+ (self.stride() as u32) << 5+ }+}++// BP 0x4E BPMEM_COPYYSCALE (display copy vertical scale)+#[chapa::bitfield(u32, order = lsb0)]+#[derive(Debug, Clone, Copy, Default)]+pub struct DispCopyYScale {+ #[bits(0..=8)]+ pub scale: u16,+}+// BP 0x52 BPMEM_TRIGGER_EFB_COPY (PE copy execute/trigger)#[chapa::bitfield(u32, order = lsb0)]#[derive(Debug, Clone, Copy, Default)]@@ -1119,6 +1168,9 @@ pub struct PeCopyCmd {#[bits(4..=6)]pub fmt_lo: u8,+ #[bits(7..=8)]+ pub gamma: u8,+#[bits(9)]pub half: bool,@@ -1133,6 +1185,12 @@ pub struct PeCopyCmd {#[bits(14)]pub copy_to_xfb: bool,++ #[bits(15)]+ pub intensity_fmt: bool,++ #[bits(16)]+ pub auto_conv: bool,}impl PeCopyCmd {diff --git a/crates/gecko/src/flipper/gx/texture.rs b/crates/gecko/src/flipper/gx/texture.rsindex b85beb8..69b369b 100644--- a/crates/gecko/src/flipper/gx/texture.rs+++ b/crates/gecko/src/flipper/gx/texture.rs@@ -122,6 +122,7 @@ fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h:for by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -161,6 +162,7 @@ fn decode_ia4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, hfor by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -203,6 +205,7 @@ fn decode_ia8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, hfor by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -244,6 +247,7 @@ fn decode_rgb565(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usizefor by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -284,6 +288,7 @@ fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usizefor by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -335,6 +340,7 @@ fn decode_rgba8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize,for by in 0..bcy {let base_y = by * BH;let th = BH.min(h - base_y);+for bx in 0..bcx {let base_x = bx * BW;let tw = BW.min(w - base_x);@@ -391,6 +397,7 @@ fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize,if sub_x >= w || sub_y >= h {continue;}+let tw = 4usize.min(w - sub_x);let th = 4usize.min(h - sub_y);@@ -475,19 +482,30 @@ fn rgb565_to_rgba(packed: u16) -> [u8; 4] {#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]pub enum CopyFormat {- I8 = 0x1,- RGB565 = 0x4,- RGB5A3 = 0x5,- RGBA8 = 0x6,- A8 = 0x7,- R8 = 0x8,- RG8 = 0xB,+ I4,+ I8,+ IA4,+ IA8,+ RGB565,+ RGB5A3,+ RGBA8,+ A8,+ R8,+ RG8,+ Z24X8,}impl CopyFormat {pub fn from_u8(code: u8) -> Option<Self> {+ Self::from_u8_color(code)+ }++ pub fn from_u8_color(code: u8) -> Option<Self> {Some(match code {+ 0x0 => Self::I4,0x1 => Self::I8,+ 0x2 => Self::IA4,+ 0x3 => Self::IA8,0x4 => Self::RGB565,0x5 => Self::RGB5A3,0x6 => Self::RGBA8,@@ -497,26 +515,149 @@ impl CopyFormat {_ => return None,})}++ pub fn from_u8_depth(code: u8) -> Option<Self> {+ Some(match code {+ 0x6 => Self::Z24X8,+ _ => Self::from_u8_color(code)?,+ })+ }++ pub const fn block_dims(self) -> BlockDims {+ match self {+ CopyFormat::I4 => block_dims(TextureFormat::I4),+ CopyFormat::I8 => block_dims(TextureFormat::I8),+ CopyFormat::IA4 => block_dims(TextureFormat::IA4),+ CopyFormat::IA8 => block_dims(TextureFormat::IA8),+ CopyFormat::RGB565 => block_dims(TextureFormat::RGB565),+ CopyFormat::RGB5A3 => block_dims(TextureFormat::RGB5A3),+ CopyFormat::RGBA8 | CopyFormat::Z24X8 => block_dims(TextureFormat::RGBA8),+ CopyFormat::A8 | CopyFormat::R8 => BlockDims {+ tile_w: 8,+ tile_h: 4,+ bytes_per_tile: 32,+ },+ CopyFormat::RG8 => BlockDims {+ tile_w: 4,+ tile_h: 4,+ bytes_per_tile: 32,+ },+ }+ }++ pub const fn base_texture_format(self) -> TextureFormat {+ match self {+ CopyFormat::I4 => TextureFormat::I4,+ CopyFormat::I8 | CopyFormat::A8 | CopyFormat::R8 => TextureFormat::I8,+ CopyFormat::IA4 => TextureFormat::IA4,+ CopyFormat::IA8 | CopyFormat::RG8 => TextureFormat::IA8,+ CopyFormat::RGB565 => TextureFormat::RGB565,+ CopyFormat::RGB5A3 => TextureFormat::RGB5A3,+ CopyFormat::RGBA8 | CopyFormat::Z24X8 => TextureFormat::RGBA8,+ }+ }}pub fn encoded_size(w: u32, h: u32, format: CopyFormat) -> usize {- let dims = match format {- CopyFormat::I8 => block_dims(TextureFormat::I8),- CopyFormat::RGB565 => block_dims(TextureFormat::RGB565),- CopyFormat::RGB5A3 => block_dims(TextureFormat::RGB5A3),- CopyFormat::RGBA8 => block_dims(TextureFormat::RGBA8),- CopyFormat::A8 | CopyFormat::R8 => BlockDims {- tile_w: 8,- tile_h: 4,- bytes_per_tile: 32,- },- CopyFormat::RG8 => BlockDims {- tile_w: 4,- tile_h: 4,- bytes_per_tile: 32,- },+ format.block_dims().bytes_for(w, h)+}++pub fn encoded_row_bytes(w: u32, format: CopyFormat) -> usize {+ let dims = format.block_dims();+ (w.div_ceil(dims.tile_w) * dims.bytes_per_tile) as usize+}++pub fn encoded_row_count(h: u32, format: CopyFormat) -> usize {+ let dims = format.block_dims();+ h.div_ceil(dims.tile_h) as usize+}++pub fn write_strided_copy_to_ram(+ ram: &mut [u8],+ dest_addr: u32,+ bytes: &[u8],+ row_bytes: usize,+ row_count: usize,+ dest_stride_bytes: usize,+) -> bool {+ if row_bytes == 0 || row_count == 0 {+ return true;+ }++ if dest_stride_bytes == 0 {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ "efb writeback with zero destination stride, dropping"+ );+ return false;+ }++ if dest_stride_bytes < row_bytes {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ dest_stride_bytes,+ row_bytes,+ "efb writeback destination stride smaller than encoded row, dropping"+ );+ return false;+ }++ if bytes.len() < row_bytes.saturating_mul(row_count) {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ len = bytes.len(),+ expected = row_bytes.saturating_mul(row_count),+ "efb writeback payload too small, dropping"+ );+ return false;+ }++ let Ok(base) = usize::try_from(dest_addr) else {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ "efb writeback destination address invalid"+ );+ return false;};- dims.bytes_for(w, h)++ for row in 0..row_count {+ let Some(dst_start) = base.checked_add(row.saturating_mul(dest_stride_bytes)) else {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ row,+ "efb writeback address overflow"+ );+ return false;+ };++ let Some(dst_end) = dst_start.checked_add(row_bytes) else {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ row,+ "efb writeback row end overflow"+ );+ return false;+ };++ if dst_end > ram.len() {+ tracing::warn!(+ addr = format!("{dest_addr:#010X}"),+ row,+ row_bytes,+ ram_len = ram.len(),+ "efb writeback OOB, dropping"+ );+ return false;+ }+ }++ for row in 0..row_count {+ let src_start = row * row_bytes;+ let dst_start = base + row * dest_stride_bytes;+ ram[dst_start..dst_start + row_bytes].copy_from_slice(&bytes[src_start..src_start + row_bytes]);+ }++ true}// ref downsample_rgba_buffer_by_2 @ beanwii, zayd is smarter than me@@ -552,13 +693,27 @@ pub fn encode_from_rgba(rgba: &[u8], w: usize, h: usize, format: CopyFormat) ->let size = encoded_size(w as u32, h as u32, format);let mut out = vec![0u8; size];match format {+ CopyFormat::I4 => encode_i4(rgba, &mut out, w, h),CopyFormat::I8 => encode_i8(rgba, &mut out, w, h),+ CopyFormat::IA4 => encode_ia4(rgba, &mut out, w, h),+ CopyFormat::IA8 => encode_ia8(rgba, &mut out, w, h),CopyFormat::A8 => encode_a8(rgba, &mut out, w, h),CopyFormat::R8 => encode_r8(rgba, &mut out, w, h),CopyFormat::RG8 => encode_rg8(rgba, &mut out, w, h),CopyFormat::RGB565 => encode_rgb565(rgba, &mut out, w, h),CopyFormat::RGB5A3 => encode_rgb5a3(rgba, &mut out, w, h),CopyFormat::RGBA8 => encode_rgba8(rgba, &mut out, w, h),+ CopyFormat::Z24X8 => encode_rgba8(rgba, &mut out, w, h),+ }+ out+}++pub fn encode_from_z24(depth: &[u32], w: usize, h: usize, format: CopyFormat) -> Vec<u8> {+ let size = encoded_size(w as u32, h as u32, format);+ let mut out = vec![0u8; size];+ match format {+ CopyFormat::Z24X8 | CopyFormat::RGBA8 => encode_z24x8(depth, &mut out, w, h),+ _ => tracing::warn!(?format, "encode_from_z24: unsupported depth copy format"),}out}@@ -568,6 +723,43 @@ fn luminance(r: u8, g: u8, b: u8) -> u8 {((r as u32 * 299 + g as u32 * 587 + b as u32 * 114) / 1000) as u8}+#[multiversion(targets = "simd")]+fn encode_i4(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {+ const BW: usize = 8;+ const BH: usize = 8;+ const BB: usize = 32;++ let bcx = w.div_ceil(BW);+ let bcy = h.div_ceil(BH);+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {+ tracing::warn!(w, h, "encode_i4: buffer OOB, skipping");+ return;+ }++ for by in 0..bcy {+ let base_y = by * BH;+ let th = BH.min(h - base_y);+ for bx in 0..bcx {+ let base_x = bx * BW;+ let tw = BW.min(w - base_x);+ let blk = (by * bcx + bx) * BB;++ for ty in 0..th {+ for tx in 0..tw {+ let s = ((base_y + ty) * w + base_x + tx) * 4;+ let i = luminance(rgba[s], rgba[s + 1], rgba[s + 2]) >> 4;+ let d = blk + (ty * BW + tx) / 2;+ if tx & 1 == 0 {+ out[d] = (out[d] & 0x0F) | (i << 4);+ } else {+ out[d] = (out[d] & 0xF0) | i;+ }+ }+ }+ }+ }+}+#[multiversion(targets = "simd")]fn encode_i8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {const BW: usize = 8;@@ -607,6 +799,73 @@ fn encode_i8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {}}+#[multiversion(targets = "simd")]+fn encode_ia4(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {+ const BW: usize = 8;+ const BH: usize = 4;+ const BB: usize = 32;++ let bcx = w.div_ceil(BW);+ let bcy = h.div_ceil(BH);+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {+ tracing::warn!(w, h, "encode_ia4: buffer OOB, skipping");+ return;+ }++ for by in 0..bcy {+ let base_y = by * BH;+ let th = BH.min(h - base_y);+ for bx in 0..bcx {+ let base_x = bx * BW;+ let tw = BW.min(w - base_x);+ let blk = (by * bcx + bx) * BB;++ for ty in 0..th {+ for tx in 0..tw {+ let s = ((base_y + ty) * w + base_x + tx) * 4;+ let i = luminance(rgba[s], rgba[s + 1], rgba[s + 2]) >> 4;+ let a = rgba[s + 3] >> 4;+ out[blk + ty * BW + tx] = (a << 4) | i;+ }+ }+ }+ }+}++#[multiversion(targets = "simd")]+fn encode_ia8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {+ const BW: usize = 4;+ const BH: usize = 4;+ const BB: usize = 32;++ let bcx = w.div_ceil(BW);+ let bcy = h.div_ceil(BH);+ if bcx * bcy * BB > out.len() || rgba.len() < w * h * 4 {+ tracing::warn!(w, h, "encode_ia8: buffer OOB, skipping");+ return;+ }++ for by in 0..bcy {+ let base_y = by * BH;+ let th = BH.min(h - base_y);+ for bx in 0..bcx {+ let base_x = bx * BW;+ let tw = BW.min(w - base_x);+ let blk = (by * bcx + bx) * BB;++ for ty in 0..th {+ for tx in 0..tw {+ let s = ((base_y + ty) * w + base_x + tx) * 4;+ let i = luminance(rgba[s], rgba[s + 1], rgba[s + 2]);+ let off = blk + (ty * BW + tx) * 2;+ out[off] = rgba[s + 3];+ out[off + 1] = i;+ }+ }+ }+ }+}+#[multiversion(targets = "simd")]fn encode_a8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {const BW: usize = 8;@@ -856,3 +1115,166 @@ fn encode_rgba8(rgba: &[u8], out: &mut [u8], w: usize, h: usize) {}}}++#[multiversion(targets = "simd")]+fn encode_z24x8(depth: &[u32], out: &mut [u8], w: usize, h: usize) {+ const BW: usize = 4;+ const BH: usize = 4;+ const BB: usize = 64;++ let bcx = w.div_ceil(BW);+ let bcy = h.div_ceil(BH);+ if bcx * bcy * BB > out.len() || depth.len() < w * h {+ tracing::warn!(w, h, "encode_z24x8: buffer OOB, skipping");+ return;+ }++ for by in 0..bcy {+ let base_y = by * BH;+ let th = BH.min(h - base_y);+ for bx in 0..bcx {+ let base_x = bx * BW;+ let tw = BW.min(w - base_x);+ let blk = (by * bcx + bx) * BB;++ for ty in 0..th {+ for tx in 0..tw {+ let z = depth[(base_y + ty) * w + base_x + tx] & 0x00FF_FFFF;+ let ti = ty * BW + tx;+ let ar = blk + ti * 2;+ let gb = blk + 32 + ti * 2;+ out[ar] = 0xFF;+ out[ar + 1] = ((z >> 16) & 0xFF) as u8;+ out[gb] = ((z >> 8) & 0xFF) as u8;+ out[gb + 1] = (z & 0xFF) as u8;+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rgba_pattern(w: usize, h: usize, f: impl Fn(usize, usize) -> [u8; 4]) -> Vec<u8> {+ let mut out = Vec::with_capacity(w * h * 4);+ for y in 0..h {+ for x in 0..w {+ out.extend_from_slice(&f(x, y));+ }+ }+ out+ }++ #[test]+ fn copy_layout_uses_encoded_block_rows() {+ assert_eq!(encoded_row_bytes(9, CopyFormat::I8), 64);+ assert_eq!(encoded_row_count(5, CopyFormat::I8), 2);+ assert_eq!(encoded_size(9, 5, CopyFormat::I8), 128);++ assert_eq!(encoded_row_bytes(4, CopyFormat::RGBA8), 64);+ assert_eq!(encoded_row_count(5, CopyFormat::RGBA8), 2);+ assert_eq!(encoded_size(4, 5, CopyFormat::RGBA8), 128);+ }++ #[test]+ fn strided_writeback_steps_by_destination_stride() {+ let mut ram = vec![0xEE; 32];+ let bytes = [1, 2, 3, 4, 5, 6, 7, 8];+ assert!(write_strided_copy_to_ram(&mut ram, 10, &bytes, 4, 2, 6));++ assert_eq!(&ram[10..14], &[1, 2, 3, 4]);+ assert_eq!(&ram[14..16], &[0xEE, 0xEE]);+ assert_eq!(&ram[16..20], &[5, 6, 7, 8]);+ }++ #[test]+ fn strided_writeback_rejects_too_small_stride() {+ let mut ram = vec![0xEE; 32];+ let bytes = [1, 2, 3, 4, 5, 6, 7, 8];+ assert!(!write_strided_copy_to_ram(&mut ram, 10, &bytes, 4, 2, 3));+ assert!(ram.iter().all(|&b| b == 0xEE));+ }++ #[test]+ fn encodes_i4_tile() {+ let rgba = rgba_pattern(8, 8, |x, y| {+ let i = (((y * 8 + x) & 0x0F) as u8) << 4;+ [i, i, i, 255]+ });++ let encoded = encode_from_rgba(&rgba, 8, 8, CopyFormat::I4);+ assert_eq!(encoded.len(), 32);+ assert_eq!(&encoded[..4], &[0x01, 0x23, 0x45, 0x67]);+ }++ #[test]+ fn encodes_i8_tile() {+ let rgba = rgba_pattern(8, 4, |x, y| {+ let i = (y * 8 + x) as u8;+ [i, i, i, 255]+ });++ let encoded = encode_from_rgba(&rgba, 8, 4, CopyFormat::I8);+ assert_eq!(encoded.len(), 32);+ assert_eq!(&encoded[..8], &[0, 1, 2, 3, 4, 5, 6, 7]);+ }++ #[test]+ fn encodes_ia4_tile() {+ let rgba = rgba_pattern(8, 4, |x, y| {+ let i = ((y * 8 + x) as u8) << 4;+ let a = 0x80;+ [i, i, i, a]+ });++ let encoded = encode_from_rgba(&rgba, 8, 4, CopyFormat::IA4);+ assert_eq!(encoded.len(), 32);+ assert_eq!(&encoded[..4], &[0x80, 0x81, 0x82, 0x83]);+ }++ #[test]+ fn encodes_ia8_tile() {+ let rgba = rgba_pattern(4, 4, |x, y| {+ let i = (y * 4 + x) as u8;+ [i, i, i, 0xA0 + i]+ });++ let encoded = encode_from_rgba(&rgba, 4, 4, CopyFormat::IA8);+ assert_eq!(encoded.len(), 32);+ assert_eq!(&encoded[..8], &[0xA0, 0, 0xA1, 1, 0xA2, 2, 0xA3, 3]);+ }++ #[test]+ fn encodes_rgb565_rgb5a3_rgba8_tiles() {+ let rgba = rgba_pattern(4, 4, |x, y| {+ if x == 0 && y == 0 {+ [255, 0, 0, 255]+ } else {+ [0, 0, 0, 255]+ }+ });++ let rgb565 = encode_from_rgba(&rgba, 4, 4, CopyFormat::RGB565);+ assert_eq!(&rgb565[..2], &[0xF8, 0x00]);++ let rgb5a3 = encode_from_rgba(&rgba, 4, 4, CopyFormat::RGB5A3);+ assert_eq!(&rgb5a3[..2], &[0xFC, 0x00]);++ let rgba8 = encode_from_rgba(&rgba, 4, 4, CopyFormat::RGBA8);+ assert_eq!(&rgba8[..2], &[0xFF, 0xFF]);+ assert_eq!(&rgba8[32..34], &[0x00, 0x00]);+ }++ #[test]+ fn encodes_z24x8_from_depth_values() {+ let mut depth = vec![0; 16];+ depth[0] = 0x0012_3456;++ let encoded = encode_from_z24(&depth, 4, 4, CopyFormat::Z24X8);+ assert_eq!(encoded.len(), 64);+ assert_eq!(&encoded[..2], &[0xFF, 0x12]);+ assert_eq!(&encoded[32..34], &[0x34, 0x56]);+ }+}diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rsindex 6d7df6d..892c454 100644--- a/crates/gecko/src/host.rs+++ b/crates/gecko/src/host.rs@@ -51,9 +51,15 @@ pub enum GxAction {src_y: u32,src_w: u32,src_h: u32,+ dst_h: u32,+ gamma: f32,clear: bool,clear_color: [f32; 4],clear_z: f32,+ color_update: bool,+ alpha_update: bool,+ z_update: bool,+ alpha_supported: bool,},/// Composite all XFB copies from this frame into the output framebuffer.@@ -91,6 +97,8 @@ pub enum GxAction {color_update: bool,alpha_update: bool,z_update: bool,+ alpha_supported: bool,+ depth_copy: bool,},}@@ -105,6 +113,9 @@ pub enum GxAction {pub struct EfbWriteback {pub dest_addr: Address,pub bytes: Vec<u8>,+ pub row_bytes: usize,+ pub row_count: usize,+ pub dest_stride_bytes: usize,}/// Identifies one tile in a composited XFB frame. The `id` matches the