Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

mipmaps!

Laylee7cb3a255bb7
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index e6dd854..7222d27 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -5,7 +5,7 @@ use crate::{
helpers,
};
use gecko::flipper::gx::draw::Primitive;
-use gecko::flipper::gx::regs::{CullMode, MagFilter, MinFilter, WrapMode};
+use gecko::flipper::gx::regs::CullMode;
use gecko::host::{DrawSegment, DrawState, GxAction};
use glam::{Mat4, UVec4, Vec4};
#[cfg(feature = "gx-stats")]
@@ -268,6 +268,7 @@ impl GxRenderer {
width,
height,
fmt,
+ mip_levels,
rgba,
} => {
let tid = *id;
@@ -276,16 +277,11 @@ impl GxRenderer {
height: *height,
depth_or_array_layers: 1,
};
- let direct_copy_layout = wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(*width * 4),
- rows_per_image: None,
- };
let keep_cached = self
.efb_copy_cache
.get(&tid.ram_addr)
- .is_some_and(|e| e.matches(*fmt, *width, *height));
+ .is_some_and(|e| *mip_levels == 1 && e.matches(*fmt, *width, *height));
let reference_only = rgba.is_empty();
assert!(
@@ -293,20 +289,26 @@ impl GxRenderer {
"pending EFB texture missing from renderer cache"
);
+ if !reference_only
+ && self
+ .draw_bg_keys
+ .iter()
+ .any(|k| k.tex_keys.iter().flatten().any(|t| t.ram_addr == tid.ram_addr))
+ {
+ self.flush_draws_keep_vertices(device, queue);
+ }
if !keep_cached && let Some(entry) = self.efb_copy_cache.remove(&tid.ram_addr) {
self.return_to_pool(entry.texture, entry.view);
+ self.bind_group_cache
+ .retain(|key, _| !key.tex_keys.iter().flatten().any(|k| k.ram_addr == tid.ram_addr));
}
if let Some((_, cached_tex, _)) = self.texture_cache.get(&tid) {
let size = cached_tex.size();
- if size.width == *width && size.height == *height {
+ if size.width == *width && size.height == *height && cached_tex.mip_level_count() == *mip_levels {
if !reference_only {
let cached_tex = cached_tex.clone();
- let staged = self.stage_texture_upload(device, &cached_tex, rgba, *width, *height);
-
- if !staged {
- queue.write_texture(cached_tex.as_image_copy(), rgba, direct_copy_layout, copy_size);
- }
+ self.upload_texture_levels(device, queue, &cached_tex, rgba);
}
if let Some((cached_fmt, _, _)) = self.texture_cache.get_mut(&tid) {
@@ -317,7 +319,10 @@ impl GxRenderer {
}
}
- let pooled = self.texture_pool.get_mut(&(*width, *height)).and_then(|v| v.pop());
+ let pooled = self
+ .texture_pool
+ .get_mut(&(*width, *height, *mip_levels))
+ .and_then(|v| v.pop());
let tex = pooled.unwrap_or_else(|| {
let texture_label = format!(
@@ -327,7 +332,7 @@ impl GxRenderer {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(&texture_label),
size: copy_size,
- mip_level_count: 1,
+ mip_level_count: *mip_levels,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
@@ -339,11 +344,7 @@ impl GxRenderer {
});
if !reference_only {
- let staged = self.stage_texture_upload(device, &tex, rgba, *width, *height);
-
- if !staged {
- queue.write_texture(tex.as_image_copy(), rgba, direct_copy_layout, copy_size);
- }
+ self.upload_texture_levels(device, queue, &tex, rgba);
}
let view = tex.create_view(&Default::default());
@@ -380,9 +381,11 @@ impl GxRenderer {
wrap_t,
mag_filter,
min_filter,
+ lod,
} => {
self.current_texture_ids[*slot] = Some(*id);
- let sampler_key: SamplerKey = (*wrap_s, *wrap_t, *mag_filter, *min_filter);
+ self.current_lod_bias[*slot] = f32::from(lod.bias) / 32.0;
+ let sampler_key: SamplerKey = (*wrap_s, *wrap_t, *mag_filter, *min_filter, lod.min, lod.max);
self.current_sampler_keys[*slot] = Some(sampler_key);
self.ensure_sampler(device, &sampler_key);
}
@@ -517,7 +520,11 @@ impl GxRenderer {
}
}
- let draw_uniform = DrawUniforms { mvp, tex_dims };
+ let draw_uniform = DrawUniforms {
+ mvp,
+ tex_dims,
+ tex_lod_bias: self.current_lod_bias,
+ };
let draw_uniform_bytes = bytemuck::bytes_of(&draw_uniform);
let bg_key = trim_bg_key(self.current_bind_group_key(), active);
let stride = crate::packed_vertex_stride(shader_key.active_texcoords);
@@ -708,9 +715,15 @@ impl GxRenderer {
/// Flush accumulated draw calls into a render pass.
pub fn flush_pending_draws(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
+ if self.flush_draws_keep_vertices(device, queue) {
+ self.scratch_vertices.clear();
+ }
+ }
+
+ fn flush_draws_keep_vertices(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> bool {
self.poll_compiled_pipelines();
if self.scratch_draws.is_empty() {
- return;
+ return false;
}
debug_assert_eq!(self.scratch_draws.len(), self.draw_pipeline_keys.len());
@@ -733,7 +746,6 @@ impl GxRenderer {
self.execute_action_render_pass(device);
- self.scratch_vertices.clear();
self.scratch_indices.clear();
self.scratch_draws.clear();
self.scratch_uniform_bytes.clear();
@@ -746,6 +758,8 @@ impl GxRenderer {
self.last_frame_uniform_index = None;
#[cfg(feature = "renderdoc-capture")]
self.draw_primitives.clear();
+
+ true
}
fn execute_action_render_pass(&mut self, device: &wgpu::Device) {
@@ -773,7 +787,7 @@ impl GxRenderer {
let target_width = self.scaled(crate::EFB_WIDTH);
let target_height = self.scaled(crate::EFB_HEIGHT);
let scale = self.efb_scale as f32;
- let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
+ let fallback_sampler_key = crate::DEFAULT_SAMPLER_KEY;
let frame_stride = self.frame_stride;
let num_draws = self.draw_bg_keys.len();
@@ -793,12 +807,17 @@ impl GxRenderer {
if let Some(tid) = &bg_key.tex_keys[slot] {
let tex_entry = self.texture_cache.get(tid);
let efb_match = tex_entry.and_then(|(tex_fmt, tex_tex, _)| {
+ if tex_tex.mip_level_count() != 1 {
+ return None;
+ }
+
let size = tex_tex.size();
self.efb_copy_cache
.get(&tid.ram_addr)
.filter(|e| e.matches(*tex_fmt, size.width, size.height))
.map(|e| &e.view)
});
+
if let Some(view) = efb_match.or_else(|| tex_entry.map(|(_, _, v)| v)) {
tex_views[slot] = view;
} else {
@@ -1216,6 +1235,49 @@ impl GxRenderer {
}
}
+ fn upload_texture_levels(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ texture: &wgpu::Texture,
+ rgba: &[u8],
+ ) {
+ let mut offset = 0;
+
+ for (level, (width, height)) in
+ gecko::flipper::gx::texture::mip_dimensions(texture.width(), texture.height(), texture.mip_level_count())
+ .enumerate()
+ {
+ let end = offset + (width * height * 4) as usize;
+ let pixels = &rgba[offset..end];
+ if !self.stage_texture_upload(device, texture, level as u32, pixels, width, height) {
+ let _ = self.submit_pending(queue);
+
+ queue.write_texture(
+ wgpu::TexelCopyTextureInfo {
+ mip_level: level as u32,
+ ..texture.as_image_copy()
+ },
+ pixels,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(width * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ offset = end;
+ }
+
+ debug_assert_eq!(offset, rgba.len());
+ }
+
fn ensure_sampler(&mut self, device: &wgpu::Device, key: &SamplerKey) {
self.sampler_cache.entry(*key).or_insert_with(|| {
device.create_sampler(&wgpu::SamplerDescriptor {
@@ -1224,6 +1286,9 @@ impl GxRenderer {
address_mode_v: helpers::map_wrap_mode(key.1),
mag_filter: helpers::map_mag_filter(key.2),
min_filter: helpers::map_min_filter(key.3),
+ mipmap_filter: helpers::map_mipmap_filter(key.3),
+ lod_min_clamp: f32::from(key.4) / 16.0,
+ lod_max_clamp: f32::from(key.5) / 16.0,
..Default::default()
})
});
diff --git a/crates/backend-wgpu/src/helpers.rs b/crates/backend-wgpu/src/helpers.rs
index 7e85f52..ce8f944 100644
--- a/crates/backend-wgpu/src/helpers.rs
+++ b/crates/backend-wgpu/src/helpers.rs
@@ -24,6 +24,13 @@ pub fn map_min_filter(filter: MinFilter) -> wgpu::FilterMode {
}
}
+pub fn map_mipmap_filter(filter: MinFilter) -> wgpu::MipmapFilterMode {
+ match filter {
+ MinFilter::NearestMipmapLinear | MinFilter::LinearMipmapLinear => wgpu::MipmapFilterMode::Linear,
+ _ => wgpu::MipmapFilterMode::Nearest,
+ }
+}
+
pub fn map_src_blend_factor(f: BlendFactor) -> wgpu::BlendFactor {
match f {
BlendFactor::Zero => wgpu::BlendFactor::Zero,
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 1aac7eb..d2a203a 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -139,7 +139,15 @@ pub(crate) fn compute_draw_buffer_layout(
}
}
-type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter);
+type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter, u8, u8);
+const DEFAULT_SAMPLER_KEY: SamplerKey = (
+ WrapMode::Clamp,
+ WrapMode::Clamp,
+ MagFilter::Linear,
+ MinFilter::Linear,
+ 0,
+ 0,
+);
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct BindGroupCacheKey {
@@ -214,6 +222,7 @@ pub(crate) struct DrawUniforms {
/// Indirect texturing needs these instead of `textureDimensions`
/// because scaled EFB copies bind a larger GPU texture.
pub tex_dims: [glam::UVec4; 4],
+ pub tex_lod_bias: [f32; 8],
}
pub(crate) const DRAW_UNIFORMS_SIZE: NonZeroU64 = match NonZeroU64::new(std::mem::size_of::<DrawUniforms>() as u64) {
@@ -289,10 +298,10 @@ pub struct GxRenderer {
// EFB: multisampled (4x) reversed depth (near = 1, far = 0).
pub(crate) efb_depth_view: wgpu::TextureView,
pub(crate) efb_needs_clear: bool,
- pub(crate) sampler_cache: FxHashMap<(WrapMode, WrapMode, MagFilter, MinFilter), wgpu::Sampler>,
+ pub(crate) sampler_cache: FxHashMap<SamplerKey, wgpu::Sampler>,
pub(crate) texture_cache: FxHashMap<TextureKey, (TextureFormat, wgpu::Texture, wgpu::TextureView)>,
- // Retired LoadTexture allocations grouped by (w, h).
- pub(crate) texture_pool: FxHashMap<(u32, u32), Vec<wgpu::Texture>>,
+ // Retired LoadTexture allocations grouped by (w, h, mip levels).
+ pub(crate) texture_pool: FxHashMap<(u32, u32, u32), Vec<wgpu::Texture>>,
pub(crate) efb_copy_cache: FxHashMap<Address, EfbCopyEntry>,
pub(crate) efb_copy_pool: FxHashMap<(u32, u32), Vec<(wgpu::Texture, wgpu::TextureView)>>,
pub(crate) efb_pack_pipelines: render::EfbPackPipelines,
@@ -348,6 +357,7 @@ pub struct GxRenderer {
pub(crate) draw_fast_path_compatible: bool,
pub(crate) current_texture_ids: [Option<TextureKey>; 8],
pub(crate) current_sampler_keys: [Option<SamplerKey>; 8],
+ pub(crate) current_lod_bias: [f32; 8],
// XFB output texture: composited from per-copy snapshots by PresentXfb.
pub xfb_texture: wgpu::Texture,
pub xfb_view: wgpu::TextureView,
@@ -529,6 +539,7 @@ impl GxRenderer {
address_mode_v: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
+ lod_max_clamp: 0.0,
..Default::default()
});
@@ -955,10 +966,7 @@ impl GxRenderer {
efb_needs_clear: true,
sampler_cache: {
let mut m = FxHashMap::default();
- m.insert(
- (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear),
- sampler,
- );
+ m.insert(DEFAULT_SAMPLER_KEY, sampler);
m
},
texture_cache: FxHashMap::default(),
@@ -1008,6 +1016,7 @@ impl GxRenderer {
draw_fast_path_compatible: false,
current_texture_ids: Default::default(),
current_sampler_keys: Default::default(),
+ current_lod_bias: [0.0; 8],
xfb_texture,
xfb_view,
xfb_has_content: false,
@@ -1157,6 +1166,7 @@ impl GxRenderer {
&mut self,
device: &wgpu::Device,
dest: &wgpu::Texture,
+ mip_level: u32,
rgba: &[u8],
width: u32,
height: u32,
@@ -1197,7 +1207,10 @@ impl GxRenderer {
rows_per_image: None,
},
},
- dest.as_image_copy(),
+ wgpu::TexelCopyTextureInfo {
+ mip_level,
+ ..dest.as_image_copy()
+ },
wgpu::Extent3d {
width,
height,
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
index fb90f35..db30846 100644
--- a/crates/backend-wgpu/src/pipeline.rs
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -179,7 +179,8 @@ impl From<FullPipelineKey> for UberPipelineKey {
pub(crate) const FULL_PIPELINE_KEY_BYTES: usize = SHADER_KEY_BYTES + SPECIALIZATION_KEY_BYTES + PipelineKey::BYTES;
const PIPELINE_CACHE_MAGIC: [u8; 4] = *b"GPKC";
-const PIPELINE_CACHE_VERSION: u32 = 10;
+const PIPELINE_CACHE_VERSION: u32 = 11;
+
pub(crate) fn pipeline_cache_path() -> std::path::PathBuf {
gecko::paths::cache("pipeline_keys.bin")
}
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index 1eaf366..c646f80 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -538,7 +538,6 @@ impl GxRenderer {
const PER_BUCKET_CAP: usize = 8;
debug_assert_eq!(tex.format(), wgpu::TextureFormat::Rgba8Unorm);
- debug_assert_eq!(tex.mip_level_count(), 1);
debug_assert_eq!(tex.sample_count(), 1);
debug_assert_eq!(tex.dimension(), wgpu::TextureDimension::D2);
debug_assert!(tex.usage().contains(
@@ -546,7 +545,10 @@ impl GxRenderer {
));
let size = tex.size();
- let bucket = self.texture_pool.entry((size.width, size.height)).or_default();
+ let bucket = self
+ .texture_pool
+ .entry((size.width, size.height, tex.mip_level_count()))
+ .or_default();
if bucket.len() < PER_BUCKET_CAP {
bucket.push(tex);
}
diff --git a/crates/backend-wgpu/src/shader_specialization.rs b/crates/backend-wgpu/src/shader_specialization.rs
index 2b2a597..5868495 100644
--- a/crates/backend-wgpu/src/shader_specialization.rs
+++ b/crates/backend-wgpu/src/shader_specialization.rs
@@ -16,7 +16,8 @@ const MAIN_WESL: &str = include_str!("shaders/main.wesl");
pub(crate) const KEY_BYTES: usize = 6;
pub(crate) const SPECIALIZATION_KEY_BYTES: usize = 82 * size_of::<u32>();
const CACHE_MAGIC: [u8; 4] = *b"GSKC";
-const CACHE_VERSION: u32 = 9;
+const CACHE_VERSION: u32 = 11;
+
pub(crate) fn shader_cache_path() -> std::path::PathBuf {
gecko::paths::cache("shader_keys.bin")
}
diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.wesl
index 0945d20..4789aeb 100644
--- a/crates/backend-wgpu/src/shaders/common.wesl
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -51,6 +51,7 @@ struct DrawUniforms {
// a larger GPU texture, so textureDimensions must not be used for
// guest texel math.
tex_dims: array<vec4<u32>, 4>,
+ tex_lod_bias: array<vec4<f32>, 2>,
};
@group(0) @binding(0) var<uniform> frame: FrameUniforms;
diff --git a/crates/backend-wgpu/src/shaders/tev_helpers.wesl b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
index f2b2805..f837b31 100644
--- a/crates/backend-wgpu/src/shaders/tev_helpers.wesl
+++ b/crates/backend-wgpu/src/shaders/tev_helpers.wesl
@@ -1,4 +1,4 @@
-import super::common::{VsOut, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
+import super::common::{VsOut, draw, tex0, tex1, tex2, tex3, tex4, tex5, tex6, tex7, samp0, samp1, samp2, samp3, samp4, samp5, samp6, samp7};
fn extract_bits(val: u32, lo: u32, width: u32) -> u32 {
return (val >> lo) & ((1u << width) - 1u);
@@ -54,15 +54,15 @@ fn stq_to_uv(stq: vec3<f32>) -> vec2<f32> {
fn sample_texmap(texmap: u32, uv: vec2<f32>) -> vec4<f32> {
switch texmap {
- case 0u: { return textureSample(tex0, samp0, uv); }
- case 1u: { return textureSample(tex1, samp1, uv); }
- case 2u: { return textureSample(tex2, samp2, uv); }
- case 3u: { return textureSample(tex3, samp3, uv); }
- case 4u: { return textureSample(tex4, samp4, uv); }
- case 5u: { return textureSample(tex5, samp5, uv); }
- case 6u: { return textureSample(tex6, samp6, uv); }
- case 7u: { return textureSample(tex7, samp7, uv); }
- default: { return textureSample(tex0, samp0, uv); }
+ case 0u: { return textureSampleBias(tex0, samp0, uv, draw.tex_lod_bias[0u][0u]); }
+ case 1u: { return textureSampleBias(tex1, samp1, uv, draw.tex_lod_bias[0u][1u]); }
+ case 2u: { return textureSampleBias(tex2, samp2, uv, draw.tex_lod_bias[0u][2u]); }
+ case 3u: { return textureSampleBias(tex3, samp3, uv, draw.tex_lod_bias[0u][3u]); }
+ case 4u: { return textureSampleBias(tex4, samp4, uv, draw.tex_lod_bias[1u][0u]); }
+ case 5u: { return textureSampleBias(tex5, samp5, uv, draw.tex_lod_bias[1u][1u]); }
+ case 6u: { return textureSampleBias(tex6, samp6, uv, draw.tex_lod_bias[1u][2u]); }
+ case 7u: { return textureSampleBias(tex7, samp7, uv, draw.tex_lod_bias[1u][3u]); }
+ default: { return textureSampleBias(tex0, samp0, uv, draw.tex_lod_bias[0u][0u]); }
}
}
diff --git a/crates/fifoplayer/src/debug/geometry.rs b/crates/fifoplayer/src/debug/geometry.rs
index 28984af..0aac4a0 100644
--- a/crates/fifoplayer/src/debug/geometry.rs
+++ b/crates/fifoplayer/src/debug/geometry.rs
@@ -87,8 +87,8 @@ impl GeometryCapture {
} => {
let size = [*width as usize, *height as usize];
- if !rgba.is_empty() && rgba.len() == size[0] * size[1] * 4 {
- let image = egui::ColorImage::from_rgba_unmultiplied(size, rgba);
+ if !rgba.is_empty() && rgba.len() >= size[0] * size[1] * 4 {
+ let image = egui::ColorImage::from_rgba_unmultiplied(size, &rgba[..size[0] * size[1] * 4]);
self.textures.insert(*id, Arc::new(image));
} else {
self.textures.remove(id);
diff --git a/crates/gecko/src/flipper/gx.rs b/crates/gecko/src/flipper/gx.rs
index d9f04ea..91f2990 100644
--- a/crates/gecko/src/flipper/gx.rs
+++ b/crates/gecko/src/flipper/gx.rs
@@ -126,7 +126,7 @@ pub struct GraphicsProcessor {
pub cached_lights: [LightData; 8],
#[cfg(feature = "gx-stats")]
pub(crate) stats: GxStats,
- pub texture_hashes: FxHashMap<TextureKey, (u64, u64)>,
+ pub texture_hashes: FxHashMap<TextureKey, texture::TextureHash>,
pub execution_mode: ExecutionMode,
}
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 2d220c5..a5880de 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -2,7 +2,7 @@ use super::constants::*;
use super::recorder::MemoryUpdateType;
use super::regs::*;
use super::{GraphicsProcessor, draw, texture};
-use crate::host::{GxAction, RenderSink, TextureKey};
+use crate::host::{GxAction, RenderSink, TextureKey, TextureLod};
use crate::mmio::{Mmio, RamView, RamViewMut};
impl GraphicsProcessor {
@@ -45,10 +45,10 @@ impl GraphicsProcessor {
// address with a stale size/format. Mark the slot dirty instead;
// `snapshot_dirty_textures` resolves it right before the next draw,
// when the full descriptor is consistent.
- let texture_slot = if idx >= BP_TX_SETMODE0_I0 && idx < BP_TX_SETMODE0_I0 + 4 {
- Some(idx - BP_TX_SETMODE0_I0)
- } else if idx >= BP_TX_SETMODE0_I4 && idx < BP_TX_SETMODE0_I4 + 4 {
- Some(idx - BP_TX_SETMODE0_I4 + 4)
+ let texture_slot = if idx >= BP_TX_SETMODE0_I0 && idx < BP_TX_SETMODE1_I0 + 4 {
+ Some((idx - BP_TX_SETMODE0_I0) & 3)
+ } else if idx >= BP_TX_SETMODE0_I4 && idx < BP_TX_SETMODE1_I4 + 4 {
+ Some(((idx - BP_TX_SETMODE0_I4) & 3) + 4)
} else if idx >= BP_TX_SETIMAGE0_I0 && idx < BP_TX_SETIMAGE3_I0 + 4 {
// IMAGE0-3 are four contiguous 4-register blocks (0x88..0x98),
// each indexed by slot, so `& 3` recovers the slot in any block.
@@ -276,6 +276,7 @@ impl GraphicsProcessor {
TxSetImage0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE0_I0, BP_TX_SETIMAGE0_I4, slot)]);
let image3 = TxSetImage3::from_raw(image3_val);
let mode0 = TxSetMode0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, slot)]);
+ let mode1 = TxSetMode1::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETMODE1_I0, BP_TX_SETMODE1_I4, slot)]);
let width = (image0.width() + 1) as u32;
let height = (image0.height() + 1) as u32;
@@ -303,13 +304,14 @@ impl GraphicsProcessor {
// tmem_offset would silently let the latest load clobber the earlier
// ones, since bind groups are built lazily and resolve to whichever
// GPU texture is current at render-pass time.
- let cache_id = self::texture_cache_id(ram_addr, format, tlut, palette);
+ let mip_levels = texture::mip_level_count(width, height, mode0.min_filter(), mode1.max_lod());
+ let cache_id = self::texture_cache_id(ram_addr, format, tlut, palette, mip_levels);
// Resolve the texture's raw bytes once, against MEM1 or MEM2. If the
// address doesn't fall in either bank, leave the slot's last binding
// alone but skip the decode (the renderer will keep its previous
// texture for this id).
- let raw_size = texture::raw_data_size(width, height, format);
+ let raw_size = texture::mip_data_size(width, height, format, mip_levels);
let tex_slice = ram.slice(ram_addr, raw_size);
if tex_slice.is_some()
@@ -318,8 +320,7 @@ impl GraphicsProcessor {
rec.use_memory(ram, ram_addr as u32, raw_size, MemoryUpdateType::TextureMap);
}
- let gpu_copy =
- self.recorder.is_none() && renderer.has_pending_efb_texture(ram_addr as u32, width, height, format);
+ let gpu_copy = self.is_pending_gpu_copy(renderer, ram_addr as u32, width, height, format, mip_levels);
let changed = !gpu_copy
&& match tex_slice {
Some(tex) => self::texture_data_changed(
@@ -328,8 +329,8 @@ impl GraphicsProcessor {
cache_id,
palette,
tlut,
- format,
ram.range_generation(ram_addr, raw_size).unwrap_or(u64::MAX),
+ (width, height, format, mip_levels),
),
None => {
tracing::warn!(
@@ -348,6 +349,7 @@ impl GraphicsProcessor {
width,
height,
fmt: format,
+ mip_levels,
rgba: Vec::new(),
});
}
@@ -374,7 +376,8 @@ impl GraphicsProcessor {
width,
height,
fmt: format,
- rgba: texture::decode_to_rgba(tex_slice.unwrap(), &desc, palette, tlut.format),
+ mip_levels,
+ rgba: texture::decode_mips_to_rgba(tex_slice.unwrap(), &desc, palette, tlut.format, mip_levels),
});
}
@@ -396,9 +399,43 @@ impl GraphicsProcessor {
wrap_t: mode0.wrap_t(),
mag_filter: mode0.mag_filter(),
min_filter: mode0.min_filter(),
+ lod: if mode0.min_filter().uses_mipmaps() {
+ TextureLod {
+ min: mode1.min_lod().min(mode1.max_lod()),
+ max: mode1.max_lod(),
+ bias: mode0.lod_bias() as i8,
+ }
+ } else {
+ TextureLod::default()
+ },
});
}
+ fn is_pending_gpu_copy(
+ &self,
+ renderer: &dyn RenderSink,
+ addr: u32,
+ width: u32,
+ height: u32,
+ format: draw::TextureFormat,
+ mip_levels: u32,
+ ) -> bool {
+ mip_levels == 1 && self.recorder.is_none() && renderer.has_pending_efb_texture(addr, width, height, format)
+ }
+
+ pub(crate) fn texture_mip_levels(&self, slot: usize) -> u32 {
+ let image =
+ TxSetImage0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE0_I0, BP_TX_SETIMAGE0_I4, slot)]);
+ let mode0 = TxSetMode0::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETMODE0_I0, BP_TX_SETMODE0_I4, slot)]);
+ let mode1 = TxSetMode1::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETMODE1_I0, BP_TX_SETMODE1_I4, slot)]);
+ texture::mip_level_count(
+ u32::from(image.width()) + 1,
+ u32::from(image.height()) + 1,
+ mode0.min_filter(),
+ mode1.max_lod(),
+ )
+ }
+
pub fn refresh_bound_textures(&mut self, renderer: &mut dyn RenderSink, ram: &RamView<'_>) {
for slot in 0..self.cur_textures.len() {
if self.cur_textures[slot].is_none() {
@@ -441,11 +478,17 @@ impl GraphicsProcessor {
TxSetImage3::from_raw(self.bp_regs[self::tx_slot_reg(BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, slot)]);
let width = (image0.width() + 1) as u32;
let height = (image0.height() + 1) as u32;
- let len = texture::raw_data_size(width, height, image0.format());
+ let mip_levels = self.texture_mip_levels(slot);
+ let len = texture::mip_data_size(width, height, image0.format(), mip_levels);
- if self.recorder.is_none()
- && renderer.has_pending_efb_texture(image3.ram_addr() as u32, width, height, image0.format())
- {
+ if self.is_pending_gpu_copy(
+ renderer,
+ image3.ram_addr() as u32,
+ width,
+ height,
+ image0.format(),
+ mip_levels,
+ ) {
continue;
}
@@ -745,8 +788,8 @@ fn slot_palette(palette_mem: &[u16], tmem_offset: u16) -> &[u16] {
/// Mint the renderer cache key for the given texture binding.
///
-/// `variant` is `0` for non-paletted formats. For paletted (CI*) formats it's
-/// a 32-bit hash of `(palette content, tlut.format, tmem_offset)` so the
+/// `variant` combines the mip count with a 32-bit hash of
+/// `(palette content, tlut.format, tmem_offset)` for paletted (CI*) formats so the
/// same RAM index stream sampled through different palettes lands
/// in distinct cache slots. FFCC's title-logo fade animation alternates
/// between palettes at a fixed `tmem_offset`; without the variant in the
@@ -754,7 +797,13 @@ fn slot_palette(palette_mem: &[u16], tmem_offset: u16) -> &[u16] {
/// renderer's cache and bind groups built at render-pass time would all
/// resolve to whichever decode landed last.
#[inline(always)]
-fn texture_cache_id(ram_addr: usize, format: draw::TextureFormat, tlut: draw::TlutRef, palette: &[u16]) -> TextureKey {
+fn texture_cache_id(
+ ram_addr: usize,
+ format: draw::TextureFormat,
+ tlut: draw::TlutRef,
+ palette: &[u16],
+ mip_levels: u32,
+) -> TextureKey {
let variant = if format.is_paletted() {
let max_entries = match format {
draw::TextureFormat::CI4 => 16,
@@ -774,7 +823,7 @@ fn texture_cache_id(ram_addr: usize, format: draw::TextureFormat, tlut: draw::Tl
};
TextureKey {
ram_addr: ram_addr as u32,
- variant,
+ variant: variant ^ (mip_levels - 1).wrapping_mul(0x9e37_79b9),
}
}
@@ -784,17 +833,18 @@ fn texture_cache_id(ram_addr: usize, format: draw::TextureFormat, tlut: draw::Tl
/// `cache_id` so paletted textures bound with multiple TLUTs are tracked
/// independently.
fn texture_data_changed(
- hashes: &mut rustc_hash::FxHashMap<TextureKey, (u64, u64)>,
+ hashes: &mut rustc_hash::FxHashMap<TextureKey, texture::TextureHash>,
tex: &[u8],
cache_id: TextureKey,
palette: &[u16],
tlut: draw::TlutRef,
- format: draw::TextureFormat,
memory_generation: u64,
+ layout: (u32, u32, draw::TextureFormat, u32),
) -> bool {
+ let format = layout.2;
if hashes
.get(&cache_id)
- .is_some_and(|&(_, previous_generation)| previous_generation == memory_generation)
+ .is_some_and(|prev| prev.generation == memory_generation && prev.layout == layout)
{
return false;
}
@@ -815,8 +865,15 @@ fn texture_data_changed(
hash ^= tlut.format as u64;
}
- let prev = hashes.insert(cache_id, (hash, memory_generation));
- prev.is_none_or(|(previous_hash, _)| previous_hash != hash)
+ let prev = hashes.insert(
+ cache_id,
+ texture::TextureHash {
+ hash,
+ generation: memory_generation,
+ layout,
+ },
+ );
+ prev.is_none_or(|prev| prev.hash != hash || prev.layout != layout)
}
impl GraphicsProcessor {
diff --git a/crates/gecko/src/flipper/gx/regs.rs b/crates/gecko/src/flipper/gx/regs.rs
index cb9cbc8..f9e512c 100644
--- a/crates/gecko/src/flipper/gx/regs.rs
+++ b/crates/gecko/src/flipper/gx/regs.rs
@@ -627,6 +627,12 @@ pub enum MinFilter {
LinearMipmapLinear = 6,
}
+impl MinFilter {
+ pub fn uses_mipmaps(self) -> bool {
+ !matches!(self, Self::Nearest | Self::Linear)
+ }
+}
+
#[derive(Debug, PartialEq, Eq, Hash, BitEnum)]
pub enum RasterChannel {
Color0 = 0,
@@ -698,6 +704,18 @@ pub struct TxSetMode0 {
#[bits(5..=7)]
pub min_filter: MinFilter,
+
+ #[bits(9..=16)]
+ pub lod_bias: u8,
+}
+
+#[chapa::bitfield(u32, order = lsb0)]
+#[derive(Debug, Clone, Copy, Default)]
+pub struct TxSetMode1 {
+ #[bits(0..=7)]
+ pub min_lod: u8,
+ #[bits(8..=15)]
+ pub max_lod: u8,
}
// TEV color combiner input select (SELA-SELD)
diff --git a/crates/gecko/src/flipper/gx/texture.rs b/crates/gecko/src/flipper/gx/texture.rs
index 83a50f3..9598963 100644
--- a/crates/gecko/src/flipper/gx/texture.rs
+++ b/crates/gecko/src/flipper/gx/texture.rs
@@ -33,6 +33,64 @@ pub fn decode_to_rgba(tex: &[u8], desc: &TextureDescriptor, palette: &[u16], tlu
rgba
}
+pub fn mip_level_count(width: u32, height: u32, filter: super::regs::MinFilter, max_lod: u8) -> u32 {
+ if !filter.uses_mipmaps() {
+ return 1;
+ }
+
+ (u32::from(max_lod).div_ceil(16) + 1).min(width.max(height).ilog2() + 1)
+}
+
+pub fn mip_dimensions(width: u32, height: u32, levels: u32) -> impl Iterator<Item = (u32, u32)> {
+ (0..levels).map(move |level| ((width >> level).max(1), (height >> level).max(1)))
+}
+
+pub fn mip_data_size(width: u32, height: u32, format: TextureFormat, levels: u32) -> usize {
+ self::mip_dimensions(width, height, levels)
+ .map(|(w, h)| self::raw_data_size(w, h, format))
+ .sum()
+}
+
+pub fn decode_mips_to_rgba(
+ tex: &[u8],
+ desc: &TextureDescriptor,
+ palette: &[u16],
+ tlut_format: TlutFormat,
+ levels: u32,
+) -> Vec<u8> {
+ if levels == 1 {
+ return self::decode_to_rgba(tex, desc, palette, tlut_format);
+ }
+
+ let mut rgba = Vec::with_capacity(
+ self::mip_dimensions(desc.width, desc.height, levels)
+ .map(|(w, h)| (w * h * 4) as usize)
+ .sum(),
+ );
+
+ let mut offset = 0;
+ for (width, height) in self::mip_dimensions(desc.width, desc.height, levels) {
+ let size = self::raw_data_size(width, height, desc.format);
+ let level = TextureDescriptor { width, height, ..*desc };
+ rgba.extend(self::decode_to_rgba(
+ tex.get(offset..offset + size).unwrap_or(&[]),
+ &level,
+ palette,
+ tlut_format,
+ ));
+ offset += size;
+ }
+
+ rgba
+}
+
+#[derive(Clone, Copy)]
+pub struct TextureHash {
+ pub hash: u64,
+ pub generation: u64,
+ pub layout: (u32, u32, TextureFormat, u32),
+}
+
#[derive(Clone, Copy, Debug)]
pub struct BlockDims {
pub tile_w: u32,
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index c77206a..7888f37 100644
--- a/crates/gecko/src/flipper/gx/vertex.rs
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -151,6 +151,7 @@ impl GraphicsProcessor {
if self.recorder.as_ref().is_some_and(|rec| rec.is_recording()) {
let vf = self.build_vertex_format(cmd);
let view = mmio.ram_view();
+ let mip_levels: [u32; 8] = std::array::from_fn(|slot| self.texture_mip_levels(slot));
let rec = self.recorder.as_deref_mut().unwrap();
let mut offset = 0;
@@ -160,8 +161,11 @@ impl GraphicsProcessor {
offset += len;
}
- for desc in self.cur_textures.iter().flatten() {
- let len = super::texture::raw_data_size(desc.width, desc.height, desc.format);
+ for (slot, desc) in self.cur_textures.iter().enumerate() {
+ let Some(desc) = desc else {
+ continue;
+ };
+ let len = super::texture::mip_data_size(desc.width, desc.height, desc.format, mip_levels[slot]);
rec.use_draw_texture(&view, desc.ram_addr as u32, len);
}
}
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index eb7173d..95d96de 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -11,8 +11,9 @@ use std::path::PathBuf;
/// frame) silently overwrite each other and bind groups built lazily at
/// render-pass time all resolve to whichever decode landed last.
///
-/// `variant` is `0` for non-paletted formats and a 32-bit hash of
-/// `(palette content, tlut.format, tmem_offset)` for paletted ones.
+/// `variant` combines mip count with a 32-bit hash of
+/// `(palette content, tlut.format, tmem_offset)` for paletted textures.
+/// Single-level, non-paletted textures use `0`.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TextureKey {
pub ram_addr: Address,
@@ -25,6 +26,13 @@ impl TextureKey {
}
}
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
+pub struct TextureLod {
+ pub min: u8,
+ pub max: u8,
+ pub bias: i8,
+}
+
#[derive(Debug)]
pub enum GxAction {
// XF
@@ -56,6 +64,7 @@ pub enum GxAction {
width: u32,
height: u32,
fmt: TextureFormat,
+ mip_levels: u32,
rgba: Vec<u8>,
},
@@ -79,6 +88,7 @@ pub enum GxAction {
wrap_t: WrapMode,
mag_filter: MagFilter,
min_filter: MinFilter,
+ lod: TextureLod,
},
/// Issue a draw call. The renderer uses its tracked state (projection,
diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs
index 05f9cad..59904a7 100644
--- a/crates/mcp/src/server.rs
+++ b/crates/mcp/src/server.rs
@@ -507,7 +507,7 @@ impl McpServer {
}
#[tool(
- description = "Return one previously uploaded GX texture as a base64 PNG. Identify by ram_addr (and variant for paletted textures)."
+ description = "Return one previously uploaded GX texture as a base64 PNG. Identify by ram_addr and the variant returned by the texture list."
)]
async fn get_texture(&self, Parameters(args): Parameters<GetTextureArgs>) -> Result<CallToolResult, McpError> {
let intro = self.shared.introspect.lock().unwrap();
diff --git a/crates/mcp/src/sink.rs b/crates/mcp/src/sink.rs
index 519f98c..2cc54c0 100644
--- a/crates/mcp/src/sink.rs
+++ b/crates/mcp/src/sink.rs
@@ -42,6 +42,7 @@ impl RenderSink for McpSink {
height,
fmt,
rgba,
+ ..
} => {
let mut i = self.introspect.lock().unwrap();
let frame = i.frame_index;
@@ -51,7 +52,10 @@ impl RenderSink for McpSink {
width: *width,
height: *height,
format: *fmt,
- rgba: rgba.clone(),
+ rgba: rgba
+ .get(..(*width as usize * *height as usize * 4))
+ .unwrap_or(&[])
+ .to_vec(),
last_seen_frame: frame,
},
);