use std::{
cell::Cell,
sync::{Arc, Weak},
};
use cranpose_ui_graphics::space::Multisample;
use super::sample_slot;
use crate::{
lazy_resource::LazyGpuResource,
pipeline_compiler::{CompileLane, CompilerSend, PipelineCompiler},
pipeline_recorder::PipelineRecorder,
};
pub(crate) struct AppShader<const N: usize> {
pub(super) source: Weak<str>,
pub(super) module: LazyGpuResource<Option<wgpu::ShaderModule>>,
pipelines: [[ShaderPipeline; N]; 2],
}
pub(crate) type VolumeShader = AppShader<4>;
pub(crate) type ShadedShader = AppShader<3>;
impl<const N: usize> AppShader<N> {
pub(super) fn new(
shader: &Arc<str>,
module: &'static str,
labels: [[&'static str; N]; 2],
) -> Self {
Self {
source: Arc::downgrade(shader),
module: LazyGpuResource::new(module),
pipelines: labels.map(|labels| labels.map(ShaderPipeline::new)),
}
}
pub(crate) fn pipeline(&self, variant: usize, samples: Multisample) -> &ShaderPipeline {
&self.pipelines[sample_slot(samples)][variant]
}
}
pub(super) fn kept_shader<'k, const N: usize>(
kept: &'k [AppShader<N>],
shader: &Arc<str>,
) -> Option<&'k AppShader<N>> {
kept.iter()
.find(|kept| std::ptr::addr_eq(kept.source.as_ptr(), Arc::as_ptr(shader)))
}
pub(crate) struct ShaderPipeline {
resource: LazyGpuResource<Option<wgpu::RenderPipeline>>,
queued: Cell<bool>,
}
impl ShaderPipeline {
fn new(label: &'static str) -> Self {
Self {
resource: LazyGpuResource::new(label),
queued: Cell::new(false),
}
}
pub(crate) fn when_ready<J>(
&self,
(recorder, compiler, backend): (&PipelineRecorder, &PipelineCompiler, wgpu::Backend),
job: impl FnOnce() -> J,
) -> Option<&Option<wgpu::RenderPipeline>>
where
J: FnOnce() -> Option<wgpu::RenderPipeline> + CompilerSend + 'static,
{
if let Some(built) = self.resource.get() {
return Some(built);
}
if !compiler.is_active() {
return Some(self.resource.for_draw(recorder, backend, job()));
}
if !self.queued.replace(true) {
self.resource
.queue(compiler, CompileLane::Demanded, backend, job());
}
None
}
}