Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

basic shader spec

Layled9c7a8e21552
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 57ddc0c..ee4eb94 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,4 +1,5 @@
-use crate::pipeline::PipelineKey;
+use crate::pipeline::{FullPipelineKey, PipelineKey};
+use crate::shader_specialization::{self, ShaderKey};
use crate::{
BindGroupCacheKey, DRAW_UNIFORMS_SIZE, DrawUniforms, FRAME_UNIFORMS_SIZE, FrameUniforms, GpuVertex, GxRenderer,
SamplerKey, helpers,
@@ -163,11 +164,22 @@ impl GxRenderer {
}
GxAction::Draw(draw) => {
- // Ensure pipeline for current tracked blend/depth state.
+ let shader_key = ShaderKey::from_draw(draw, self.current_alpha_compare);
+ if !self.shader_cache.contains_key(&shader_key) {
+ let wgsl = shader_specialization::compile_variant(shader_key);
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some(&format!("gx_shader_{shader_key:?}")),
+ source: wgpu::ShaderSource::Wgsl(wgsl.into()),
+ });
+ self.shader_cache.insert(shader_key, module);
+ tracing::info!(?shader_key, "compiled specialized shader variant");
+ }
let pipeline_key = self.current_pipeline_key();
- if !self.pipeline_cache.contains_key(&pipeline_key) {
- let pipeline = self.create_pipeline(device, &pipeline_key);
- self.pipeline_cache.insert(pipeline_key, pipeline);
+ let full_key = FullPipelineKey { shader: shader_key, fixed: pipeline_key };
+ if !self.pipeline_cache.contains_key(&full_key) {
+ let module = &self.shader_cache[&shader_key];
+ let pipeline = self.create_pipeline(device, module, &pipeline_key);
+ self.pipeline_cache.insert(full_key, pipeline);
}
// Triangulate.
@@ -241,7 +253,7 @@ impl GxRenderer {
};
// Snapshot tracked state for this draw.
- self.draw_pipeline_keys.push(pipeline_key);
+ self.draw_pipeline_keys.push(full_key);
self.draw_bg_keys.push(self.current_bind_group_key());
self.draw_viewports.push(self.current_viewport);
self.draw_scissors.push(self.current_scissor);
@@ -543,18 +555,19 @@ impl GxRenderer {
);
rpass.push_debug_group(&draw_label);
}
- let pipeline_key = &self.draw_pipeline_keys[index];
- let pipeline = &self.pipeline_cache[pipeline_key];
+ let full_key = &self.draw_pipeline_keys[index];
+ let pipeline = &self.pipeline_cache[full_key];
rpass.set_pipeline(pipeline);
#[cfg(feature = "renderdoc-capture")]
{
let pipeline_marker = format!(
- "Pipeline: blend={} z={} z_write={} color_update={} alpha_update={}",
- pipeline_key.blend_enable,
- pipeline_key.z_enable,
- pipeline_key.z_write,
- pipeline_key.color_update,
- pipeline_key.alpha_update
+ "Pipeline: blend={} z={} z_write={} color_update={} alpha_update={} shader={:?}",
+ full_key.fixed.blend_enable,
+ full_key.fixed.z_enable,
+ full_key.fixed.z_write,
+ full_key.fixed.color_update,
+ full_key.fixed.alpha_update,
+ full_key.shader,
);
rpass.insert_debug_marker(&pipeline_marker);
}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 9b96c96..a024389 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -8,6 +8,7 @@ mod pipeline;
mod render;
#[cfg(feature = "renderdoc-capture")]
mod renderdoc_capture;
+mod shader_specialization;
pub mod sink;
use gecko::common::Address;
@@ -19,8 +20,9 @@ use gecko::flipper::gx::regs::{AlphaCompare, BlendMode, CompareFunc, CullMode, M
use gecko::host::EfbWriteback;
use gecko::host::TextureKey;
use glam::Mat4;
-use pipeline::PipelineKey;
+use pipeline::FullPipelineKey;
use rustc_hash::FxHashMap;
+use shader_specialization::ShaderKey;
use std::num::NonZeroU64;
#[repr(C)]
@@ -114,15 +116,13 @@ pub(crate) const DRAW_UNIFORMS_SIZE: NonZeroU64 = match NonZeroU64::new(std::mem
None => panic!("DrawUniforms must be non-zero sized"),
};
-const SHADER: &str = wesl::include_wesl!("gx_shader");
-
pub const EFB_WIDTH: u32 = 640;
pub const EFB_HEIGHT: u32 = 528;
pub const EFB_SAMPLE_COUNT: u32 = 4;
pub struct GxRenderer {
- pub(crate) pipeline_cache: FxHashMap<PipelineKey, wgpu::RenderPipeline>,
- pub(crate) shader: wgpu::ShaderModule,
+ pub(crate) pipeline_cache: FxHashMap<FullPipelineKey, wgpu::RenderPipeline>,
+ pub(crate) shader_cache: FxHashMap<ShaderKey, wgpu::ShaderModule>,
pub(crate) pipeline_layout: wgpu::PipelineLayout,
pub(crate) surface_format: wgpu::TextureFormat,
pub(crate) bind_group_layout: wgpu::BindGroupLayout,
@@ -163,7 +163,7 @@ pub struct GxRenderer {
// Per-frame draw accumulation (persists across process_action calls,
// flushed by flush_pending_draws).
pub(crate) frame_uniform_bytes: Vec<u8>,
- pub(crate) draw_pipeline_keys: Vec<PipelineKey>,
+ pub(crate) draw_pipeline_keys: Vec<FullPipelineKey>,
pub(crate) draw_bg_keys: Vec<BindGroupCacheKey>,
pub(crate) draw_viewports: Vec<Viewport>,
pub(crate) draw_scissors: Vec<Scissor>,
@@ -221,10 +221,6 @@ impl GxRenderer {
device.limits().min_uniform_buffer_offset_alignment as u64,
);
- let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- 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()),
@@ -623,7 +619,7 @@ impl GxRenderer {
GxRenderer {
pipeline_cache: FxHashMap::default(),
- shader,
+ shader_cache: FxHashMap::default(),
pipeline_layout,
surface_format,
bind_group_layout,
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
index 83169d8..1ae5d0b 100644
--- a/crates/backend-wgpu/src/pipeline.rs
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -1,3 +1,4 @@
+use crate::shader_specialization::ShaderKey;
use crate::{GpuVertex, GxRenderer, helpers};
use gecko::flipper::gx::regs::{BlendFactor, CompareFunc, CullMode};
@@ -15,8 +16,19 @@ pub(crate) struct PipelineKey {
pub cull_mode: CullMode,
}
+#[derive(Clone, Copy, Hash, PartialEq, Eq)]
+pub(crate) struct FullPipelineKey {
+ pub shader: ShaderKey,
+ pub fixed: PipelineKey,
+}
+
impl GxRenderer {
- pub(crate) fn create_pipeline(&self, device: &wgpu::Device, key: &PipelineKey) -> wgpu::RenderPipeline {
+ pub(crate) fn create_pipeline(
+ &self,
+ device: &wgpu::Device,
+ shader: &wgpu::ShaderModule,
+ key: &PipelineKey,
+ ) -> wgpu::RenderPipeline {
let vertex_layout = wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<GpuVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
@@ -147,13 +159,13 @@ impl GxRenderer {
label: Some("gx_pipeline"),
layout: Some(&self.pipeline_layout),
vertex: wgpu::VertexState {
- module: &self.shader,
+ module: shader,
entry_point: Some("vs_main"),
buffers: &[vertex_layout],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
- module: &self.shader,
+ module: shader,
entry_point: Some("fs_main"),
targets: &[Some(wgpu::ColorTargetState {
format: self.surface_format,
diff --git a/crates/backend-wgpu/src/shader_specialization.rs b/crates/backend-wgpu/src/shader_specialization.rs
new file mode 100644
index 0000000..51015f6
--- /dev/null
+++ b/crates/backend-wgpu/src/shader_specialization.rs
@@ -0,0 +1,71 @@
+use gecko::flipper::gx::regs::{AlphaCompare, AlphaOp, CompareFunc};
+use gecko::host::DrawData;
+use wesl::{VirtualResolver, Wesl};
+
+const COMMON_WESL: &str = include_str!("shaders/common.wesl");
+const TEV_HELPERS_WESL: &str = include_str!("shaders/tev_helpers.wesl");
+const TEV_COMBINERS_WESL: &str = include_str!("shaders/tev_combiners.wesl");
+const TEV_INDIRECT_WESL: &str = include_str!("shaders/tev_indirect.wesl");
+const ALPHA_TEST_WESL: &str = include_str!("shaders/alpha_test.wesl");
+const LIGHTING_WESL: &str = include_str!("shaders/lighting.wesl");
+const MAIN_WESL: &str = include_str!("shaders/main.wesl");
+
+#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
+pub(crate) struct ShaderKey {
+ pub num_tev_stages: u8,
+ pub num_indirect_stages: u8,
+ pub has_lighting: bool,
+ pub alpha_test_enabled: bool,
+}
+
+impl ShaderKey {
+ pub(crate) fn from_draw(draw: &DrawData, alpha_cmp: AlphaCompare) -> Self {
+ let num_tev_stages = draw.num_tev_stages.clamp(1, 16);
+ let num_indirect_stages = draw.num_indirect_stages.min(4);
+ let has_lighting = draw.color_ctrl[0].enable()
+ || draw.alpha_ctrl[0].enable()
+ || draw.color_ctrl[1].enable()
+ || draw.alpha_ctrl[1].enable();
+ let comp0 = alpha_cmp.comp0();
+ let comp1 = alpha_cmp.comp1();
+ let op = alpha_cmp.op();
+ let always_pass = comp0 == CompareFunc::Always
+ && comp1 == CompareFunc::Always
+ && matches!(op, AlphaOp::And | AlphaOp::Or);
+ Self {
+ num_tev_stages,
+ num_indirect_stages,
+ has_lighting,
+ alpha_test_enabled: !always_pass,
+ }
+ }
+}
+
+fn make_resolver() -> VirtualResolver<'static> {
+ let mut r = VirtualResolver::new();
+ r.add_module("package::common".parse().unwrap(), COMMON_WESL.into());
+ r.add_module("package::tev_helpers".parse().unwrap(), TEV_HELPERS_WESL.into());
+ r.add_module("package::tev_combiners".parse().unwrap(), TEV_COMBINERS_WESL.into());
+ r.add_module("package::tev_indirect".parse().unwrap(), TEV_INDIRECT_WESL.into());
+ r.add_module("package::alpha_test".parse().unwrap(), ALPHA_TEST_WESL.into());
+ r.add_module("package::lighting".parse().unwrap(), LIGHTING_WESL.into());
+ r.add_module("package::main".parse().unwrap(), MAIN_WESL.into());
+ r
+}
+
+pub(crate) fn compile_variant(key: ShaderKey) -> String {
+ let mut compiler = Wesl::new("").set_custom_resolver(make_resolver());
+ for i in 1..=16u8 {
+ compiler.set_feature(&format!("TEV_STAGE_{i}_ENABLED"), i <= key.num_tev_stages);
+ }
+ for i in 0..4u8 {
+ compiler.set_feature(&format!("IND_STAGE_{i}_ENABLED"), i < key.num_indirect_stages);
+ }
+ compiler.set_feature("HAS_LIGHTING", key.has_lighting);
+ compiler.set_feature("ALPHA_TEST_ENABLED", key.alpha_test_enabled);
+ let entry = "package::main".parse().expect("valid module path");
+ compiler
+ .compile(&entry)
+ .expect("WESL specialization failed")
+ .to_string()
+}
diff --git a/crates/backend-wgpu/src/shaders/lighting.wesl b/crates/backend-wgpu/src/shaders/lighting.wesl
index a19b046..55ddc13 100644
--- a/crates/backend-wgpu/src/shaders/lighting.wesl
+++ b/crates/backend-wgpu/src/shaders/lighting.wesl
@@ -106,51 +106,54 @@ fn compute_channel_lighting(
amb_a = ambient.a;
}
- let color_lit_off = extract_bits(color_ctrl, 1u, 1u) == 0u;
- let alpha_lit_off = extract_bits(alpha_ctrl, 1u, 1u) == 0u;
-
- // When lighting disabled, return material directly
- if color_lit_off && alpha_lit_off {
+ @if(!HAS_LIGHTING) {
return vec4(mat_rgb, mat_a);
}
- // RGB lighting accumulator
- var rgb_out = mat_rgb;
- if !color_lit_off {
- let mask_lo = extract_bits(color_ctrl, 2u, 4u);
- let mask_hi = extract_bits(color_ctrl, 11u, 4u);
- let light_mask = mask_lo | (mask_hi << 4u);
-
- var acc = amb_rgb;
- for (var i = 0u; i < 8u; i++) {
- if ((light_mask >> i) & 1u) == 0u {
- continue;
+ @if(HAS_LIGHTING) {
+ let color_lit_off = extract_bits(color_ctrl, 1u, 1u) == 0u;
+ let alpha_lit_off = extract_bits(alpha_ctrl, 1u, 1u) == 0u;
+
+ if color_lit_off && alpha_lit_off {
+ return vec4(mat_rgb, mat_a);
+ }
+
+ var rgb_out = mat_rgb;
+ if !color_lit_off {
+ let mask_lo = extract_bits(color_ctrl, 2u, 4u);
+ let mask_hi = extract_bits(color_ctrl, 11u, 4u);
+ let light_mask = mask_lo | (mask_hi << 4u);
+
+ var acc = amb_rgb;
+ for (var i = 0u; i < 8u; i++) {
+ if ((light_mask >> i) & 1u) == 0u {
+ continue;
+ }
+ let lc = frame.light_colors[i];
+ let factor = compute_light_factor(color_ctrl, i, normal, pos);
+ acc += lc.rgb * factor;
}
- let lc = frame.light_colors[i];
- let factor = compute_light_factor(color_ctrl, i, normal, pos);
- acc += lc.rgb * factor;
+ rgb_out = mat_rgb * clamp(acc, vec3(0.0), vec3(1.0));
}
- rgb_out = mat_rgb * clamp(acc, vec3(0.0), vec3(1.0));
- }
- // Alpha lighting accumulator
- var a_out = mat_a;
- if !alpha_lit_off {
- let mask_lo = extract_bits(alpha_ctrl, 2u, 4u);
- let mask_hi = extract_bits(alpha_ctrl, 11u, 4u);
- let light_mask = mask_lo | (mask_hi << 4u);
-
- var acc_a = amb_a;
- for (var i = 0u; i < 8u; i++) {
- if ((light_mask >> i) & 1u) == 0u {
- continue;
+ var a_out = mat_a;
+ if !alpha_lit_off {
+ let mask_lo = extract_bits(alpha_ctrl, 2u, 4u);
+ let mask_hi = extract_bits(alpha_ctrl, 11u, 4u);
+ let light_mask = mask_lo | (mask_hi << 4u);
+
+ var acc_a = amb_a;
+ for (var i = 0u; i < 8u; i++) {
+ if ((light_mask >> i) & 1u) == 0u {
+ continue;
+ }
+ let lc = frame.light_colors[i];
+ let factor = compute_light_factor(alpha_ctrl, i, normal, pos);
+ acc_a += lc.a * factor;
}
- let lc = frame.light_colors[i];
- let factor = compute_light_factor(alpha_ctrl, i, normal, pos);
- acc_a += lc.a * factor;
+ a_out = mat_a * clamp(acc_a, 0.0, 1.0);
}
- a_out = mat_a * clamp(acc_a, 0.0, 1.0);
- }
- return vec4(rgb_out, a_out);
+ return vec4(rgb_out, a_out);
+ }
}
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
index d7e7a18..4db79f2 100644
--- a/crates/backend-wgpu/src/shaders/main.wesl
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -9,7 +9,6 @@ import super::lighting::compute_channel_lighting;
fn vs_main(in: VsIn) -> VsOut {
var out: VsOut;
out.clip_pos = draw.mvp * vec4<f32>(in.pos_view, 1.0);
- // Remap depth: GameCube z is [-1,0], wgpu uses [0,1]
out.clip_pos.z = out.clip_pos.z + out.clip_pos.w;
out.color = compute_channel_lighting(
frame.color_ctrl0, frame.alpha_ctrl0,
@@ -32,133 +31,137 @@ fn vs_main(in: VsIn) -> VsOut {
return out;
}
-@fragment
-fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- // Initialize TEV registers from uniforms
- var regs: array<vec4<f32>, 4>;
- regs[0] = frame.tev_color_reg0;
- regs[1] = frame.tev_color_reg1;
- regs[2] = frame.tev_color_reg2;
- regs[3] = frame.tev_color_reg3;
+struct TevState {
+ regs: array<vec4<f32>, 4>,
+ running_uv: vec2<f32>,
+ last_color_dest: u32,
+ last_alpha_dest: u32,
+}
- let color0 = in.color;
- let num_stages = frame.num_tev_stages;
+fn run_stage(
+ stage: u32,
+ in: VsOut,
+ color0: vec4<f32>,
+ presampled: IndirectSamples,
+ state: ptr<function, TevState>,
+) {
+ let order = read_packed(frame.tev_orders, stage);
+ let texmap_idx = order & 7u;
+ let texcoord_idx = (order >> 3u) & 7u;
+ let tex_enabled = ((order >> 6u) & 1u) != 0u;
+ let ras_channel = (order >> 7u) & 7u;
+ let aenv = read_packed(frame.tev_alpha_env, stage);
+
+ let stq = select_texcoord(in, texcoord_idx);
+ let direct_uv = stq_to_uv(stq);
+ let direct_size = texmap_size(texmap_idx);
+ let indirect = apply_indirect(stage, direct_uv, direct_size, presampled, (*state).running_uv);
+ (*state).running_uv = indirect.uv;
+
+ var ras_color: vec4<f32>;
+ switch ras_channel {
+ case 0u: { ras_color = color0; }
+ case 1u: { ras_color = in.color1; }
+ case 2u: { ras_color = vec4(color0.a, color0.a, color0.a, color0.a); }
+ case 3u: { ras_color = vec4(in.color1.a, in.color1.a, in.color1.a, in.color1.a); }
+ case 4u: { ras_color = color0; }
+ case 5u: { ras_color = in.color1; }
+ case 6u: { ras_color = vec4(0.0, 0.0, 0.0, 0.0); }
+ default: { ras_color = vec4(indirect.bump_alpha); }
+ }
- var last_color_dest = 0u;
- var last_alpha_dest = 0u;
+ var tex_color: vec4<f32>;
+ if tex_enabled {
+ tex_color = sample_texmap(texmap_idx, indirect.uv);
+ } else {
+ tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+ }
- let presampled = sample_indirect_textures(in);
- var running_uv = vec2<f32>(0.0, 0.0);
+ ras_color = swizzle_tev_color(extract_bits(aenv, 0u, 2u), ras_color);
+ tex_color = swizzle_tev_color(extract_bits(aenv, 2u, 2u), tex_color);
+
+ let cenv = read_packed(frame.tev_color_env, stage);
+ let c_d = extract_bits(cenv, 0u, 4u);
+ let c_c = extract_bits(cenv, 4u, 4u);
+ let c_b = extract_bits(cenv, 8u, 4u);
+ let c_a = extract_bits(cenv, 12u, 4u);
+ let c_bias = extract_bits(cenv, 16u, 2u);
+ let c_sub = extract_bits(cenv, 18u, 1u) != 0u;
+ let c_clamp = extract_bits(cenv, 19u, 1u) != 0u;
+ let c_scale = extract_bits(cenv, 20u, 2u);
+ let c_dest = extract_bits(cenv, 22u, 2u);
+
+ let konst_color = frame.tev_konst_colors[stage];
+
+ let in_a = tev_color_in(c_a, tex_color, ras_color, (*state).regs, konst_color);
+ let in_b = tev_color_in(c_b, tex_color, ras_color, (*state).regs, konst_color);
+ let in_c = tev_color_in(c_c, tex_color, ras_color, (*state).regs, konst_color);
+ let in_d = tev_color_in(c_d, tex_color, ras_color, (*state).regs, konst_color);
+
+ let color_result = tev_combine_color(in_a, in_b, in_c, in_d, c_bias, c_sub, c_scale, c_clamp);
+ (*state).regs[c_dest] = vec4(color_result, (*state).regs[c_dest].a);
+
+ let a_d = extract_bits(aenv, 4u, 3u);
+ let a_c = extract_bits(aenv, 7u, 3u);
+ let a_b = extract_bits(aenv, 10u, 3u);
+ let a_a = extract_bits(aenv, 13u, 3u);
+ let a_bias = extract_bits(aenv, 16u, 2u);
+ let a_sub = extract_bits(aenv, 18u, 1u) != 0u;
+ let a_clamp = extract_bits(aenv, 19u, 1u) != 0u;
+ let a_scale = extract_bits(aenv, 20u, 2u);
+ let a_dest = extract_bits(aenv, 22u, 2u);
+
+ let ain_a = tev_alpha_in(a_a, tex_color, ras_color, (*state).regs, konst_color);
+ let ain_b = tev_alpha_in(a_b, tex_color, ras_color, (*state).regs, konst_color);
+ let ain_c = tev_alpha_in(a_c, tex_color, ras_color, (*state).regs, konst_color);
+ let ain_d = tev_alpha_in(a_d, tex_color, ras_color, (*state).regs, konst_color);
+
+ let alpha_result = tev_combine_alpha(ain_a, ain_b, ain_c, ain_d, in_a, in_b, a_bias, a_sub, a_scale, a_clamp);
+ (*state).regs[a_dest] = vec4((*state).regs[a_dest].rgb, alpha_result);
+
+ (*state).last_color_dest = c_dest;
+ (*state).last_alpha_dest = a_dest;
+}
- for (var stage = 0u; stage < 16u; stage++) {
- if stage >= num_stages {
- break;
- }
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ var state: TevState;
+ state.regs[0] = frame.tev_color_reg0;
+ state.regs[1] = frame.tev_color_reg1;
+ state.regs[2] = frame.tev_color_reg2;
+ state.regs[3] = frame.tev_color_reg3;
+ state.running_uv = vec2<f32>(0.0, 0.0);
+ state.last_color_dest = 0u;
+ state.last_alpha_dest = 0u;
- // Resolve per-stage texture from TevOrder
- // TevStageOrder bit layout: texmap(0-2), texcoord(3-5), tex_enable(6), channel(7-9)
- let order = read_packed(frame.tev_orders, stage);
- let texmap_idx = order & 7u;
- let texcoord_idx = (order >> 3u) & 7u;
- let tex_enabled = ((order >> 6u) & 1u) != 0u;
- let ras_channel = (order >> 7u) & 7u;
- let aenv = read_packed(frame.tev_alpha_env, stage);
-
- // Run the stage's indirect pipeline first. It yields the final
- // direct-texmap UV, the fixpoint chaining value, and any bump
- // alpha produced. When the stage doesn't use indirect this
- // returns the raw direct UV and zero bump alpha.
- let stq = select_texcoord(in, texcoord_idx);
- let direct_uv = stq_to_uv(stq);
- let direct_size = texmap_size(texmap_idx);
- let indirect = apply_indirect(stage, direct_uv, direct_size, presampled, running_uv);
- running_uv = indirect.uv;
-
- // Select raster color based on channel:
- // 0=Color0, 1=Color1, 2=Alpha0, 3=Alpha1, 4=Color0A0, 5=Color1A1, 6=Zero, 7=Bump
- var ras_color: vec4<f32>;
- switch ras_channel {
- case 0u: { ras_color = color0; } // Color0
- case 1u: { ras_color = in.color1; } // Color1
- case 2u: { ras_color = vec4(color0.a, color0.a, color0.a, color0.a); } // Alpha0
- case 3u: { ras_color = vec4(in.color1.a, in.color1.a, in.color1.a, in.color1.a); } // Alpha1
- case 4u: { ras_color = color0; } // Color0A0
- case 5u: { ras_color = in.color1; } // Color1A1
- case 6u: { ras_color = vec4(0.0, 0.0, 0.0, 0.0); } // Zero
- default: { ras_color = vec4(indirect.bump_alpha); } // Bump
- }
+ let color0 = in.color;
+ let presampled = sample_indirect_textures(in);
- var tex_color: vec4<f32>;
- if tex_enabled {
- tex_color = sample_texmap(texmap_idx, indirect.uv);
- } else {
- tex_color = vec4<f32>(1.0, 1.0, 1.0, 1.0);
+ @if(TEV_STAGE_1_ENABLED) { run_stage( 0u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_2_ENABLED) { run_stage( 1u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_3_ENABLED) { run_stage( 2u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_4_ENABLED) { run_stage( 3u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_5_ENABLED) { run_stage( 4u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_6_ENABLED) { run_stage( 5u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_7_ENABLED) { run_stage( 6u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_8_ENABLED) { run_stage( 7u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_9_ENABLED) { run_stage( 8u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_10_ENABLED) { run_stage( 9u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_11_ENABLED) { run_stage(10u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_12_ENABLED) { run_stage(11u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_13_ENABLED) { run_stage(12u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_14_ENABLED) { run_stage(13u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_15_ENABLED) { run_stage(14u, in, color0, presampled, &state); }
+ @if(TEV_STAGE_16_ENABLED) { run_stage(15u, in, color0, presampled, &state); }
+
+ let color = vec4<f32>(state.regs[state.last_color_dest].rgb, state.regs[state.last_alpha_dest].a);
+
+ @if(ALPHA_TEST_ENABLED) {
+ let c0 = alpha_compare(color.a, frame.alpha_ref0, frame.alpha_comp0);
+ let c1 = alpha_compare(color.a, frame.alpha_ref1, frame.alpha_comp1);
+ if !alpha_combine(c0, c1, frame.alpha_op) {
+ discard;
}
-
- ras_color = swizzle_tev_color(extract_bits(aenv, 0u, 2u), ras_color);
- tex_color = swizzle_tev_color(extract_bits(aenv, 2u, 2u), tex_color);
-
- // Combine colors
- let cenv = read_packed(frame.tev_color_env, stage);
-
- // TevColorEnv bit layout (LSB0):
- // [3:0]=d [7:4]=c [11:8]=b [15:12]=a
- // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
- let c_d = extract_bits(cenv, 0u, 4u);
- let c_c = extract_bits(cenv, 4u, 4u);
- let c_b = extract_bits(cenv, 8u, 4u);
- let c_a = extract_bits(cenv, 12u, 4u);
- let c_bias = extract_bits(cenv, 16u, 2u);
- let c_sub = extract_bits(cenv, 18u, 1u) != 0u;
- let c_clamp = extract_bits(cenv, 19u, 1u) != 0u;
- let c_scale = extract_bits(cenv, 20u, 2u);
- let c_dest = extract_bits(cenv, 22u, 2u);
-
- let konst_color = frame.tev_konst_colors[stage];
-
- let in_a = tev_color_in(c_a, tex_color, ras_color, regs, konst_color);
- let in_b = tev_color_in(c_b, tex_color, ras_color, regs, konst_color);
- let in_c = tev_color_in(c_c, tex_color, ras_color, regs, konst_color);
- let in_d = tev_color_in(c_d, tex_color, ras_color, regs, konst_color);
-
- let color_result = tev_combine_color(in_a, in_b, in_c, in_d, c_bias, c_sub, c_scale, c_clamp);
- // Write RGB to dest, preserve alpha
- regs[c_dest] = vec4(color_result, regs[c_dest].a);
-
- // TevAlphaEnv bit layout (LSB0):
- // [6:4]=d [9:7]=c [12:10]=b [15:13]=a
- // [17:16]=bias [18]=sub [19]=clamp [21:20]=scale [23:22]=dest
- let a_d = extract_bits(aenv, 4u, 3u);
- let a_c = extract_bits(aenv, 7u, 3u);
- let a_b = extract_bits(aenv, 10u, 3u);
- let a_a = extract_bits(aenv, 13u, 3u);
- let a_bias = extract_bits(aenv, 16u, 2u);
- let a_sub = extract_bits(aenv, 18u, 1u) != 0u;
- let a_clamp = extract_bits(aenv, 19u, 1u) != 0u;
- let a_scale = extract_bits(aenv, 20u, 2u);
- let a_dest = extract_bits(aenv, 22u, 2u);
-
- let ain_a = tev_alpha_in(a_a, tex_color, ras_color, regs, konst_color);
- let ain_b = tev_alpha_in(a_b, tex_color, ras_color, regs, konst_color);
- let ain_c = tev_alpha_in(a_c, tex_color, ras_color, regs, konst_color);
- let ain_d = tev_alpha_in(a_d, tex_color, ras_color, regs, konst_color);
-
- let alpha_result = tev_combine_alpha(ain_a, ain_b, ain_c, ain_d, in_a, in_b, a_bias, a_sub, a_scale, a_clamp);
-
- // Write alpha to dest, preserve RGB
- regs[a_dest] = vec4(regs[a_dest].rgb, alpha_result);
-
- last_color_dest = c_dest;
- last_alpha_dest = a_dest;
- }
-
- // Output from the dest registers of the last active TEV stage (not always TEVPREV)
- let color = vec4<f32>(regs[last_color_dest].rgb, regs[last_alpha_dest].a);
-
- let c0 = alpha_compare(color.a, frame.alpha_ref0, frame.alpha_comp0);
- let c1 = alpha_compare(color.a, frame.alpha_ref1, frame.alpha_comp1);
- if !alpha_combine(c0, c1, frame.alpha_op) {
- discard;
}
return color;
diff --git a/crates/backend-wgpu/src/shaders/tev_indirect.wesl b/crates/backend-wgpu/src/shaders/tev_indirect.wesl
index e39fd65..cf1a995 100644
--- a/crates/backend-wgpu/src/shaders/tev_indirect.wesl
+++ b/crates/backend-wgpu/src/shaders/tev_indirect.wesl
@@ -72,6 +72,24 @@ struct IndirectSamples {
samples: array<vec3<f32>, 4>,
}
+fn sample_indirect_one(i: u32, in: VsOut, result: ptr<function, IndirectSamples>) {
+ let shift = i * 6u;
+ let texmap = (frame.indirect_refs >> shift) & 7u;
+ let texcoord = (frame.indirect_refs >> (shift + 3u)) & 7u;
+ let scale_pair = frame.indirect_scales[i / 2u];
+ let scale_s: u32 = select(scale_pair.x, scale_pair.z, (i & 1u) == 1u);
+ let scale_t: u32 = select(scale_pair.y, scale_pair.w, (i & 1u) == 1u);
+
+ let stq = select_texcoord(in, texcoord);
+ let direct_uv = stq_to_uv(stq);
+ let sample_uv = vec2<f32>(
+ direct_uv.x * exp2(-f32(scale_s)),
+ direct_uv.y * exp2(-f32(scale_t)),
+ );
+ let sample = sample_texmap(texmap, sample_uv);
+ (*result).samples[i] = sample.abg;
+}
+
fn sample_indirect_textures(in: VsOut) -> IndirectSamples {
var result: IndirectSamples;
result.samples[0] = vec3<f32>(0.0);
@@ -79,29 +97,10 @@ fn sample_indirect_textures(in: VsOut) -> IndirectSamples {
result.samples[2] = vec3<f32>(0.0);
result.samples[3] = vec3<f32>(0.0);
- let num_stages = frame.num_indirect_stages;
- for (var i = 0u; i < 4u; i = i + 1u) {
- if i >= num_stages {
- break;
- }
-
- let shift = i * 6u;
- let texmap = (frame.indirect_refs >> shift) & 7u;
- let texcoord = (frame.indirect_refs >> (shift + 3u)) & 7u;
- let scale_pair = frame.indirect_scales[i / 2u];
- let scale_s: u32 = select(scale_pair.x, scale_pair.z, (i & 1u) == 1u);
- let scale_t: u32 = select(scale_pair.y, scale_pair.w, (i & 1u) == 1u);
-
- let stq = select_texcoord(in, texcoord);
- let direct_uv = stq_to_uv(stq);
- let sample_uv = vec2<f32>(
- direct_uv.x * exp2(-f32(scale_s)),
- direct_uv.y * exp2(-f32(scale_t)),
- );
- let sample = sample_texmap(texmap, sample_uv);
-
- result.samples[i] = sample.abg;
- }
+ @if(IND_STAGE_0_ENABLED) { sample_indirect_one(0u, in, &result); }
+ @if(IND_STAGE_1_ENABLED) { sample_indirect_one(1u, in, &result); }
+ @if(IND_STAGE_2_ENABLED) { sample_indirect_one(2u, in, &result); }
+ @if(IND_STAGE_3_ENABLED) { sample_indirect_one(3u, in, &result); }
return result;
}