#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
use std::{
hash::{Hash, Hasher},
sync::Arc,
};
use cranpose_ui_graphics::{DrawSpecialization, FxHashMap, FxHashSet, RuntimeShader, ShaderTarget};
#[cfg(not(target_arch = "wasm32"))]
use cranpose_ui_graphics::{runtime_shader_overrides_hash, runtime_shader_source_hash};
#[cfg(not(target_arch = "wasm32"))]
use crate::pipeline_records::ShaderPipelineRecord;
use crate::{
lazy_resource::LazyGpuResource,
pipeline_compiler::{CompileLane, PipelineCompiler},
};
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) enum RuntimeShaderPipelineMode {
Replace,
PremultipliedSrcOver,
}
impl RuntimeShaderPipelineMode {
pub(crate) fn for_target(target: ShaderTarget) -> Self {
match target {
ShaderTarget::Layer => Self::Replace,
ShaderTarget::Page => Self::PremultipliedSrcOver,
}
}
fn blend_state(self) -> wgpu::BlendState {
match self {
Self::Replace => wgpu::BlendState::REPLACE,
Self::PremultipliedSrcOver => wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING,
}
}
#[cfg(not(target_arch = "wasm32"))]
fn disk_byte(self) -> u8 {
match self {
Self::Replace => 0,
Self::PremultipliedSrcOver => 1,
}
}
#[cfg(not(target_arch = "wasm32"))]
fn from_disk_byte(byte: u8) -> Option<Self> {
match byte {
0 => Some(Self::Replace),
1 => Some(Self::PremultipliedSrcOver),
_ => None,
}
}
}
pub(crate) fn shader_specialization_enabled() -> bool {
!cranpose_core::DIAGNOSTICS
.no_shader_specialization
.equals("1")
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ShaderPipelineFit {
Specialized,
General,
Fallback,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct PipelineKey {
source: u64,
overrides: u64,
forced: u64,
mode: RuntimeShaderPipelineMode,
}
#[cfg(not(target_arch = "wasm32"))]
type PipelineIdentity = (u64, u64, u8);
impl PipelineKey {
#[cfg(not(target_arch = "wasm32"))]
fn identity(self) -> PipelineIdentity {
(self.source, self.overrides, self.mode.disk_byte())
}
fn general(self) -> Self {
Self {
overrides: 0,
..self
}
}
fn is_general(self) -> bool {
self == self.general()
}
}
struct ShaderSource {
text: Arc<str>,
module: LazyGpuResource<Option<RuntimeShaderModule>>,
#[cfg(target_arch = "wasm32")]
module_ahead: bool,
}
impl ShaderSource {
fn new(text: &str) -> Self {
Self {
text: Arc::from(text),
module: LazyGpuResource::new("runtime-shader module"),
#[cfg(target_arch = "wasm32")]
module_ahead: false,
}
}
}
struct RuntimeShaderModule {
module: wgpu::ShaderModule,
position_independent: bool,
}
#[derive(Clone)]
struct PipelineFactory {
device: wgpu::Device,
pipeline_cache: Option<wgpu::PipelineCache>,
layout: wgpu::PipelineLayout,
format: wgpu::TextureFormat,
backend: wgpu::Backend,
#[cfg(test)]
counters: Arc<BuildCounters>,
}
impl PipelineFactory {
fn module(&self, source: &str, source_hash: u64) -> Option<RuntimeShaderModule> {
#[cfg(test)]
self.counters.modules.fetch_add(1, Relaxed);
create_runtime_shader_module(&self.device, source, source_hash, self.backend)
}
}
#[cfg(test)]
#[derive(Default)]
struct BuildCounters {
modules: AtomicUsize,
pipelines: AtomicUsize,
}
struct PipelineJob {
factory: PipelineFactory,
source: Arc<str>,
key: PipelineKey,
module: LazyGpuResource<Option<RuntimeShaderModule>>,
constants: Vec<(&'static str, f64)>,
}
impl PipelineJob {
fn build(self) -> Option<wgpu::RenderPipeline> {
let Self {
factory,
source,
key,
module,
constants,
} = self;
let module = module
.get_or_init(factory.backend, || factory.module(&source, key.source))
.as_ref()?;
let mode = key.mode;
#[cfg(test)]
factory.counters.pipelines.fetch_add(1, Relaxed);
Some(crate::shared_shader::create_fullscreen_strip_pipeline(
&factory.device,
factory.pipeline_cache.as_ref(),
&format!(
"runtime-shader mode={mode:?} source={:016x} \
overrides={:016x} forced={:016x} constants={}",
key.source,
key.overrides,
key.forced,
constants.len(),
),
"RuntimeShader Effect Pipeline",
&factory.layout,
crate::shared_shader::StripStages {
vertex: (&module.module, crate::render::FULLSCREEN_VS),
fragment: (&module.module, "effect_fs"),
constants: &constants,
},
(
wgpu::ColorTargetState {
format: factory.format,
blend: Some(mode.blend_state()),
write_mask: wgpu::ColorWrites::ALL,
},
None,
),
))
}
}
pub(crate) struct ShaderPipelineCache {
factory: PipelineFactory,
compiler: PipelineCompiler,
sources: FxHashMap<u64, ShaderSource>,
pipelines: FxHashMap<PipelineKey, LazyGpuResource<Option<wgpu::RenderPipeline>>>,
demanded: FxHashSet<PipelineKey>,
forced: Vec<&'static str>,
forced_hash: u64,
stand_ins: Vec<StandIn>,
after_first_frame: Vec<(PipelineKey, Vec<(&'static str, f64)>)>,
#[cfg(not(target_arch = "wasm32"))]
noted: FxHashSet<PipelineKey>,
#[cfg(not(target_arch = "wasm32"))]
cached: FxHashSet<PipelineIdentity>,
recorder: crate::pipeline_recorder::PipelineRecorder,
}
impl ShaderPipelineCache {
pub(crate) fn new(
device: &wgpu::Device,
compiler: PipelineCompiler,
pipeline_cache: Option<wgpu::PipelineCache>,
backend: wgpu::Backend,
format: wgpu::TextureFormat,
bind_group_layouts: [&wgpu::BindGroupLayout; 2],
recorder: crate::pipeline_recorder::PipelineRecorder,
) -> Self {
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Effect Pipeline Layout"),
bind_group_layouts: &bind_group_layouts.map(Some),
immediate_size: 0,
});
Self {
factory: PipelineFactory {
device: device.clone(),
pipeline_cache,
layout,
format,
backend,
#[cfg(test)]
counters: Arc::default(),
},
compiler,
sources: FxHashMap::default(),
pipelines: FxHashMap::default(),
demanded: FxHashSet::default(),
forced: Vec::new(),
forced_hash: 0,
stand_ins: Vec::new(),
after_first_frame: Vec::new(),
#[cfg(not(target_arch = "wasm32"))]
noted: FxHashSet::default(),
#[cfg(not(target_arch = "wasm32"))]
cached: FxHashSet::default(),
recorder,
}
}
pub(crate) fn set_forced_flags(&mut self, flags: impl Iterator<Item = &'static str>) {
let mut forced: Vec<&'static str> = flags.collect();
forced.sort_unstable();
if forced == self.forced {
return;
}
let mut hasher = std::collections::hash_map::DefaultHasher::new();
forced.hash(&mut hasher);
self.forced_hash = if forced.is_empty() {
0
} else {
hasher.finish()
};
self.forced = forced;
}
fn force_declared_flags(
forced: &[&'static str],
source: &str,
constants: &mut Vec<(&'static str, f64)>,
) {
for flag in forced {
if !source.contains(&format!("override {flag}:")) {
continue;
}
match constants.iter_mut().find(|(name, _)| name == flag) {
Some(constant) => constant.1 = 1.0,
None => constants.push((flag, 1.0)),
}
}
}
fn key(
&self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
mode: RuntimeShaderPipelineMode,
) -> PipelineKey {
PipelineKey {
source: shader.source_hash(),
overrides: if shader_specialization_enabled() {
specialization.overrides_hash()
} else {
0
},
forced: self.forced_hash,
mode,
}
}
fn job(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
key: PipelineKey,
) -> PipelineJob {
self.sources
.entry(key.source)
.or_insert_with(|| ShaderSource::new(shader.source()));
let constants = if key.overrides == 0 {
Vec::new()
} else {
specialization.overrides().to_vec()
};
self.source_job(key, constants)
}
fn source_job(&self, key: PipelineKey, mut constants: Vec<(&'static str, f64)>) -> PipelineJob {
let source = &self.sources[&key.source];
Self::force_declared_flags(&self.forced, &source.text, &mut constants);
PipelineJob {
factory: self.factory.clone(),
source: Arc::clone(&source.text),
key,
module: source.module.clone(),
constants,
}
}
pub(crate) fn position_independent(&mut self, shader: &RuntimeShader) -> bool {
if shader.position_independent() {
return true;
}
let hash = shader.source_hash();
let source = self
.sources
.entry(hash)
.or_insert_with(|| ShaderSource::new(shader.source()));
source
.module
.for_draw(&self.recorder, self.factory.backend, || {
self.factory.module(&source.text, hash)
})
.as_ref()
.is_some_and(|module| module.position_independent)
}
fn slot(&mut self, key: PipelineKey) -> LazyGpuResource<Option<wgpu::RenderPipeline>> {
self.pipelines
.entry(key)
.or_insert_with(|| LazyGpuResource::new("runtime-shader"))
.clone()
}
fn ready(&self, key: PipelineKey) -> bool {
self.pipelines
.get(&key)
.is_some_and(|slot| slot.get().is_some())
}
fn request(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
key: PipelineKey,
lane: CompileLane,
) {
let queued = self.pipelines.contains_key(&key);
let first_demand = lane == CompileLane::Demanded && self.demanded.insert(key);
if queued && !first_demand {
return;
}
let job = self.job(shader, specialization, key);
#[cfg(target_arch = "wasm32")]
if lane == CompileLane::WarmUp {
self.make_module_ahead(key.source);
}
self.slot(key)
.queue(&self.compiler, lane, self.factory.backend, || job.build());
}
#[cfg(target_arch = "wasm32")]
fn make_module_ahead(&mut self, source_hash: u64) {
let Some(source) = self.sources.get_mut(&source_hash) else {
return;
};
if std::mem::replace(&mut source.module_ahead, true) {
return;
}
let factory = self.factory.clone();
let text = Arc::clone(&source.text);
let module = source.module.clone();
self.compiler.make_module_ahead(move || {
module.get_or_init(factory.backend, || factory.module(&text, source_hash));
});
}
pub(crate) fn warm(&mut self, shader: &RuntimeShader, mode: RuntimeShaderPipelineMode) {
if !self.compiler.takes_warm_ups() {
return;
}
let specialization = shader.draw_specialization(0);
let key = self.key(shader, specialization, mode);
self.request(shader, specialization, key, CompileLane::WarmUp);
}
pub(crate) fn get_or_create(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
mode: RuntimeShaderPipelineMode,
) -> Option<(&wgpu::RenderPipeline, ShaderPipelineFit)> {
let key = self.key(shader, specialization, mode);
#[cfg(not(target_arch = "wasm32"))]
self.note_drawn(specialization, key);
let (build, fit, stand_in) = self.choose(shader, specialization, key);
if !self.ready(build) {
self.build_now(shader, specialization, build, stand_in);
}
self.pipelines[&build]
.get()
.and_then(Option::as_ref)
.map(|pipeline| (pipeline, fit))
}
pub(crate) fn ready_to_draw(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
mode: RuntimeShaderPipelineMode,
) -> bool {
if !self.compiler.is_active() {
return true;
}
let key = self.key(shader, specialization, mode);
if self.ready(key) || self.cached(key) {
return true;
}
if specialization.exact()
&& key != key.general()
&& let Some(index) = self.stand_in_for(key, specialization)
{
return self.ready(self.stand_ins[index].key);
}
self.demand(shader, specialization, key);
false
}
fn cached(&self, key: PipelineKey) -> bool {
#[cfg(not(target_arch = "wasm32"))]
return key.forced == 0 && self.cached.contains(&key.identity());
#[cfg(target_arch = "wasm32")]
{
let _ = key;
false
}
}
fn demand(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
key: PipelineKey,
) {
if !self
.after_first_frame
.iter()
.any(|(later, _)| *later == key)
{
self.request(shader, specialization, key, CompileLane::Demanded);
}
}
fn choose(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
key: PipelineKey,
) -> (PipelineKey, ShaderPipelineFit, Option<usize>) {
let own_fit = if key.is_general() {
ShaderPipelineFit::General
} else {
ShaderPipelineFit::Specialized
};
if self.ready(key)
|| key == key.general()
|| !self.compiler.is_active()
|| !specialization.exact()
|| self.cached(key)
{
return (key, own_fit, None);
}
self.demand(shader, specialization, key);
match self.stand_in_for(key, specialization) {
Some(index) => (
self.stand_ins[index].key,
ShaderPipelineFit::Fallback,
Some(index),
),
None => (key, own_fit, None),
}
}
fn build_now(
&mut self,
shader: &RuntimeShader,
specialization: DrawSpecialization<'_>,
build: PipelineKey,
stand_in: Option<usize>,
) {
let job = match stand_in {
Some(index) => {
let stand_in = &self.stand_ins[index];
self.source_job(stand_in.key, stand_in.constants.clone())
}
None => self.job(shader, specialization, build),
};
let backend = self.factory.backend;
self.slot(build)
.for_draw(&self.recorder, backend, || job.build());
}
#[cfg(not(target_arch = "wasm32"))]
fn note_drawn(&mut self, specialization: DrawSpecialization<'_>, key: PipelineKey) {
if key.forced != 0 || !self.noted.insert(key) {
return;
}
let first_screen = self.recorder.in_first_screen();
let record = ShaderPipelineRecord {
source: key.source,
overrides: key.overrides,
mode: key.mode.disk_byte(),
constants: if key.overrides == 0 {
Vec::new()
} else {
specialization
.overrides()
.iter()
.map(|&(name, value)| (name.to_owned(), value))
.collect()
},
};
self.recorder.note_shader(record, first_screen);
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn warm_recorded<'a>(
&mut self,
records: impl IntoIterator<Item = &'a ShaderPipelineRecord>,
sources: impl IntoIterator<Item = &'static str>,
) {
for (key, constants) in self.decode_records(records, sources) {
self.queue_warm_up(key, constants);
}
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn warm_first_screen<'a>(
&mut self,
records: impl IntoIterator<Item = &'a ShaderPipelineRecord>,
sources: impl IntoIterator<Item = &'static str>,
) {
let recorded = self.decode_records(records, sources);
let (cached, recorded): (Vec<_>, Vec<_>) =
recorded.into_iter().partition(|(key, _)| self.cached(*key));
for (key, constants) in cached {
self.queue_warm_up(key, constants);
}
let mut groups: Vec<(StandIn, usize)> = Vec::new();
for (key, constants) in &recorded {
match groups
.iter_mut()
.find(|(group, _)| group.key == key.general())
{
Some((group, members)) => {
group.constants.retain(|&shared| holds(constants, shared));
*members += 1;
}
None => groups.push((
StandIn {
key: key.general(),
constants: constants.clone(),
},
1,
)),
}
}
for (mut stand_in, members) in groups {
if members < 2 || stand_in.constants.is_empty() {
continue;
}
stand_in.key.overrides =
runtime_shader_overrides_hash(stand_in.constants.iter().copied());
self.queue_warm_up(stand_in.key, stand_in.constants.clone());
self.stand_ins.push(stand_in);
}
for (key, constants) in recorded {
let covered = self.stand_ins.iter().any(|stand_in| {
stand_in.key.general() == key.general()
&& stand_in
.constants
.iter()
.all(|&shared| holds(&constants, shared))
});
if covered {
self.after_first_frame.push((key, constants));
} else {
self.queue_warm_up(key, constants);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn trust_cached<'a>(
&mut self,
records: impl IntoIterator<Item = &'a ShaderPipelineRecord>,
) {
self.cached.extend(
records
.into_iter()
.map(|record| (record.source, record.overrides, record.mode)),
);
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn queue_after_first_frame(&mut self) {
for (key, constants) in std::mem::take(&mut self.after_first_frame) {
self.queue_warm_up(key, constants);
}
}
#[cfg(not(target_arch = "wasm32"))]
fn decode_records<'a>(
&mut self,
records: impl IntoIterator<Item = &'a ShaderPipelineRecord>,
sources: impl IntoIterator<Item = &'static str>,
) -> Vec<(PipelineKey, Vec<(&'static str, f64)>)> {
if !self.compiler.is_active() || self.forced_hash != 0 {
return Vec::new();
}
let sources: smallvec::SmallVec<[(u64, &'static str); 8]> = sources
.into_iter()
.map(|text| (runtime_shader_source_hash(text), text))
.collect();
let mut decoded = Vec::new();
for record in records {
let Some(&(_, text)) = sources.iter().find(|(hash, _)| *hash == record.source) else {
continue;
};
let Some(recorded) = recorded_key(record, text) else {
continue;
};
self.sources
.entry(recorded.0.source)
.or_insert_with(|| ShaderSource::new(text));
decoded.push(recorded);
}
decoded
}
#[cfg(not(target_arch = "wasm32"))]
fn queue_warm_up(&mut self, key: PipelineKey, constants: Vec<(&'static str, f64)>) {
if self.pipelines.contains_key(&key) {
return;
}
let job = self.source_job(key, constants);
self.slot(key).queue(
&self.compiler,
CompileLane::WarmUp,
self.factory.backend,
|| job.build(),
);
}
fn stand_in_for(
&self,
key: PipelineKey,
specialization: DrawSpecialization<'_>,
) -> Option<usize> {
self.stand_ins.iter().position(|stand_in| {
stand_in.key.general() == key.general()
&& stand_in.key != key
&& stand_in
.constants
.iter()
.all(|&shared| holds(specialization.overrides(), shared))
})
}
}
fn holds(overrides: &[(&'static str, f64)], (name, value): (&'static str, f64)) -> bool {
overrides
.iter()
.any(|&(own, fixed)| own == name && fixed.to_bits() == value.to_bits())
}
struct StandIn {
key: PipelineKey,
constants: Vec<(&'static str, f64)>,
}
#[cfg(not(target_arch = "wasm32"))]
fn recorded_key(
record: &ShaderPipelineRecord,
text: &'static str,
) -> Option<(PipelineKey, Vec<(&'static str, f64)>)> {
let constants = record
.constants
.iter()
.map(|(name, value)| Some((declared_override(text, name)?, *value)))
.collect::<Option<Vec<_>>>()?;
let key = PipelineKey {
source: record.source,
overrides: record.overrides,
forced: 0,
mode: RuntimeShaderPipelineMode::from_disk_byte(record.mode)?,
};
Some((key, constants))
}
#[cfg(not(target_arch = "wasm32"))]
fn declared_override(text: &'static str, name: &str) -> Option<&'static str> {
const OVERRIDE: &str = "override ";
text.match_indices(OVERRIDE).find_map(|(at, _)| {
let declared = &text[at + OVERRIDE.len()..];
declared
.strip_prefix(name)?
.starts_with(':')
.then(|| &declared[..name.len()])
})
}
fn create_runtime_shader_module(
device: &wgpu::Device,
source: &str,
source_hash: u64,
backend: wgpu::Backend,
) -> Option<RuntimeShaderModule> {
#[cfg(target_arch = "wasm32")]
if crate::effect_renderer::framework_shader_sources().any(|wgsl| wgsl == source) {
return Some(RuntimeShaderModule {
module: device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("RuntimeShader Effect"),
source: wgpu::ShaderSource::Wgsl(source.into()),
}),
position_independent: false,
});
}
let (parsed, position_independent) = match validate_runtime_shader_source(source, backend) {
Ok(validated) => validated,
Err(err) => {
log::warn!(
"Disabling RuntimeShader (hash={source_hash}): {err}. Falling back to pass-through."
);
return None;
}
};
Some(RuntimeShaderModule {
module: device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("RuntimeShader Effect"),
source: validated_source(source, parsed),
}),
position_independent,
})
}
#[cfg(not(target_arch = "wasm32"))]
fn validated_source(_text: &str, parsed: naga::Module) -> wgpu::ShaderSource<'static> {
wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(parsed))
}
#[cfg(target_arch = "wasm32")]
fn validated_source(text: &str, _parsed: naga::Module) -> wgpu::ShaderSource<'_> {
wgpu::ShaderSource::Wgsl(text.into())
}
pub(crate) fn create_volume_shader_module(
device: &wgpu::Device,
source: &str,
backend: wgpu::Backend,
) -> Option<wgpu::ShaderModule> {
create_app_shader_module(
device,
(
cranpose_ui_graphics::framework_shaders::MESH_VOLUME_PRELUDE_WGSL,
source,
),
(backend, ("mesh_volume_vs", "mesh_volume_fs")),
("Scene Volume", "Leaving out the volumes"),
)
}
pub(crate) fn create_shaded_shader_module(
device: &wgpu::Device,
source: &str,
backend: wgpu::Backend,
) -> Option<wgpu::ShaderModule> {
create_app_shader_module(
device,
(
cranpose_ui_graphics::framework_shaders::MESH_SHADED_PRELUDE_WGSL,
source,
),
(backend, ("mesh_shaded_vs", "mesh_shaded_fs")),
("Scene Shaded Surface", "Drawing lit the surfaces"),
)
}
fn create_app_shader_module(
device: &wgpu::Device,
(prelude, source): (&str, &str),
(backend, entry_points): (wgpu::Backend, (&str, &str)),
(label, left_out): (&'static str, &str),
) -> Option<wgpu::ShaderModule> {
let text = format!("{prelude}{source}");
match validate_shader_source(&text, backend, entry_points) {
Ok((parsed, _, _)) => Some(device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: validated_source(&text, parsed),
})),
Err(err) => {
log::warn!("{left_out} of a shader that does not build: {err}");
None
}
}
}
mod validation;
use validation::{validate_runtime_shader_source, validate_shader_source};
#[cfg(test)]
#[path = "tests/shader_cache_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/shader_cache_target_tests.rs"]
mod target_tests;