Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

texture formats, passes texturetest.dol

Layle16f1dc8bae54
diff --git a/crates/backend-wgpu/src/gx.wgsl b/crates/backend-wgpu/src/gx.wgsl
index 93c8646..138d884 100644
--- a/crates/backend-wgpu/src/gx.wgsl
+++ b/crates/backend-wgpu/src/gx.wgsl
@@ -1,18 +1,28 @@
struct Uniforms {
mvp: mat4x4<f32>,
+ has_texture: u32,
+ _pad: vec3<u32>,
};
@group(0) @binding(0)
var<uniform> uniforms: Uniforms;
+@group(0) @binding(1)
+var tex: texture_2d<f32>;
+
+@group(0) @binding(2)
+var tex_sampler: sampler;
+
struct VsIn {
@location(0) position: vec3<f32>,
@location(1) color: vec4<f32>,
+ @location(2) tex0: vec2<f32>,
};
struct VsOut {
@builtin(position) clip_pos: vec4<f32>,
@location(0) color: vec4<f32>,
+ @location(1) tex0: vec2<f32>,
};
@vertex
@@ -22,10 +32,16 @@ fn vs_main(in: VsIn) -> VsOut {
// Remap depth: GameCube/OpenGL uses [-1,1], wgpu uses [0,1]
out.clip_pos.z = out.clip_pos.z * 0.5 + out.clip_pos.w * 0.5;
out.color = in.color;
+ out.tex0 = in.tex0;
return out;
}
@fragment
fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- return in.color;
+ // TODO: pretty sure this is wrong but it works for texturetest.dol
+ if uniforms.has_texture == 1u {
+ return textureSample(tex, tex_sampler, in.tex0);
+ } else {
+ return in.color;
+ }
}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 524414c..ce6eb65 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -1,22 +1,39 @@
-use gekko::flipper::gx::draw::{DrawCall, DrawCommands, Primitive};
+mod texture;
+
+use gekko::flipper::gx::draw::{DrawCall, DrawCommands, Primitive, TextureFormat};
+use std::collections::HashMap;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct GpuVertex {
position: [f32; 3],
color: [f32; 4],
+ tex0: [f32; 2],
+}
+
+impl From<&gekko::flipper::gx::draw::Vertex> for GpuVertex {
+ fn from(v: &gekko::flipper::gx::draw::Vertex) -> Self {
+ Self {
+ position: v.position,
+ color: v.color0,
+ tex0: v.tex0.unwrap_or([0.0, 0.0]),
+ }
+ }
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Uniforms {
- mvp: [[f32; 4]; 4],
+ mvp: [[f32; 4]; 4], // 64 bytes
+ has_texture: u32, // 4 bytes
+ _padding: [u8; 28], // 28 bytes
}
const SHADER: &str = include_str!("gx.wgsl");
pub struct GxRenderer {
pipeline: wgpu::RenderPipeline,
+ bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
uniform_buffer: wgpu::Buffer,
vertex_buffer: wgpu::Buffer,
@@ -25,10 +42,21 @@ pub struct GxRenderer {
depth_view: wgpu::TextureView,
depth_width: u32,
depth_height: u32,
+ sampler: wgpu::Sampler,
+ /// Cache: (ram_addr, width, height, format) -> (wgpu Texture, TextureView)
+ texture_cache: HashMap<(usize, u32, u32, TextureFormat), (wgpu::Texture, wgpu::TextureView)>,
+ /// Fallback 1x1 white texture view used when no texture is bound
+ fallback_view: wgpu::TextureView,
}
impl GxRenderer {
- pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat, width: u32, height: u32) -> Self {
+ pub fn new(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ surface_format: wgpu::TextureFormat,
+ width: u32,
+ height: u32,
+ ) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("gx_shader"),
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
@@ -36,16 +64,34 @@ impl GxRenderer {
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
- entries: &[wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::VERTEX,
- ty: wgpu::BindingType::Buffer {
- ty: wgpu::BufferBindingType::Uniform,
- has_dynamic_offset: false,
- min_binding_size: None,
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX | 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 {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
},
- count: None,
- }],
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
@@ -68,6 +114,11 @@ impl GxRenderer {
offset: 12,
shader_location: 1,
},
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x2,
+ offset: 28,
+ shader_location: 2,
+ },
],
};
@@ -115,13 +166,63 @@ impl GxRenderer {
mapped_at_creation: false,
});
+ let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("gx_sampler"),
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+
+ let fallback_texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("gx_fallback_tex"),
+ size: wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ // White pixel
+ queue.write_texture(
+ fallback_texture.as_image_copy(),
+ &[255u8, 255, 255, 255],
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: 1,
+ height: 1,
+ depth_or_array_layers: 1,
+ },
+ );
+ let fallback_view = fallback_texture.create_view(&Default::default());
+
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bind_group_layout,
- entries: &[wgpu::BindGroupEntry {
- binding: 0,
- resource: uniform_buffer.as_entire_binding(),
- }],
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(&fallback_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&sampler),
+ },
+ ],
});
let initial_capacity = 1024;
@@ -138,6 +239,7 @@ impl GxRenderer {
GxRenderer {
pipeline,
+ bind_group_layout,
bind_group,
uniform_buffer,
vertex_buffer,
@@ -146,6 +248,9 @@ impl GxRenderer {
depth_view,
depth_width,
depth_height,
+ sampler,
+ texture_cache: HashMap::new(),
+ fallback_view,
}
}
@@ -171,6 +276,7 @@ impl GxRenderer {
device: &wgpu::Device,
queue: &wgpu::Queue,
commands: &DrawCommands,
+ ram: &[u8],
target: &wgpu::TextureView,
target_width: u32,
target_height: u32,
@@ -178,7 +284,47 @@ impl GxRenderer {
self.ensure_depth_texture(device, target_width, target_height);
let mvp = commands.projection * commands.modelview;
- queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&Uniforms { mvp: mvp.0 }));
+ let has_texture = commands.textures[0].is_some() as u32;
+ queue.write_buffer(
+ &self.uniform_buffer,
+ 0,
+ bytemuck::bytes_of(&Uniforms {
+ mvp: mvp.0,
+ has_texture,
+ _padding: [0; 28],
+ }),
+ );
+
+ // Upload texture slot 0 if present, using cache to avoid redundant uploads
+ let tex_view = 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));
+ }
+ &self.texture_cache[&key].1
+ } else {
+ &self.fallback_view
+ };
+
+ self.bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &self.bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: self.uniform_buffer.as_entire_binding(),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(tex_view),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ });
let vertices = triangulate(&commands.commands);
if vertices.is_empty() {
@@ -250,50 +396,26 @@ fn create_depth_texture(device: &wgpu::Device, w: u32, h: u32) -> (wgpu::Texture
let view = tex.create_view(&Default::default());
(tex, view)
}
-
fn triangulate(draw_calls: &[DrawCall]) -> Vec<GpuVertex> {
let mut out = Vec::new();
for dc in draw_calls {
match dc.primitive {
Primitive::Triangles => {
for v in &dc.vertices {
- out.push(GpuVertex {
- position: v.position,
- color: v.color0,
- });
+ out.push(v.into());
}
}
Primitive::Quads => {
for quad in dc.vertices.chunks(4) {
if quad.len() < 4 {
- println!("quad with less than 4 vertices");
continue;
}
-
- out.push(GpuVertex {
- position: quad[0].position,
- color: quad[0].color0,
- });
- out.push(GpuVertex {
- position: quad[1].position,
- color: quad[1].color0,
- });
- out.push(GpuVertex {
- position: quad[2].position,
- color: quad[2].color0,
- });
- out.push(GpuVertex {
- position: quad[0].position,
- color: quad[0].color0,
- });
- out.push(GpuVertex {
- position: quad[2].position,
- color: quad[2].color0,
- });
- out.push(GpuVertex {
- position: quad[3].position,
- color: quad[3].color0,
- });
+ out.push((&quad[0]).into());
+ out.push((&quad[1]).into());
+ out.push((&quad[2]).into());
+ out.push((&quad[0]).into());
+ out.push((&quad[2]).into());
+ out.push((&quad[3]).into());
}
}
_ => unimplemented!("triangulation for {:?}", dc.primitive),
diff --git a/crates/backend-wgpu/src/texture.rs b/crates/backend-wgpu/src/texture.rs
new file mode 100644
index 0000000..c3674bb
--- /dev/null
+++ b/crates/backend-wgpu/src/texture.rs
@@ -0,0 +1,414 @@
+use gekko::flipper::gx::draw::{TextureDescriptor, TextureFormat};
+
+pub fn upload_texture(
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ ram: &[u8],
+ desc: &TextureDescriptor,
+) -> (wgpu::Texture, wgpu::TextureView) {
+ let w = desc.width as usize;
+ let h = desc.height as usize;
+ let mut rgba = vec![0u8; w * h * 4];
+
+ match desc.format {
+ TextureFormat::I4 => decode_i4(ram, desc, &mut rgba, w, h),
+ TextureFormat::I8 => decode_i8(ram, desc, &mut rgba, w, h),
+ TextureFormat::IA4 => decode_ia4(ram, desc, &mut rgba, w, h),
+ TextureFormat::IA8 => decode_ia8(ram, desc, &mut rgba, w, h),
+ TextureFormat::RGB565 => decode_rgb565(ram, desc, &mut rgba, w, h),
+ TextureFormat::RGB5A3 => decode_rgb5a3(ram, desc, &mut rgba, w, h),
+ TextureFormat::RGBA8 => decode_rgba8(ram, desc, &mut rgba, w, h),
+ TextureFormat::CMPR => decode_cmpr(ram, desc, &mut rgba, w, h),
+ _ => eprintln!("unsupported GX texture format: {:?}", desc.format),
+ }
+
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("gx_tex"),
+ size: wgpu::Extent3d {
+ width: desc.width,
+ height: desc.height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8UnormSrgb,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ tex.as_image_copy(),
+ &rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(desc.width * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: desc.width,
+ height: desc.height,
+ depth_or_array_layers: 1,
+ },
+ );
+ let view = tex.create_view(&Default::default());
+ (tex, view)
+}
+
+#[inline(always)]
+fn put_pixel(rgba: &mut [u8], stride: usize, x: usize, y: usize, r: u8, g: u8, b: u8, a: u8) {
+ let offset = (y * stride + x) * 4;
+ rgba[offset] = r;
+ rgba[offset + 1] = g;
+ rgba[offset + 2] = b;
+ rgba[offset + 3] = a;
+}
+
+#[inline(always)]
+fn expand_to_8bit(value: u16, max: u16) -> u8 {
+ (value * 255 / max) as u8
+}
+
+#[inline(always)]
+fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
+ let red_5bit = (packed >> 11) & 0x1F;
+ let green_6bit = (packed >> 5) & 0x3F;
+ let blue_5bit = packed & 0x1F;
+ [
+ expand_to_8bit(red_5bit, 31),
+ expand_to_8bit(green_6bit, 63),
+ expand_to_8bit(blue_5bit, 31),
+ 255,
+ ]
+}
+
+// GX textures are stored in a tiled layout. The image is divided into
+// fixed-size blocks (e.g. 4x4 or 8x8 pixels). Blocks are stored left-to-right,
+// top-to-bottom, and within each block pixels are also stored row by row.
+
+fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 8;
+ const BLOCK_H: usize = 8;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) / 2;
+ if byte_offset >= ram.len() {
+ continue;
+ }
+
+ let is_left_pixel = tile_x % 2 == 0;
+ let nibble = if is_left_pixel {
+ ram[byte_offset] >> 4
+ } else {
+ ram[byte_offset] & 0x0F
+ };
+
+ let intensity = expand_to_8bit(nibble as u16, 15);
+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, 255);
+ }
+ }
+ }
+ }
+}
+
+fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 8;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + tile_y * BLOCK_W + tile_x;
+ if byte_offset >= ram.len() {
+ continue;
+ }
+
+ let intensity = ram[byte_offset];
+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, 255);
+ }
+ }
+ }
+ }
+}
+
+fn decode_ia4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 8;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + tile_y * BLOCK_W + tile_x;
+ if byte_offset >= ram.len() {
+ continue;
+ }
+
+ let packed = ram[byte_offset];
+ let alpha = expand_to_8bit((packed >> 4) as u16, 15);
+ let intensity = expand_to_8bit((packed & 0x0F) as u16, 15);
+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, alpha);
+ }
+ }
+ }
+ }
+}
+
+fn decode_ia8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 4;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
+ if byte_offset + 1 >= ram.len() {
+ continue;
+ }
+
+ let alpha = ram[byte_offset];
+ let intensity = ram[byte_offset + 1];
+ put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, alpha);
+ }
+ }
+ }
+ }
+}
+
+fn decode_rgb565(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 4;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
+ if byte_offset + 1 >= ram.len() {
+ continue;
+ }
+
+ let [r, g, b, a] = rgb565_to_rgba(u16::from_be_bytes([ram[byte_offset], ram[byte_offset + 1]]));
+ put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
+ }
+ }
+ }
+ }
+}
+
+fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 4;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 32;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
+ if byte_offset + 1 >= ram.len() {
+ continue;
+ }
+
+ let packed = u16::from_be_bytes([ram[byte_offset], ram[byte_offset + 1]]);
+ let has_no_alpha = packed & 0x8000 != 0;
+
+ if has_no_alpha {
+ let r = expand_to_8bit((packed >> 10) & 0x1F, 31);
+ let g = expand_to_8bit((packed >> 5) & 0x1F, 31);
+ let b = expand_to_8bit(packed & 0x1F, 31);
+ put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, 255);
+ } else {
+ let a = expand_to_8bit((packed >> 12) & 0x7, 7);
+ let r = expand_to_8bit((packed >> 8) & 0xF, 15);
+ let g = expand_to_8bit((packed >> 4) & 0xF, 15);
+ let b = expand_to_8bit(packed & 0xF, 15);
+ put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn decode_rgba8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const BLOCK_W: usize = 4;
+ const BLOCK_H: usize = 4;
+ const BLOCK_BYTES: usize = 64;
+
+ let blocks_x = (width + BLOCK_W - 1) / BLOCK_W;
+ let blocks_y = (height + BLOCK_H - 1) / BLOCK_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+
+ for tile_y in 0..BLOCK_H {
+ for tile_x in 0..BLOCK_W {
+ let pixel_x = block_x * BLOCK_W + tile_x;
+ let pixel_y = block_y * BLOCK_H + tile_y;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let texel_index = tile_y * BLOCK_W + tile_x;
+ let ar_offset = block_start + texel_index * 2;
+ let gb_offset = block_start + 32 + texel_index * 2;
+ if gb_offset + 1 >= ram.len() {
+ continue;
+ }
+
+ let alpha = ram[ar_offset];
+ let red = ram[ar_offset + 1];
+ let green = ram[gb_offset];
+ let blue = ram[gb_offset + 1];
+ put_pixel(rgba, width, pixel_x, pixel_y, red, green, blue, alpha);
+ }
+ }
+ }
+ }
+}
+
+fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
+ const MACRO_W: usize = 8;
+ const MACRO_H: usize = 8;
+ const MACRO_BYTES: usize = 32;
+ const SUB_BLOCK_BYTES: usize = 8;
+
+ let blocks_x = (width + MACRO_W - 1) / MACRO_W;
+ let blocks_y = (height + MACRO_H - 1) / MACRO_H;
+
+ for block_y in 0..blocks_y {
+ for block_x in 0..blocks_x {
+ let macro_start = desc.ram_addr + (block_y * blocks_x + block_x) * MACRO_BYTES;
+
+ for sub_index in 0..4usize {
+ let sub_start = macro_start + sub_index * SUB_BLOCK_BYTES;
+ let sub_x_offset = (sub_index % 2) * 4;
+ let sub_y_offset = (sub_index / 2) * 4;
+
+ if sub_start + 7 >= ram.len() {
+ continue;
+ }
+
+ let color0 = u16::from_be_bytes([ram[sub_start], ram[sub_start + 1]]);
+ let color1 = u16::from_be_bytes([ram[sub_start + 2], ram[sub_start + 3]]);
+ let palette = build_dxt1_palette(color0, color1);
+
+ for row in 0..4usize {
+ let index_byte = ram[sub_start + 4 + row];
+ for col in 0..4usize {
+ let pixel_x = block_x * MACRO_W + sub_x_offset + col;
+ let pixel_y = block_y * MACRO_H + sub_y_offset + row;
+ if pixel_x >= width || pixel_y >= height {
+ continue;
+ }
+
+ let shift = (3 - col) * 2;
+ let palette_index = ((index_byte >> shift) & 0x03) as usize;
+ let [r, g, b, a] = palette[palette_index];
+ put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
+ }
+ }
+ }
+ }
+ }
+}
+
+fn build_dxt1_palette(color0: u16, color1: u16) -> [[u8; 4]; 4] {
+ let [r0, g0, b0, _] = rgb565_to_rgba(color0);
+ let [r1, g1, b1, _] = rgb565_to_rgba(color1);
+
+ let blend = |a: u8, b: u8, weight_a: u16, weight_b: u16| -> u8 {
+ ((a as u16 * weight_a + b as u16 * weight_b) / (weight_a + weight_b)) as u8
+ };
+
+ let mut palette = [[0u8; 4]; 4];
+ palette[0] = [r0, g0, b0, 255];
+ palette[1] = [r1, g1, b1, 255];
+
+ if color0 > color1 {
+ palette[2] = [blend(r0, r1, 2, 1), blend(g0, g1, 2, 1), blend(b0, b1, 2, 1), 255];
+ palette[3] = [blend(r0, r1, 1, 2), blend(g0, g1, 1, 2), blend(b0, b1, 1, 2), 255];
+ } else {
+ palette[2] = [blend(r0, r1, 1, 1), blend(g0, g1, 1, 1), blend(b0, b1, 1, 1), 255];
+ palette[3] = [0, 0, 0, 0];
+ }
+
+ palette
+}
diff --git a/crates/gekko/src/flipper/gx.rs b/crates/gekko/src/flipper/gx.rs
index 594730b..b4948f0 100644
--- a/crates/gekko/src/flipper/gx.rs
+++ b/crates/gekko/src/flipper/gx.rs
@@ -7,11 +7,13 @@ use super::pi::InterruptFlag;
use crate::{
flipper::gx::{
constants::{
- ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_POS, ARRAY_STRIDE_REG, BP_REG_SIZE, CP_REG_SIZE, VATA_REG, VCD_HI_REG,
- VCD_LO_REG, XF_MEM_SIZE, XF_MODELVIEW_BASE, XF_MODELVIEW_END, XF_PROJECTION_BASE, XF_PROJECTION_END,
+ ARRAY_BASE_REG, ARRAY_CLR0, ARRAY_POS, ARRAY_STRIDE_REG, BP_PE_DONE, BP_PE_DONE_FINISH_BIT, BP_REG_SIZE,
+ BP_TX_SETIMAGE0_I0, BP_TX_SETIMAGE0_I4, BP_TX_SETIMAGE3_I0, BP_TX_SETIMAGE3_I4, CP_REG_SIZE, VATA_REG,
+ VCD_HI_REG, VCD_LO_REG, XF_MEM_SIZE, XF_MODELVIEW_BASE, XF_MODELVIEW_END, XF_PROJECTION_BASE,
+ XF_PROJECTION_END,
},
draw::DrawCommands,
- regs::{VatA, VcdHi, VcdLo},
+ regs::{TxSetImage0, TxSetImage3, VatA, VcdHi, VcdLo},
},
gekko::Gekko,
mmio::Mmio,
@@ -78,7 +80,8 @@ impl Gx {
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_size = match vcd_hi.tex0() {
+ 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,
@@ -104,8 +107,17 @@ impl Gx {
let clr0_size = vat_a.clr0_data_size();
let clr0_data = &mmio.ram[clr0_addr..clr0_addr + clr0_size];
- // Skip tex0 bytes
- cur.set_position(cur.position() + tex0_size as u64);
+ // 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
+ };
tracing::debug!(
vertex = i,
@@ -119,7 +131,7 @@ impl Gx {
let position = Self::decode_position(pos_data, &vat_a);
let color0 = Self::decode_color(clr0_data, &vat_a);
- vertices.push(draw::Vertex { position, color0 });
+ vertices.push(draw::Vertex { position, color0, tex0 });
}
if let Some(primitive) = draw::Primitive::from_cmd(cmd) {
@@ -281,8 +293,49 @@ impl Gx {
"BP register write"
);
- // PE finish: register 0x45, bit 1
- if idx == 0x45 && (val & 0x02) != 0 {
+ // TX_SETIMAGE3 is written last for each texture slot, so we use it as
+ // the trigger to snapshot the full texture descriptor
+ let texture_slot = if idx >= BP_TX_SETIMAGE3_I0 && idx < BP_TX_SETIMAGE3_I0 + 4 {
+ Some(idx - BP_TX_SETIMAGE3_I0)
+ } else if idx >= BP_TX_SETIMAGE3_I4 && idx < BP_TX_SETIMAGE3_I4 + 4 {
+ Some(idx - BP_TX_SETIMAGE3_I4 + 4)
+ } else {
+ None
+ };
+
+ if let Some(slot) = texture_slot {
+ let image0_reg = if slot < 4 {
+ BP_TX_SETIMAGE0_I0 + slot
+ } else {
+ BP_TX_SETIMAGE0_I4 + (slot - 4)
+ };
+
+ let image0 = TxSetImage0::from_raw(self.bp_regs[image0_reg]);
+ let image3 = TxSetImage3::from_raw(val);
+
+ let width = image0.width();
+ let height = image0.height();
+ let ram_addr = image3.ram_addr();
+
+ tracing::debug!(
+ slot,
+ width,
+ height,
+ format = format!("{:?}", image0.format()),
+ ram_addr = format!("{ram_addr:#010X}"),
+ "texture descriptor updated"
+ );
+
+ self.draw_commands.textures[slot] = Some(draw::TextureDescriptor {
+ ram_addr,
+ width: width as u32,
+ height: height as u32,
+ format: image0.format(),
+ });
+ }
+
+ // PE finish
+ if idx == BP_PE_DONE && (val & BP_PE_DONE_FINISH_BIT) != 0 {
self.raise_interrupt = true;
}
}
diff --git a/crates/gekko/src/flipper/gx/constants.rs b/crates/gekko/src/flipper/gx/constants.rs
index 6f98cd4..6d1d5bc 100644
--- a/crates/gekko/src/flipper/gx/constants.rs
+++ b/crates/gekko/src/flipper/gx/constants.rs
@@ -33,3 +33,21 @@ pub const XF_MODELVIEW_BASE: usize = 0x0000;
pub const XF_MODELVIEW_END: usize = 0x000B;
pub const XF_PROJECTION_BASE: usize = 0x1020;
pub const XF_PROJECTION_END: usize = 0x1026;
+
+// 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
+pub const BP_TX_SETMODE1_I0: usize = 0x84; // TX_SETMODE1 maps 0-3
+pub const BP_TX_SETIMAGE0_I0: usize = 0x88; // TX_SETIMAGE0 maps 0-3 (width/height/format)
+pub const BP_TX_SETIMAGE1_I0: usize = 0x8C; // TX_SETIMAGE1 maps 0-3
+pub const BP_TX_SETIMAGE2_I0: usize = 0x90; // TX_SETIMAGE2 maps 0-3
+pub const BP_TX_SETIMAGE3_I0: usize = 0x94; // TX_SETIMAGE3 maps 0-3 (IMAGE_BASE = addr >> 5)
+pub const BP_TX_SETMODE0_I4: usize = 0xA0; // TX_SETMODE0 maps 4-7
+pub const BP_TX_SETMODE1_I4: usize = 0xA4; // TX_SETMODE1 maps 4-7
+pub const BP_TX_SETIMAGE0_I4: usize = 0xA8; // TX_SETIMAGE0 maps 4-7
+pub const BP_TX_SETIMAGE1_I4: usize = 0xAC; // TX_SETIMAGE1 maps 4-7
+pub const BP_TX_SETIMAGE2_I4: usize = 0xB0; // TX_SETIMAGE2 maps 4-7
+pub const BP_TX_SETIMAGE3_I4: usize = 0xB4; // TX_SETIMAGE3 maps 4-7 (IMAGE_BASE = addr >> 5)
+
+// BP PE (Pixel Engine) registers
+pub const BP_PE_DONE: usize = 0x45;
+pub const BP_PE_DONE_FINISH_BIT: u32 = 0x02;
diff --git a/crates/gekko/src/flipper/gx/draw.rs b/crates/gekko/src/flipper/gx/draw.rs
index c21412c..bc9c0c9 100644
--- a/crates/gekko/src/flipper/gx/draw.rs
+++ b/crates/gekko/src/flipper/gx/draw.rs
@@ -1,3 +1,5 @@
+use chapa::BitEnum;
+
#[derive(Debug)]
pub enum Primitive {
Quads,
@@ -33,6 +35,30 @@ impl Primitive {
pub struct Vertex {
pub position: [f32; 3],
pub color0: [f32; 4],
+ pub tex0: Option<[f32; 2]>,
+}
+
+#[derive(BitEnum, Debug, PartialEq, Eq, Hash)]
+pub enum TextureFormat {
+ I4 = 0x0,
+ I8 = 0x1,
+ IA4 = 0x2,
+ IA8 = 0x3,
+ RGB565 = 0x4,
+ RGB5A3 = 0x5,
+ RGBA8 = 0x6,
+ CI4 = 0x8,
+ CI8 = 0x9,
+ CI14 = 0xA,
+ CMPR = 0xE,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct TextureDescriptor {
+ pub ram_addr: usize,
+ pub width: u32,
+ pub height: u32,
+ pub format: TextureFormat,
}
pub struct DrawCall {
@@ -70,4 +96,5 @@ pub struct DrawCommands {
pub modelview: Matrix4,
pub projection: Matrix4,
pub commands: Vec<DrawCall>,
+ pub textures: [Option<TextureDescriptor>; 8],
}
diff --git a/crates/gekko/src/flipper/gx/regs.rs b/crates/gekko/src/flipper/gx/regs.rs
index 6266e8a..45e0852 100644
--- a/crates/gekko/src/flipper/gx/regs.rs
+++ b/crates/gekko/src/flipper/gx/regs.rs
@@ -1,5 +1,7 @@
use chapa::BitEnum;
+use crate::flipper::gx::draw::TextureFormat;
+
#[derive(Debug, PartialEq, BitEnum)]
pub enum TexCount {
S, // 1D coordinate
@@ -159,3 +161,30 @@ pub struct VcdLo {
#[bits(13..=14)]
pub color0: AttributeType,
}
+
+#[chapa::bitfield(u32, order = lsb0)]
+#[derive(Debug, Clone, Copy)]
+pub struct TxSetImage0 {
+ #[bits(0..=9)]
+ pub width: u16, // width - 1
+
+ #[bits(10..=19)]
+ pub height: u16, // height - 1
+
+ #[bits(20..=23)]
+ pub format: TextureFormat,
+}
+
+#[chapa::bitfield(u32, order = lsb0)]
+#[derive(Debug, Clone, Copy)]
+pub struct TxSetImage3 {
+ #[bits(0..=23)]
+ pub image_base: u32,
+}
+
+impl TxSetImage3 {
+ /// Physical RAM address (image_base << 5)
+ pub fn ram_addr(&self) -> usize {
+ self.image_base() as usize * 32
+ }
+}
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index d7285d3..f5be8d1 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -128,8 +128,13 @@ impl State {
});
let (texture, bind_group) = create_xfb_texture(&device, &bind_group_layout, w, h);
- let gx_renderer =
- backend_wgpu::GxRenderer::new(&device, surface_format, surface_config.width, surface_config.height);
+ let gx_renderer = backend_wgpu::GxRenderer::new(
+ &device,
+ &queue,
+ surface_format,
+ surface_config.width,
+ surface_config.height,
+ );
State {
surface,
@@ -182,6 +187,7 @@ impl State {
&self.device,
&self.queue,
&emulator.gx.draw_commands,
+ &emulator.mmio.ram,
view,
self.surface_config.width,
self.surface_config.height,