Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

dst alpha + cleaning up

Layle0543bd8ed124
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 0f49219..454c8ed 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -102,7 +102,7 @@ fn build_frame_uniform(
ztex_bias: draw.ztex_bias,
ztex_type: draw.ztex_type as u32,
ztex_op: draw.ztex_op as u32,
- _pad2: 0,
+ dst_alpha: draw.dst_alpha.unwrap_or(0) as u32,
zfreeze_plane: draw.zfreeze.map_or(Vec4::ZERO, |p| {
Vec4::new(p.dx / efb_scale as f32, p.dy / efb_scale as f32, p.c, 1.0)
}),
@@ -127,9 +127,42 @@ impl GxRenderer {
alpha_update: blend.alpha_update(),
cull_mode: self.current_cull_mode,
per_pixel_depth,
+ dst_alpha: blend.alpha_update() && self.current_draw_state.dst_alpha.is_some(),
+ alpha_pass: false,
}
}
+ fn ensure_pipeline(&mut self, device: &wgpu::Device, key: FullPipelineKey) {
+ if self.pipeline_cache.contains_key(&key) {
+ return;
+ }
+
+ let uber_key = UberPipelineKey::from(key);
+
+ if !self.uber_pipeline_cache.contains_key(&uber_key) {
+ #[cfg(feature = "gx-stats")]
+ let pipeline_started = std::time::Instant::now();
+ let module = &self.shader_cache[&key.shader];
+ let pipeline = crate::pipeline::create_uber_pipeline(
+ device,
+ &self.pipeline_layout,
+ self.surface_format,
+ module,
+ &uber_key,
+ );
+ self.uber_pipeline_cache.insert(uber_key, pipeline);
+ #[cfg(feature = "gx-stats")]
+ {
+ self.stats.pipelines_created.fetch_add(1, Ordering::Relaxed);
+ self.stats
+ .pipeline_create_cpu_ns
+ .fetch_add(pipeline_started.elapsed().as_nanos() as u64, Ordering::Relaxed);
+ }
+ }
+
+ self.request_specialized_pipeline(key);
+ }
+
/// Build a bind-group cache key from the current tracked textures.
fn current_bind_group_key(&self) -> BindGroupCacheKey {
BindGroupCacheKey {
@@ -448,31 +481,8 @@ impl GxRenderer {
fixed: pipeline_key,
};
- if !self.pipeline_cache.contains_key(&full_key) {
- let uber_key = UberPipelineKey::from(full_key);
-
- if !self.uber_pipeline_cache.contains_key(&uber_key) {
- #[cfg(feature = "gx-stats")]
- let pipeline_started = std::time::Instant::now();
- let module = &self.shader_cache[&shader_key];
- let pipeline = crate::pipeline::create_uber_pipeline(
- device,
- &self.pipeline_layout,
- self.surface_format,
- module,
- &uber_key,
- );
- self.uber_pipeline_cache.insert(uber_key, pipeline);
- #[cfg(feature = "gx-stats")]
- {
- self.stats.pipelines_created.fetch_add(1, Ordering::Relaxed);
- self.stats
- .pipeline_create_cpu_ns
- .fetch_add(pipeline_started.elapsed().as_nanos() as u64, Ordering::Relaxed);
- }
- }
-
- self.request_specialized_pipeline(full_key);
+ for key in std::iter::once(full_key).chain(full_key.alpha_pass_key()) {
+ self.ensure_pipeline(device, key);
}
let first_vertex = draw.base_vertex;
@@ -767,6 +777,8 @@ impl GxRenderer {
let frame_stride = self.frame_stride;
let num_draws = self.draw_bg_keys.len();
+ #[cfg(feature = "gx-stats")]
+ let mut draws_encoded = num_draws as u64;
for i in 0..num_draws {
let bg_key = &self.draw_bg_keys[i];
if self.bind_group_cache.contains_key(bg_key) {
@@ -967,10 +979,7 @@ impl GxRenderer {
rpass.push_debug_group(&draw_label);
}
let full_key = &self.draw_pipeline_keys[index];
- let pipeline = self
- .pipeline_cache
- .get(full_key)
- .unwrap_or_else(|| &self.uber_pipeline_cache[&UberPipelineKey::from(*full_key)]);
+ let pipeline = self.resolve_pipeline(full_key);
let pipeline_ptr = pipeline as *const wgpu::RenderPipeline;
if pipeline_ptr != last_pipeline_ptr {
rpass.set_pipeline(pipeline);
@@ -1123,10 +1132,35 @@ impl GxRenderer {
rpass.insert_debug_marker(&raster_marker);
}
- if index_count == 0 {
- rpass.draw(first_vertex..first_vertex + vertex_count, 0..1);
+ let draw_range = |rpass: &mut wgpu::RenderPass<'_>, start: u32, len: u32| {
+ if index_count == 0 {
+ rpass.draw(first_vertex + start..first_vertex + start + len, 0..1);
+ } else {
+ rpass.draw_indexed(first_index + start..first_index + start + len, first_vertex as i32, 0..1);
+ }
+ };
+ let count = if index_count == 0 { vertex_count } else { index_count };
+
+ if let Some(alpha_key) = full_key.alpha_pass_key() {
+ let alpha_pipeline = self.resolve_pipeline(&alpha_key);
+ let triangles = count / 3;
+ for triangle in 0..triangles {
+ if triangle > 0 {
+ rpass.set_pipeline(pipeline);
+ }
+ draw_range(&mut rpass, triangle * 3, 3);
+ rpass.set_pipeline(alpha_pipeline);
+ draw_range(&mut rpass, triangle * 3, 3);
+ }
+ last_pipeline_ptr = alpha_pipeline as *const wgpu::RenderPipeline;
+ #[cfg(feature = "gx-stats")]
+ {
+ let extra = (2 * u64::from(triangles)).saturating_sub(1);
+ pipeline_changes += extra;
+ draws_encoded += extra;
+ }
} else {
- rpass.draw_indexed(first_index..first_index + index_count, first_vertex as i32, 0..1);
+ draw_range(&mut rpass, 0, count);
}
#[cfg(feature = "renderdoc-capture")]
@@ -1142,7 +1176,7 @@ impl GxRenderer {
#[cfg(feature = "gx-stats")]
{
- self.stats.draws_encoded.fetch_add(num_draws as u64, Ordering::Relaxed);
+ self.stats.draws_encoded.fetch_add(draws_encoded, Ordering::Relaxed);
self.stats.draw_render_passes.fetch_add(1, Ordering::Relaxed);
self.stats
.pipeline_changes
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index ef6d673..1aac7eb 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -195,7 +195,7 @@ pub(crate) struct FrameUniforms {
pub ztex_bias: u32,
pub ztex_type: u32,
pub ztex_op: u32,
- pub _pad2: u32,
+ pub dst_alpha: u32,
pub zfreeze_plane: glam::Vec4,
}
@@ -1314,6 +1314,12 @@ impl GxRenderer {
#[cfg(target_arch = "wasm32")]
pub(crate) fn request_specialized_pipeline(&mut self, _key: FullPipelineKey) {}
+ pub(crate) fn resolve_pipeline(&self, key: &FullPipelineKey) -> &wgpu::RenderPipeline {
+ self.pipeline_cache
+ .get(key)
+ .unwrap_or_else(|| &self.uber_pipeline_cache[&UberPipelineKey::from(*key)])
+ }
+
pub(crate) fn invalidate_pipeline_caches(&mut self) {
self.pipeline_cache.clear();
self.uber_pipeline_cache.clear();
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
index 3fb6b82..fb90f35 100644
--- a/crates/backend-wgpu/src/pipeline.rs
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -64,10 +64,55 @@ pub(crate) struct PipelineKey {
/// Z-texturing or Z-freeze active: selects the `fs_main_depth` entry
/// point, which writes `frag_depth` (disabling early-Z only where needed).
pub per_pixel_depth: bool,
+ pub dst_alpha: bool,
+ pub alpha_pass: bool,
}
impl PipelineKey {
- const BYTES: usize = 13;
+ const BYTES: usize = 15;
+
+ fn color_blend(&self) -> Option<wgpu::BlendState> {
+ if self.blend_enable {
+ // In subtract mode the hardware ignores the configured src/dst
+ // factors and computes `dst = dst - src` with ONE/ONE.
+ let (src_factor, dst_factor, operation) = if self.subtract {
+ (
+ wgpu::BlendFactor::One,
+ wgpu::BlendFactor::One,
+ wgpu::BlendOperation::ReverseSubtract,
+ )
+ } else {
+ (
+ helpers::map_src_blend_factor(self.src_factor),
+ helpers::map_dst_blend_factor(self.dst_factor),
+ wgpu::BlendOperation::Add,
+ )
+ };
+ Some(make_blend_state(src_factor, dst_factor, operation))
+ } else if self.logic_op_enable {
+ let (be, sub, sf, df) = logic_op_approximation(self.logic_op);
+ be.then(|| {
+ let operation = if sub {
+ wgpu::BlendOperation::ReverseSubtract
+ } else {
+ wgpu::BlendOperation::Add
+ };
+ make_blend_state(sf, df, operation)
+ })
+ } else {
+ None
+ }
+ }
+
+ fn splits_dst_alpha(&self) -> bool {
+ use wgpu::BlendFactor::{OneMinusSrcAlpha, SrcAlpha, SrcAlphaSaturated};
+ self.dst_alpha
+ && self.color_blend().is_some_and(|b| {
+ [b.color.src_factor, b.color.dst_factor]
+ .iter()
+ .any(|f| matches!(f, SrcAlpha | OneMinusSrcAlpha | SrcAlphaSaturated))
+ })
+ }
fn to_bytes(self) -> [u8; Self::BYTES] {
[
@@ -84,6 +129,8 @@ impl PipelineKey {
self.alpha_update as u8,
self.cull_mode.raw(),
self.per_pixel_depth as u8,
+ self.dst_alpha as u8,
+ self.alpha_pass as u8,
]
}
@@ -102,6 +149,8 @@ impl PipelineKey {
alpha_update: b[10] != 0,
cull_mode: CullMode::from_raw(b[11]),
per_pixel_depth: b[12] != 0,
+ dst_alpha: b[13] != 0,
+ alpha_pass: b[14] != 0,
}
}
}
@@ -130,12 +179,22 @@ 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 = crate::shader_specialization::CACHE_VERSION;
+const PIPELINE_CACHE_VERSION: u32 = 10;
pub(crate) fn pipeline_cache_path() -> std::path::PathBuf {
gecko::paths::cache("pipeline_keys.bin")
}
impl FullPipelineKey {
+ pub(crate) fn alpha_pass_key(&self) -> Option<Self> {
+ self.fixed.splits_dst_alpha().then_some(Self {
+ fixed: PipelineKey {
+ alpha_pass: true,
+ ..self.fixed
+ },
+ ..*self
+ })
+ }
+
fn to_bytes(self) -> [u8; FULL_PIPELINE_KEY_BYTES] {
let mut out = [0u8; FULL_PIPELINE_KEY_BYTES];
out[..SHADER_KEY_BYTES].copy_from_slice(&self.shader.to_bytes());
@@ -309,41 +368,23 @@ fn create_pipeline(
attributes: &attrs,
};
- let blend = if key.blend_enable {
- // In subtract mode the hardware ignores the configured src/dst
- // factors and computes `dst = dst - src` with ONE/ONE.
- let (src_factor, dst_factor, operation) = if key.subtract {
- (
- wgpu::BlendFactor::One,
- wgpu::BlendFactor::One,
- wgpu::BlendOperation::ReverseSubtract,
- )
- } else {
- (
- helpers::map_src_blend_factor(key.src_factor),
- helpers::map_dst_blend_factor(key.dst_factor),
- wgpu::BlendOperation::Add,
- )
- };
- Some(make_blend_state(src_factor, dst_factor, operation))
- } else if key.logic_op_enable {
- let (be, sub, sf, df) = logic_op_approximation(key.logic_op);
- be.then(|| {
- let operation = if sub {
- wgpu::BlendOperation::ReverseSubtract
- } else {
- wgpu::BlendOperation::Add
- };
- make_blend_state(sf, df, operation)
+ let color_pass = key.splits_dst_alpha() && !key.alpha_pass;
+ let stored_alpha = key.dst_alpha && !color_pass;
+ let blend = if key.alpha_pass {
+ None
+ } else if stored_alpha {
+ key.color_blend().map(|blend| wgpu::BlendState {
+ alpha: wgpu::BlendComponent::REPLACE,
+ ..blend
})
} else {
- None
+ key.color_blend()
};
let depth_stencil = if key.z_enable {
Some(wgpu::DepthStencilState {
format: wgpu::TextureFormat::Depth24Plus,
- depth_write_enabled: Some(key.z_write),
+ depth_write_enabled: Some(key.z_write && !color_pass),
depth_compare: Some(helpers::map_depth_compare_func(key.z_func)),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
@@ -359,10 +400,10 @@ fn create_pipeline(
};
let mut write_mask = wgpu::ColorWrites::empty();
- if key.color_update {
+ if key.color_update && !key.alpha_pass {
write_mask |= wgpu::ColorWrites::RED | wgpu::ColorWrites::GREEN | wgpu::ColorWrites::BLUE;
}
- if key.alpha_update {
+ if key.alpha_update && !color_pass {
write_mask |= wgpu::ColorWrites::ALPHA;
}
@@ -380,10 +421,11 @@ fn create_pipeline(
},
fragment: Some(wgpu::FragmentState {
module: shader,
- entry_point: Some(if key.per_pixel_depth {
- "fs_main_depth"
- } else {
- "fs_main"
+ entry_point: Some(match (key.per_pixel_depth, stored_alpha) {
+ (false, false) => "fs_main",
+ (true, false) => "fs_main_depth",
+ (false, true) => "fs_main_alpha",
+ (true, true) => "fs_main_depth_alpha",
}),
targets: &[Some(wgpu::ColorTargetState {
format: surface_format,
diff --git a/crates/backend-wgpu/src/shader_specialization.rs b/crates/backend-wgpu/src/shader_specialization.rs
index 46e1e02..2b2a597 100644
--- a/crates/backend-wgpu/src/shader_specialization.rs
+++ b/crates/backend-wgpu/src/shader_specialization.rs
@@ -16,7 +16,7 @@ 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";
-pub(crate) const CACHE_VERSION: u32 = 9;
+const CACHE_VERSION: u32 = 9;
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 3cb4087..0945d20 100644
--- a/crates/backend-wgpu/src/shaders/common.wesl
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -40,7 +40,7 @@ struct FrameUniforms {
ztex_bias: u32,
ztex_type: u32,
ztex_op: u32,
- _pad2: u32,
+ dst_alpha: u32,
zfreeze_plane: vec4<f32>,
};
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
index f55b436..ffcd83d 100644
--- a/crates/backend-wgpu/src/shaders/main.wesl
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -329,8 +329,7 @@ struct FsOutDepth {
@builtin(frag_depth) depth: f32,
}
-@fragment
-fn fs_main_depth(in: VsOut) -> FsOutDepth {
+fn shade_depth(in: VsOut) -> FsOutDepth {
let r = run_tev(in);
var depth = in.clip_pos.z;
var z24 = round((1.0 - depth) * 16777215.0);
@@ -362,3 +361,25 @@ fn fs_main_depth(in: VsOut) -> FsOutDepth {
out_.depth = depth;
return out_;
}
+
+@fragment
+fn fs_main_depth(in: VsOut) -> FsOutDepth {
+ return shade_depth(in);
+}
+
+fn stored_alpha() -> f32 {
+ return f32(frame.dst_alpha >> 2u) / 63.0;
+}
+
+@fragment
+fn fs_main_alpha(in: VsOut) -> @location(0) vec4<f32> {
+ let r = run_tev(in);
+ return vec4<f32>(r.color.rgb, stored_alpha());
+}
+
+@fragment
+fn fs_main_depth_alpha(in: VsOut) -> FsOutDepth {
+ var r = shade_depth(in);
+ r.color.a = stored_alpha();
+ return r;
+}
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index ac4f574..2d220c5 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -108,6 +108,7 @@ impl GraphicsProcessor {
self.cur_blend_mode = BlendMode::from_raw(val);
renderer.exec(GxAction::SetBlendMode(self.cur_blend_mode));
}
+ BP_PE_CMODE1 => self.frame_state_dirty = true,
BP_PE_ZCOMPARE => {
self.cur_pe_control = PeControl::from_raw(val);
// early_ztest feeds DrawData::ztex_op
diff --git a/crates/gecko/src/flipper/gx/constants.rs b/crates/gecko/src/flipper/gx/constants.rs
index 3987b40..07eacef 100644
--- a/crates/gecko/src/flipper/gx/constants.rs
+++ b/crates/gecko/src/flipper/gx/constants.rs
@@ -121,6 +121,7 @@ pub const TLUT_MEM_ENTRIES: usize = 1024 * TLUT_ENTRIES_PER_UNIT;
// BP PE (Pixel Engine) registers
pub const BP_PE_ZMODE: usize = 0x40;
pub const BP_PE_CMODE0: usize = 0x41; // blend mode
+pub const BP_PE_CMODE1: usize = 0x42; // destination alpha
pub const BP_PE_ZCOMPARE: usize = 0x43;
pub const BP_PE_ALPHA_COMPARE: usize = 0xF3;
pub const BP_TEV_ZTEX1: usize = 0xF4; // Z-texture bias (24-bit)
diff --git a/crates/gecko/src/flipper/gx/regs.rs b/crates/gecko/src/flipper/gx/regs.rs
index 7a88907..cb9cbc8 100644
--- a/crates/gecko/src/flipper/gx/regs.rs
+++ b/crates/gecko/src/flipper/gx/regs.rs
@@ -102,6 +102,15 @@ pub struct BlendMode {
pub logic_op: LogicOp,
}
+#[chapa::bitfield(u32, order = lsb0)]
+#[derive(Debug, Clone, Copy, Default)]
+pub struct DstAlpha {
+ #[bits(0..=7)]
+ pub alpha: u8,
+ #[bits(8)]
+ pub enable: bool,
+}
+
#[derive(Debug, PartialEq, BitEnum, Hash, Eq)]
pub enum PixelFormat {
Rgb8Z24 = 0,
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index 5fa23bf..c77206a 100644
--- a/crates/gecko/src/flipper/gx/vertex.rs
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -250,7 +250,10 @@ impl GraphicsProcessor {
let ztex2 = TevZtex2::from_raw(self.bp_regs[BP_TEV_ZTEX2]);
+ let dst_alpha = DstAlpha::from_raw(self.bp_regs[BP_PE_CMODE1]);
DrawState {
+ dst_alpha: (dst_alpha.enable() && self.cur_pe_control.pixel_format().has_alpha())
+ .then_some(dst_alpha.alpha()),
zfreeze: zfreeze.then_some(self.zfreeze_plane),
tev_color_env: std::array::from_fn(|i| self.cur_tev_color_env[i].raw()),
tev_alpha_env: std::array::from_fn(|i| self.cur_tev_alpha_env[i].raw()),
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index 431ca1e..eb7173d 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -181,6 +181,7 @@ pub struct DrawData {
#[derive(Debug, Clone, Default)]
pub struct DrawState {
+ pub dst_alpha: Option<u8>,
pub active_texcoords: u8,
pub zfreeze: Option<crate::flipper::gx::depth::DepthPlane>,
// TEV combiner state