use std::{cell::Cell, sync::Arc};
use cranpose_ui_graphics::{BlendMode, ImagePixelFormat};
use super::{
CompileLane, CompilerSend, FixedPipeline, GlyphDrawCmd, GlyphInstances, GlyphQuads,
ImageBindGroups, ImageDrawCmd, ImageVariant, PassDepth, PassFrame, Pending, ShapePipelines,
SharedShader, TurnedGlyph, ViewportUniforms, create_glyph_atlas_pipeline,
create_image_pipeline,
};
use crate::{
draw_pass::TrackedPass,
gpu_stats::FrameStats,
instant_triangles::{InstantBuffers, InstantDraw, InstantStandIn, InstantTriangles},
pipeline_compiler::PipelineCompiler,
rrect_shadow::create_rrect_shadow_pipeline,
run_store::RunDrawCall,
shaders,
shape_pipelines::PipelineDemand,
};
pub(super) const IMAGE_SRC_OVER_PIPELINES: [&str; 8] = [
"image/src-over",
"image/src-over/depth",
"image/src-over/alpha-mask",
"image/src-over/alpha-mask/depth",
"image/src-over/rounded",
"image/src-over/rounded/depth",
"image/src-over/alpha-mask/rounded",
"image/src-over/alpha-mask/rounded/depth",
];
pub(super) const IMAGE_DST_OUT_PIPELINES: [&str; 8] = [
"image/dst-out",
"image/dst-out/depth",
"image/dst-out/alpha-mask",
"image/dst-out/alpha-mask/depth",
"image/dst-out/rounded",
"image/dst-out/rounded/depth",
"image/dst-out/alpha-mask/rounded",
"image/dst-out/alpha-mask/rounded/depth",
];
pub(super) const GLYPH_ATLAS_PIPELINES: [&str; 6] = [
"glyph/atlas",
"glyph/atlas/depth",
"glyph/atlas/aligned",
"glyph/atlas/aligned/depth",
"glyph/atlas/turned",
"glyph/atlas/turned/depth",
];
pub(super) const RRECT_SHADOW_PIPELINES: [&str; 2] = ["shadow/rrect", "shadow/rrect/depth"];
#[cfg(not(target_arch = "wasm32"))]
pub(super) const MESH_FALLBACK_PIPELINES: [&str; 2] = ["mesh/fallback", "mesh/fallback/depth"];
pub(super) fn overlay_shaders(
device: &wgpu::Device,
backend: wgpu::Backend,
(uniform, texture): (&wgpu::BindGroupLayout, &wgpu::BindGroupLayout),
) -> [SharedShader; 3] {
let textured = [Some(uniform), Some(texture)];
[
SharedShader::new(device, backend, "Image Shader", shaders::IMAGE, &textured),
SharedShader::new(
device,
backend,
"Glyph Atlas Shader",
shaders::GLYPH_ATLAS,
&textured,
),
SharedShader::new(
device,
backend,
"Round Rect Shadow Shader",
shaders::RRECT_SHADOW,
&[Some(uniform)],
),
]
}
pub(crate) enum FixedDraw<'a> {
Own(&'a wgpu::RenderPipeline),
Instant(InstantStandIn<'a>),
LeftOut,
}
pub(crate) struct RendererPipelines {
pub(super) device: Arc<wgpu::Device>,
pub(crate) composition_format: wgpu::TextureFormat,
pub(crate) adapter_backend: wgpu::Backend,
pub(crate) pipeline_cache: Option<wgpu::PipelineCache>,
#[cfg(not(target_arch = "wasm32"))]
pub(crate) _pipeline_cache_watcher: Option<crate::pipeline_disk_cache::PersistWatcher>,
#[cfg(not(target_arch = "wasm32"))]
pub(crate) recent_after_update: Option<Arc<crate::pipeline_records::PipelineRecords>>,
pub(crate) recorder: crate::pipeline_recorder::PipelineRecorder,
pub(crate) compiler: PipelineCompiler,
#[cfg(not(target_arch = "wasm32"))]
pub(crate) landing: Option<Arc<crate::pipeline_compiler::Landing>>,
pub(crate) built_at_frame_start: u64,
pub(crate) drew_placeholder: Cell<bool>,
pub(crate) stand_ins_kept: Cell<bool>,
pub(crate) shape_pipelines: ShapePipelines,
pub(crate) image_pipeline: [FixedPipeline; 8],
pub(crate) image_pipeline_dst_out: [FixedPipeline; 8],
pub(crate) glyph_atlas_pipeline: [FixedPipeline; 6],
pub(crate) rrect_shadow_pipeline: [FixedPipeline; 2],
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mesh_pipelines: [FixedPipeline; 2],
#[cfg(not(target_arch = "wasm32"))]
pub(crate) instant: crate::instant_triangles::InstantPipelines,
pub(crate) image_shader: SharedShader,
pub(crate) glyph_atlas_shader: SharedShader,
pub(crate) rrect_shadow_shader: SharedShader,
pub(crate) uniform_bind_group_layout: wgpu::BindGroupLayout,
pub(crate) image_bind_group_layout: wgpu::BindGroupLayout,
pub(crate) image_nearest_sampler: wgpu::Sampler,
pub(crate) image_linear_sampler: wgpu::Sampler,
}
impl RendererPipelines {
pub(crate) fn awaits_shape_pipeline(
&self,
draws: &[RunDrawCall],
range: std::ops::Range<usize>,
) -> bool {
draws.get(range).is_some_and(|draws| {
draws
.iter()
.any(|draw| self.shape_pipelines.get(draw.key).is_none())
})
}
pub(crate) fn compile_pipelines_in_background(&mut self) {
self.shape_pipelines.build_in_background();
#[cfg(target_arch = "wasm32")]
self.compiler.compile_in_background();
}
pub(crate) fn landings(&self) -> u64 {
#[cfg(not(target_arch = "wasm32"))]
let built = self.landing.as_ref().map_or(0, |landing| landing.built());
#[cfg(target_arch = "wasm32")]
let built = self.compiler.landings();
built + self.shape_pipelines.landings()
}
pub(crate) fn take_landing_at_frame_start(&mut self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
let Some(landing) = &self.landing else {
return false;
};
self.built_at_frame_start = landing.built();
landing.take_landed()
}
#[cfg(target_arch = "wasm32")]
{
let landings = self.landings();
let started = std::mem::replace(&mut self.built_at_frame_start, landings);
started != landings && self.stand_ins_kept.get()
}
}
pub(crate) fn count_landings(&mut self) -> u64 {
self.shape_pipelines.count_landings();
self.landings()
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn compiling(&self) -> bool {
self.landing
.as_ref()
.is_some_and(|landing| landing.in_flight())
}
pub(crate) fn ensure_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
for key in pipelines.drain() {
self.shape_pipelines.ensure(key);
if let Some(interior) = key.interior() {
self.shape_pipelines.ensure(interior);
}
}
}
pub(crate) fn frame_lane(&self) -> CompileLane {
if self.compiler.is_active() {
CompileLane::Demanded
} else {
CompileLane::WarmUp
}
}
pub(crate) fn image_pipeline_resource(
&self,
blend_mode: BlendMode,
variant: ImageVariant,
) -> &FixedPipeline {
let pipelines = match blend_mode {
BlendMode::DstOut => &self.image_pipeline_dst_out,
_ => &self.image_pipeline,
};
&pipelines[variant.depth.index()
+ 2 * usize::from(variant.alpha_mask)
+ 4 * usize::from(variant.rounded)]
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
self.landing.clone()
}
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
if let Some(landing) = &self.landing {
landing.wake_with(wake);
}
}
pub(crate) fn demand_depth(
&mut self,
keys: &PipelineDemand,
awaited: &mut Vec<Pending<wgpu::RenderPipeline>>,
) {
for key in keys.keys() {
self.shape_pipelines
.demand_with_interior(key, &mut |pending| awaited.push(pending));
}
let (depth, lane) = (PassDepth::On, CompileLane::Demanded);
let aligned = self.glyph_atlas_pipeline_resource(depth, GlyphQuads::Aligned);
awaited.extend(
aligned.prefetch(lane, &self.compiler, self.adapter_backend, || {
self.glyph_atlas_pipeline_job(depth, GlyphQuads::Aligned)
}),
);
#[cfg(not(target_arch = "wasm32"))]
awaited.extend(self.instant.pipeline(PassDepth::On).prefetch(
CompileLane::Demanded,
&self.compiler,
self.adapter_backend,
|| {
let cache = self.pipeline_cache.clone();
self.instant
.job(&self.device, cache, self.composition_format, PassDepth::On)
},
));
}
#[cold]
#[inline(never)]
pub(crate) fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
self.recorder.first_screen_records(self.adapter_backend)
}
pub(super) fn app_shader_pipeline<'p, J>(
&'p self,
stats: &FrameStats,
pipeline: &'p crate::scene_pass::ShaderPipeline,
job: impl FnOnce() -> J,
) -> Option<&'p wgpu::RenderPipeline>
where
J: FnOnce() -> Option<wgpu::RenderPipeline> + CompilerSend + 'static,
{
let ready =
pipeline.when_ready((&self.recorder, &self.compiler, self.adapter_backend), job);
match ready {
Some(built) => built.as_ref(),
None => {
self.note_placeholder(stats);
None
}
}
}
pub(super) fn image_pipeline_job(
&self,
blend_mode: BlendMode,
variant: ImageVariant,
) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
let device = Arc::clone(&self.device);
let cache = self.pipeline_cache.clone();
let format = self.composition_format;
let shader = self.image_shader.clone();
move || {
create_image_pipeline(
&device,
cache.as_ref(),
format,
&shader,
blend_mode,
variant,
)
}
}
pub(crate) fn prefetch_image_pipelines(
&self,
cmds: &[ImageDrawCmd],
blend_mode: BlendMode,
(depth, lane): (PassDepth, CompileLane),
awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
) {
let mut last = None;
for cmd in cmds {
let variant = ImageVariant {
depth,
alpha_mask: cmd.image.alpha_mask,
rounded: cmd.clip.is_some(),
};
if last.replace(variant) == Some(variant) {
continue;
}
if let Some(pending) = self.image_pipeline_resource(blend_mode, variant).prefetch(
lane,
&self.compiler,
self.adapter_backend,
|| self.image_pipeline_job(blend_mode, variant),
) {
awaited(pending);
}
}
}
pub(crate) fn prefetch_glyph_pipelines(
&self,
cmds: &[GlyphDrawCmd],
(depth, lane): (PassDepth, CompileLane),
awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
) {
let mut last = None;
for cmd in cmds {
let quads = cmd.quads();
if last.replace(quads) == Some(quads) {
continue;
}
if let Some(pending) = self.glyph_atlas_pipeline_resource(depth, quads).prefetch(
lane,
&self.compiler,
self.adapter_backend,
|| self.glyph_atlas_pipeline_job(depth, quads),
) {
awaited(pending);
}
}
}
pub(crate) fn prefetch_shadow_pipeline(
&self,
(depth, lane): (PassDepth, CompileLane),
awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
) {
if let Some(pending) = self.rrect_shadow_pipeline[depth.index()].prefetch(
lane,
&self.compiler,
self.adapter_backend,
|| self.rrect_shadow_pipeline_job(depth),
) {
awaited(pending);
}
}
pub(crate) fn image_pipeline(
&self,
stats: &FrameStats,
blend_mode: BlendMode,
variant: ImageVariant,
) -> FixedDraw<'_> {
let own = self.image_pipeline_resource(blend_mode, variant);
let job = || self.image_pipeline_job(blend_mode, variant);
if let Some(pipeline) =
own.when_ready(&self.recorder, &self.compiler, self.adapter_backend, job)
{
return FixedDraw::Own(pipeline);
}
match self.instant_stand_in(variant.depth) {
Some(stand_in) if blend_mode == BlendMode::SrcOver => {
self.note_instant(stats);
FixedDraw::Instant(stand_in)
}
_ => {
self.note_placeholder(stats);
FixedDraw::LeftOut
}
}
}
#[cfg_attr(
target_arch = "wasm32",
expect(unused_variables, reason = "no stand-ins")
)]
pub(crate) fn instant_stand_in(&self, depth: PassDepth) -> Option<InstantStandIn<'_>> {
#[cfg(not(target_arch = "wasm32"))]
return self.instant.stand_in(depth);
#[cfg(target_arch = "wasm32")]
None
}
pub(crate) fn shadows_stand_in(&self, depth: PassDepth) -> bool {
self.instant_stand_in(depth).is_some()
&& !self.rrect_shadow_pipeline[depth.index()].ready_or_queue(
&self.compiler,
self.adapter_backend,
|| self.rrect_shadow_pipeline_job(depth),
)
}
pub(crate) fn turned_glyphs_ready(&self, depth: PassDepth) -> bool {
self.glyph_atlas_pipeline_resource(depth, GlyphQuads::Turned)
.ready_or_queue(&self.compiler, self.adapter_backend, || {
self.glyph_atlas_pipeline_job(depth, GlyphQuads::Turned)
})
}
pub(super) fn ready_or_left_out<'a, J>(
&self,
stats: &FrameStats,
pipeline: &'a FixedPipeline,
job: impl FnOnce() -> J,
) -> Option<&'a wgpu::RenderPipeline>
where
J: FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static,
{
let ready = pipeline.when_ready(&self.recorder, &self.compiler, self.adapter_backend, job);
if ready.is_none() {
self.note_placeholder(stats);
}
ready
}
pub(super) fn glyph_atlas_pipeline_job(
&self,
depth: PassDepth,
quads: GlyphQuads,
) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
let device = Arc::clone(&self.device);
let cache = self.pipeline_cache.clone();
let format = self.composition_format;
let shader = self.glyph_atlas_shader.clone();
move || {
create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
}
}
pub(super) fn glyph_atlas_pipeline(
&self,
stats: &FrameStats,
depth: PassDepth,
quads: GlyphQuads,
) -> Option<&wgpu::RenderPipeline> {
let resource = self.glyph_atlas_pipeline_resource(depth, quads);
let ready =
resource.when_ready(&self.recorder, &self.compiler, self.adapter_backend, || {
self.glyph_atlas_pipeline_job(depth, quads)
});
let ready = ready.or_else(|| {
(quads == GlyphQuads::Aligned).then_some(())?;
self.glyph_atlas_pipeline_resource(depth, GlyphQuads::Plain)
.built()
});
if ready.is_none() {
self.note_placeholder(stats);
}
ready
}
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn warm_instant_tier(
&self,
first_screen: crate::pipeline_disk_cache::FirstScreenPipelines,
) {
let lane = match first_screen {
crate::pipeline_disk_cache::FirstScreenPipelines::Cold => CompileLane::StandIn,
crate::pipeline_disk_cache::FirstScreenPipelines::Cached
| crate::pipeline_disk_cache::FirstScreenPipelines::Compiled => CompileLane::Demanded,
};
let (compiler, backend) = (&self.compiler, self.adapter_backend);
let (device, format) = (&self.device, self.composition_format);
for depth in PassDepth::BOTH {
let lane = match depth {
PassDepth::Off => lane,
PassDepth::On => CompileLane::Demanded,
};
self.mesh_pipelines[depth.index()].queue(
compiler,
lane,
backend,
crate::mesh_fallback::mesh_pipeline_job(
device,
self.pipeline_cache.clone(),
format,
depth,
),
);
}
let depth = PassDepth::Off;
self.instant.pipeline(depth).queue(
compiler,
lane,
backend,
self.instant
.job(device, self.pipeline_cache.clone(), format, depth),
);
}
pub(super) fn rrect_shadow_pipeline_job(
&self,
depth: PassDepth,
) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
let device = Arc::clone(&self.device);
let cache = self.pipeline_cache.clone();
let format = self.composition_format;
let shader = self.rrect_shadow_shader.clone();
move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
}
pub(super) fn glyph_atlas_pipeline_resource(
&self,
depth: PassDepth,
quads: GlyphQuads,
) -> &FixedPipeline {
let kind = match quads {
GlyphQuads::Plain => 0,
GlyphQuads::Aligned => 1,
GlyphQuads::Turned => 2,
};
&self.glyph_atlas_pipeline[depth.index() + 2 * kind]
}
#[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "no meshes"))]
pub(super) fn mesh_pipeline(&self, depth: PassDepth) -> Option<&wgpu::RenderPipeline> {
#[cfg(not(target_arch = "wasm32"))]
return self.mesh_pipelines[depth.index()].built();
#[cfg(target_arch = "wasm32")]
None
}
pub(super) fn mesh_unready(
&self,
draws: &[RunDrawCall],
range: std::ops::Range<usize>,
tables: crate::mesh_fallback::MeshRecords<'_>,
placement: &dyn Fn(
&cranpose_ui_graphics::ShapeRecordBody,
) -> Option<crate::mesh_fallback::MeshPlacement>,
target: crate::mesh_fallback::MeshTarget,
meshes: &mut crate::mesh_fallback::PassMeshes,
) {
for index in range {
let Some(draw) = draws.get(index) else {
continue;
};
if self.shape_pipelines.get(draw.key).is_some() {
continue;
}
let indices =
meshes
.builder
.push_records(tables, draw.records.clone(), placement, target);
meshes.set(index, indices);
}
}
pub(crate) fn note_placeholder(&self, stats: &FrameStats) {
stats
.placeholder_draws
.set(stats.placeholder_draws.get() + 1);
self.await_landing();
}
pub(crate) fn lay_turned_glyphs(
&self,
depth: PassDepth,
glyphs: &GlyphInstances,
instant: &mut InstantTriangles,
) {
if !glyphs.turned.is_empty()
&& self.instant_stand_in(depth).is_some()
&& !self.turned_glyphs_ready(depth)
{
instant.lay_turned_glyphs(glyphs.turned.iter().map(TurnedGlyph::instant_corners));
}
}
pub(crate) fn draw_instant(
&self,
pass: &mut TrackedPass<'_, '_>,
(frame, draw): (PassFrame, &InstantDraw<'_>),
buffers: Option<&InstantBuffers>,
(uniforms, stats): (&ViewportUniforms, &FrameStats),
) -> Result<(), String> {
if draw.indices.is_empty() {
return Ok(());
}
let stand_in = self
.instant_stand_in(frame.depth)
.ok_or_else(|| "instant draw without the instant pipeline".to_string())?;
let buffers = buffers.ok_or_else(|| "instant draw without its triangles".to_string())?;
let (x, y, width, height) = frame.scissor(draw.scissor);
pass.set_scissor_rect(x, y, width, height);
uniforms.bind(pass, draw.uniform_slot)?;
let texture = (draw.texture, draw.texels);
stand_in.draw(pass, buffers, texture, draw.indices.clone());
self.note_instant(stats);
Ok(())
}
pub(crate) fn note_instant(&self, stats: &FrameStats) {
stats.instant_draws.set(stats.instant_draws.get() + 1);
self.await_landing();
}
pub(super) fn note_mesh_fallback(&self, stats: &FrameStats) {
stats
.shape_pipeline_fallback_draws
.set(stats.shape_pipeline_fallback_draws.get() + 1);
self.await_landing();
}
fn await_landing(&self) {
self.stand_ins_kept.set(true);
self.await_landing_over_stand_ins();
}
pub(crate) fn await_landing_over_stand_ins(&self) {
self.drew_placeholder.set(true);
self.recorder.hold_first_screen();
#[cfg(not(target_arch = "wasm32"))]
if let Some(landing) = &self.landing {
landing.await_since(self.built_at_frame_start);
}
}
pub(super) fn placeholder_awaits_frame(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if let Some(landing) = &self.landing {
return landing.landed() || (self.drew_placeholder.get() && !landing.has_wake());
}
self.drew_placeholder.get()
}
pub(crate) fn awaits_pipelines(&self) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if let Some(landing) = &self.landing {
return self.drew_placeholder.get() && landing.in_flight();
}
self.drew_placeholder.get()
}
pub(super) fn image_bind_groups(
&self,
view: &wgpu::TextureView,
format: ImagePixelFormat,
) -> ImageBindGroups {
ImageBindGroups {
alpha_mask: matches!(format, ImagePixelFormat::Alpha8 { .. }),
nearest: self.image_bind_group(view, &self.image_nearest_sampler),
linear: self.image_bind_group(view, &self.image_linear_sampler),
}
}
fn image_bind_group(
&self,
view: &wgpu::TextureView,
sampler: &wgpu::Sampler,
) -> wgpu::BindGroup {
self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Image Texture Bind Group"),
layout: &self.image_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(sampler),
},
],
})
}
}