Skip to main content

cranpose_render_wgpu/
render.rs

1use std::{
2    borrow::Cow,
3    cell::Cell,
4    hash::{Hash, Hasher},
5    rc::Rc,
6    sync::{Arc, mpsc},
7    time::Duration,
8};
9
10use bytemuck::{Pod, Zeroable};
11use cranpose_core::{
12    NodeId,
13    collections::{bounded_lru::BoundedLruCache, map::HashMap},
14    hash::default as default_hash,
15};
16use cranpose_render_common::{
17    geometry::blur_reach,
18    graph::{DrawCommandId, quad_bounds},
19    software_text_raster::{
20        SoftwareGlyphAtlasGlyph, SoftwareGlyphAtlasKey, SoftwareGlyphAtlasPlacement,
21        SoftwareGlyphAtlasRunGlyph, SoftwareGlyphRasterCache, SoftwareTextFontSet,
22        collect_solid_text_atlas_run, rasterize_annotated_text_region,
23    },
24    text_mask_gamma::TextLuminance,
25};
26use cranpose_ui_graphics::{
27    BlendMode, Color, ColorFilter, FRAGMENT_KIND_ARC, FRAGMENT_KIND_FILL, FRAGMENT_KIND_LINE,
28    FRAGMENT_KIND_STROKE, FRAGMENT_KIND_TRAPEZOID, FxHasher, ImageBitmap, ImageSampling, Point,
29    RecordLane, RecordSegment, Rect, RenderHash, TileMode,
30};
31use smallvec::SmallVec;
32use web_time::Instant;
33
34use crate::{
35    DebugCpuAllocationStats,
36    ablation::{Ablation, ShapeAblation},
37    arc_trig_fill::ArcTrigFill,
38    collect::LayerScene,
39    debug_toggles::DebugToggle,
40    draw_pass::{
41        PassSegment, PassTarget, ResolvedComposite, ResolvedCompositeKind, SourceContent,
42        TrackedPass,
43    },
44    effect_renderer::{CompositeSampleMode, EffectRenderer, RoundedCompositeMask},
45    fixed_pipeline::{FixedPipeline, FixedPipelineJob},
46    frame::{AdmissionGate, FrameExecutor, StageSideScratch},
47    frame_graph::{
48        BufferUpload, FrameCommandRecorder, FrameCommandStats, FrameTextureDescriptor,
49        FrameUploadAllocators, UniformUpload, UploadAllocatorId, UploadAllocatorSpec, UploadMode,
50        WgpuFrameGraph, WgpuFrameGraphExecutor,
51    },
52    frame_packet::{CancelReason, FramePacket, FrameSceneStorage, PresentOutcome, RenderReturns},
53    geometry::{
54        DevicePixelBounds, SegmentTransform, anchored_device_rect, axis_aligned_quad_rect,
55        canonicalize_device_coordinate, canonicalized_scaled_quad, offscreen_byte_size,
56        scaled_quad, snap_delta_for_anchor, snapped_anchor_device_origin, translate_quad,
57        translation_stable_anchored_device_pixel_bounds,
58    },
59    glyph_run::{RunGlyphBox, RunGlyphScratch, RunGlyphs},
60    glyph_run_arena::{GlyphRunArena, GlyphRunSpan},
61    gpu_stats::{self, gpu_stats_enabled},
62    idle_pool::FrameScratch,
63    layer_cache::LayerCache,
64    lazy_resource::Pending,
65    offscreen::{COMPOSITION_BYTES_PER_PIXEL, OffscreenTarget},
66    output_conversion::OutputConverter,
67    pipeline_compiler::{CompileLane, CompilerSend, PipelineCompilation, PipelineCompiler},
68    record_columns::record_vertex_layouts,
69    rect_to_quad,
70    rrect_shadow::{SHADOW_QUAD_CORNERS, ShadowInstance, create_rrect_shadow_pipeline},
71    run_store::{ArenaBinding, PlacementData, RunBufferMode, RunDrawCall, RunStore, StoredTables},
72    scene::{
73        CompositorScene, DrawOp, DrawOpKind, DrawnText, ImageDraw, RunDraw, ShadowDraw, SnapAnchor,
74        TextDraw,
75    },
76    shaders,
77    shape_pipelines::{PipelineDemand, ShapePipelineFactory, ShapePipelines},
78    shared_shader::{ShaderCode, SharedShader},
79};
80const MAX_SHADOW_SURFACE_CACHE_ITEMS: usize = 512;
81const MAX_TRANSPARENT_SOURCES: usize = 16;
82const MAX_SHADOW_SURFACE_CACHE_BYTES: u64 = 384 * 1024 * 1024;
83
84static SKIP_SHADOWS: DebugToggle = DebugToggle::new("CRANPOSE_SKIP_SHADOWS");
85
86fn skip_shadow_draws() -> bool {
87    SKIP_SHADOWS.flag()
88}
89const MAX_TEXT_IMAGE_CACHE_ITEMS: usize = 1024;
90const MAX_TEXT_GLYPH_MASK_CACHE_ITEMS: usize = 8192;
91const MAX_TEXT_GLYPH_ATLAS_ITEMS: usize = 8192;
92/// The fewest text runs the run cache holds. It holds twice the runs the
93/// last frame drew when that is more, so a frame never evicts runs the next
94/// one draws again; idle runs leave it after `TEXT_GLYPH_RUN_IDLE_FRAMES`.
95const MIN_TEXT_GLYPH_RUN_CACHE_ITEMS: usize = 1024;
96const MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS: usize = 1024;
97/// Frames a text run may go undrawn before its glyphs and quads are freed,
98/// on the CPU and in retained GPU buffers alike. Shorter than the shape
99/// store's span: a list scrolling at speed leaves several screens of text
100/// behind each second, which at 120 frames held 12 to 19 MB of GPU quads on
101/// a scrolling feed, and the CPU runs, bounded only by their count, held
102/// another 4.6 MB of placements and quads.
103const TEXT_GLYPH_RUN_IDLE_FRAMES: u64 = 30;
104/// Frames a retained run's quads stay on the GPU undrawn. Writing a run's
105/// quads again costs far less than laying its glyphs out, which the CPU run
106/// keeps for [`TEXT_GLYPH_RUN_IDLE_FRAMES`]. On the desktop gauntlet at tier
107/// 16, 270 retained runs drew each frame while 30 frames held 650 of them;
108/// 8 frames hold 400 and write 25 runs a frame again instead of 16.
109const TEXT_GLYPH_GPU_RUN_IDLE_FRAMES: u64 = 8;
110/// Text runs with at least this many glyphs keep their quads in retained GPU
111/// buffers and draw on their own; shorter ones are written into the frame's
112/// shared quads each frame, where consecutive runs share a draw.
113const RETAINED_TEXT_GLYPH_RUN_MIN_QUADS: usize = 64;
114
115const TEXT_GLYPH_ATLAS_MIN_SIZE: u32 = 512;
116const TEXT_GLYPH_ATLAS_MAX_SIZE: u32 = 4096;
117const _: () = assert!(TEXT_GLYPH_ATLAS_MAX_SIZE <= u16::MAX as u32);
118const TEXT_GLYPH_ATLAS_PADDING: u32 = 1;
119const MAX_TEXT_LINE_INDEX_CACHE_ITEMS: usize = 512;
120const MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER: usize = 2;
121
122const CACHE_MISS_WARMUP_FRAMES: u8 = 1;
123pub(crate) const CLEAR_COLOR: wgpu::Color = wgpu::Color {
124    r: cranpose_render_common::FRAME_CLEAR_COLOR[0] as f64,
125    g: cranpose_render_common::FRAME_CLEAR_COLOR[1] as f64,
126    b: cranpose_render_common::FRAME_CLEAR_COLOR[2] as f64,
127    a: cranpose_render_common::FRAME_CLEAR_COLOR[3] as f64,
128};
129const MAX_TEXTURE_CACHE_ITEMS: usize = 256;
130const MAX_IMAGE_TEXTURE_CACHE_BYTES: usize = 256 * 1024 * 1024;
131const MAX_EXTERNAL_TEXTURE_BINDINGS: usize = 8;
132
133const DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS: f64 = 4.0;
134
135fn wgpu_render_stage_telemetry_threshold_ms() -> Option<f64> {
136    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
137    *THRESHOLD_MS.get_or_init(|| {
138        let explicit =
139            crate::debug_toggles::debug_toggle("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY_MS")
140                .and_then(|value| value.parse::<f64>().ok())
141                .filter(|value| value.is_finite() && *value >= 0.0);
142        explicit.or_else(|| {
143            std::env::var_os("CRANPOSE_WGPU_RENDER_STAGE_TELEMETRY")
144                .is_some()
145                .then_some(DEFAULT_WGPU_RENDER_STAGE_TELEMETRY_THRESHOLD_MS)
146        })
147    })
148}
149
150pub(crate) fn instant_ms(start: Instant, end: Instant) -> f64 {
151    end.duration_since(start).as_secs_f64() * 1000.0
152}
153
154pub(crate) fn should_log_wgpu_render_stage(start: Instant, end: Instant) -> Option<f64> {
155    let threshold_ms = wgpu_render_stage_telemetry_threshold_ms()?;
156    let total_ms = instant_ms(start, end);
157    (total_ms >= threshold_ms).then_some(total_ms)
158}
159
160pub static PRESENTED_FRAMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
161
162pub fn frames_presented() -> u64 {
163    PRESENTED_FRAMES.load(std::sync::atomic::Ordering::Relaxed)
164}
165
166fn text_atlas_fallback_diag_enabled() -> bool {
167    cranpose_core::env_flag!("CRANPOSE_TEXT_ATLAS_FALLBACK_DIAG")
168}
169
170#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
171struct ShadowSurfaceCacheKey {
172    content_hash: u64,
173    pixel_size: [u32; 2],
174    root_scale_bits: u32,
175    blur_radius_bits: u32,
176}
177
178struct CachedShadowSurface {
179    target: Rc<OffscreenTarget>,
180    byte_size: u64,
181}
182
183type DeviceRect4 = (f32, f32, f32, f32);
184/// A rect of whole target pixels: x, y, width, height.
185pub(crate) type TargetRect = (u32, u32, u32, u32);
186
187/// The target pixels a clipped shape variant keeps of `placement`'s records
188/// under `viewport`, as a scissor that stands in for its clip test: every
189/// pixel whose centre, moved by the viewport's offset, lies inside the
190/// device clip, inclusive of its edges, as the shader compares them. `None`
191/// without a clip or under a turn, where the variant tests the clip itself.
192/// An empty clip keeps an empty scissor.
193pub(crate) fn clip_scissor(
194    placement: &crate::scene::Placement,
195    root_scale: f32,
196    viewport: ViewportUniformParams,
197) -> Option<TargetRect> {
198    if !viewport.transform.is_identity() {
199        return None;
200    }
201    let [x, y, width, height] = crate::run_store::device_clip(placement, root_scale)?;
202    let columns = kept_pixels(x, x + width, viewport.offset[0], viewport.width);
203    let rows = kept_pixels(y, y + height, viewport.offset[1], viewport.height);
204    Some((
205        columns.start,
206        rows.start,
207        columns.end - columns.start,
208        rows.end - rows.start,
209    ))
210}
211
212/// The pixels along one axis whose centre, moved by `offset`, lies within
213/// `low..=high`, within `0..extent`: stepped with the shader's own float
214/// sums so the edges fall where its comparisons put them.
215fn kept_pixels(low: f32, high: f32, offset: f32, extent: u32) -> std::ops::Range<u32> {
216    let centre = |pixel: u32| pixel as f32 + 0.5 + offset;
217    let guess = |edge: f32| (edge - offset - 0.5).ceil().clamp(0.0, extent as f32) as u32;
218    let mut start = guess(low);
219    while start > 0 && centre(start - 1) >= low {
220        start -= 1;
221    }
222    while start < extent && centre(start) < low {
223        start += 1;
224    }
225    let mut end = guess(high).max(start);
226    while end > start && centre(end - 1) > high {
227        end -= 1;
228    }
229    while end < extent && centre(end) <= high {
230        end += 1;
231    }
232    start..end
233}
234
235/// The pixels both scissors keep, `None` when they share none.
236pub(crate) fn intersect_target_rects(a: TargetRect, b: TargetRect) -> Option<TargetRect> {
237    let left = a.0.max(b.0);
238    let top = a.1.max(b.1);
239    let right = (a.0 + a.2).min(b.0 + b.2);
240    let bottom = (a.1 + a.3).min(b.1 + b.3);
241    (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
242}
243
244/// A draw's scissor cut down to the pixels its pass segment may touch;
245/// `None` when nothing of it remains.
246pub(crate) fn bounded_scissor(
247    scissor: (u32, u32, u32, u32),
248    bound: Option<(u32, u32, u32, u32)>,
249) -> Option<(u32, u32, u32, u32)> {
250    let Some((bx, by, bw, bh)) = bound else {
251        return Some(scissor);
252    };
253    let (x, y, width, height) = scissor;
254    let left = x.max(bx);
255    let top = y.max(by);
256    let right = (x + width).min(bx + bw);
257    let bottom = (y + height).min(by + bh);
258    (right > left && bottom > top).then(|| (left, top, right - left, bottom - top))
259}
260
261#[derive(Clone, Copy, Debug, PartialEq)]
262pub(crate) struct GlyphExtent {
263    left: f32,
264    top: f32,
265    right: f32,
266    bottom: f32,
267}
268
269impl GlyphExtent {
270    pub(crate) const EMPTY: Self = Self {
271        left: f32::INFINITY,
272        top: f32::INFINITY,
273        right: f32::NEG_INFINITY,
274        bottom: f32::NEG_INFINITY,
275    };
276
277    pub(crate) fn add(&mut self, rect: [f32; 4]) {
278        self.left = self.left.min(rect[0]);
279        self.top = self.top.min(rect[1]);
280        self.right = self.right.max(rect[2]);
281        self.bottom = self.bottom.max(rect[3]);
282    }
283}
284
285/// The scissor an unturned shared glyph run needs and the target pixels it
286/// touches. A run whose quads all lie inside `scissor` needs none of its own,
287/// which lets it share a draw with its neighbours. A turned run never needs
288/// one: its quads were cut to its clip before the turn.
289fn shared_glyph_clip(
290    extent: GlyphExtent,
291    scissor: TargetRect,
292    viewport: ViewportUniformParams,
293) -> (Option<TargetRect>, TargetRect) {
294    let GlyphExtent {
295        left,
296        top,
297        right,
298        bottom,
299    } = extent;
300    if left > right {
301        return (Some(scissor), scissor);
302    }
303    let left = (left - viewport.offset[0]).floor().max(0.0);
304    let top = (top - viewport.offset[1]).floor().max(0.0);
305    let right = (right - viewport.offset[0]).ceil();
306    let bottom = (bottom - viewport.offset[1]).ceil();
307    let (x, y, width, height) = scissor;
308    let inside = left >= x as f32
309        && top >= y as f32
310        && right <= (x + width) as f32
311        && bottom <= (y + height) as f32;
312    if !inside || right <= left || bottom <= top {
313        return (Some(scissor), scissor);
314    }
315    let bounds = (
316        left as u32,
317        top as u32,
318        (right - left) as u32,
319        (bottom - top) as u32,
320    );
321    (None, bounds)
322}
323
324fn intersect_device_rects(a: DeviceRect4, b: DeviceRect4) -> Option<DeviceRect4> {
325    let left = a.0.max(b.0);
326    let top = a.1.max(b.1);
327    let right = (a.0 + a.2).min(b.0 + b.2);
328    let bottom = (a.1 + a.3).min(b.1 + b.3);
329    (right > left && bottom > top).then_some((left, top, right - left, bottom - top))
330}
331
332pub(crate) fn anchored_rect_to_device(
333    rect: Rect,
334    snap_anchor: Option<SnapAnchor>,
335    root_scale: f32,
336) -> DeviceRect4 {
337    let device = anchored_device_rect(rect, snap_anchor, root_scale);
338    (device.x, device.y, device.width, device.height)
339}
340
341fn mask_rect(rect: Rect) -> [f32; 4] {
342    [rect.x, rect.y, rect.width, rect.height]
343}
344
345#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
346struct TextImageCacheKey(u64);
347
348struct CachedTextImage {
349    image: ImageBitmap,
350}
351
352#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
353struct TextGlyphRunCacheKey(u64);
354
355#[derive(Clone, Copy)]
356struct CachedTextGlyphQuad {
357    x: i32,
358    y: i32,
359    width: usize,
360    height: usize,
361    color: (f32, f32, f32, f32),
362    uv: ImageUvRect,
363}
364
365struct CachedTextGlyphRun {
366    /// The run's glyphs that draw: zero-sized and transparent ones are left
367    /// out when the run is collected.
368    glyphs: RunGlyphs,
369    bounds: GlyphRunBounds,
370    /// Where each of `glyphs` sits in the atlas at `atlas_generation`. A
371    /// glyph's quad is derived from the two as it is drawn, so no glyph is
372    /// held twice.
373    atlas_entries: Option<Rc<[GlyphAtlasEntry]>>,
374    atlas_generation: u64,
375    /// The frame the run last drew in; see [`TEXT_GLYPH_RUN_IDLE_FRAMES`].
376    last_frame: Cell<u64>,
377}
378
379/// A cached run drawn as quads: its glyphs and their atlas entries, each
380/// quad derived as it is read.
381#[derive(Clone, Copy)]
382struct GlyphRunQuads<'a> {
383    glyphs: &'a RunGlyphs,
384    entries: &'a [GlyphAtlasEntry],
385    /// One atlas texel's share of the atlas side: see
386    /// [`TextGlyphAtlas::texel`].
387    texel: f32,
388    bounds: GlyphRunBounds,
389}
390
391/// The pixel box a run's drawing glyphs cover, from its raster origin.
392#[derive(Clone, Copy, Debug, PartialEq)]
393struct GlyphRunBounds {
394    min: [i32; 2],
395    max: [i32; 2],
396}
397
398impl GlyphRunBounds {
399    fn of(glyphs: impl IntoIterator<Item = SoftwareGlyphAtlasPlacement>) -> Self {
400        let mut bounds = Self {
401            min: [i32::MAX; 2],
402            max: [i32::MIN; 2],
403        };
404        for glyph in glyphs {
405            let width = i32::try_from(glyph.width).unwrap_or(i32::MAX);
406            let height = i32::try_from(glyph.height).unwrap_or(i32::MAX);
407            bounds.min = [bounds.min[0].min(glyph.x), bounds.min[1].min(glyph.y)];
408            bounds.max = [
409                bounds.max[0].max(glyph.x.saturating_add(width)),
410                bounds.max[1].max(glyph.y.saturating_add(height)),
411            ];
412        }
413        bounds
414    }
415
416    /// The box the glyphs cover from `origin`, as left, top, right, bottom.
417    fn at(self, origin: [f32; 2]) -> [f32; 4] {
418        [
419            origin[0] + self.min[0] as f32,
420            origin[1] + self.min[1] as f32,
421            origin[0] + self.max[0] as f32,
422            origin[1] + self.max[1] as f32,
423        ]
424    }
425
426    /// Whether every glyph of the run at `source_raster_rect` lies inside
427    /// what `viewport` shows of `clip`, so none needs its own test.
428    fn within_viewport(
429        self,
430        source_raster_rect: Rect,
431        clip: Option<Rect>,
432        viewport: ViewportUniformParams,
433        root_scale: f32,
434    ) -> bool {
435        if self.min[0] > self.max[0] || !root_scale.is_finite() || root_scale <= 0.0 {
436            return false;
437        }
438        let left = (source_raster_rect.x + self.min[0] as f32) / root_scale;
439        let top = (source_raster_rect.y + self.min[1] as f32) / root_scale;
440        let right = (source_raster_rect.x + self.max[0] as f32) / root_scale;
441        let bottom = (source_raster_rect.y + self.max[1] as f32) / root_scale;
442        let viewport_rect = viewport.scene_rect(root_scale);
443        let visible = match clip {
444            Some(clip) => clip.intersect(viewport_rect),
445            None => Some(viewport_rect),
446        };
447        visible
448            .is_some_and(|visible| visible.contains(left, top) && visible.contains(right, bottom))
449    }
450}
451
452/// A text's glyph run as the frame found it.
453struct TextGlyphRunLookup {
454    glyphs: RunGlyphs,
455    bounds: GlyphRunBounds,
456    /// Whether the run came from the cache rather than from this frame's
457    /// collection.
458    cached: bool,
459    /// The glyphs' atlas entries, while the atlas they were taken from holds.
460    entries: Option<Rc<[GlyphAtlasEntry]>>,
461}
462
463/// A text's glyph run and where it draws.
464struct TextGlyphRunDraw<'a> {
465    text_draw: &'a TextDraw,
466    raster_rect: Rect,
467    run_key: TextGlyphRunCacheKey,
468    run: TextGlyphRunLookup,
469}
470
471/// Logs why a text fell back from the glyph atlas, when
472/// `CRANPOSE_TEXT_ATLAS_FALLBACK_DIAG` asks.
473fn log_text_atlas_fallback(text_draw: &TextDraw) {
474    if !text_atlas_fallback_diag_enabled() {
475        return;
476    }
477    let preview: String = text_draw.text.string().text().chars().take(96).collect();
478    log::warn!(
479        "[text-atlas-fallback] node={:?} spans={} links={} text_len={} preview={:?} span_style={:?} paragraph_style={:?}",
480        text_draw.node_id,
481        text_draw.text.string().span_styles().len(),
482        text_draw.text.string().links().len(),
483        text_draw.text.string().text().len(),
484        preview,
485        text_draw.text_style.span_style,
486        text_draw.text_style.paragraph_style,
487    );
488}
489
490impl GlyphRunQuads<'_> {
491    fn len(&self) -> usize {
492        self.entries.len()
493    }
494
495    /// Each glyph as an instance at `origin`. Every glyph of a run draws: its
496    /// collection leaves out the zero-sized and the transparent ones.
497    fn instances_at(&self, origin: [f32; 2]) -> impl Iterator<Item = GlyphInstance> + '_ {
498        let texel = self.texel;
499        self.glyphs
500            .boxes()
501            .zip(self.entries)
502            .map(move |(glyph, entry)| {
503                let x0 = origin[0] + glyph.x as f32;
504                let y0 = origin[1] + glyph.y as f32;
505                let uv = glyph_atlas_uv_rect(*entry, texel);
506                GlyphInstance {
507                    rect: [
508                        x0,
509                        y0,
510                        x0 + f32::from(glyph.width),
511                        y0 + f32::from(glyph.height),
512                    ],
513                    uv: [uv.min[0], uv.min[1], uv.max[0], uv.max[1]],
514                    uv_bounds: uv.sample_bounds,
515                    color: [
516                        glyph.color.0.clamp(0.0, 1.0),
517                        glyph.color.1.clamp(0.0, 1.0),
518                        glyph.color.2.clamp(0.0, 1.0),
519                        glyph.color.3.clamp(0.0, 1.0),
520                    ],
521                }
522            })
523    }
524
525    fn iter(&self) -> impl Iterator<Item = CachedTextGlyphQuad> + '_ {
526        self.glyphs
527            .boxes()
528            .zip(self.entries)
529            .map(|(glyph, entry)| cached_text_glyph_quad(&glyph, *entry, self.texel))
530    }
531}
532
533struct CachedGpuTextGlyphRun {
534    span: GlyphRunSpan,
535    atlas_generation: u64,
536    /// The frame the run last drew in; a run idle for
537    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] gives its quads back.
538    last_frame: Cell<u64>,
539}
540
541#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
542struct TextLineIndexCacheKey(usize);
543
544struct CachedTextLineIndex {
545    text: std::sync::Weak<cranpose_ui::text::RenderString>,
546    len: usize,
547    starts: Rc<[usize]>,
548}
549
550struct TextLineIndexCache {
551    entries: BoundedLruCache<TextLineIndexCacheKey, CachedTextLineIndex>,
552}
553
554impl TextLineIndexCache {
555    fn new(capacity: usize) -> Self {
556        Self {
557            entries: BoundedLruCache::with_capacity_at_least_one(capacity),
558        }
559    }
560
561    fn line_starts(&mut self, text: &Arc<cranpose_ui::text::RenderString>) -> Rc<[usize]> {
562        let key = TextLineIndexCacheKey(Arc::as_ptr(text) as usize);
563        if let Some(cached) = self.entries.get(&key)
564            && cached.len == text.text().len()
565            && cached
566                .text
567                .upgrade()
568                .is_some_and(|cached_text| Arc::ptr_eq(&cached_text, text))
569        {
570            return cached.starts.clone();
571        }
572
573        let starts = Rc::<[usize]>::from(line_start_offsets(text.text()));
574        self.entries.put(
575            key,
576            CachedTextLineIndex {
577                text: Arc::downgrade(text),
578                len: text.text().len(),
579                starts: starts.clone(),
580            },
581        );
582        starts
583    }
584}
585
586#[derive(Default)]
587struct DeviceErrorSentry {
588    errors: std::sync::atomic::AtomicU64,
589    poisoned: std::sync::atomic::AtomicBool,
590}
591
592impl DeviceErrorSentry {
593    fn record(&self, error: &wgpu::Error) {
594        use std::sync::atomic::Ordering;
595        self.poisoned.store(true, Ordering::Release);
596        let count = self.errors.fetch_add(1, Ordering::Relaxed) + 1;
597        if count.is_power_of_two() {
598            log::error!("[gpu-device] uncaptured wgpu error #{count}: {error}");
599        }
600    }
601
602    fn take_poison(&self) -> bool {
603        self.poisoned
604            .swap(false, std::sync::atomic::Ordering::AcqRel)
605    }
606
607    fn error_count(&self) -> u64 {
608        self.errors.load(std::sync::atomic::Ordering::Relaxed)
609    }
610}
611
612fn is_blend_mode_supported(mode: BlendMode) -> bool {
613    matches!(
614        mode,
615        BlendMode::Src | BlendMode::SrcOver | BlendMode::DstOut
616    )
617}
618
619pub(crate) fn blend_state_for_mode(mode: BlendMode) -> wgpu::BlendState {
620    match mode {
621        BlendMode::Src => wgpu::BlendState::REPLACE,
622        BlendMode::DstOut => wgpu::BlendState {
623            color: wgpu::BlendComponent {
624                src_factor: wgpu::BlendFactor::Zero,
625                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
626                operation: wgpu::BlendOperation::Add,
627            },
628            alpha: wgpu::BlendComponent {
629                src_factor: wgpu::BlendFactor::Zero,
630                dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha,
631                operation: wgpu::BlendOperation::Add,
632            },
633        },
634        _ => wgpu::BlendState::ALPHA_BLENDING,
635    }
636}
637
638pub(crate) fn supported_blend_mode(mode: BlendMode) -> BlendMode {
639    if is_blend_mode_supported(mode) {
640        return mode;
641    }
642
643    BlendMode::SrcOver
644}
645
646pub(crate) fn hash_f32_for_cache<H: Hasher>(value: f32, state: &mut H) {
647    value.to_bits().hash(state);
648}
649
650fn hash_text_raster_geometry_for_cache<H: Hasher>(
651    rect: Rect,
652    static_text_motion: bool,
653    state: &mut H,
654) {
655    hash_f32_for_cache(rect.width, state);
656    hash_f32_for_cache(rect.height, state);
657    static_text_motion.hash(state);
658    if !static_text_motion {
659        hash_f32_for_cache(rect.x.fract(), state);
660        hash_f32_for_cache(rect.y.fract(), state);
661    }
662}
663
664/// Hashes what a text draws apart from where and how large its rect is.
665fn hash_text_draw_for_cache<H: Hasher>(
666    text_draw: &TextDraw,
667    raster_rect: Rect,
668    text_scale: f32,
669    state: &mut H,
670) {
671    text_draw.text.render_hash().hash(state);
672    text_draw.style_hash.hash(state);
673    text_draw.color.render_hash().hash(state);
674    hash_text_gradient_phase_for_cache(text_draw, raster_rect, state);
675    text_draw.font_size.to_bits().hash(state);
676    text_scale.to_bits().hash(state);
677    text_draw.layout_options.hash(state);
678}
679
680pub(crate) fn hash_text_gradient_phase_for_cache<H: Hasher>(
681    text_draw: &TextDraw,
682    raster_rect: Rect,
683    state: &mut H,
684) {
685    if text_draw.text.gradient() {
686        for coordinate in [raster_rect.x, raster_rect.y] {
687            let phase = if coordinate >= 0.0 {
688                coordinate.rem_euclid(4.0)
689            } else {
690                coordinate
691            };
692            phase.to_bits().hash(state);
693        }
694    }
695}
696
697/// Where a text draws in the scene, snapped, and the scale its glyphs
698/// raster at; `None` for a text that draws nothing.
699pub(crate) fn text_logical_geometry_for_draw(
700    text_draw: &TextDraw,
701    root_scale: f32,
702) -> Option<(Rect, f32)> {
703    if text_draw.text.is_empty()
704        || text_draw.rect.width <= 0.0
705        || text_draw.rect.height <= 0.0
706        || !root_scale.is_finite()
707        || root_scale <= 0.0
708    {
709        return None;
710    }
711
712    let text_scale = text_draw.scale * root_scale;
713    if !text_scale.is_finite() || text_scale <= 0.0 {
714        return None;
715    }
716
717    let snap_delta = text_draw
718        .snap_anchor
719        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
720        .unwrap_or_default();
721    let logical_rect = text_draw.rect.translate(snap_delta.x, snap_delta.y);
722    Some((logical_rect, text_scale))
723}
724
725pub(crate) fn text_raster_geometry_for_draw(
726    text_draw: &TextDraw,
727    root_scale: f32,
728) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
729    text_logical_geometry_for_draw(text_draw, root_scale)
730        .map(|logical| text_raster_geometry_at(text_draw, logical, root_scale))
731}
732
733/// The raster geometry of a text whose logical geometry is
734/// `(logical_rect, text_scale)`: see [`text_raster_geometry_for_draw`].
735fn text_raster_geometry_at(
736    text_draw: &TextDraw,
737    (logical_rect, text_scale): (Rect, f32),
738    root_scale: f32,
739) -> (Rect, Rect, Option<Rect>, f32, bool) {
740    let static_text_motion = text_draw.text.static_motion();
741    let clip = text_draw.clip;
742    let mut raster_rect = Rect {
743        x: logical_rect.x * root_scale,
744        y: logical_rect.y * root_scale,
745        width: logical_rect.width * root_scale,
746        height: logical_rect.height * root_scale,
747    };
748    if text_draw.snap_anchor.is_some() {
749        raster_rect.x = canonicalize_device_coordinate(raster_rect.x);
750        raster_rect.y = canonicalize_device_coordinate(raster_rect.y);
751    }
752    if static_text_motion {
753        raster_rect.x = raster_rect.x.round();
754        raster_rect.y = raster_rect.y.round();
755    }
756    raster_rect.width = raster_rect.width.ceil().max(1.0);
757    raster_rect.height = raster_rect.height.ceil().max(1.0);
758    (
759        logical_rect,
760        raster_rect,
761        clip,
762        text_scale,
763        static_text_motion,
764    )
765}
766
767fn text_draw_is_visible_in_viewport(
768    logical_rect: Rect,
769    clip: Option<Rect>,
770    viewport: ViewportUniformParams,
771    root_scale: f32,
772) -> bool {
773    draw_rect_is_visible_in_viewport(logical_rect, clip, viewport, root_scale)
774}
775
776fn expand_rect(rect: Rect, margin_x: f32, margin_y: f32) -> Rect {
777    Rect {
778        x: rect.x - margin_x,
779        y: rect.y - margin_y,
780        width: rect.width + margin_x * 2.0,
781        height: rect.height + margin_y * 2.0,
782    }
783}
784
785fn draw_rect_is_visible_in_viewport(
786    rect: Rect,
787    clip: Option<Rect>,
788    viewport: ViewportUniformParams,
789    root_scale: f32,
790) -> bool {
791    if !root_scale.is_finite() || root_scale <= 0.0 {
792        return false;
793    }
794    rect_is_visible_in_rect(rect, clip, viewport.scene_rect(root_scale))
795}
796
797fn rect_is_visible_in_rect(rect: Rect, clip: Option<Rect>, viewport_rect: Rect) -> bool {
798    let visible_rect = match clip {
799        Some(clip) => clip.intersect(viewport_rect),
800        None => Some(viewport_rect),
801    };
802    visible_rect.is_some_and(|visible| rect.intersect(visible).is_some())
803}
804
805fn snapped_quad_bounds(quad: [[f32; 2]; 4], anchor: Option<SnapAnchor>, root_scale: f32) -> Rect {
806    let snap_delta = anchor
807        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
808        .unwrap_or_default();
809    quad_bounds(translate_quad(quad, snap_delta))
810}
811
812/// The logical rect a draw may touch: its snapped bounds within its clip,
813/// `None` when the clip leaves nothing.
814fn clipped_bounds(rect: Rect, clip: Option<Rect>) -> Option<Rect> {
815    match clip {
816        Some(clip) => rect.intersect(clip),
817        None => Some(rect),
818    }
819}
820
821pub(crate) fn text_draw_bounds(text: &TextDraw, root_scale: f32) -> Option<Rect> {
822    text_logical_geometry_for_draw(text, root_scale)
823        .and_then(|(logical_rect, _)| clipped_bounds(logical_rect, text.clip))
824}
825
826pub(crate) fn image_draw_bounds(image: &ImageDraw, root_scale: f32) -> Option<Rect> {
827    clipped_bounds(
828        snapped_quad_bounds(image.quad, image.snap_anchor, root_scale),
829        image.clip,
830    )
831}
832
833pub(crate) fn run_draw_bounds(run: &RunDraw, root_scale: f32) -> Option<Rect> {
834    let snap_delta = run
835        .placement
836        .snap_anchor
837        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
838        .unwrap_or_default();
839    clipped_bounds(
840        run.bounds.translate(snap_delta.x, snap_delta.y),
841        run.placement.clip,
842    )
843}
844
845/// The logical geometry of `text` (see [`text_logical_geometry_for_draw`])
846/// when it draws any pixel inside `viewport_rect`.
847pub(crate) fn text_draw_geometry_in_rect(
848    text: &TextDraw,
849    viewport_rect: Rect,
850    root_scale: f32,
851) -> Option<(Rect, f32)> {
852    text_logical_geometry_for_draw(text, root_scale).filter(|(logical_rect, _)| {
853        clipped_bounds(*logical_rect, text.clip)
854            .is_some_and(|bounds| bounds.intersect(viewport_rect).is_some())
855    })
856}
857
858fn cached_text_glyph_quad(
859    glyph: &RunGlyphBox,
860    entry: GlyphAtlasEntry,
861    texel: f32,
862) -> CachedTextGlyphQuad {
863    CachedTextGlyphQuad {
864        x: glyph.x,
865        y: glyph.y,
866        width: usize::from(glyph.width),
867        height: usize::from(glyph.height),
868        color: (
869            glyph.color.0.clamp(0.0, 1.0),
870            glyph.color.1.clamp(0.0, 1.0),
871            glyph.color.2.clamp(0.0, 1.0),
872            glyph.color.3.clamp(0.0, 1.0),
873        ),
874        uv: glyph_atlas_uv_rect(entry, texel),
875    }
876}
877
878/// `quad` at `source_raster_rect`'s origin. `None` for a quad that draws
879/// nothing.
880fn cached_text_glyph_instance(
881    source_raster_rect: Rect,
882    quad: &CachedTextGlyphQuad,
883) -> Option<GlyphInstance> {
884    if quad.width == 0 || quad.height == 0 || quad.color.3 <= 0.0 {
885        return None;
886    }
887    let x0 = source_raster_rect.x + quad.x as f32;
888    let y0 = source_raster_rect.y + quad.y as f32;
889    Some(GlyphInstance {
890        rect: [x0, y0, x0 + quad.width as f32, y0 + quad.height as f32],
891        uv: [
892            quad.uv.min[0],
893            quad.uv.min[1],
894            quad.uv.max[0],
895            quad.uv.max[1],
896        ],
897        uv_bounds: quad.uv.sample_bounds,
898        color: [quad.color.0, quad.color.1, quad.color.2, quad.color.3],
899    })
900}
901
902fn cached_text_glyph_quad_logical_rect(
903    source_raster_rect: Rect,
904    quad: &CachedTextGlyphQuad,
905    root_scale: f32,
906) -> Option<Rect> {
907    if !root_scale.is_finite() || root_scale <= 0.0 {
908        return None;
909    }
910    Some(Rect {
911        x: (source_raster_rect.x + quad.x as f32) / root_scale,
912        y: (source_raster_rect.y + quad.y as f32) / root_scale,
913        width: quad.width as f32 / root_scale,
914        height: quad.height as f32 / root_scale,
915    })
916}
917
918fn cached_text_glyph_quad_is_visible_in_viewport(
919    source_raster_rect: Rect,
920    quad: &CachedTextGlyphQuad,
921    clip: Option<Rect>,
922    viewport: ViewportUniformParams,
923    root_scale: f32,
924) -> bool {
925    cached_text_glyph_quad_logical_rect(source_raster_rect, quad, root_scale)
926        .is_some_and(|rect| draw_rect_is_visible_in_viewport(rect, clip, viewport, root_scale))
927}
928
929pub(crate) fn hash_device_offset<H: Hasher>(
930    value: f32,
931    origin: f32,
932    root_scale: f32,
933    state: &mut H,
934) {
935    hash_f32_for_cache((value - origin) * root_scale, state);
936}
937
938pub(crate) fn hash_device_rect<H: Hasher>(
939    rect: Rect,
940    origin_x: f32,
941    origin_y: f32,
942    root_scale: f32,
943    state: &mut H,
944) {
945    hash_device_offset(rect.x, origin_x, root_scale, state);
946    hash_device_offset(rect.y, origin_y, root_scale, state);
947    hash_device_offset(rect.width, 0.0, root_scale, state);
948    hash_device_offset(rect.height, 0.0, root_scale, state);
949}
950
951/// Hashes the rect `placement` is clipped to, `clip`, and its rounding, in
952/// device pixels from `origin`.
953fn hash_placement_clips<H: Hasher>(
954    placement: &crate::scene::Placement,
955    clip: Option<Rect>,
956    (origin_x, origin_y): (f32, f32),
957    root_scale: f32,
958    state: &mut H,
959) {
960    let rounding = placement.rounding;
961    for (rect, radius) in [
962        (clip, 0.0),
963        (
964            rounding.map(|rounding| rounding.rect),
965            rounding.map_or(0.0, |rounding| rounding.radius),
966        ),
967    ] {
968        rect.is_some().hash(state);
969        if let Some(rect) = rect {
970            let [x, y, width, height] =
971                crate::run_store::placement_device_rect(placement, rect, root_scale);
972            for value in [
973                x - origin_x,
974                y - origin_y,
975                width,
976                height,
977                radius * root_scale,
978            ] {
979                hash_f32_for_cache(value, state);
980            }
981        }
982    }
983}
984
985pub(crate) fn hash_run_item_with_clip<H: Hasher>(
986    run: &RunDraw,
987    clip: Option<Rect>,
988    origin_x: f32,
989    origin_y: f32,
990    root_scale: f32,
991    state: &mut H,
992) {
993    let tables = run.tables();
994    tables.fingerprint().hash(state);
995    run.segments.start.hash(state);
996    run.segments.end.hash(state);
997    let placement = &run.placement;
998    let snap = placement
999        .snap_anchor
1000        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
1001        .unwrap_or_default();
1002    let offset = Point::new(placement.offset.x + snap.x, placement.offset.y + snap.y);
1003    let canonicalize = placement.snap_anchor.is_some();
1004    canonicalize.hash(state);
1005    for segment in &tables.segments[run.segments.start as usize..run.segments.end as usize] {
1006        if segment.lane != RecordLane::Shapes {
1007            continue;
1008        }
1009        let exact_placement =
1010            !canonicalize || segment.kinds & ((1u8 << FRAGMENT_KIND_ARC) | LINE_KINDS) != 0;
1011        exact_placement.hash(state);
1012        if exact_placement {
1013            for value in [offset.x, offset.y, origin_x, origin_y, root_scale] {
1014                hash_f32_for_cache(value, state);
1015            }
1016            continue;
1017        }
1018        for index in segment.start..segment.start + segment.count {
1019            let record = tables
1020                .shapes
1021                .get(index as usize)
1022                .expect("shape segment record");
1023            let half_width = if record.is_stroked() {
1024                record.stroke_width * 0.5
1025            } else {
1026                0.0
1027            };
1028            let [left, top, right, bottom] = crate::run_geometry::device_shape_edges(
1029                record.rect,
1030                half_width,
1031                offset,
1032                root_scale,
1033                canonicalize,
1034            );
1035            for value in [left - origin_x, top - origin_y, right - left, bottom - top] {
1036                hash_f32_for_cache(value, state);
1037            }
1038        }
1039    }
1040    hash_placement_clips(placement, clip, (origin_x, origin_y), root_scale, state);
1041    if tables.segments[run.segments.start as usize..run.segments.end as usize]
1042        .iter()
1043        .any(|segment| segment.gradient || segment.vertex_gradient)
1044    {
1045        let dither = placement
1046            .snap_anchor
1047            .map(|anchor| snapped_anchor_device_origin(anchor, root_scale))
1048            .unwrap_or_default();
1049        hash_f32_for_cache(dither.x - origin_x, state);
1050        hash_f32_for_cache(dither.y - origin_y, state);
1051    }
1052    hash_f32_for_cache(placement.alpha, state);
1053    match &placement.color_filter {
1054        Some(filter) => {
1055            1u8.hash(state);
1056            filter.render_hash().hash(state);
1057        }
1058        None => 0u8.hash(state),
1059    }
1060}
1061
1062pub(crate) fn shadow_content_hash(shadow: &ShadowDraw, root_scale: f32) -> u64 {
1063    let mut hasher = FxHasher::default();
1064    let origin = shape_shadow_bounds(shadow).unwrap_or(Rect {
1065        x: 0.0,
1066        y: 0.0,
1067        width: 0.0,
1068        height: 0.0,
1069    });
1070    let device = anchored_device_rect(
1071        origin,
1072        shadow
1073            .shapes
1074            .as_ref()
1075            .and_then(|run| run.placement.snap_anchor),
1076        root_scale,
1077    );
1078    for run in shadow.shapes.iter().chain(&shadow.post_blur_cutouts) {
1079        hash_run_item_with_clip(
1080            run,
1081            run.placement.clip,
1082            device.x.floor(),
1083            device.y.floor(),
1084            root_scale,
1085            &mut hasher,
1086        );
1087    }
1088    hasher.finish()
1089}
1090
1091fn shape_shadow_surface_cache_key(
1092    shadow: &ShadowDraw,
1093    device_bounds: DevicePixelBounds,
1094    pixel_radius: f32,
1095    root_scale: f32,
1096) -> Option<ShadowSurfaceCacheKey> {
1097    (root_scale.is_finite() && root_scale > 0.0).then(|| ShadowSurfaceCacheKey {
1098        content_hash: shadow_content_hash(shadow, root_scale),
1099        pixel_size: [device_bounds.width, device_bounds.height],
1100        root_scale_bits: root_scale.to_bits(),
1101        blur_radius_bits: pixel_radius.to_bits(),
1102    })
1103}
1104
1105fn shape_shadow_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1106    shadow.shapes.as_ref().map(|run| run.bounds)
1107}
1108
1109pub(crate) fn shadow_draw_bounds(shadow: &ShadowDraw) -> Option<Rect> {
1110    shape_shadow_bounds(shadow)
1111        .into_iter()
1112        .chain(shadow.texts.iter().map(|text| text.rect))
1113        .reduce(|a, b| Rect {
1114            x: a.x.min(b.x),
1115            y: a.y.min(b.y),
1116            width: (a.x + a.width).max(b.x + b.width) - a.x.min(b.x),
1117            height: (a.y + a.height).max(b.y + b.height) - a.y.min(b.y),
1118        })
1119}
1120
1121/// The shape shader's source for `mode`, built when its module is parsed.
1122fn shape_shader_code(mode: RunBufferMode) -> ShaderCode {
1123    if mode.trig_fill {
1124        ShaderCode::wgsl(|| Cow::Owned(shaders::filling_shape_shader()))
1125    } else if mode.storage {
1126        ShaderCode::wgsl(|| Cow::Owned(shaders::storage_shape_shader()))
1127    } else {
1128        shaders::SHAPE
1129    }
1130}
1131
1132/// The vertex entry point of every fullscreen strip.
1133pub(crate) const FULLSCREEN_VS: &str = "fullscreen_vs";
1134
1135/// A pipeline that draws one full-screen triangle strip from `fullscreen_vs`
1136/// into a single color target, the shape every effect and composite pass
1137/// shares; `constants` fixes the shader's override constants.
1138#[expect(clippy::too_many_arguments)]
1139pub(crate) fn create_fullscreen_strip_pipeline(
1140    device: &wgpu::Device,
1141    cache: Option<&wgpu::PipelineCache>,
1142    log_label: &str,
1143    label: &'static str,
1144    layout: &wgpu::PipelineLayout,
1145    (vertex_module, fragment_module): (&wgpu::ShaderModule, &wgpu::ShaderModule),
1146    (vertex_entry, fragment_entry): (&'static str, &'static str),
1147    constants: &[(&str, f64)],
1148    (target, depth_stencil): (wgpu::ColorTargetState, Option<wgpu::DepthStencilState>),
1149) -> wgpu::RenderPipeline {
1150    create_render_pipeline_logged(
1151        device,
1152        cache,
1153        log_label,
1154        wgpu::RenderPipelineDescriptor {
1155            label: Some(label),
1156            layout: Some(layout),
1157            vertex: wgpu::VertexState {
1158                module: vertex_module,
1159                entry_point: Some(vertex_entry),
1160                buffers: &[],
1161                compilation_options: wgpu::PipelineCompilationOptions {
1162                    constants,
1163                    ..wgpu::PipelineCompilationOptions::default()
1164                },
1165            },
1166            fragment: Some(wgpu::FragmentState {
1167                module: fragment_module,
1168                entry_point: Some(fragment_entry),
1169                targets: &[Some(target)],
1170                compilation_options: wgpu::PipelineCompilationOptions {
1171                    constants,
1172                    ..wgpu::PipelineCompilationOptions::default()
1173                },
1174            }),
1175            primitive: wgpu::PrimitiveState {
1176                topology: wgpu::PrimitiveTopology::TriangleStrip,
1177                strip_index_format: None,
1178                front_face: wgpu::FrontFace::Ccw,
1179                cull_mode: None,
1180                ..Default::default()
1181            },
1182            depth_stencil,
1183            multisample: wgpu::MultisampleState::default(),
1184            multiview_mask: None,
1185            cache: None,
1186        },
1187    )
1188}
1189
1190pub(crate) fn create_render_pipeline_logged<'a>(
1191    device: &wgpu::Device,
1192    cache: Option<&'a wgpu::PipelineCache>,
1193    tag: &str,
1194    mut descriptor: wgpu::RenderPipelineDescriptor<'a>,
1195) -> wgpu::RenderPipeline {
1196    descriptor.cache = cache;
1197    build_pipeline_logged(tag, || device.create_render_pipeline(&descriptor))
1198}
1199
1200pub(crate) fn build_pipeline_logged<T>(tag: &str, build: impl FnOnce() -> T) -> T {
1201    let started = Instant::now();
1202    let pipeline = build();
1203    log::info!(
1204        "[pipeline-create] {tag} {:.1}ms on {}",
1205        instant_ms(started, Instant::now()),
1206        std::thread::current().name().unwrap_or("unnamed thread"),
1207    );
1208    crate::thread_state::with(|state| {
1209        if state.off_frame_builds.get() {
1210            PIPELINES_CREATED_OFF_FRAME.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1211        } else {
1212            PIPELINES_CREATED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1213            state.thread_builds.set(state.thread_builds.get() + 1);
1214        }
1215    });
1216    #[cfg(not(target_arch = "wasm32"))]
1217    crate::pipeline_disk_cache::note_change();
1218    pipeline
1219}
1220
1221/// Pipelines this process has built on a thread that draws.
1222///
1223/// A build runs the backend's shader compiler, and whoever asks for one while
1224/// drawing waits for it there. A count that grows across an interaction names
1225/// work a person waited on, whatever the driver's own caches made a compile
1226/// cost on this machine. Builds handed to [`crate::pipeline_compiler`] are
1227/// counted apart, by [`pipelines_created_off_frame`]: they cost a frame
1228/// nothing.
1229static PIPELINES_CREATED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1230static PIPELINES_CREATED_OFF_FRAME: std::sync::atomic::AtomicU64 =
1231    std::sync::atomic::AtomicU64::new(0);
1232
1233/// The pipelines this thread has built while drawing: a frame that drew
1234/// with this unchanged built nothing itself.
1235#[cfg(not(target_arch = "wasm32"))]
1236fn thread_builds() -> u64 {
1237    crate::thread_state::with(|state| state.thread_builds.get())
1238}
1239
1240/// Declares that pipelines built on this thread are built away from any
1241/// frame. The compiler thread says so once, when it starts.
1242#[cfg(not(target_arch = "wasm32"))]
1243pub(crate) fn mark_thread_off_frame() {
1244    crate::thread_state::with(|state| state.off_frame_builds.set(true));
1245}
1246
1247pub fn pipelines_created() -> u64 {
1248    PIPELINES_CREATED.load(std::sync::atomic::Ordering::Relaxed)
1249}
1250
1251/// Pipelines built away from every frame, on the compiler thread.
1252pub fn pipelines_created_off_frame() -> u64 {
1253    PIPELINES_CREATED_OFF_FRAME.load(std::sync::atomic::Ordering::Relaxed)
1254}
1255
1256#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1257#[repr(u8)]
1258pub(crate) enum RunTier {
1259    Store = 0,
1260    Arena = 1,
1261    Either = 2,
1262}
1263
1264#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1265pub(crate) struct ShapeVariant {
1266    kinds: u8,
1267    brush: Option<u8>,
1268    solid: bool,
1269    /// How its records meet their placements' clips. A rounded clip gives
1270    /// every fragment its coverage, on the general entry points.
1271    clip: SegmentClip,
1272    interior: bool,
1273    dither: bool,
1274    ablation: ShapeAblation,
1275}
1276
1277const FLAT_FILL_ENTRIES: [[(&str, &str); 2]; 2] = [
1278    [
1279        ("vs_record_plain_fill", "fs_plain_fill"),
1280        ("vs_record_dithered_fill", "fs_dithered_fill"),
1281    ],
1282    [
1283        ("vs_record_clipped_fill", "fs_clipped_fill"),
1284        ("vs_record_solid", "fs_solid"),
1285    ],
1286];
1287
1288/// The entry points of a variant that draws slices of path fills alone and
1289/// flat: a solid brush, and a gradient between two stops from the vertices.
1290const SLICE_ENTRIES: [(&str, &str); 2] = [
1291    ("vs_record_slice", "fs_slice"),
1292    ("vs_record_gradient_slice", "fs_gradient_slice"),
1293];
1294
1295const ALL_SHAPE_KINDS: u8 =
1296    (1 << FRAGMENT_KIND_FILL) | (1 << FRAGMENT_KIND_STROKE) | (1 << FRAGMENT_KIND_ARC) | LINE_KINDS;
1297/// The kinds the shader draws from line records: segments, and slices of
1298/// path fills. A variant compiles in the code of only those it draws.
1299const LINE_KINDS: u8 = (1 << FRAGMENT_KIND_LINE) | TRAPEZOID_KIND;
1300const TRAPEZOID_KIND: u8 = 1 << FRAGMENT_KIND_TRAPEZOID;
1301
1302fn variant_kinds(kinds: u8) -> u8 {
1303    if kinds.count_ones() <= 1 {
1304        kinds
1305    } else {
1306        (ALL_SHAPE_KINDS & !LINE_KINDS) | (kinds & LINE_KINDS)
1307    }
1308}
1309
1310impl ShapeVariant {
1311    /// Every kind but slices of path fills, which only a segment holding
1312    /// them compiles in.
1313    const GENERAL: Self = Self {
1314        kinds: ALL_SHAPE_KINDS & !TRAPEZOID_KIND,
1315        brush: None,
1316        solid: false,
1317        clip: SegmentClip::Tested,
1318        interior: true,
1319        dither: false,
1320        ablation: ShapeAblation {
1321            material: false,
1322            fill: false,
1323        },
1324    };
1325
1326    /// The variant `segment` draws with. `vertex_gradients` says a rect
1327    /// fill may take its gradient from its vertices here; a segment of
1328    /// slices of path fills may wherever it is drawn `flat`. Under a rounded
1329    /// clip the variant keeps the general entry points, which carry the
1330    /// clip's radius to the fragment, but compiles in only the segment's
1331    /// kinds and brush: the general program with every kind and brush is
1332    /// twice the code (Mali-G76: 108-115 ms to compile or link, the
1333    /// specialized ones 22-62).
1334    pub(crate) fn of_segment(
1335        segment: &RecordSegment,
1336        clip: SegmentClip,
1337        ablation: ShapeAblation,
1338        laid: bool,
1339        (flat, vertex_gradients): (bool, bool),
1340    ) -> Self {
1341        if !shape_variants_enabled() {
1342            return Self {
1343                kinds: Self::GENERAL.kinds | (segment.kinds & TRAPEZOID_KIND),
1344                ablation,
1345                ..Self::GENERAL
1346            }
1347            .clipped_by(clip);
1348        }
1349        let vertex_gradients = if segment.kinds == TRAPEZOID_KIND {
1350            flat
1351        } else {
1352            vertex_gradients
1353        };
1354        let gradient = segment.gradient || (segment.vertex_gradient && !vertex_gradients);
1355        Self {
1356            kinds: variant_kinds(segment.kinds),
1357            brush: gradient
1358                .then(|| segment.uniform_brush())
1359                .flatten()
1360                .map(|brush| brush as u8),
1361            solid: !gradient,
1362            clip,
1363            // A rounded clip's corners are not opaque: no interior path.
1364            interior: clip != SegmentClip::Rounded
1365                && gradient
1366                && segment.interiors
1367                && !(laid && segment.occluders && !segment.bare_interiors),
1368            dither: segment.vertex_gradient && vertex_gradients,
1369            ablation,
1370        }
1371    }
1372
1373    /// The one kind the variant draws, as the shader's packed kind names
1374    /// it: a slice of a path fill is a line record.
1375    fn kind(self) -> Option<u8> {
1376        (self.kinds.count_ones() == 1).then(|| match self.kinds.trailing_zeros() {
1377            FRAGMENT_KIND_TRAPEZOID => FRAGMENT_KIND_LINE as u8,
1378            kind => kind as u8,
1379        })
1380    }
1381
1382    /// The vertex and fragment entry points of this variant, for records
1383    /// drawn `flat` (none of them turned).
1384    fn entries(self, flat: bool) -> (&'static str, &'static str) {
1385        let fill = self.kind() == Some(FRAGMENT_KIND_FILL as u8);
1386        if self.rounded() {
1387            ("vs_record", "fs_main")
1388        } else if self.solid && flat && self.kinds == TRAPEZOID_KIND {
1389            SLICE_ENTRIES[usize::from(self.dither)]
1390        } else if self.solid && fill && flat {
1391            FLAT_FILL_ENTRIES[usize::from(self.clip == SegmentClip::Tested)]
1392                [usize::from(self.dither)]
1393        } else if self.solid {
1394            ("vs_record_solid", "fs_solid")
1395        } else if fill && !self.ablation.material {
1396            ("vs_record_gradient_fill", "fs_gradient_fill")
1397        } else {
1398            ("vs_record", "fs_main")
1399        }
1400    }
1401
1402    fn general(self) -> Self {
1403        Self {
1404            kinds: (ALL_SHAPE_KINDS & !LINE_KINDS) | (self.kinds & LINE_KINDS),
1405            ablation: self.ablation,
1406            ..Self::GENERAL
1407        }
1408        .clipped_by(self.clip)
1409    }
1410
1411    /// The general variant with every kind, lines and path slices too.
1412    fn universal(self) -> Self {
1413        Self {
1414            kinds: ALL_SHAPE_KINDS,
1415            ablation: self.ablation,
1416            ..Self::GENERAL
1417        }
1418        .clipped_by(self.clip)
1419    }
1420
1421    /// The variant, keeping the rounded clip `clip` names: the general
1422    /// variant tests every rect clip, but no fallback may drop a rounding.
1423    fn clipped_by(self, clip: SegmentClip) -> Self {
1424        if clip == SegmentClip::Rounded {
1425            Self { clip, ..self }
1426        } else {
1427            self
1428        }
1429    }
1430
1431    fn rounded(self) -> bool {
1432        self.clip == SegmentClip::Rounded
1433    }
1434
1435    fn joined(self) -> Self {
1436        if self.solid {
1437            Self {
1438                dither: true,
1439                ..self
1440            }
1441        } else {
1442            Self {
1443                interior: true,
1444                ..self
1445            }
1446        }
1447    }
1448}
1449
1450/// How a segment's draw meets its placement's clip: a scissor or no clip
1451/// leaves the shader nothing to test, a rect clip off the scissor's grid is
1452/// tested per fragment, and a rounded clip gives every fragment coverage.
1453#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1454pub(crate) enum SegmentClip {
1455    Untested,
1456    Tested,
1457    Rounded,
1458}
1459
1460impl SegmentClip {
1461    /// The clip a draw under `placement` tests, given whether its rect clip
1462    /// became the draw's scissor.
1463    pub(crate) fn of(placement: &crate::scene::Placement, scissored: bool) -> Self {
1464        if placement.clip_rounded() {
1465            Self::Rounded
1466        } else if placement.clip.is_some() && !scissored {
1467            Self::Tested
1468        } else {
1469            Self::Untested
1470        }
1471    }
1472}
1473
1474static SHAPE_VARIANTS: DebugToggle = DebugToggle::new("CRANPOSE_SHAPE_VARIANTS");
1475
1476fn shape_variants_enabled() -> bool {
1477    !SHAPE_VARIANTS.equals("0")
1478}
1479
1480/// What every draw of one pass shares: its target's size and whether the
1481/// pass has a depth buffer its opaque interiors fill first.
1482#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1483pub(crate) struct PassFrame {
1484    pub(crate) size: (u32, u32),
1485    pub(crate) depth: bool,
1486}
1487
1488impl PassFrame {
1489    /// The scissor a draw bounded by `scissor`, or by nothing, sets.
1490    pub(crate) fn scissor(self, scissor: Option<(u32, u32, u32, u32)>) -> (u32, u32, u32, u32) {
1491        scissor.unwrap_or((0, 0, self.size.0, self.size.1))
1492    }
1493}
1494
1495/// Which of a pass's two stages a shape draw records: the front-to-back
1496/// opaque interiors, or the paint in draw order.
1497#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1498pub(crate) enum RunStage {
1499    Interiors,
1500    Paint,
1501}
1502
1503/// The depth buffer of a pass that lays opaque interiors down first.
1504pub(crate) const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
1505
1506/// How a pipeline meets its pass's depth buffer.
1507#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1508pub(crate) enum ShapeDepth {
1509    /// The pass has no depth buffer.
1510    Off,
1511    /// Paints what the opaque interiors of later records leave visible.
1512    Tested,
1513    /// Lays down opaque interiors, front to back, ahead of the paint.
1514    Interior,
1515}
1516
1517impl ShapeDepth {
1518    fn stencil_state(self) -> Option<wgpu::DepthStencilState> {
1519        let (depth_write_enabled, depth_compare) = match self {
1520            Self::Off => return None,
1521            Self::Tested => (false, wgpu::CompareFunction::Less),
1522            Self::Interior => (true, wgpu::CompareFunction::Less),
1523        };
1524        Some(wgpu::DepthStencilState {
1525            format: DEPTH_FORMAT,
1526            depth_write_enabled: Some(depth_write_enabled),
1527            depth_compare: Some(depth_compare),
1528            stencil: wgpu::StencilState::default(),
1529            bias: wgpu::DepthBiasState::default(),
1530        })
1531    }
1532}
1533
1534/// Depth steps one draw apart in a pass's order, as the shaders'
1535/// `DEPTH_STEP`.
1536const PASS_DEPTH_STEP: f32 = 1.0 / 1_048_576.0;
1537
1538/// The depth of the draw at `index` in its pass's order, as the shaders'
1539/// `record_depth` and `batch_depth` place it: later draws nearer.
1540pub(crate) fn pass_order_depth(index: u32) -> f32 {
1541    (1.0 - (index as f32 + 1.0) * PASS_DEPTH_STEP).max(0.0)
1542}
1543
1544/// The depth state of a glyph or image pipeline: in a pass with a depth
1545/// buffer it paints what later opaque interiors leave visible, as shapes do.
1546pub(crate) fn overlay_depth_state(depth: bool) -> Option<wgpu::DepthStencilState> {
1547    if depth {
1548        ShapeDepth::Tested.stencil_state()
1549    } else {
1550        None
1551    }
1552}
1553
1554/// Which records a shape pipeline draws turned, as `SHAPE_TURNS` in the
1555/// shape shader: none, every one, or each as its placement says.
1556#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1557pub(crate) enum ShapeTurns {
1558    None,
1559    All,
1560    Mixed,
1561}
1562
1563impl ShapeTurns {
1564    /// The turns of records placed under `turn`, in a pass whose flat and
1565    /// turned records alternate often when `mixed`.
1566    pub(crate) fn of(turn: SegmentTransform, mixed: bool) -> Self {
1567        if mixed {
1568            Self::Mixed
1569        } else if turn.is_identity() {
1570            Self::None
1571        } else {
1572            Self::All
1573        }
1574    }
1575
1576    fn constant(self) -> f64 {
1577        match self {
1578            Self::None => 0.0,
1579            Self::All => 1.0,
1580            Self::Mixed => 2.0,
1581        }
1582    }
1583}
1584
1585#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1586pub(crate) struct ShapePipelineKey {
1587    pub(crate) blend_mode: BlendMode,
1588    pub(crate) tier: RunTier,
1589    pub(crate) variant: ShapeVariant,
1590    pub(crate) turns: ShapeTurns,
1591    pub(crate) depth: ShapeDepth,
1592}
1593
1594/// Packs a key's fields into a number, low bit first.
1595#[derive(Default)]
1596struct KeyWriter {
1597    bits: u64,
1598    width: u32,
1599}
1600
1601impl KeyWriter {
1602    fn put(&mut self, value: u64, width: u32) {
1603        self.bits |= value << self.width;
1604        self.width += width;
1605    }
1606
1607    fn put_byte(&mut self, value: Option<u8>) {
1608        self.put(u64::from(value.is_some()), 1);
1609        self.put(u64::from(value.unwrap_or_default()), 8);
1610    }
1611}
1612
1613/// Unpacks what [`KeyWriter`] packed, low bit first.
1614/// The bits a key's shape kinds take: one per fragment kind.
1615const KIND_BITS: u32 = FRAGMENT_KIND_TRAPEZOID + 1;
1616
1617struct KeyReader(u64);
1618
1619impl KeyReader {
1620    fn take(&mut self, width: u32) -> u64 {
1621        let value = self.0 & ((1 << width) - 1);
1622        self.0 >>= width;
1623        value
1624    }
1625
1626    fn take_flag(&mut self) -> bool {
1627        self.take(1) == 1
1628    }
1629
1630    fn take_byte(&mut self) -> Option<u8> {
1631        let present = self.take_flag();
1632        let value = u8::try_from(self.take(8)).ok()?;
1633        present.then_some(value)
1634    }
1635
1636    fn take_kinds(&mut self) -> Option<u8> {
1637        u8::try_from(self.take(KIND_BITS))
1638            .ok()
1639            .filter(|kinds| *kinds != 0)
1640    }
1641}
1642
1643impl ShapePipelineKey {
1644    pub(crate) const DISK_LAYOUT: [u8; 8] = *b"CPKEY003";
1645
1646    /// The flat solid rect fill of a pass without a depth buffer, which
1647    /// every screen draws: on all 38 demo pages, and in a launch's first
1648    /// frames, which draw without the depth pre-pass.
1649    #[cfg(not(target_arch = "wasm32"))]
1650    const SOLID_RECT: Self = Self {
1651        blend_mode: BlendMode::SrcOver,
1652        tier: RunTier::Arena,
1653        variant: ShapeVariant {
1654            kinds: 1 << FRAGMENT_KIND_FILL,
1655            brush: None,
1656            solid: true,
1657            clip: SegmentClip::Untested,
1658            interior: false,
1659            dither: false,
1660            ablation: ShapeAblation {
1661                material: false,
1662                fill: false,
1663            },
1664        },
1665        turns: ShapeTurns::None,
1666        depth: ShapeDepth::Off,
1667    };
1668
1669    /// The key as a number a later launch reads back with
1670    /// [`Self::from_bits`], to build the pipeline ahead of its first frame.
1671    pub(crate) fn to_bits(self) -> u64 {
1672        let mut bits = KeyWriter::default();
1673        bits.put(self.blend_mode as u64, 5);
1674        bits.put(self.tier as u64, 2);
1675        let variant = self.variant;
1676        bits.put(u64::from(variant.kinds), KIND_BITS);
1677        bits.put_byte(variant.brush);
1678        bits.put(u64::from(variant.solid), 1);
1679        bits.put(
1680            match variant.clip {
1681                SegmentClip::Untested => 0,
1682                SegmentClip::Tested => 1,
1683                SegmentClip::Rounded => 2,
1684            },
1685            2,
1686        );
1687        bits.put(u64::from(variant.interior), 1);
1688        bits.put(u64::from(variant.dither), 1);
1689        bits.put(u64::from(variant.ablation.material), 1);
1690        bits.put(u64::from(variant.ablation.fill), 1);
1691        bits.put(
1692            match self.turns {
1693                ShapeTurns::None => 0,
1694                ShapeTurns::All => 1,
1695                ShapeTurns::Mixed => 2,
1696            },
1697            2,
1698        );
1699        bits.put(
1700            match self.depth {
1701                ShapeDepth::Off => 0,
1702                ShapeDepth::Tested => 1,
1703                ShapeDepth::Interior => 2,
1704            },
1705            2,
1706        );
1707        bits.bits
1708    }
1709
1710    /// The key [`Self::to_bits`] packed, or `None` for a number no key
1711    /// packs to.
1712    pub(crate) fn from_bits(packed: u64) -> Option<Self> {
1713        let mut bits = KeyReader(packed);
1714        let blend_mode = *BlendMode::ALL.get(usize::try_from(bits.take(5)).ok()?)?;
1715        let tier = match bits.take(2) {
1716            0 => RunTier::Store,
1717            1 => RunTier::Arena,
1718            2 => RunTier::Either,
1719            _ => return None,
1720        };
1721        let kinds = bits.take_kinds()?;
1722        let brush = bits.take_byte();
1723        let solid = bits.take_flag();
1724        let clip = match bits.take(2) {
1725            0 => SegmentClip::Untested,
1726            1 => SegmentClip::Tested,
1727            2 => SegmentClip::Rounded,
1728            _ => return None,
1729        };
1730        let interior = bits.take_flag();
1731        let dither = bits.take_flag();
1732        let ablation = ShapeAblation {
1733            material: bits.take_flag(),
1734            fill: bits.take_flag(),
1735        };
1736        let turns = match bits.take(2) {
1737            0 => ShapeTurns::None,
1738            1 => ShapeTurns::All,
1739            2 => ShapeTurns::Mixed,
1740            _ => return None,
1741        };
1742        let depth = match bits.take(2) {
1743            0 => ShapeDepth::Off,
1744            1 => ShapeDepth::Tested,
1745            2 => ShapeDepth::Interior,
1746            _ => return None,
1747        };
1748        (bits.0 == 0).then_some(Self {
1749            blend_mode,
1750            tier,
1751            variant: ShapeVariant {
1752                kinds,
1753                brush,
1754                solid,
1755                clip,
1756                interior,
1757                dither,
1758                ablation,
1759            },
1760            turns,
1761            depth,
1762        })
1763    }
1764
1765    #[cfg(test)]
1766    pub(crate) fn general_for(blend_mode: BlendMode, tier: RunTier) -> Self {
1767        Self {
1768            blend_mode,
1769            tier,
1770            variant: ShapeVariant::GENERAL,
1771            turns: ShapeTurns::None,
1772            depth: ShapeDepth::Off,
1773        }
1774    }
1775
1776    /// The pipeline that lays down the opaque interiors of this key's
1777    /// draws, if they have any: plain source-over draws. A turned record's
1778    /// layer draws in place only under a rigid turn, which keeps the
1779    /// interior's half-pixel inset from the fill's edge exact. The interior
1780    /// shader reads only the tier and the turns, so every variant shares one
1781    /// pipeline per tier and turns: one compile, and draws of different
1782    /// variants lay their interiors down together.
1783    pub(crate) fn interior(self) -> Option<Self> {
1784        (self.depth == ShapeDepth::Tested
1785            && !self.variant.rounded()
1786            && self.blend_mode == BlendMode::SrcOver
1787            && !self.variant.ablation.material
1788            && !self.variant.ablation.fill)
1789            .then_some(Self {
1790                variant: ShapeVariant::GENERAL,
1791                depth: ShapeDepth::Interior,
1792                ..self
1793            })
1794    }
1795
1796    pub(crate) fn general(self) -> Self {
1797        Self {
1798            tier: RunTier::Either,
1799            variant: self.variant.general(),
1800            ..self
1801        }
1802    }
1803
1804    /// The one pipeline that draws every key with this one's blend, depth
1805    /// and clip rounding: every kind, records turned or not, from either
1806    /// tier.
1807    pub(crate) fn universal(self) -> Self {
1808        Self {
1809            tier: RunTier::Either,
1810            variant: self.variant.universal(),
1811            turns: ShapeTurns::Mixed,
1812            ..self
1813        }
1814    }
1815
1816    pub(crate) fn is_general(self) -> bool {
1817        self.variant == self.variant.general()
1818    }
1819
1820    pub(crate) fn joined(self) -> Self {
1821        Self {
1822            variant: self.variant.joined(),
1823            ..self
1824        }
1825    }
1826}
1827
1828/// The entry points and pipeline constants of the shape program a key names.
1829pub(crate) struct ShapeProgram {
1830    pub(crate) vertex_entry: &'static str,
1831    pub(crate) fragment_entry: &'static str,
1832    pub(crate) constants: [(&'static str, f64); 14],
1833}
1834
1835impl ShapePipelineKey {
1836    pub(crate) fn program(self, mode: RunBufferMode) -> ShapeProgram {
1837        let Self {
1838            tier,
1839            variant,
1840            turns,
1841            depth,
1842            ..
1843        } = self;
1844        let constants = [
1845            ("SHAPE_KIND_FIXED", variant.kind().map_or(-1.0, f64::from)),
1846            ("SHAPE_KINDS", f64::from(variant.kinds)),
1847            ("BRUSH_KIND_FIXED", variant.brush.map_or(-1.0, f64::from)),
1848            ("SHAPE_SOLID", f64::from(u8::from(variant.solid))),
1849            (
1850                "SHAPE_CLIPPED",
1851                f64::from(u8::from(variant.clip != SegmentClip::Untested)),
1852            ),
1853            ("SHAPE_ROUNDED_CLIP", f64::from(u8::from(variant.rounded()))),
1854            (
1855                "SHAPE_INTERIOR",
1856                f64::from(u8::from(variant.interior && !variant.rounded())),
1857            ),
1858            ("SHAPE_DITHER", f64::from(u8::from(variant.dither))),
1859            ("SHAPE_TURNS", turns.constant()),
1860            ("SHAPE_TIER", f64::from(tier as u8)),
1861            ("SHAPE_BANDS", f64::from(u8::from(mode.storage))),
1862            ("SHAPE_TRIG_FILLED", f64::from(u8::from(mode.trig_fill))),
1863            ("SHAPE_FLAT", f64::from(u8::from(variant.ablation.material))),
1864            ("SHAPE_DISCARD", f64::from(u8::from(variant.ablation.fill))),
1865        ];
1866        let (vertex_entry, fragment_entry) = if depth == ShapeDepth::Interior {
1867            ("vs_record_interior", "fs_interior")
1868        } else {
1869            variant.entries(turns == ShapeTurns::None)
1870        };
1871        ShapeProgram {
1872            vertex_entry,
1873            fragment_entry,
1874            constants,
1875        }
1876    }
1877}
1878
1879pub(crate) fn create_shape_pipeline(
1880    device: &wgpu::Device,
1881    cache: Option<&wgpu::PipelineCache>,
1882    surface_format: wgpu::TextureFormat,
1883    shader: &SharedShader,
1884    key: ShapePipelineKey,
1885    mode: RunBufferMode,
1886) -> wgpu::RenderPipeline {
1887    let ShapePipelineKey {
1888        blend_mode,
1889        tier,
1890        variant,
1891        turns,
1892        depth,
1893    } = key;
1894    let ShapeProgram {
1895        vertex_entry,
1896        fragment_entry,
1897        constants,
1898    } = key.program(mode);
1899    let blend = (depth != ShapeDepth::Interior).then(|| blend_state_for_mode(blend_mode));
1900    let instance_layout = record_vertex_layouts().map(Some);
1901    let stages = shader.stages((vertex_entry, fragment_entry), &constants);
1902
1903    create_render_pipeline_logged(
1904        device,
1905        cache,
1906        &format!(
1907            "shape blend={blend_mode:?} tier={tier:?} variant={variant:?} turns={turns:?} depth={depth:?}"
1908        ),
1909        wgpu::RenderPipelineDescriptor {
1910            label: Some("Shape Pipeline"),
1911            layout: Some(shader.layout()),
1912            vertex: wgpu::VertexState {
1913                module: &stages.vertex,
1914                entry_point: Some(vertex_entry),
1915                compilation_options: wgpu::PipelineCompilationOptions {
1916                    constants: stages.constants,
1917                    ..wgpu::PipelineCompilationOptions::default()
1918                },
1919                buffers: &instance_layout,
1920            },
1921            fragment: Some(wgpu::FragmentState {
1922                module: &stages.fragment,
1923                entry_point: Some(fragment_entry),
1924                compilation_options: wgpu::PipelineCompilationOptions {
1925                    constants: stages.constants,
1926                    ..wgpu::PipelineCompilationOptions::default()
1927                },
1928                targets: &[Some(wgpu::ColorTargetState {
1929                    format: surface_format,
1930                    blend,
1931                    write_mask: wgpu::ColorWrites::ALL,
1932                })],
1933            }),
1934            primitive: wgpu::PrimitiveState {
1935                topology: wgpu::PrimitiveTopology::TriangleList,
1936                strip_index_format: None,
1937                front_face: wgpu::FrontFace::Ccw,
1938                cull_mode: None,
1939                unclipped_depth: false,
1940                polygon_mode: wgpu::PolygonMode::Fill,
1941                conservative: false,
1942            },
1943            depth_stencil: depth.stencil_state(),
1944            multisample: wgpu::MultisampleState::default(),
1945            multiview_mask: None,
1946            cache: None,
1947        },
1948    )
1949}
1950fn create_image_pipeline(
1951    device: &wgpu::Device,
1952    cache: Option<&wgpu::PipelineCache>,
1953    surface_format: wgpu::TextureFormat,
1954    shader: &SharedShader,
1955    blend_mode: BlendMode,
1956    variant: ImageVariant,
1957) -> wgpu::RenderPipeline {
1958    let module = shader.module();
1959    let ImageVariant {
1960        depth,
1961        alpha_mask,
1962        rounded,
1963    } = variant;
1964    let (vertex_entry, fragment_entry) = match (alpha_mask, rounded) {
1965        (false, false) => ("image_vs_main", "image_fs_main"),
1966        (true, false) => ("image_vs_main", "image_mask_fs_main"),
1967        (false, true) => ("image_rounded_vs_main", "image_rounded_fs_main"),
1968        (true, true) => ("image_rounded_vs_main", "image_mask_rounded_fs_main"),
1969    };
1970    // A rounded image reads its clip from an instance beside its vertices.
1971    let buffers = [Some(Vertex::desc()), Some(DeviceRoundedClip::desc())];
1972    create_render_pipeline_logged(
1973        device,
1974        cache,
1975        &format!(
1976            "image blend={blend_mode:?} depth={depth} alpha_mask={alpha_mask} rounded={rounded}"
1977        ),
1978        wgpu::RenderPipelineDescriptor {
1979            label: Some("Image Pipeline"),
1980            layout: Some(shader.layout()),
1981            vertex: wgpu::VertexState {
1982                module,
1983                entry_point: Some(vertex_entry),
1984                compilation_options: wgpu::PipelineCompilationOptions::default(),
1985                buffers: if rounded { &buffers } else { &buffers[..1] },
1986            },
1987            fragment: Some(wgpu::FragmentState {
1988                module,
1989                entry_point: Some(fragment_entry),
1990                compilation_options: wgpu::PipelineCompilationOptions::default(),
1991                targets: &[Some(wgpu::ColorTargetState {
1992                    format: surface_format,
1993                    blend: Some(blend_state_for_mode(blend_mode)),
1994                    write_mask: wgpu::ColorWrites::ALL,
1995                })],
1996            }),
1997            primitive: wgpu::PrimitiveState {
1998                topology: wgpu::PrimitiveTopology::TriangleList,
1999                strip_index_format: None,
2000                front_face: wgpu::FrontFace::Ccw,
2001                cull_mode: None,
2002                unclipped_depth: false,
2003                polygon_mode: wgpu::PolygonMode::Fill,
2004                conservative: false,
2005            },
2006            depth_stencil: overlay_depth_state(depth),
2007            multisample: wgpu::MultisampleState::default(),
2008            multiview_mask: None,
2009            cache: None,
2010        },
2011    )
2012}
2013
2014fn create_glyph_atlas_pipeline(
2015    device: &wgpu::Device,
2016    cache: Option<&wgpu::PipelineCache>,
2017    surface_format: wgpu::TextureFormat,
2018    shader: &SharedShader,
2019    (depth, quads): (bool, GlyphQuads),
2020) -> wgpu::RenderPipeline {
2021    let module = shader.module();
2022    create_render_pipeline_logged(
2023        device,
2024        cache,
2025        match (depth, quads) {
2026            (false, GlyphQuads::Plain) => "glyph-atlas",
2027            (true, GlyphQuads::Plain) => "glyph-atlas depth",
2028            (false, GlyphQuads::Aligned) => "glyph-atlas aligned",
2029            (true, GlyphQuads::Aligned) => "glyph-atlas aligned depth",
2030            (false, GlyphQuads::Turned) => "glyph-atlas turned",
2031            (true, GlyphQuads::Turned) => "glyph-atlas turned depth",
2032        },
2033        wgpu::RenderPipelineDescriptor {
2034            label: Some("Glyph Atlas Pipeline"),
2035            layout: Some(shader.layout()),
2036            vertex: wgpu::VertexState {
2037                module,
2038                entry_point: Some(match quads {
2039                    GlyphQuads::Plain => "glyph_atlas_vs_main",
2040                    GlyphQuads::Aligned => "glyph_atlas_aligned_vs_main",
2041                    GlyphQuads::Turned => "glyph_atlas_turned_vs_main",
2042                }),
2043                compilation_options: wgpu::PipelineCompilationOptions::default(),
2044                buffers: &[Some(match quads {
2045                    GlyphQuads::Turned => TurnedGlyph::desc(),
2046                    GlyphQuads::Plain | GlyphQuads::Aligned => GlyphInstance::desc(),
2047                })],
2048            },
2049            fragment: Some(wgpu::FragmentState {
2050                module,
2051                entry_point: Some(match quads {
2052                    GlyphQuads::Aligned => "glyph_atlas_aligned_fs_main",
2053                    GlyphQuads::Plain | GlyphQuads::Turned => "glyph_atlas_fs_main",
2054                }),
2055                compilation_options: wgpu::PipelineCompilationOptions::default(),
2056                targets: &[Some(wgpu::ColorTargetState {
2057                    format: surface_format,
2058                    blend: Some(blend_state_for_mode(BlendMode::SrcOver)),
2059                    write_mask: wgpu::ColorWrites::ALL,
2060                })],
2061            }),
2062            primitive: wgpu::PrimitiveState {
2063                topology: wgpu::PrimitiveTopology::TriangleStrip,
2064                strip_index_format: None,
2065                front_face: wgpu::FrontFace::Ccw,
2066                cull_mode: None,
2067                unclipped_depth: false,
2068                polygon_mode: wgpu::PolygonMode::Fill,
2069                conservative: false,
2070            },
2071            depth_stencil: overlay_depth_state(depth),
2072            multisample: wgpu::MultisampleState::default(),
2073            multiview_mask: None,
2074            cache: None,
2075        },
2076    )
2077}
2078
2079#[repr(C)]
2080#[derive(Copy, Clone, Debug, Pod, Zeroable)]
2081pub(crate) struct Vertex {
2082    position: [f32; 2],
2083    color: [f32; 4],
2084    uv: [f32; 2],
2085    uv_bounds: [f32; 4],
2086}
2087
2088impl Vertex {
2089    const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
2090        0 => Float32x2,
2091        1 => Float32x4,
2092        2 => Float32x2,
2093        3 => Float32x4,
2094    ];
2095
2096    fn desc() -> wgpu::VertexBufferLayout<'static> {
2097        wgpu::VertexBufferLayout {
2098            array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
2099            step_mode: wgpu::VertexStepMode::Vertex,
2100            attributes: &Self::ATTRIBS,
2101        }
2102    }
2103}
2104
2105/// The corners a glyph instance draws as a triangle strip: top-left,
2106/// top-right, bottom-left, bottom-right.
2107const GLYPH_QUAD_CORNERS: u32 = 4;
2108
2109/// One glyph quad as the glyph pipeline draws it: an instance whose four
2110/// corners the vertex stage picks from `rect` and `uv`.
2111#[repr(C)]
2112#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
2113pub(crate) struct GlyphInstance {
2114    rect: [f32; 4],
2115    uv: [f32; 4],
2116    uv_bounds: [f32; 4],
2117    color: [f32; 4],
2118}
2119
2120impl GlyphInstance {
2121    const ATTRIBS: [wgpu::VertexAttribute; 4] = wgpu::vertex_attr_array![
2122        0 => Float32x4,
2123        1 => Float32x4,
2124        2 => Float32x4,
2125        3 => Float32x4
2126    ];
2127
2128    fn desc() -> wgpu::VertexBufferLayout<'static> {
2129        wgpu::VertexBufferLayout {
2130            array_stride: std::mem::size_of::<GlyphInstance>() as wgpu::BufferAddress,
2131            step_mode: wgpu::VertexStepMode::Instance,
2132            attributes: &Self::ATTRIBS,
2133        }
2134    }
2135
2136    /// The part of the quad inside `edges` (left, top, right, bottom, in the
2137    /// quad's own space), its atlas coordinates cut to match; `None` when
2138    /// none of it is inside.
2139    pub(crate) fn clipped_to(self, edges: [f32; 4]) -> Option<Self> {
2140        let [x0, y0, x1, y1] = self.rect;
2141        let rect = [
2142            x0.max(edges[0]),
2143            y0.max(edges[1]),
2144            x1.min(edges[2]),
2145            y1.min(edges[3]),
2146        ];
2147        if rect[2] <= rect[0] || rect[3] <= rect[1] {
2148            return None;
2149        }
2150        if rect == self.rect {
2151            return Some(self);
2152        }
2153        let [u0, v0, u1, v1] = self.uv;
2154        let u = |x: f32| u0 + (x - x0) / (x1 - x0) * (u1 - u0);
2155        let v = |y: f32| v0 + (y - y0) / (y1 - y0) * (v1 - v0);
2156        Some(Self {
2157            rect,
2158            uv: [u(rect[0]), v(rect[1]), u(rect[2]), v(rect[3])],
2159            ..self
2160        })
2161    }
2162}
2163
2164/// Hands `sink` each quad of a glyph run at `source_raster_rect` that the
2165/// viewport shows, as an instance cut to `cut` when the text is cut.
2166#[inline]
2167fn for_each_visible_glyph(
2168    source_raster_rect: Rect,
2169    quads: GlyphRunQuads<'_>,
2170    (clip, cut): (Option<Rect>, Option<[f32; 4]>),
2171    viewport: ViewportUniformParams,
2172    root_scale: f32,
2173    mut sink: impl FnMut(GlyphInstance),
2174) {
2175    let whole_run_visible =
2176        quads
2177            .bounds
2178            .within_viewport(source_raster_rect, clip, viewport, root_scale);
2179    for quad in quads.iter() {
2180        if !whole_run_visible
2181            && !cached_text_glyph_quad_is_visible_in_viewport(
2182                source_raster_rect,
2183                &quad,
2184                clip,
2185                viewport,
2186                root_scale,
2187            )
2188        {
2189            continue;
2190        }
2191        let Some(glyph) = cached_text_glyph_instance(source_raster_rect, &quad) else {
2192            continue;
2193        };
2194        let glyph = match cut {
2195            Some(edges) => glyph.clipped_to(edges),
2196            None => Some(glyph),
2197        };
2198        if let Some(glyph) = glyph {
2199            sink(glyph);
2200        }
2201    }
2202}
2203
2204/// A glyph quad of a layer drawn in place under a turn, with the turn that
2205/// places it: glyphs of layers turned differently then share a draw, and
2206/// every other glyph keeps [`GlyphInstance`]'s smaller layout.
2207#[repr(C)]
2208#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
2209pub(crate) struct TurnedGlyph {
2210    glyph: GlyphInstance,
2211    /// The turn, row-major.
2212    turn: [f32; 4],
2213    /// The turn's translation in `xy`.
2214    translation: [f32; 4],
2215}
2216
2217impl TurnedGlyph {
2218    const ATTRIBS: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
2219        0 => Float32x4,
2220        1 => Float32x4,
2221        2 => Float32x4,
2222        3 => Float32x4,
2223        4 => Float32x4,
2224        5 => Float32x4
2225    ];
2226
2227    pub(crate) fn new(glyph: GlyphInstance, turn: SegmentTransform) -> Self {
2228        let (linear, [x, y], _) = turn.uniform_parts();
2229        Self {
2230            glyph,
2231            turn: linear,
2232            translation: [x, y, 0.0, 0.0],
2233        }
2234    }
2235
2236    fn desc() -> wgpu::VertexBufferLayout<'static> {
2237        wgpu::VertexBufferLayout {
2238            array_stride: std::mem::size_of::<TurnedGlyph>() as wgpu::BufferAddress,
2239            step_mode: wgpu::VertexStepMode::Instance,
2240            attributes: &Self::ATTRIBS,
2241        }
2242    }
2243}
2244
2245/// The glyph quads a pass draws from its shared buffers: the plain ones and
2246/// those of layers drawn in place under a turn.
2247#[derive(Default)]
2248pub(crate) struct GlyphInstances {
2249    pub(crate) plain: FrameScratch<GlyphInstance>,
2250    pub(crate) turned: FrameScratch<TurnedGlyph>,
2251}
2252
2253impl GlyphInstances {
2254    pub(crate) fn clear(&mut self) {
2255        self.plain.clear();
2256        self.turned.clear();
2257    }
2258
2259    /// Ends a frame: see [`FrameScratch::end_frame`]. Passes need the
2260    /// most glyphs at startup, when nothing is cached yet.
2261    pub(crate) fn end_frame(&mut self) {
2262        self.plain.end_frame();
2263        self.turned.end_frame();
2264    }
2265
2266    fn lens(&self) -> (usize, usize) {
2267        (self.plain.len(), self.turned.len())
2268    }
2269
2270    /// How many turned glyphs, or plain ones, the pass holds.
2271    fn len_of(&self, turned: bool) -> usize {
2272        if turned {
2273            self.turned.len()
2274        } else {
2275            self.plain.len()
2276        }
2277    }
2278
2279    fn truncate(&mut self, (plain, turned): (usize, usize)) {
2280        self.plain.truncate(plain);
2281        self.turned.truncate(turned);
2282    }
2283}
2284
2285/// A text clip's edges in device pixels of the space its glyph quads are
2286/// laid out in, before a viewport transform moves them.
2287fn glyph_clip_edges(clip: Rect, root_scale: f32) -> [f32; 4] {
2288    [
2289        canonicalize_device_coordinate(clip.x * root_scale),
2290        canonicalize_device_coordinate(clip.y * root_scale),
2291        canonicalize_device_coordinate((clip.x + clip.width) * root_scale),
2292        canonicalize_device_coordinate((clip.y + clip.height) * root_scale),
2293    ]
2294}
2295
2296/// Where the glyph quads of a text are cut, in the quads' own space. Under a
2297/// turned viewport the cut is the text's `clip` itself, before the turn,
2298/// which no scissor can follow; the text then draws without one. Otherwise
2299/// it is the pixel edges of the text's `scissor`, its draw rect within its
2300/// clip: cut there, the quads cover exactly the pixels the scissor would
2301/// pass, with the same texels, so the text needs no scissor of its own and
2302/// draws in one call with its neighbours, even where a last line's
2303/// descenders or a glyph's padding reach past its draw rect.
2304fn glyph_cut_edges(
2305    clip: Option<Rect>,
2306    scissor: TargetRect,
2307    viewport: ViewportUniformParams,
2308    root_scale: f32,
2309) -> Option<[f32; 4]> {
2310    if !viewport.transform.is_identity() {
2311        return clip.map(|clip| glyph_clip_edges(clip, root_scale));
2312    }
2313    let (x, y, width, height) = scissor;
2314    let [offset_x, offset_y] = viewport.offset;
2315    Some([
2316        x as f32 + offset_x,
2317        y as f32 + offset_y,
2318        (x + width) as f32 + offset_x,
2319        (y + height) as f32 + offset_y,
2320    ])
2321}
2322
2323#[repr(C)]
2324#[derive(Copy, Clone, Debug, Pod, Zeroable)]
2325struct Uniforms {
2326    viewport: [f32; 2],
2327    viewport_offset: [f32; 2],
2328    transform: [f32; 4],
2329    translation: [f32; 2],
2330    reserved: [f32; 2],
2331    inverse: [f32; 4],
2332    origin: [f32; 2],
2333    origin_reserved: [f32; 2],
2334    placement: PlacementData,
2335}
2336
2337impl Uniforms {
2338    fn of(params: ViewportUniformParams, placement: PlacementData, tier: RunTier) -> Self {
2339        let (transform, translation, inverse) = params.transform.uniform_parts();
2340        Self {
2341            viewport: [params.width as f32, params.height as f32],
2342            viewport_offset: params.offset,
2343            transform,
2344            translation,
2345            reserved: [params.depth_base, f32::from(tier as u8)],
2346            inverse,
2347            origin: params.origin,
2348            origin_reserved: [0.0; 2],
2349            placement,
2350        }
2351    }
2352}
2353
2354static SURVIVE_GPU_ERRORS: DebugToggle = DebugToggle::new("CRANPOSE_SURVIVE_GPU_ERRORS");
2355
2356fn survive_gpu_errors_enabled() -> bool {
2357    !SURVIVE_GPU_ERRORS.equals("0")
2358}
2359
2360struct CachedImageTexture {
2361    bind_groups: ImageBindGroups,
2362    _texture: wgpu::Texture,
2363    _view: wgpu::TextureView,
2364    bytes: usize,
2365}
2366
2367struct ImageBindGroups {
2368    alpha_mask: bool,
2369    nearest: wgpu::BindGroup,
2370    linear: wgpu::BindGroup,
2371}
2372
2373impl ImageBindGroups {
2374    fn binding(&self, sampling: ImageSampling) -> ImageBinding {
2375        ImageBinding {
2376            bind_group: match sampling {
2377                ImageSampling::Nearest => self.nearest.clone(),
2378                ImageSampling::Linear => self.linear.clone(),
2379            },
2380            alpha_mask: self.alpha_mask,
2381        }
2382    }
2383}
2384
2385/// What an image's draw binds: its texture's bind group for the draw's
2386/// sampling, which keeps the texture alive whatever the cache evicts before
2387/// the pass is drawn, and whether the texture is an alpha mask.
2388pub(crate) struct ImageBinding {
2389    bind_group: wgpu::BindGroup,
2390    alpha_mask: bool,
2391}
2392
2393#[derive(Clone, Copy)]
2394struct GlyphAtlasEntry {
2395    x: u16,
2396    y: u16,
2397    width: u16,
2398    height: u16,
2399}
2400
2401fn next_glyph_atlas_size(current: u32, max: u32) -> u32 {
2402    current.saturating_mul(2).clamp(1, max.max(1))
2403}
2404
2405/// The samplers the glyph atlas binds: nearest for glyphs on the pixel grid,
2406/// linear for glyphs a segment transform turns.
2407#[derive(Clone, Copy)]
2408struct GlyphSamplers<'a> {
2409    nearest: &'a wgpu::Sampler,
2410    linear: &'a wgpu::Sampler,
2411}
2412
2413/// A glyph's atlas slot: its mask corrected for the luminance class of the
2414/// text it is drawn in, so one glyph in light and dark text takes two slots.
2415#[derive(Clone, Copy, PartialEq, Eq, Hash)]
2416struct GlyphAtlasSlotKey {
2417    glyph: SoftwareGlyphAtlasKey,
2418    luminance: TextLuminance,
2419}
2420
2421impl GlyphAtlasSlotKey {
2422    fn new(glyph: SoftwareGlyphAtlasKey, color: Color) -> Self {
2423        Self {
2424            glyph,
2425            luminance: TextLuminance::of_color(color),
2426        }
2427    }
2428}
2429
2430/// Slots of [`RunAtlasEntries`], by glyph id.
2431const RUN_ATLAS_ENTRY_SLOTS: usize = 64;
2432
2433/// The atlas entries a run's preparation has looked up, by glyph id: a run
2434/// repeats its letters, and each atlas lookup hashes the slot key and moves
2435/// the entry up the atlas's recency order, where the first lookup already
2436/// put it for this frame.
2437struct RunAtlasEntries {
2438    slots: [Option<(GlyphAtlasSlotKey, GlyphAtlasEntry)>; RUN_ATLAS_ENTRY_SLOTS],
2439}
2440
2441impl RunAtlasEntries {
2442    fn new() -> Self {
2443        Self {
2444            slots: [None; RUN_ATLAS_ENTRY_SLOTS],
2445        }
2446    }
2447
2448    /// `glyph`'s entry from an earlier glyph of the run, else from
2449    /// `look_up`, remembered for the rest of it.
2450    fn entry(
2451        &mut self,
2452        renderer: &mut GpuRenderer,
2453        glyph: &SoftwareGlyphAtlasPlacement,
2454        look_up: impl FnOnce(&mut GpuRenderer) -> Result<GlyphAtlasEntry, String>,
2455    ) -> Result<GlyphAtlasEntry, String> {
2456        let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2457        let slot = &mut self.slots[glyph.key.glyph_id as usize % RUN_ATLAS_ENTRY_SLOTS];
2458        if let Some((seen, entry)) = *slot
2459            && seen == key
2460        {
2461            renderer.frame_stats.record_text_glyph_atlas_hits(1);
2462            return Ok(entry);
2463        }
2464        let entry = look_up(renderer)?;
2465        *slot = Some((key, entry));
2466        Ok(entry)
2467    }
2468}
2469
2470struct TextGlyphAtlas {
2471    texture: wgpu::Texture,
2472    _view: wgpu::TextureView,
2473    texel_bind_group: Rc<wgpu::BindGroup>,
2474    filtered_bind_group: Rc<wgpu::BindGroup>,
2475    entries: BoundedLruCache<GlyphAtlasSlotKey, GlyphAtlasEntry>,
2476    generation: u64,
2477    size: u32,
2478    max_size: u32,
2479    cursor_x: u32,
2480    cursor_y: u32,
2481    row_height: u32,
2482    /// The glyphs placed since [`Self::flush_uploads`], in the order they
2483    /// were placed, and their coverage one after another.
2484    pending: Vec<GlyphAtlasEntry>,
2485    pending_coverage: Vec<u8>,
2486    upload_scratch: Vec<u8>,
2487}
2488
2489impl TextGlyphAtlas {
2490    fn new(
2491        device: &wgpu::Device,
2492        image_layout: &wgpu::BindGroupLayout,
2493        samplers: GlyphSamplers<'_>,
2494        size: u32,
2495    ) -> Self {
2496        // The side stays a power of two, whose texel is exact: see
2497        // [`TextGlyphAtlas::texel`].
2498        let device_max = device.limits().max_texture_dimension_2d.max(1);
2499        let max_size = TEXT_GLYPH_ATLAS_MAX_SIZE.min(1 << device_max.ilog2());
2500        let size = size
2501            .next_power_of_two()
2502            .clamp(TEXT_GLYPH_ATLAS_MIN_SIZE.min(max_size), max_size);
2503        let texture = Self::create_texture(device, size);
2504        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
2505        let bind = |label: &'static str, sampler: &wgpu::Sampler| {
2506            Rc::new(device.create_bind_group(&wgpu::BindGroupDescriptor {
2507                label: Some(label),
2508                layout: image_layout,
2509                entries: &[
2510                    wgpu::BindGroupEntry {
2511                        binding: 0,
2512                        resource: wgpu::BindingResource::TextureView(&view),
2513                    },
2514                    wgpu::BindGroupEntry {
2515                        binding: 1,
2516                        resource: wgpu::BindingResource::Sampler(sampler),
2517                    },
2518                ],
2519            }))
2520        };
2521        let texel_bind_group = bind("Text Glyph Atlas Bind Group", samplers.nearest);
2522        let filtered_bind_group = bind("Filtered Text Glyph Atlas Bind Group", samplers.linear);
2523        Self {
2524            texture,
2525            _view: view,
2526            texel_bind_group,
2527            filtered_bind_group,
2528            entries: BoundedLruCache::with_capacity_at_least_one(MAX_TEXT_GLYPH_ATLAS_ITEMS),
2529            generation: 0,
2530            size,
2531            max_size,
2532            cursor_x: TEXT_GLYPH_ATLAS_PADDING,
2533            cursor_y: TEXT_GLYPH_ATLAS_PADDING,
2534            row_height: 0,
2535            pending: Vec::new(),
2536            pending_coverage: Vec::new(),
2537            upload_scratch: Vec::new(),
2538        }
2539    }
2540
2541    fn create_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture {
2542        device.create_texture(&wgpu::TextureDescriptor {
2543            label: Some("Text Glyph Atlas Texture"),
2544            size: wgpu::Extent3d {
2545                width: size,
2546                height: size,
2547                depth_or_array_layers: 1,
2548            },
2549            mip_level_count: 1,
2550            sample_count: 1,
2551            dimension: wgpu::TextureDimension::D2,
2552            format: wgpu::TextureFormat::R8Unorm,
2553            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
2554            view_formats: &[],
2555        })
2556    }
2557
2558    fn reset(
2559        &mut self,
2560        device: &wgpu::Device,
2561        image_layout: &wgpu::BindGroupLayout,
2562        samplers: GlyphSamplers<'_>,
2563    ) {
2564        let generation = self.generation.wrapping_add(1);
2565        let grown = next_glyph_atlas_size(self.size, self.max_size);
2566        let mut next = Self::new(device, image_layout, samplers, grown);
2567        next.generation = generation;
2568        *self = next;
2569    }
2570
2571    /// The atlas bound for glyphs drawn under `transform`: texel for texel
2572    /// on the pixel grid, filtered once a transform turns the glyph quads
2573    /// off it.
2574    fn bind_group(&self, transform: SegmentTransform) -> Rc<wgpu::BindGroup> {
2575        Rc::clone(if transform.is_identity() {
2576            &self.texel_bind_group
2577        } else {
2578            &self.filtered_bind_group
2579        })
2580    }
2581
2582    fn generation(&self) -> u64 {
2583        self.generation
2584    }
2585
2586    fn size(&self) -> u32 {
2587        self.size
2588    }
2589
2590    /// One texel's share of the atlas side. The side is a power of two, so
2591    /// this reciprocal is exact and a coordinate times it is the coordinate
2592    /// divided by the side: a glyph's quad takes eight of them.
2593    fn texel(&self) -> f32 {
2594        (self.size() as f32).recip()
2595    }
2596
2597    fn entry(&mut self, key: &GlyphAtlasSlotKey) -> Option<GlyphAtlasEntry> {
2598        self.entries.get(key).copied()
2599    }
2600
2601    fn allocate(&mut self, width: u32, height: u32) -> Option<GlyphAtlasEntry> {
2602        let max_extent = self.size.saturating_sub(TEXT_GLYPH_ATLAS_PADDING * 2);
2603        if width == 0 || height == 0 || width > max_extent || height > max_extent {
2604            return None;
2605        }
2606
2607        if self.cursor_x + width + TEXT_GLYPH_ATLAS_PADDING > self.size {
2608            self.cursor_x = TEXT_GLYPH_ATLAS_PADDING;
2609            self.cursor_y = self
2610                .cursor_y
2611                .saturating_add(self.row_height)
2612                .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2613            self.row_height = 0;
2614        }
2615        if self.cursor_y > self.size - height - TEXT_GLYPH_ATLAS_PADDING {
2616            return None;
2617        }
2618
2619        let entry = GlyphAtlasEntry {
2620            x: self.cursor_x as u16,
2621            y: self.cursor_y as u16,
2622            width: width as u16,
2623            height: height as u16,
2624        };
2625        self.cursor_x = self
2626            .cursor_x
2627            .saturating_add(width)
2628            .saturating_add(TEXT_GLYPH_ATLAS_PADDING);
2629        self.row_height = self.row_height.max(height);
2630        Some(entry)
2631    }
2632
2633    /// The atlas entry of `glyph`, placed now if the atlas does not hold it
2634    /// yet; a placed glyph reaches the texture at [`Self::flush_uploads`].
2635    /// `None` when the atlas is full.
2636    fn upload_glyph(
2637        &mut self,
2638        glyph: &SoftwareGlyphAtlasGlyph,
2639        frame_stats: &mut gpu_stats::FrameStats,
2640    ) -> Option<GlyphAtlasEntry> {
2641        let key = GlyphAtlasSlotKey::new(glyph.key, glyph.color);
2642        if let Some(entry) = self.entry(&key) {
2643            frame_stats.record_text_glyph_atlas_hits(1);
2644            return Some(entry);
2645        }
2646
2647        let width = u32::try_from(glyph.mask.width).ok()?;
2648        let height = u32::try_from(glyph.mask.height).ok()?;
2649        let entry = self.allocate(width, height)?;
2650        let correction = key.luminance.correction();
2651        self.pending_coverage.extend(
2652            glyph
2653                .mask
2654                .alpha
2655                .iter()
2656                .map(|&coverage| correction.apply(coverage)),
2657        );
2658        self.pending.push(entry);
2659        frame_stats.record_text_glyph_atlas_miss(width, height);
2660        self.entries.put(key, entry);
2661        Some(entry)
2662    }
2663
2664    /// Writes the glyphs placed since the last call to the texture, one
2665    /// write for each run of them placed side by side on a row. The atlas
2666    /// never places a glyph where one was, so the run's padding and the
2667    /// rows under its shorter glyphs are empty, and the write leaves them
2668    /// so. A frame calls this before it submits draws that read them.
2669    fn flush_uploads(
2670        &mut self,
2671        queue: &wgpu::Queue,
2672        executor: &mut WgpuFrameGraphExecutor,
2673        frame_stats: &mut gpu_stats::FrameStats,
2674    ) {
2675        let mut coverage = 0;
2676        let mut run_start = 0;
2677        while run_start < self.pending.len() {
2678            let first = self.pending[run_start];
2679            let mut run_end = run_start + 1;
2680            while self
2681                .pending
2682                .get(run_end)
2683                .is_some_and(|next| next.y == first.y && next.x > self.pending[run_end - 1].x)
2684            {
2685                run_end += 1;
2686            }
2687            let run = &self.pending[run_start..run_end];
2688            let last = run[run.len() - 1];
2689            let x = u32::from(first.x);
2690            let width = u32::from(last.x) + u32::from(last.width) - x;
2691            let height = run
2692                .iter()
2693                .map(|entry| u32::from(entry.height))
2694                .max()
2695                .unwrap_or(0);
2696            self.upload_scratch.clear();
2697            self.upload_scratch.resize((width * height) as usize, 0);
2698            for entry in run {
2699                let glyph_width = usize::from(entry.width);
2700                let left = usize::from(entry.x) - x as usize;
2701                for row in 0..usize::from(entry.height) {
2702                    let source = coverage + row * glyph_width;
2703                    let target = row * width as usize + left;
2704                    self.upload_scratch[target..target + glyph_width]
2705                        .copy_from_slice(&self.pending_coverage[source..source + glyph_width]);
2706                }
2707                coverage += glyph_width * usize::from(entry.height);
2708            }
2709            let upload_stats = executor.upload_texture(
2710                queue,
2711                wgpu::TexelCopyTextureInfo {
2712                    texture: &self.texture,
2713                    mip_level: 0,
2714                    origin: wgpu::Origin3d {
2715                        x,
2716                        y: u32::from(first.y),
2717                        z: 0,
2718                    },
2719                    aspect: wgpu::TextureAspect::All,
2720                },
2721                &self.upload_scratch,
2722                wgpu::TexelCopyBufferLayout {
2723                    offset: 0,
2724                    bytes_per_row: Some(width),
2725                    rows_per_image: Some(height),
2726                },
2727                wgpu::Extent3d {
2728                    width,
2729                    height,
2730                    depth_or_array_layers: 1,
2731                },
2732            );
2733            frame_stats.record_command_stats(upload_stats);
2734            run_start = run_end;
2735        }
2736        self.pending.clear();
2737        self.pending_coverage.clear();
2738    }
2739}
2740
2741/// The image pipeline a draw takes: in a pass with depth or not, for an
2742/// alpha mask or a color image, and taking a rounded clip in place or not.
2743#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2744pub(crate) struct ImageVariant {
2745    depth: bool,
2746    alpha_mask: bool,
2747    rounded: bool,
2748}
2749
2750pub(crate) struct ImageDrawCmd {
2751    index_start: u32,
2752    scissor: (u32, u32, u32, u32),
2753    image: ImageBinding,
2754    /// The rounded clip whose coverage the image takes in place: its index
2755    /// among the pass's clip instances.
2756    clip: Option<u32>,
2757}
2758
2759impl ImageVariant {
2760    /// The variant `cmd` draws with in a pass with a depth buffer or not.
2761    fn of(cmd: &ImageDrawCmd, depth: bool) -> Self {
2762        Self {
2763            depth,
2764            alpha_mask: cmd.image.alpha_mask,
2765            rounded: cmd.clip.is_some(),
2766        }
2767    }
2768}
2769
2770impl ImageDrawCmd {
2771    /// Target pixels the draw can touch: its scissor.
2772    pub(crate) fn bounds(&self) -> TargetRect {
2773        self.scissor
2774    }
2775}
2776
2777/// Which glyph pipeline draws a stretch of quads: plain quads, sampled
2778/// within their glyph's texel centers; plain quads on whole pixels at one
2779/// texel a pixel, whose samples land on those centers unclamped; or quads
2780/// of a layer drawn in place under a turn, which are [`TurnedGlyph`]s.
2781#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2782pub(crate) enum GlyphQuads {
2783    Plain,
2784    Aligned,
2785    Turned,
2786}
2787
2788impl GlyphQuads {
2789    fn turned(self) -> bool {
2790        self == Self::Turned
2791    }
2792
2793    /// The plain kind that fits quads whose every corner is `aligned`.
2794    fn plain(aligned: bool) -> Self {
2795        if aligned { Self::Aligned } else { Self::Plain }
2796    }
2797}
2798
2799/// Whether a plain glyph quad at `rect` lands on whole pixels of a target
2800/// whose origin sits at `offset`: its quads hold one texel a pixel.
2801fn glyph_rect_aligned(rect: [f32; 4], offset: [f32; 2]) -> bool {
2802    let whole = |value: f32| value.fract() == 0.0;
2803    whole(rect[0] - offset[0])
2804        && whole(rect[1] - offset[1])
2805        && whole(rect[2] - offset[0])
2806        && whole(rect[3] - offset[1])
2807}
2808
2809#[derive(Clone)]
2810enum GlyphDrawSource {
2811    Shared {
2812        instance_start: u32,
2813        instance_count: u32,
2814        quads: GlyphQuads,
2815    },
2816    Retained {
2817        run: Rc<CachedGpuTextGlyphRun>,
2818        uniform_slot: usize,
2819        aligned: bool,
2820    },
2821}
2822
2823#[derive(Clone)]
2824pub(crate) struct GlyphDrawCmd {
2825    atlas: Rc<wgpu::BindGroup>,
2826    source: GlyphDrawSource,
2827    /// The scissor the text's own clip needs, `None` when its quads lie
2828    /// inside that clip anyway and only the batch's bound applies.
2829    scissor: Option<(u32, u32, u32, u32)>,
2830    /// Target pixels the draw can touch, for ordering it against others.
2831    bounds: (u32, u32, u32, u32),
2832}
2833
2834/// One draw of a glyph batch: a stretch of shared quads, or a retained run.
2835struct GlyphDraw<'a> {
2836    atlas: &'a Rc<wgpu::BindGroup>,
2837    scissor: Option<(u32, u32, u32, u32)>,
2838    step: GlyphDrawStep<'a>,
2839}
2840
2841enum GlyphDrawStep<'a> {
2842    /// A stretch of the shared instances of one kind.
2843    Shared(std::ops::Range<u32>, GlyphQuads),
2844    Retained {
2845        run: &'a CachedGpuTextGlyphRun,
2846        uniform_slot: usize,
2847        aligned: bool,
2848    },
2849}
2850
2851/// The draws a batch's glyph commands take: consecutive shared commands with
2852/// one atlas and one scissor whose quads follow each other in the frame's
2853/// shared buffer draw as one.
2854struct GlyphDraws<'a> {
2855    cmds: &'a [GlyphDrawCmd],
2856}
2857
2858impl<'a> GlyphDraws<'a> {
2859    fn new(cmds: &'a [GlyphDrawCmd]) -> Self {
2860        Self { cmds }
2861    }
2862}
2863
2864impl<'a> Iterator for GlyphDraws<'a> {
2865    type Item = GlyphDraw<'a>;
2866
2867    fn next(&mut self) -> Option<Self::Item> {
2868        let (first, rest) = self.cmds.split_first()?;
2869        self.cmds = rest;
2870        let step = match &first.source {
2871            GlyphDrawSource::Retained {
2872                run,
2873                uniform_slot,
2874                aligned,
2875            } => GlyphDrawStep::Retained {
2876                run,
2877                uniform_slot: *uniform_slot,
2878                aligned: *aligned,
2879            },
2880            GlyphDrawSource::Shared {
2881                instance_start,
2882                instance_count,
2883                quads,
2884            } => {
2885                let mut end = instance_start + instance_count;
2886                while let Some((next, rest)) = self.cmds.split_first() {
2887                    match next.source {
2888                        GlyphDrawSource::Shared {
2889                            instance_start,
2890                            instance_count,
2891                            quads: next_quads,
2892                        } if instance_start == end
2893                            && next_quads == *quads
2894                            && next.scissor == first.scissor
2895                            && Rc::ptr_eq(&next.atlas, &first.atlas) =>
2896                        {
2897                            end += instance_count;
2898                            self.cmds = rest;
2899                        }
2900                        _ => break,
2901                    }
2902                }
2903                GlyphDrawStep::Shared(*instance_start..end, *quads)
2904            }
2905        };
2906        Some(GlyphDraw {
2907            atlas: &first.atlas,
2908            scissor: first.scissor,
2909            step,
2910        })
2911    }
2912}
2913
2914impl GlyphDrawCmd {
2915    /// The quads the command draws, which pick its pipeline.
2916    fn quads(&self) -> GlyphQuads {
2917        match &self.source {
2918            GlyphDrawSource::Shared { quads, .. } => *quads,
2919            GlyphDrawSource::Retained { aligned, .. } => GlyphQuads::plain(*aligned),
2920        }
2921    }
2922
2923    fn shared(
2924        (instances, quads): (std::ops::Range<usize>, GlyphQuads),
2925        scissor: Option<(u32, u32, u32, u32)>,
2926        bounds: (u32, u32, u32, u32),
2927        atlas: Rc<wgpu::BindGroup>,
2928    ) -> Self {
2929        let start = u32::try_from(instances.start).unwrap_or(u32::MAX);
2930        let end = u32::try_from(instances.end).unwrap_or(u32::MAX);
2931        Self {
2932            atlas,
2933            source: GlyphDrawSource::Shared {
2934                instance_start: start,
2935                instance_count: end.saturating_sub(start),
2936                quads,
2937            },
2938            scissor,
2939            bounds,
2940        }
2941    }
2942
2943    fn retained(
2944        (run, uniform_slot, aligned): (Rc<CachedGpuTextGlyphRun>, usize, bool),
2945        scissor: (u32, u32, u32, u32),
2946        atlas: Rc<wgpu::BindGroup>,
2947    ) -> Self {
2948        Self {
2949            atlas,
2950            source: GlyphDrawSource::Retained {
2951                run,
2952                uniform_slot,
2953                aligned,
2954            },
2955            scissor: Some(scissor),
2956            bounds: scissor,
2957        }
2958    }
2959
2960    /// Target pixels the draw can touch.
2961    pub(crate) fn bounds(&self) -> (u32, u32, u32, u32) {
2962        self.bounds
2963    }
2964
2965    /// Whether the draw's quads are [`TurnedGlyph`]s, or `None` for a
2966    /// retained run, which draws on its own.
2967    fn turned(&self) -> Option<bool> {
2968        match self.source {
2969            GlyphDrawSource::Shared { quads, .. } => Some(quads.turned()),
2970            GlyphDrawSource::Retained { .. } => None,
2971        }
2972    }
2973}
2974
2975/// The kind of glyph draw, turned (`true`) or plain, that can move after
2976/// every draw of the other kind in `draws` without moving past a draw it
2977/// shares a pixel with: glyphs blend, so only draws that share pixels must
2978/// keep their order. The fewer kind is tried first, which checks fewer
2979/// pairs. `None` when neither can move, a retained run is among them, or
2980/// the kinds do not change back and forth.
2981pub(crate) fn movable_glyph_kind<T>(
2982    draws: &[T],
2983    kind: impl Fn(&T) -> Option<bool>,
2984    bounds: impl Fn(&T) -> TargetRect,
2985) -> Option<bool> {
2986    let mut turned = 0;
2987    for draw in draws {
2988        turned += usize::from(kind(draw)?);
2989    }
2990    let changes = draws
2991        .windows(2)
2992        .filter(|pair| kind(&pair[0]) != kind(&pair[1]))
2993        .count();
2994    if changes < 2 {
2995        return None;
2996    }
2997    let fewer = turned * 2 < draws.len();
2998    [fewer, !fewer].into_iter().find(|&moved| {
2999        draws.iter().enumerate().all(|(index, draw)| {
3000            kind(draw) != Some(moved)
3001                || draws[index + 1..].iter().all(|later| {
3002                    kind(later) == Some(moved)
3003                        || !crate::draw_pass::target_rects_overlap(bounds(draw), bounds(later))
3004                })
3005        })
3006    })
3007}
3008
3009/// Moves a glyph batch's retained runs after its shared quads, each in its
3010/// order, when no run shares a pixel with a shared draw after it: the
3011/// shared quads around a run, which follow each other in the frame's
3012/// buffer, then draw at once. A card's body text, a retained run between
3013/// its title and its labels, split them into two draws. Returns how many
3014/// shared draws lead the batch, none when its runs keep their places;
3015/// `moved` is scratch.
3016pub(crate) fn defer_retained_glyph_runs(
3017    cmds: &mut [GlyphDrawCmd],
3018    moved: &mut Vec<GlyphDrawCmd>,
3019) -> usize {
3020    let retained = |cmd: &GlyphDrawCmd| cmd.turned().is_none();
3021    let shared = cmds.iter().filter(|cmd| !retained(cmd)).count();
3022    if cmds[..shared].iter().all(|cmd| !retained(cmd)) {
3023        return shared;
3024    }
3025    let deferrable = cmds.iter().enumerate().all(|(index, cmd)| {
3026        !retained(cmd)
3027            || cmds[index + 1..].iter().all(|later| {
3028                retained(later)
3029                    || !crate::draw_pass::target_rects_overlap(cmd.bounds(), later.bounds())
3030            })
3031    });
3032    if !deferrable {
3033        return 0;
3034    }
3035    moved.clear();
3036    let mut kept = 0;
3037    for read in 0..cmds.len() {
3038        if retained(&cmds[read]) {
3039            moved.push(cmds[read].clone());
3040        } else {
3041            cmds.swap(kept, read);
3042            kept += 1;
3043        }
3044    }
3045    for (slot, cmd) in cmds[kept..].iter_mut().zip(moved.drain(..)) {
3046        *slot = cmd;
3047    }
3048    shared
3049}
3050
3051/// Moves a glyph batch's draws of the kind [`movable_glyph_kind`] picks
3052/// after those of the other kind, each kind in its order, so each draws
3053/// once instead of once per change between them. `moved` is scratch.
3054pub(crate) fn group_glyph_kinds(cmds: &mut [GlyphDrawCmd], moved: &mut Vec<GlyphDrawCmd>) {
3055    let Some(kind) = movable_glyph_kind(cmds, GlyphDrawCmd::turned, GlyphDrawCmd::bounds) else {
3056        return;
3057    };
3058    moved.clear();
3059    let mut kept = 0;
3060    for read in 0..cmds.len() {
3061        if cmds[read].turned() == Some(kind) {
3062            moved.push(cmds[read].clone());
3063        } else {
3064            cmds.swap(kept, read);
3065            kept += 1;
3066        }
3067    }
3068    for (slot, cmd) in cmds[kept..].iter_mut().zip(moved.drain(..)) {
3069        *slot = cmd;
3070    }
3071}
3072
3073#[derive(Clone, Copy, Debug, PartialEq)]
3074struct ImageUvRect {
3075    min: [f32; 2],
3076    max: [f32; 2],
3077    sample_bounds: [f32; 4],
3078}
3079
3080/// A growable vertex buffer and index buffer pair.
3081/// One pass's image and shared glyph quads: the frame's vertex and index
3082/// uploads they were appended to.
3083pub(crate) struct ImageSlot {
3084    vertices: BufferUpload,
3085    indices: BufferUpload,
3086    /// The rounded clips the pass's images take in place, one instance each.
3087    clips: Option<BufferUpload>,
3088}
3089
3090fn image_vertex_spec() -> UploadAllocatorSpec {
3091    UploadAllocatorSpec::vertex("Image Vertex Buffer", std::mem::size_of::<Vertex>() as u64)
3092}
3093
3094fn image_index_spec() -> UploadAllocatorSpec {
3095    UploadAllocatorSpec::index("Image Index Buffer", std::mem::size_of::<u32>() as u64)
3096}
3097
3098fn glyph_instance_spec() -> UploadAllocatorSpec {
3099    UploadAllocatorSpec::vertex(
3100        "Glyph Instance Buffer",
3101        std::mem::size_of::<GlyphInstance>() as u64,
3102    )
3103}
3104
3105fn turned_glyph_spec() -> UploadAllocatorSpec {
3106    UploadAllocatorSpec::vertex(
3107        "Turned Glyph Instance Buffer",
3108        std::mem::size_of::<TurnedGlyph>() as u64,
3109    )
3110}
3111
3112#[derive(Default)]
3113struct ViewportUniforms {
3114    uploads: FrameUploadAllocators,
3115    slots: Vec<UniformUpload>,
3116}
3117
3118impl ViewportUniforms {
3119    fn begin_frame(&mut self) {
3120        self.slots.clear();
3121        self.uploads.reset();
3122    }
3123
3124    fn claim(
3125        &mut self,
3126        device: &wgpu::Device,
3127        layout: &wgpu::BindGroupLayout,
3128        uniforms: &Uniforms,
3129    ) -> usize {
3130        let slot = self.slots.len();
3131        self.slots.push(self.uploads.upload_uniform(
3132            UploadAllocatorId::Viewport,
3133            UploadAllocatorSpec::uniform(
3134                "Viewport Uniform Buffer",
3135                "Viewport Uniform Bind Group",
3136                std::mem::size_of::<Uniforms>() as u64,
3137            ),
3138            device,
3139            layout,
3140            bytemuck::bytes_of(uniforms),
3141        ));
3142        slot
3143    }
3144
3145    fn bind(&self, pass: &mut TrackedPass<'_, '_>, slot: usize) -> Result<(), String> {
3146        let uniform = self
3147            .slots
3148            .get(slot)
3149            .ok_or_else(|| "viewport uniform slot was never claimed this frame".to_string())?;
3150        pass.set_bind_group(0, &uniform.bind_group, &[uniform.offset]);
3151        Ok(())
3152    }
3153
3154    fn stage_pending(
3155        &mut self,
3156        device: &wgpu::Device,
3157        recorder: &mut impl FrameCommandRecorder,
3158    ) -> FrameCommandStats {
3159        self.uploads.stage_pending(|buffer, offset, bytes| {
3160            recorder.stage_frame_buffer_copy(device, buffer, offset, bytes)
3161        })
3162    }
3163}
3164
3165#[derive(Clone, Copy, Debug, PartialEq)]
3166pub(crate) struct ViewportUniformParams {
3167    pub(crate) width: u32,
3168    pub(crate) height: u32,
3169    pub(crate) offset: [f32; 2],
3170    pub(crate) transform: SegmentTransform,
3171    /// Where the drawn vertices' origin sits in the segment's device space,
3172    /// added before the transform: zero, except for a retained glyph run
3173    /// drawn under a transform, whose vertices sit at its raster origin. The
3174    /// sum is the one the shared path writes, so both draw the same pixels.
3175    pub(crate) origin: [f32; 2],
3176    /// The pass-order index of the batch's first shape record, from which
3177    /// each record's depth counts.
3178    pub(crate) depth_base: f32,
3179}
3180
3181impl ViewportUniformParams {
3182    /// The logical rect of the drawn scene that the target shows.
3183    pub(crate) fn scene_rect(self, root_scale: f32) -> Rect {
3184        segment_scene_rect(
3185            self.transform,
3186            Rect {
3187                x: self.offset[0],
3188                y: self.offset[1],
3189                width: self.width as f32,
3190                height: self.height as f32,
3191            },
3192            root_scale,
3193        )
3194    }
3195}
3196
3197/// The logical rect of a scene drawn under `transform` that the device rect
3198/// `device` of the target's scene space shows: the rect itself when the
3199/// scene is not transformed, else the bounds it maps back to.
3200pub(crate) fn segment_scene_rect(
3201    transform: SegmentTransform,
3202    device: Rect,
3203    root_scale: f32,
3204) -> Rect {
3205    let device = if transform.is_identity() {
3206        device
3207    } else {
3208        transform.segment_bounds(device)
3209    };
3210    Rect {
3211        x: device.x / root_scale,
3212        y: device.y / root_scale,
3213        width: device.width / root_scale,
3214        height: device.height / root_scale,
3215    }
3216}
3217
3218/// A stored run's draws for one pass: the tables current when it was
3219/// prepared, the uniform slot holding its placement, and the range of the
3220/// pass's run draws with the pipeline and vertex range of each segment's
3221/// quads and bands.
3222pub(crate) struct StoreRunBatch {
3223    pub(crate) tables: StoredTables,
3224    pub(crate) uniform_slot: usize,
3225    pub(crate) draws: std::ops::Range<usize>,
3226    /// The scissor an unturned run's clip puts on its paint: see
3227    /// [`clip_scissor`].
3228    pub(crate) clip: Option<TargetRect>,
3229}
3230
3231struct CompositionTarget {
3232    target: Rc<OffscreenTarget>,
3233    output_bind_group: wgpu::BindGroup,
3234}
3235
3236/// Where a frame renders: straight into the presentable image, or into the
3237/// reusable composition target that the output conversion then copies out.
3238enum FrameRoot {
3239    Surface(Rc<OffscreenTarget>),
3240    Composition(CompositionTarget),
3241}
3242
3243impl FrameRoot {
3244    fn target(&self) -> &Rc<OffscreenTarget> {
3245        match self {
3246            Self::Surface(target) => target,
3247            Self::Composition(composition) => &composition.target,
3248        }
3249    }
3250
3251    /// The output conversion's destination and source bind group; nothing
3252    /// when the frame already rendered into the presentable image.
3253    fn output<'a>(
3254        &'a self,
3255        output_view: Option<&'a wgpu::TextureView>,
3256        screenshot_bind_group: Option<&'a wgpu::BindGroup>,
3257    ) -> Option<(&'a wgpu::TextureView, &'a wgpu::BindGroup)> {
3258        match self {
3259            Self::Surface(_) => None,
3260            Self::Composition(composition) => output_view.map(|view| {
3261                (
3262                    view,
3263                    screenshot_bind_group.unwrap_or(&composition.output_bind_group),
3264                )
3265            }),
3266        }
3267    }
3268}
3269
3270/// What a presentable image must allow to be the frame's root target:
3271/// rendering, and the copies a capture and the opaque-prefix cache take of
3272/// the page and put back.
3273const DIRECT_SURFACE_ROOT_USAGES: wgpu::TextureUsages = wgpu::TextureUsages::RENDER_ATTACHMENT
3274    .union(wgpu::TextureUsages::COPY_SRC)
3275    .union(wgpu::TextureUsages::COPY_DST);
3276
3277/// The usages to ask of a presentable image: rendering, and whichever of
3278/// the copies and sampling the surface offers. Sampling lets a frame whose
3279/// backdrops read the page draw straight into the image too.
3280pub fn presentable_root_usages(supported: wgpu::TextureUsages) -> wgpu::TextureUsages {
3281    wgpu::TextureUsages::RENDER_ATTACHMENT
3282        | (supported & (DIRECT_SURFACE_ROOT_USAGES | wgpu::TextureUsages::TEXTURE_BINDING))
3283}
3284
3285/// Whether the presented image can be the frame's root target: its bytes
3286/// are the composition format (so the 8-bit output conversion would be an
3287/// identity), it is the viewport's size, it can be copied as the page is,
3288/// and it can be sampled when the frame `reads_page` through a backdrop.
3289/// Metal's images cannot be sampled, so only a frame without backdrops
3290/// draws straight into one there.
3291fn surface_is_direct_root(
3292    texture: &wgpu::Texture,
3293    composition_format: wgpu::TextureFormat,
3294    viewport: (u32, u32),
3295    reads_page: bool,
3296) -> bool {
3297    let usage = texture.usage();
3298    texture.format().remove_srgb_suffix() == composition_format
3299        && usage.contains(DIRECT_SURFACE_ROOT_USAGES)
3300        && (!reads_page || usage.contains(wgpu::TextureUsages::TEXTURE_BINDING))
3301        && (texture.width(), texture.height()) == viewport
3302}
3303
3304#[derive(Clone, Copy)]
3305enum OutputMode {
3306    Display,
3307    Screenshot,
3308}
3309
3310pub struct GpuRenderer {
3311    pub(crate) device: Arc<wgpu::Device>,
3312    pub(crate) queue: Arc<wgpu::Queue>,
3313    device_errors: Arc<DeviceErrorSentry>,
3314    renderer_epoch: u64,
3315    pub(crate) composition_format: wgpu::TextureFormat,
3316    #[cfg(not(target_arch = "wasm32"))]
3317    display_format: wgpu::TextureFormat,
3318    composition_target: Option<CompositionTarget>,
3319    output_converter: OutputConverter,
3320    screenshot_converter: OutputConverter,
3321    adapter_backend: wgpu::Backend,
3322    pipeline_cache: Option<wgpu::PipelineCache>,
3323    #[cfg(not(target_arch = "wasm32"))]
3324    _pipeline_cache_watcher: Option<crate::pipeline_disk_cache::PersistWatcher>,
3325    /// The pipelines recent launches of another build drew with, built once
3326    /// this renderer's first frame is drawn.
3327    #[cfg(not(target_arch = "wasm32"))]
3328    recent_after_update: Option<Arc<crate::pipeline_records::PipelineRecords>>,
3329    /// What this renderer draws with, for the next launches.
3330    recorder: crate::pipeline_recorder::PipelineRecorder,
3331    /// The background compiler, which builds a pass's missing pipelines side
3332    /// by side.
3333    pipeline_compiler: PipelineCompiler,
3334    /// Where the background compiler says a pipeline a placeholder waited
3335    /// for landed.
3336    #[cfg(not(target_arch = "wasm32"))]
3337    landing: Option<Arc<crate::pipeline_compiler::Landing>>,
3338    /// The pipelines the background threads had built when this frame
3339    /// started.
3340    #[cfg(not(target_arch = "wasm32"))]
3341    built_at_frame_start: u64,
3342    /// Whether this frame drew a placeholder in place of an effect whose
3343    /// pipelines were compiling.
3344    pub(crate) drew_placeholder: bool,
3345    shape_pipelines: ShapePipelines,
3346    /// Image and glyph pipelines for passes without and with a depth buffer.
3347    image_pipeline: [FixedPipeline; 8],
3348    image_pipeline_dst_out: [FixedPipeline; 8],
3349    /// Indexed by depth, then turned: see [`GpuRenderer::glyph_atlas_pipeline`].
3350    glyph_atlas_pipeline: [FixedPipeline; 6],
3351    /// Round rect shadow pipelines without and with a depth buffer.
3352    rrect_shadow_pipeline: [FixedPipeline; 2],
3353    image_shader: SharedShader,
3354    glyph_atlas_shader: SharedShader,
3355    rrect_shadow_shader: SharedShader,
3356    /// Transient depth buffers by target size, for passes that lay opaque
3357    /// interiors down first, dropped once no frame has used them for
3358    /// [`crate::idle_pool::IDLE_FRAMES`].
3359    depth_targets: crate::idle_pool::IdlePool<((u32, u32), wgpu::TextureView)>,
3360    pub(crate) depth_gate: crate::depth_gate::DepthGate,
3361    /// The size of the atlas the layer surfaces drawn again go into.
3362    pub(crate) surface_atlas_sizes: crate::frame::SurfaceAtlasSizes,
3363    uniform_bind_group_layout: wgpu::BindGroupLayout,
3364    image_bind_group_layout: wgpu::BindGroupLayout,
3365    image_nearest_sampler: wgpu::Sampler,
3366    image_linear_sampler: wgpu::Sampler,
3367    text_fonts: SoftwareTextFontSet,
3368    viewport_uniforms: ViewportUniforms,
3369    run_store: RunStore,
3370    image_texture_cache: BoundedLruCache<u64, CachedImageTexture>,
3371    image_texture_cache_bytes: usize,
3372    external_texture_bindings: BoundedLruCache<u64, ImageBindGroups>,
3373    text_image_cache: BoundedLruCache<TextImageCacheKey, CachedTextImage>,
3374    text_glyph_atlas: TextGlyphAtlas,
3375    text_glyph_run_cache: BoundedLruCache<TextGlyphRunCacheKey, CachedTextGlyphRun>,
3376    text_glyph_gpu_run_cache: BoundedLruCache<TextGlyphRunCacheKey, Rc<CachedGpuTextGlyphRun>>,
3377    text_glyph_run_arena: GlyphRunArena,
3378    /// How run tables and retained glyph runs reach the GPU, and whether
3379    /// kept layer surfaces stay in their atlas: see [`UploadMode::copy_free`].
3380    pub(crate) copy_free: UploadMode,
3381    text_glyph_run_frame: u64,
3382    /// Text runs the frame has drawn so far, cached or not.
3383    text_glyph_runs_drawn: usize,
3384    text_glyph_mask_cache: SoftwareGlyphRasterCache,
3385    text_line_index_cache: TextLineIndexCache,
3386    pub(crate) scratch_image_vertices: Vec<Vertex>,
3387    pub(crate) scratch_image_indices: Vec<u32>,
3388    pub(crate) scratch_glyph_instances: GlyphInstances,
3389    pub(crate) scratch_image_cmds: Vec<ImageDrawCmd>,
3390    pub(crate) scratch_image_clips: Vec<DeviceRoundedClip>,
3391    pub(crate) scratch_glyph_cmds: Vec<GlyphDrawCmd>,
3392    pub(crate) scratch_glyph_moved: Vec<GlyphDrawCmd>,
3393    pub(crate) scratch_shadow_instances: Vec<ShadowInstance>,
3394    pub(crate) scratch_arena_draws: Vec<RunDrawCall>,
3395    pub(crate) scratch_pipelines: PipelineDemand,
3396    pub(crate) scratch_held: crate::draw_pass::HeldDraws,
3397    scratch_text_glyph_run: Vec<SoftwareGlyphAtlasRunGlyph>,
3398    scratch_text_glyph_entries: Vec<GlyphAtlasEntry>,
3399    run_glyph_scratch: RunGlyphScratch,
3400    frame_graph_executor: WgpuFrameGraphExecutor,
3401    pub(crate) stage_side_scratch: StageSideScratch,
3402    deferred_offscreen_releases: Vec<OffscreenTarget>,
3403    pub(crate) effect_renderer: EffectRenderer,
3404    pub(crate) layer_cache: LayerCache,
3405    pub(crate) ablation: Ablation,
3406    pub(crate) ablation_frames: u32,
3407    pub(crate) nesting_overflow_reported: bool,
3408    pub(crate) backdrop_gates: HashMap<NodeId, AdmissionGate>,
3409    pub(crate) fill_gates: HashMap<DrawCommandId, AdmissionGate>,
3410    pub(crate) effect_gates: HashMap<NodeId, AdmissionGate>,
3411    pub(crate) source_gates: HashMap<NodeId, AdmissionGate>,
3412    transparent_sources: HashMap<(u32, u32), Rc<OffscreenTarget>>,
3413    shadow_surface_cache: BoundedLruCache<ShadowSurfaceCacheKey, CachedShadowSurface>,
3414    shadow_surface_cache_bytes: u64,
3415    pub(crate) frame_stats: gpu_stats::FrameStats,
3416    last_frame_stats: Option<gpu_stats::FrameStatsSnapshot>,
3417    pending_frame_warmup_frames: u8,
3418    frame_count: u64,
3419    /// Whether the next frame first learns its pipelines: see
3420    /// [`Self::discover_frame_pipelines`].
3421    #[cfg(not(target_arch = "wasm32"))]
3422    discovers_next_frame: bool,
3423    /// Whether the pipeline cache file holds the last launch's first screen,
3424    /// which builds ahead of this renderer's first frame.
3425    #[cfg(not(target_arch = "wasm32"))]
3426    first_screen_recorded: bool,
3427    /// Whether the frame drawing learns its pipelines and draws nothing.
3428    #[cfg(not(target_arch = "wasm32"))]
3429    pub(crate) discovering: bool,
3430    /// How many requested shader warm-ups this renderer has queued.
3431    shader_warm_ups_queued: usize,
3432}
3433
3434/// What a frame clears to before it draws: nothing for a transparent
3435/// window, the framework's background for every other surface.
3436pub fn frame_clear_color(transparent: bool) -> wgpu::Color {
3437    if transparent {
3438        wgpu::Color::TRANSPARENT
3439    } else {
3440        CLEAR_COLOR
3441    }
3442}
3443
3444fn image_sampler_descriptor(sampling: ImageSampling) -> wgpu::SamplerDescriptor<'static> {
3445    let filter = match sampling {
3446        ImageSampling::Nearest => wgpu::FilterMode::Nearest,
3447        ImageSampling::Linear => wgpu::FilterMode::Linear,
3448    };
3449    wgpu::SamplerDescriptor {
3450        label: Some(match sampling {
3451            ImageSampling::Nearest => "Nearest Image Sampler",
3452            ImageSampling::Linear => "Linear Image Sampler",
3453        }),
3454        address_mode_u: wgpu::AddressMode::ClampToEdge,
3455        address_mode_v: wgpu::AddressMode::ClampToEdge,
3456        address_mode_w: wgpu::AddressMode::ClampToEdge,
3457        mag_filter: filter,
3458        min_filter: filter,
3459        mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3460        ..Default::default()
3461    }
3462}
3463
3464/// What a [`GpuRenderer`] is built from. It crosses to the present thread
3465/// whole, so it holds only owned, `Send` parts.
3466pub(crate) struct GpuRendererInit {
3467    pub(crate) device: Arc<wgpu::Device>,
3468    pub(crate) queue: Arc<wgpu::Queue>,
3469    pub(crate) surface_format: wgpu::TextureFormat,
3470    pub(crate) adapter_backend: wgpu::Backend,
3471    pub(crate) adapter_downlevel: wgpu::DownlevelFlags,
3472    pub(crate) text_fonts: SoftwareTextFontSet,
3473    pub(crate) renderer_epoch: u64,
3474    pub(crate) pipeline_compilation: PipelineCompilation,
3475    pub(crate) on_device_lost: Option<crate::DeviceLostHandler>,
3476}
3477
3478impl GpuRenderer {
3479    pub fn new(init: GpuRendererInit) -> Self {
3480        let GpuRendererInit {
3481            device,
3482            queue,
3483            surface_format,
3484            adapter_backend,
3485            adapter_downlevel,
3486            text_fonts,
3487            renderer_epoch,
3488            pipeline_compilation,
3489            on_device_lost,
3490        } = init;
3491        let display_format = surface_format;
3492        let construction_started = Instant::now();
3493        let device_errors = Arc::new(DeviceErrorSentry::default());
3494        if survive_gpu_errors_enabled() {
3495            let sentry = Arc::clone(&device_errors);
3496            device.on_uncaptured_error(Arc::new(move |error| sentry.record(&error)));
3497        }
3498        let composition_format = crate::offscreen::composition_format(display_format);
3499        device.set_device_lost_callback(move |reason, message| {
3500            log::error!("[gpu-device] device lost ({reason:?}): {message}");
3501            if let Some(on_device_lost) = &on_device_lost {
3502                on_device_lost();
3503            }
3504        });
3505        let copy_free = UploadMode::copy_free(&device, adapter_backend);
3506        let mut run_store = RunStore::new(
3507            &device,
3508            RunBufferMode::for_device(&device, adapter_downlevel),
3509            copy_free,
3510        );
3511        let uniform_bind_group_layout =
3512            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3513                label: Some("Viewport Uniform Bind Group Layout"),
3514                entries: &[wgpu::BindGroupLayoutEntry {
3515                    binding: 0,
3516                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3517                    ty: wgpu::BindingType::Buffer {
3518                        ty: wgpu::BufferBindingType::Uniform,
3519                        has_dynamic_offset: true,
3520                        min_binding_size: wgpu::BufferSize::new(
3521                            std::mem::size_of::<Uniforms>() as u64
3522                        ),
3523                    },
3524                    count: None,
3525                }],
3526            });
3527        let image_bind_group_layout =
3528            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3529                label: Some("Image Texture Bind Group Layout"),
3530                entries: &[
3531                    wgpu::BindGroupLayoutEntry {
3532                        binding: 0,
3533                        visibility: wgpu::ShaderStages::FRAGMENT,
3534                        ty: wgpu::BindingType::Texture {
3535                            multisampled: false,
3536                            view_dimension: wgpu::TextureViewDimension::D2,
3537                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
3538                        },
3539                        count: None,
3540                    },
3541                    wgpu::BindGroupLayoutEntry {
3542                        binding: 1,
3543                        visibility: wgpu::ShaderStages::FRAGMENT,
3544                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3545                        count: None,
3546                    },
3547                ],
3548            });
3549        let image_nearest_sampler =
3550            device.create_sampler(&image_sampler_descriptor(ImageSampling::Nearest));
3551        let image_linear_sampler =
3552            device.create_sampler(&image_sampler_descriptor(ImageSampling::Linear));
3553        let text_glyph_atlas = TextGlyphAtlas::new(
3554            &device,
3555            &image_bind_group_layout,
3556            GlyphSamplers {
3557                nearest: &image_nearest_sampler,
3558                linear: &image_linear_sampler,
3559            },
3560            TEXT_GLYPH_ATLAS_MIN_SIZE,
3561        );
3562        let viewport_uniforms = ViewportUniforms::default();
3563
3564        static GLASS_MATERIAL_FOLDS: DebugToggle =
3565            DebugToggle::new("CRANPOSE_GLASS_MATERIAL_FOLDS");
3566        if GLASS_MATERIAL_FOLDS.equals("1") {
3567            cranpose_ui_graphics::set_glass_material_folds(true);
3568        } else if GLASS_MATERIAL_FOLDS.equals("0") {
3569            cranpose_ui_graphics::set_glass_material_folds(false);
3570        }
3571        log::info!(
3572            "[gpu-init] liquid glass material folds {}",
3573            if cranpose_ui_graphics::glass_material_folds_enabled() {
3574                "on: a pipeline per material's feature set"
3575            } else {
3576                "off: one pipeline per blend mode"
3577            }
3578        );
3579
3580        #[cfg(not(target_arch = "wasm32"))]
3581        let crate::pipeline_disk_cache::Loaded {
3582            cache: pipeline_cache,
3583            records,
3584            updated,
3585            holds_recorded,
3586        } = crate::pipeline_disk_cache::load(&device);
3587        #[cfg(not(target_arch = "wasm32"))]
3588        let first_screen: Vec<u64> = records
3589            .shapes
3590            .iter()
3591            .filter(|shape| shape.first_screen)
3592            .map(|shape| shape.entry)
3593            .collect();
3594        #[cfg(target_arch = "wasm32")]
3595        let (pipeline_cache, first_screen): (Option<wgpu::PipelineCache>, Vec<u64>) =
3596            (None, Vec::new());
3597        let recorder = crate::pipeline_recorder::PipelineRecorder::default();
3598        #[cfg(not(target_arch = "wasm32"))]
3599        let pipeline_cache_watcher = crate::pipeline_disk_cache::spawn_persist_watcher(
3600            pipeline_cache.clone(),
3601            Arc::clone(&records),
3602            recorder.clone(),
3603        );
3604
3605        let effects_started = Instant::now();
3606        let pipeline_compiler =
3607            PipelineCompiler::for_compilation(pipeline_compilation, adapter_backend);
3608        // A launch with no record of its first screen learns its first
3609        // frame's pipelines before it draws, where they compile side by side.
3610        // `CRANPOSE_FIRST_FRAME_DISCOVERY=0` draws it pass by pass instead.
3611        #[cfg(not(target_arch = "wasm32"))]
3612        static FIRST_FRAME_DISCOVERY: DebugToggle =
3613            DebugToggle::new("CRANPOSE_FIRST_FRAME_DISCOVERY");
3614        #[cfg(not(target_arch = "wasm32"))]
3615        let first_screen_recorded = records.shapes.iter().any(|shape| shape.first_screen);
3616        #[cfg(not(target_arch = "wasm32"))]
3617        let discovers_first_frame = !FIRST_FRAME_DISCOVERY.equals("0")
3618            && adapter_backend == wgpu::Backend::Metal
3619            && pipeline_compiler.is_active()
3620            && !first_screen_recorded;
3621        let depth_gate = crate::depth_gate::DepthGate::new(
3622            crate::draw_pass::lays_interiors_first(adapter_backend),
3623            pipeline_compiler.is_active(),
3624        );
3625        let effect_renderer = EffectRenderer::new(
3626            &device,
3627            pipeline_compiler.clone(),
3628            pipeline_cache.clone(),
3629            composition_format,
3630            adapter_backend,
3631            recorder.clone(),
3632        );
3633        let output_converter = OutputConverter::new(&device, adapter_backend, display_format);
3634        let screenshot_converter =
3635            OutputConverter::new(&device, adapter_backend, wgpu::TextureFormat::Rgba8Unorm);
3636        let effects_ms = instant_ms(effects_started, Instant::now());
3637        let mut frame_graph_executor = WgpuFrameGraphExecutor::new();
3638        frame_graph_executor.init_pass_timing(&device, &queue);
3639        #[cfg(target_arch = "wasm32")]
3640        frame_graph_executor.batch_queue_writes(adapter_backend == wgpu::Backend::BrowserWebGpu);
3641        let shape_shader = SharedShader::new(
3642            &device,
3643            adapter_backend,
3644            "Shape Shader",
3645            shape_shader_code(run_store.mode()),
3646            &[Some(&uniform_bind_group_layout), Some(run_store.layout())],
3647        );
3648        if run_store.mode().trig_fill {
3649            let fill = ArcTrigFill::new(
3650                &device,
3651                adapter_backend,
3652                pipeline_cache.clone(),
3653                shape_shader.clone(),
3654                recorder.clone(),
3655            );
3656            if first_screen.contains(&crate::arc_trig_fill::FIRST_SCREEN_KEY) {
3657                fill.warm(&pipeline_compiler);
3658            }
3659            run_store.attach_trig_fill(fill);
3660        }
3661        let shape_pipelines = ShapePipelines::new(
3662            ShapePipelineFactory {
3663                device: Arc::clone(&device),
3664                cache: pipeline_cache.clone(),
3665                format: composition_format,
3666                shader: shape_shader,
3667                mode: run_store.mode(),
3668            },
3669            adapter_backend,
3670            &pipeline_compiler,
3671            first_screen
3672                .into_iter()
3673                .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3674                .filter_map(ShapePipelineKey::from_bits),
3675            recorder.clone(),
3676        );
3677        let image_layouts = [
3678            Some(&uniform_bind_group_layout),
3679            Some(&image_bind_group_layout),
3680        ];
3681        let image_shader = SharedShader::new(
3682            &device,
3683            adapter_backend,
3684            "Image Shader",
3685            shaders::IMAGE,
3686            &image_layouts,
3687        );
3688        let glyph_atlas_shader = SharedShader::new(
3689            &device,
3690            adapter_backend,
3691            "Glyph Atlas Shader",
3692            shaders::GLYPH_ATLAS,
3693            &image_layouts,
3694        );
3695        let rrect_shadow_shader = SharedShader::new(
3696            &device,
3697            adapter_backend,
3698            "Round Rect Shadow Shader",
3699            shaders::RRECT_SHADOW,
3700            &[Some(&uniform_bind_group_layout)],
3701        );
3702
3703        let mut renderer = Self {
3704            device,
3705            queue,
3706            device_errors,
3707            renderer_epoch,
3708            composition_format,
3709            #[cfg(not(target_arch = "wasm32"))]
3710            display_format,
3711            composition_target: None,
3712            output_converter,
3713            screenshot_converter,
3714            adapter_backend,
3715            pipeline_cache,
3716            #[cfg(not(target_arch = "wasm32"))]
3717            _pipeline_cache_watcher: pipeline_cache_watcher,
3718            #[cfg(not(target_arch = "wasm32"))]
3719            recent_after_update: updated.then(|| Arc::clone(&records)),
3720            recorder,
3721            #[cfg(not(target_arch = "wasm32"))]
3722            landing: pipeline_compiler.landing(),
3723            pipeline_compiler,
3724            #[cfg(not(target_arch = "wasm32"))]
3725            built_at_frame_start: 0,
3726            drew_placeholder: false,
3727            shape_pipelines,
3728            image_pipeline: [
3729                FixedPipeline::new("image/src-over"),
3730                FixedPipeline::new("image/src-over/depth"),
3731                FixedPipeline::new("image/src-over/alpha-mask"),
3732                FixedPipeline::new("image/src-over/alpha-mask/depth"),
3733                FixedPipeline::new("image/src-over/rounded"),
3734                FixedPipeline::new("image/src-over/rounded/depth"),
3735                FixedPipeline::new("image/src-over/alpha-mask/rounded"),
3736                FixedPipeline::new("image/src-over/alpha-mask/rounded/depth"),
3737            ],
3738            image_pipeline_dst_out: [
3739                FixedPipeline::new("image/dst-out"),
3740                FixedPipeline::new("image/dst-out/depth"),
3741                FixedPipeline::new("image/dst-out/alpha-mask"),
3742                FixedPipeline::new("image/dst-out/alpha-mask/depth"),
3743                FixedPipeline::new("image/dst-out/rounded"),
3744                FixedPipeline::new("image/dst-out/rounded/depth"),
3745                FixedPipeline::new("image/dst-out/alpha-mask/rounded"),
3746                FixedPipeline::new("image/dst-out/alpha-mask/rounded/depth"),
3747            ],
3748            glyph_atlas_pipeline: [
3749                FixedPipeline::new("glyph/atlas"),
3750                FixedPipeline::new("glyph/atlas/depth"),
3751                FixedPipeline::new("glyph/atlas/aligned"),
3752                FixedPipeline::new("glyph/atlas/aligned/depth"),
3753                FixedPipeline::new("glyph/atlas/turned"),
3754                FixedPipeline::new("glyph/atlas/turned/depth"),
3755            ],
3756            rrect_shadow_pipeline: [
3757                FixedPipeline::new("shadow/rrect"),
3758                FixedPipeline::new("shadow/rrect/depth"),
3759            ],
3760            image_shader,
3761            glyph_atlas_shader,
3762            rrect_shadow_shader,
3763            depth_targets: crate::idle_pool::IdlePool::default(),
3764            depth_gate,
3765            surface_atlas_sizes: crate::frame::SurfaceAtlasSizes::for_backend(adapter_backend),
3766            uniform_bind_group_layout,
3767            image_bind_group_layout,
3768            image_nearest_sampler,
3769            image_linear_sampler,
3770            text_fonts,
3771            viewport_uniforms,
3772            run_store,
3773            image_texture_cache: BoundedLruCache::with_capacity_at_least_one(
3774                MAX_TEXTURE_CACHE_ITEMS,
3775            ),
3776            image_texture_cache_bytes: 0,
3777            external_texture_bindings: BoundedLruCache::with_capacity_at_least_one(
3778                MAX_EXTERNAL_TEXTURE_BINDINGS,
3779            ),
3780            text_image_cache: BoundedLruCache::with_capacity_at_least_one(
3781                MAX_TEXT_IMAGE_CACHE_ITEMS,
3782            ),
3783            text_glyph_atlas,
3784            text_glyph_run_cache: BoundedLruCache::with_capacity_at_least_one(
3785                MIN_TEXT_GLYPH_RUN_CACHE_ITEMS,
3786            ),
3787            text_glyph_runs_drawn: 0,
3788            text_glyph_gpu_run_cache: BoundedLruCache::with_capacity_at_least_one(
3789                MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS,
3790            ),
3791            text_glyph_run_arena: GlyphRunArena::new(copy_free),
3792            copy_free,
3793            text_glyph_run_frame: 0,
3794            text_glyph_mask_cache: SoftwareGlyphRasterCache::with_capacity_at_least_one(
3795                MAX_TEXT_GLYPH_MASK_CACHE_ITEMS,
3796            ),
3797            text_line_index_cache: TextLineIndexCache::new(MAX_TEXT_LINE_INDEX_CACHE_ITEMS),
3798            scratch_image_vertices: Vec::new(),
3799            scratch_image_indices: Vec::new(),
3800            scratch_glyph_instances: GlyphInstances::default(),
3801            scratch_image_cmds: Vec::new(),
3802            scratch_image_clips: Vec::new(),
3803            scratch_glyph_cmds: Vec::new(),
3804            scratch_glyph_moved: Vec::new(),
3805            scratch_shadow_instances: Vec::new(),
3806            scratch_arena_draws: Vec::new(),
3807            scratch_pipelines: PipelineDemand::default(),
3808            scratch_held: crate::draw_pass::HeldDraws::default(),
3809            scratch_text_glyph_run: Vec::new(),
3810            scratch_text_glyph_entries: Vec::new(),
3811            run_glyph_scratch: RunGlyphScratch::default(),
3812            frame_graph_executor,
3813            stage_side_scratch: StageSideScratch::default(),
3814            deferred_offscreen_releases: Vec::new(),
3815            effect_renderer,
3816            layer_cache: LayerCache::new(),
3817            ablation: Ablation::default(),
3818            ablation_frames: 0,
3819            nesting_overflow_reported: false,
3820            backdrop_gates: HashMap::default(),
3821            fill_gates: HashMap::default(),
3822            effect_gates: HashMap::default(),
3823            source_gates: HashMap::default(),
3824            transparent_sources: HashMap::default(),
3825            shadow_surface_cache: BoundedLruCache::with_capacity_at_least_one(
3826                MAX_SHADOW_SURFACE_CACHE_ITEMS,
3827            ),
3828            shadow_surface_cache_bytes: 0,
3829            frame_stats: gpu_stats::FrameStats::default(),
3830            last_frame_stats: None,
3831            pending_frame_warmup_frames: 0,
3832            frame_count: 0,
3833            #[cfg(not(target_arch = "wasm32"))]
3834            discovers_next_frame: discovers_first_frame,
3835            #[cfg(not(target_arch = "wasm32"))]
3836            first_screen_recorded,
3837            #[cfg(not(target_arch = "wasm32"))]
3838            discovering: false,
3839            shader_warm_ups_queued: 0,
3840        };
3841        #[cfg(not(target_arch = "wasm32"))]
3842        renderer.warm_first_screen(&records, holds_recorded);
3843        renderer.warm_requested_shaders();
3844        log::info!(
3845            "[gpu-init] {:?} renderer ready in {:.1} ms (effects {:.1} ms)",
3846            adapter_backend,
3847            instant_ms(construction_started, Instant::now()),
3848            effects_ms,
3849        );
3850        renderer
3851    }
3852
3853    /// Prepares the first screen the last launches recorded. The first frame
3854    /// waits for its shapes and fixed pipelines, but draws placeholders for
3855    /// runtime shaders that have not compiled: those queue behind, since a
3856    /// Mali driver compiles largely one pipeline at a time. A driver cache
3857    /// that `holds_recorded` pipelines builds them as cache hits, so those
3858    /// draw from it, and need no stand-in.
3859    #[cfg(not(target_arch = "wasm32"))]
3860    fn warm_first_screen(
3861        &mut self,
3862        records: &crate::pipeline_records::PipelineRecords,
3863        holds_recorded: bool,
3864    ) {
3865        self.warm_fixed_pipelines(&|label| {
3866            records
3867                .fixed
3868                .iter()
3869                .any(|fixed| fixed.first_screen && fixed.entry == label)
3870        });
3871        if holds_recorded {
3872            self.effect_renderer.trust_cached(records);
3873        }
3874        self.effect_renderer.warm_first_screen_shaders(
3875            records
3876                .shaders
3877                .iter()
3878                .filter(|shader| shader.first_screen)
3879                .map(|shader| &shader.entry),
3880        );
3881        if !records.shapes.iter().any(|shape| shape.first_screen) {
3882            self.warm_every_screen();
3883        }
3884    }
3885
3886    /// Queues the pipelines every screen draws with, for a launch with no
3887    /// record of its first screen: flat solid rects and text on whole
3888    /// pixels. They build while the first screen composes, when the
3889    /// compiler's threads have nothing else; on a Mate 20 X the gauntlet's
3890    /// first content showed 333-366 ms after the first frame with them
3891    /// against 383-399 ms without.
3892    #[cfg(not(target_arch = "wasm32"))]
3893    fn warm_every_screen(&mut self) {
3894        self.shape_pipelines.warm(ShapePipelineKey::SOLID_RECT);
3895        self.glyph_atlas_pipeline_resource(false, GlyphQuads::Aligned)
3896            .prefetch(
3897                CompileLane::WarmUp,
3898                &self.pipeline_compiler,
3899                self.adapter_backend,
3900                || self.glyph_atlas_pipeline_job(false, GlyphQuads::Aligned),
3901            );
3902    }
3903
3904    fn ensure_shape_pipeline(&mut self, key: ShapePipelineKey, vertices: u64) {
3905        self.shape_pipelines.ensure(key, vertices);
3906    }
3907
3908    /// Queues the shader warm-ups requested since the last call, each at the
3909    /// target it draws to (`cranpose_ui_graphics::request_shader_warm_ups`).
3910    fn warm_requested_shaders(&mut self) {
3911        let requested = cranpose_ui_graphics::shader_warm_ups_after(self.shader_warm_ups_queued);
3912        if requested.is_empty() {
3913            return;
3914        }
3915        self.shader_warm_ups_queued += requested.len();
3916        self.effect_renderer.warm_shaders(&requested);
3917    }
3918
3919    /// Queues every pipeline recent launches of another build drew with:
3920    /// after an update their compiled pipelines are gone, and each would
3921    /// otherwise compile inside the first frame that draws with it.
3922    #[cfg(not(target_arch = "wasm32"))]
3923    fn warm_recent(&mut self, records: &crate::pipeline_records::PipelineRecords) {
3924        self.warm_fixed_pipelines(&|label| records.fixed.iter().any(|fixed| fixed.entry == label));
3925        let shapes = records
3926            .shapes
3927            .iter()
3928            .map(|shape| shape.entry)
3929            .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3930            .filter_map(ShapePipelineKey::from_bits);
3931        for key in shapes {
3932            self.shape_pipelines.warm(key);
3933        }
3934        self.effect_renderer
3935            .warm_recorded_shaders(records.shaders.iter().map(|shader| &shader.entry));
3936    }
3937
3938    /// Queues the fixed pipelines whose labels `wanted` accepts.
3939    #[cfg(not(target_arch = "wasm32"))]
3940    fn warm_fixed_pipelines(&self, wanted: &dyn Fn(&str) -> bool) {
3941        let compiler = self.effect_renderer.compiler();
3942        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3943            if wanted(pipeline.label()) {
3944                pipeline.queue(
3945                    compiler,
3946                    crate::pipeline_compiler::CompileLane::WarmUp,
3947                    self.adapter_backend,
3948                    job(),
3949                );
3950            }
3951        });
3952    }
3953
3954    /// Builds here, ahead of the first frame, the pipelines named by the
3955    /// first screens in `records` that this renderer's backend drew (see
3956    /// [`crate::WgpuRenderer::build_first_screen_pipelines`]).
3957    pub(crate) fn build_first_screen(&mut self, records: &[u8], viewport: (u32, u32)) {
3958        let records =
3959            crate::pipeline_records::decode_first_screen(records, self.adapter_backend, viewport);
3960        for shape in &records.shapes {
3961            if let Some(key) = ShapePipelineKey::from_bits(shape.entry) {
3962                self.shape_pipelines.build_ahead(key);
3963            }
3964        }
3965        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3966            if records
3967                .fixed
3968                .iter()
3969                .any(|fixed| fixed.entry == pipeline.label())
3970            {
3971                pipeline.build_ahead(&self.recorder, self.adapter_backend, job());
3972            }
3973        });
3974    }
3975
3976    /// See [`crate::WgpuRenderer::first_screen_recorded`].
3977    #[cfg(not(target_arch = "wasm32"))]
3978    pub(crate) fn first_screen_recorded(&self) -> bool {
3979        self.first_screen_recorded
3980    }
3981
3982    /// See [`crate::WgpuRenderer::first_screen_pipelines`].
3983    #[cold]
3984    #[inline(never)]
3985    pub(crate) fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
3986        self.recorder.first_screen_records(self.adapter_backend)
3987    }
3988
3989    /// Hands `visit` every fixed pipeline, the effect renderer's too, with
3990    /// the job that builds it.
3991    fn for_each_fixed_pipeline(
3992        &self,
3993        visit: &mut dyn FnMut(&FixedPipeline, &dyn Fn() -> FixedPipelineJob),
3994    ) {
3995        self.effect_renderer.for_each_fixed(&self.device, visit);
3996        for depth in [false, true] {
3997            for (alpha_mask, rounded) in
3998                [(false, false), (true, false), (false, true), (true, true)]
3999            {
4000                let variant = ImageVariant {
4001                    depth,
4002                    alpha_mask,
4003                    rounded,
4004                };
4005                for blend_mode in [BlendMode::SrcOver, BlendMode::DstOut] {
4006                    visit(self.image_pipeline_resource(blend_mode, variant), &|| {
4007                        Box::new(self.image_pipeline_job(blend_mode, variant))
4008                    });
4009                }
4010            }
4011            for quads in [GlyphQuads::Plain, GlyphQuads::Aligned, GlyphQuads::Turned] {
4012                visit(self.glyph_atlas_pipeline_resource(depth, quads), &|| {
4013                    Box::new(self.glyph_atlas_pipeline_job(depth, quads))
4014                });
4015            }
4016            visit(&self.rrect_shadow_pipeline[usize::from(depth)], &|| {
4017                Box::new(self.rrect_shadow_pipeline_job(depth))
4018            });
4019        }
4020    }
4021
4022    fn image_pipeline_resource(
4023        &self,
4024        blend_mode: BlendMode,
4025        variant: ImageVariant,
4026    ) -> &FixedPipeline {
4027        let pipelines = match blend_mode {
4028            BlendMode::DstOut => &self.image_pipeline_dst_out,
4029            _ => &self.image_pipeline,
4030        };
4031        &pipelines[usize::from(variant.depth)
4032            + 2 * usize::from(variant.alpha_mask)
4033            + 4 * usize::from(variant.rounded)]
4034    }
4035
4036    fn image_pipeline_job(
4037        &self,
4038        blend_mode: BlendMode,
4039        variant: ImageVariant,
4040    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4041        let device = Arc::clone(&self.device);
4042        let cache = self.pipeline_cache.clone();
4043        let format = self.composition_format;
4044        let shader = self.image_shader.clone();
4045        move || {
4046            create_image_pipeline(
4047                &device,
4048                cache.as_ref(),
4049                format,
4050                &shader,
4051                blend_mode,
4052                variant,
4053            )
4054        }
4055    }
4056
4057    /// Queues the builds of the image pipelines `cmds` draw with that are
4058    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4059    /// `awaited` each still to land.
4060    pub(crate) fn prefetch_image_pipelines(
4061        &self,
4062        cmds: &[ImageDrawCmd],
4063        blend_mode: BlendMode,
4064        (depth, lane): (bool, CompileLane),
4065        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4066    ) {
4067        let mut last = None;
4068        for cmd in cmds {
4069            let variant = ImageVariant::of(cmd, depth);
4070            if last.replace(variant) == Some(variant) {
4071                continue;
4072            }
4073            if let Some(pending) = self.image_pipeline_resource(blend_mode, variant).prefetch(
4074                lane,
4075                &self.pipeline_compiler,
4076                self.adapter_backend,
4077                || self.image_pipeline_job(blend_mode, variant),
4078            ) {
4079                awaited(pending);
4080            }
4081        }
4082    }
4083
4084    /// Queues the builds of the glyph pipelines `cmds` draw with that are
4085    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4086    /// `awaited` each still to land.
4087    pub(crate) fn prefetch_glyph_pipelines(
4088        &self,
4089        cmds: &[GlyphDrawCmd],
4090        (depth, lane): (bool, CompileLane),
4091        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4092    ) {
4093        let mut last = None;
4094        for cmd in cmds {
4095            let quads = cmd.quads();
4096            if last.replace(quads) == Some(quads) {
4097                continue;
4098            }
4099            if let Some(pending) = self.glyph_atlas_pipeline_resource(depth, quads).prefetch(
4100                lane,
4101                &self.pipeline_compiler,
4102                self.adapter_backend,
4103                || self.glyph_atlas_pipeline_job(depth, quads),
4104            ) {
4105                awaited(pending);
4106            }
4107        }
4108    }
4109
4110    /// Queues the build of the shadow pipeline on `lane` when it is missing
4111    /// (see [`FixedPipeline::prefetch`]), handing `awaited` the pipeline
4112    /// while it is still to land.
4113    pub(crate) fn prefetch_shadow_pipeline(
4114        &self,
4115        (depth, lane): (bool, CompileLane),
4116        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4117    ) {
4118        if let Some(pending) = self.rrect_shadow_pipeline[usize::from(depth)].prefetch(
4119            lane,
4120            &self.pipeline_compiler,
4121            self.adapter_backend,
4122            || self.rrect_shadow_pipeline_job(depth),
4123        ) {
4124            awaited(pending);
4125        }
4126    }
4127
4128    pub(crate) fn image_pipeline(
4129        &self,
4130        blend_mode: BlendMode,
4131        variant: ImageVariant,
4132    ) -> &wgpu::RenderPipeline {
4133        self.image_pipeline_resource(blend_mode, variant).for_draw(
4134            &self.recorder,
4135            self.adapter_backend,
4136            || self.image_pipeline_job(blend_mode, variant)(),
4137        )
4138    }
4139
4140    fn glyph_atlas_pipeline_job(
4141        &self,
4142        depth: bool,
4143        quads: GlyphQuads,
4144    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4145        let device = Arc::clone(&self.device);
4146        let cache = self.pipeline_cache.clone();
4147        let format = self.composition_format;
4148        let shader = self.glyph_atlas_shader.clone();
4149        move || {
4150            create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
4151        }
4152    }
4153
4154    /// The glyph pipeline for a pass with a depth buffer or not, drawing
4155    /// `quads`.
4156    fn glyph_atlas_pipeline(&self, depth: bool, quads: GlyphQuads) -> &wgpu::RenderPipeline {
4157        self.glyph_atlas_pipeline_resource(depth, quads).for_draw(
4158            &self.recorder,
4159            self.adapter_backend,
4160            || self.glyph_atlas_pipeline_job(depth, quads)(),
4161        )
4162    }
4163
4164    fn rrect_shadow_pipeline_job(
4165        &self,
4166        depth: bool,
4167    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4168        let device = Arc::clone(&self.device);
4169        let cache = self.pipeline_cache.clone();
4170        let format = self.composition_format;
4171        let shader = self.rrect_shadow_shader.clone();
4172        move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
4173    }
4174
4175    /// Draws `instances` of the pass's uploaded shadow instances, bound with
4176    /// `uniform_slot` under `scissor`.
4177    pub(crate) fn draw_shadow_instances(
4178        &self,
4179        pass: &mut TrackedPass<'_, '_>,
4180        buffer: &BufferUpload,
4181        uniform_slot: usize,
4182        instances: std::ops::Range<u32>,
4183        scissor: Option<(u32, u32, u32, u32)>,
4184        frame: PassFrame,
4185    ) -> Result<(), String> {
4186        let depth = frame.depth;
4187        let pipeline = self.rrect_shadow_pipeline[usize::from(depth)].for_draw(
4188            &self.recorder,
4189            self.adapter_backend,
4190            || self.rrect_shadow_pipeline_job(depth)(),
4191        );
4192        let (x, y, width, height) = frame.scissor(scissor);
4193        pass.set_scissor_rect(x, y, width, height);
4194        pass.set_pipeline(pipeline);
4195        self.viewport_uniforms.bind(pass, uniform_slot)?;
4196        pass.set_vertex_buffer(0, buffer.slice());
4197        pass.draw(0..SHADOW_QUAD_CORNERS, instances);
4198        self.frame_stats.add_draw_calls(1);
4199        Ok(())
4200    }
4201
4202    pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
4203        &self,
4204        recorder: &mut C,
4205        instances: &[ShadowInstance],
4206    ) -> BufferUpload {
4207        recorder.upload_buffer(
4208            UploadAllocatorSpec::vertex(
4209                "Shadow Instance Buffer",
4210                std::mem::size_of::<ShadowInstance>() as u64,
4211            ),
4212            &self.device,
4213            bytemuck::cast_slice(instances),
4214        )
4215    }
4216
4217    fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
4218        let kind = match quads {
4219            GlyphQuads::Plain => 0,
4220            GlyphQuads::Aligned => 1,
4221            GlyphQuads::Turned => 2,
4222        };
4223        &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
4224    }
4225
4226    /// The transient depth buffer for a target of `size`, created on first
4227    /// use; the few sizes recent frames used are kept.
4228    pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
4229        const KEPT_DEPTH_TARGETS: usize = 4;
4230        let view = match self.depth_targets.take(|(kept, _)| *kept == size) {
4231            Some((_, view)) => view,
4232            None => self.create_depth_target(size),
4233        };
4234        self.depth_targets
4235            .put((size, view.clone()), KEPT_DEPTH_TARGETS, u64::MAX, |_| 0);
4236        view
4237    }
4238
4239    fn create_depth_target(&self, size: (u32, u32)) -> wgpu::TextureView {
4240        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4241            label: Some("Opaque interior depth"),
4242            size: wgpu::Extent3d {
4243                width: size.0,
4244                height: size.1,
4245                depth_or_array_layers: 1,
4246            },
4247            mip_level_count: 1,
4248            sample_count: 1,
4249            dimension: wgpu::TextureDimension::D2,
4250            format: DEPTH_FORMAT,
4251            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4252                | wgpu::TextureUsages::TRANSIENT_ATTACHMENT,
4253            view_formats: &[],
4254        });
4255        texture.create_view(&wgpu::TextureViewDescriptor::default())
4256    }
4257
4258    /// The binding a draw of `image` sampled by `sampling` takes, uploading
4259    /// the image the first time a draw needs it.
4260    fn image_binding(
4261        &mut self,
4262        image: &ImageBitmap,
4263        sampling: ImageSampling,
4264    ) -> Result<ImageBinding, String> {
4265        if image.format() == cranpose_ui_graphics::ImagePixelFormat::External {
4266            return self.external_texture_binding(image, sampling);
4267        }
4268        if let Some(cached) = self.image_texture_cache.get(&image.id()) {
4269            return Ok(cached.bind_groups.binding(sampling));
4270        }
4271
4272        let size = wgpu::Extent3d {
4273            width: image.width(),
4274            height: image.height(),
4275            depth_or_array_layers: 1,
4276        };
4277
4278        let alpha_mask = matches!(
4279            image.format(),
4280            cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
4281        );
4282        let (format, bytes_per_pixel) = if alpha_mask {
4283            (wgpu::TextureFormat::R8Unorm, 1)
4284        } else {
4285            (wgpu::TextureFormat::Rgba8Unorm, 4)
4286        };
4287
4288        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4289            label: Some("Image Texture"),
4290            size,
4291            mip_level_count: 1,
4292            sample_count: 1,
4293            dimension: wgpu::TextureDimension::D2,
4294            format,
4295            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4296            view_formats: &[],
4297        });
4298
4299        let upload_stats = self.frame_graph_executor.upload_texture(
4300            &self.queue,
4301            wgpu::TexelCopyTextureInfo {
4302                texture: &texture,
4303                mip_level: 0,
4304                origin: wgpu::Origin3d::ZERO,
4305                aspect: wgpu::TextureAspect::All,
4306            },
4307            image.pixels(),
4308            wgpu::TexelCopyBufferLayout {
4309                offset: 0,
4310                bytes_per_row: Some(bytes_per_pixel * image.width()),
4311                rows_per_image: Some(image.height()),
4312            },
4313            size,
4314        );
4315        self.frame_stats.record_command_stats(upload_stats);
4316
4317        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4318        let bytes = image.pixels().len();
4319        let cached = CachedImageTexture {
4320            bind_groups: self.image_bind_groups(&view, alpha_mask),
4321            _texture: texture,
4322            _view: view,
4323            bytes,
4324        };
4325        let binding = cached.bind_groups.binding(sampling);
4326        if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
4327            self.image_texture_cache_bytes = self
4328                .image_texture_cache_bytes
4329                .saturating_sub(replaced.bytes);
4330        }
4331        self.image_texture_cache_bytes += bytes;
4332        while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
4333            && self.image_texture_cache.len() > 1
4334        {
4335            let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
4336                break;
4337            };
4338            self.image_texture_cache_bytes =
4339                self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
4340        }
4341        Ok(binding)
4342    }
4343
4344    fn external_texture_binding(
4345        &mut self,
4346        image: &ImageBitmap,
4347        sampling: ImageSampling,
4348    ) -> Result<ImageBinding, String> {
4349        let key = image.storage_id();
4350        if let Some(bind_groups) = self.external_texture_bindings.get(&key) {
4351            return Ok(bind_groups.binding(sampling));
4352        }
4353        let view = image
4354            .external_handle::<wgpu::TextureView>()
4355            .ok_or("an external texture's handle is not a wgpu::TextureView")?;
4356        let bind_groups = self.image_bind_groups(view, false);
4357        let binding = bind_groups.binding(sampling);
4358        self.external_texture_bindings.put(key, bind_groups);
4359        Ok(binding)
4360    }
4361
4362    fn image_bind_groups(&self, view: &wgpu::TextureView, alpha_mask: bool) -> ImageBindGroups {
4363        ImageBindGroups {
4364            alpha_mask,
4365            nearest: self.image_bind_group(view, &self.image_nearest_sampler),
4366            linear: self.image_bind_group(view, &self.image_linear_sampler),
4367        }
4368    }
4369
4370    fn image_bind_group(
4371        &self,
4372        view: &wgpu::TextureView,
4373        sampler: &wgpu::Sampler,
4374    ) -> wgpu::BindGroup {
4375        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4376            label: Some("Image Texture Bind Group"),
4377            layout: &self.image_bind_group_layout,
4378            entries: &[
4379                wgpu::BindGroupEntry {
4380                    binding: 0,
4381                    resource: wgpu::BindingResource::TextureView(view),
4382                },
4383                wgpu::BindGroupEntry {
4384                    binding: 1,
4385                    resource: wgpu::BindingResource::Sampler(sampler),
4386                },
4387            ],
4388        })
4389    }
4390
4391    pub(crate) fn max_texture_dim(&self) -> u32 {
4392        self.effect_renderer.max_texture_dim()
4393    }
4394
4395    /// A pooled texture that outlives the frame: layer cache entries and
4396    /// cached shadow surfaces.
4397    pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
4398        self.effect_renderer
4399            .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
4400    }
4401
4402    fn frame_root(
4403        &mut self,
4404        output_mode: OutputMode,
4405        output_view: Option<&wgpu::TextureView>,
4406        output_texture: Option<&wgpu::Texture>,
4407        viewport: (u32, u32),
4408        reads_page: bool,
4409    ) -> FrameRoot {
4410        if let (OutputMode::Display, Some(view), Some(texture)) =
4411            (output_mode, output_view, output_texture)
4412            && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
4413        {
4414            return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
4415                texture.clone(),
4416                view.clone(),
4417            )));
4418        }
4419        FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
4420    }
4421
4422    fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
4423        if let Some(target) = self.composition_target.take()
4424            && target.target.width == width
4425            && target.target.height == height
4426        {
4427            return target;
4428        }
4429        let target = Rc::new(OffscreenTarget::new(
4430            &self.device,
4431            self.composition_format,
4432            width,
4433            height,
4434        ));
4435        let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
4436        CompositionTarget {
4437            target,
4438            output_bind_group,
4439        }
4440    }
4441
4442    fn transient_offscreen_descriptor(
4443        &self,
4444        label: &'static str,
4445        width: u32,
4446        height: u32,
4447    ) -> FrameTextureDescriptor {
4448        let max_texture_dim = self.max_texture_dim();
4449        FrameTextureDescriptor::render_attachment(
4450            label,
4451            width.min(max_texture_dim),
4452            height.min(max_texture_dim),
4453            self.composition_format,
4454        )
4455    }
4456
4457    /// A texture of the given size that stays transparent: the input of a
4458    /// runtime shader whose layer draws nothing itself, so the shader needs
4459    /// no surface pass and reads the same empty content every frame.
4460    #[inline(never)]
4461    pub(crate) fn transparent_source<C: FrameCommandRecorder>(
4462        &mut self,
4463        recorder: &mut C,
4464        width: u32,
4465        height: u32,
4466    ) -> Rc<OffscreenTarget> {
4467        if let Some(source) = self.transparent_sources.get(&(width, height)) {
4468            return Rc::clone(source);
4469        }
4470        if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
4471            for (_, source) in self.transparent_sources.drain() {
4472                if let Ok(target) = Rc::try_unwrap(source) {
4473                    self.deferred_offscreen_releases.push(target);
4474                }
4475            }
4476        }
4477        let source = Rc::new(self.acquire_retained_surface(width, height));
4478        self.clear_target(
4479            recorder,
4480            &source.view,
4481            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4482        );
4483        self.transparent_sources
4484            .insert((width, height), Rc::clone(&source));
4485        source
4486    }
4487
4488    fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
4489        self.deferred_offscreen_releases.push(target);
4490    }
4491
4492    fn flush_deferred_offscreen_releases(&mut self) {
4493        let layer_cache = &mut self.layer_cache;
4494        let mut retire = |gate: &mut AdmissionGate| {
4495            let seen = gate.end_frame();
4496            if !seen && let Some(dead) = gate.dead_entry() {
4497                layer_cache.remove(&dead);
4498            }
4499            seen
4500        };
4501        self.backdrop_gates.retain(|_, gate| retire(gate));
4502        self.fill_gates.retain(|_, gate| retire(gate));
4503        self.effect_gates.retain(|_, gate| retire(gate));
4504        self.source_gates.retain(|_, gate| retire(gate));
4505        for target in self.deferred_offscreen_releases.drain(..) {
4506            self.effect_renderer.release_offscreen(target);
4507        }
4508        self.layer_cache.end_frame();
4509        for (transient, target) in self.layer_cache.take_released() {
4510            match transient {
4511                Some(descriptor) => self
4512                    .frame_graph_executor
4513                    .return_cached_transient(descriptor, target),
4514                None => self.effect_renderer.release_offscreen(target),
4515            }
4516        }
4517        self.effect_renderer.end_offscreen_frame();
4518        self.frame_graph_executor.end_transient_frame();
4519        self.depth_targets.end_frame();
4520        self.surface_atlas_sizes.end_frame();
4521    }
4522
4523    fn insert_cached_shadow_surface(
4524        &mut self,
4525        key: ShadowSurfaceCacheKey,
4526        target: Rc<OffscreenTarget>,
4527    ) {
4528        let byte_size = offscreen_byte_size(target.width, target.height);
4529        while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
4530            let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
4531                break;
4532            };
4533            self.shadow_surface_cache_bytes = self
4534                .shadow_surface_cache_bytes
4535                .saturating_sub(evicted.byte_size);
4536        }
4537        let cached = CachedShadowSurface { target, byte_size };
4538        if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4539            self.shadow_surface_cache_bytes = self
4540                .shadow_surface_cache_bytes
4541                .saturating_sub(replaced.byte_size);
4542        }
4543        self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4544    }
4545}
4546fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4547    snapshot.layer_cache_misses > 0
4548        || snapshot.shadow_shape_cache_misses > 0
4549        || snapshot.text_image_cache_misses > 0
4550        || snapshot.text_glyph_atlas_misses > 0
4551}
4552
4553fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4554    if *pending_frames > 0 {
4555        *pending_frames = pending_frames.saturating_sub(1);
4556    } else if frame_stats_need_warmup_frame(snapshot) {
4557        *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4558    }
4559}
4560
4561impl GpuRenderer {
4562    #[expect(clippy::too_many_arguments)]
4563    pub fn render(
4564        &mut self,
4565        texture: &wgpu::Texture,
4566        view: &wgpu::TextureView,
4567        width: u32,
4568        height: u32,
4569        packet: FramePacket,
4570        surface_epoch: u64,
4571        returns: &mut RenderReturns,
4572    ) -> Result<(), String> {
4573        self.render_internal(
4574            width,
4575            height,
4576            packet,
4577            surface_epoch,
4578            returns,
4579            OutputMode::Display,
4580            Some(view),
4581            Some(texture),
4582        )
4583    }
4584
4585    #[expect(clippy::too_many_arguments)]
4586    fn render_internal(
4587        &mut self,
4588        width: u32,
4589        height: u32,
4590        packet: FramePacket,
4591        surface_epoch: u64,
4592        returns: &mut RenderReturns,
4593        output_mode: OutputMode,
4594        output_view: Option<&wgpu::TextureView>,
4595        output_texture: Option<&wgpu::Texture>,
4596    ) -> Result<(), String> {
4597        let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
4598            Some(CancelReason::RendererEpoch)
4599        } else if packet.surface_epoch != surface_epoch {
4600            Some(CancelReason::SurfaceEpoch)
4601        } else if packet.viewport != (width, height) {
4602            Some(CancelReason::Viewport)
4603        } else {
4604            None
4605        };
4606        if let Some(reason) = cancel_reason {
4607            return Self::cancel_packet(packet, reason, returns);
4608        }
4609        if self.device_errors.take_poison() {
4610            return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
4611        }
4612        returns.frame_id = packet.frame_id;
4613        let render_start = Instant::now();
4614        #[cfg(not(target_arch = "wasm32"))]
4615        let builds_before = thread_builds();
4616        self.warm_requested_shaders();
4617        self.shape_pipelines.begin_frame();
4618        self.recorder.begin_frame((width, height));
4619        self.begin_placeholder_frame();
4620        self.viewport_uniforms.begin_frame();
4621        self.run_store.begin_frame(gpu_stats_enabled());
4622        self.begin_text_glyph_run_frame();
4623
4624        let text_cache_len = packet.text_cache_len;
4625        let reads_page = packet.root.contains_backdrop()
4626            || packet
4627                .overlay
4628                .as_ref()
4629                .is_some_and(LayerScene::contains_backdrop);
4630        let frame_root = self.frame_root(
4631            output_mode,
4632            output_view,
4633            output_texture,
4634            (width, height),
4635            reads_page,
4636        );
4637        let root = frame_root.target();
4638        let screenshot_bind_group = output_view.and_then(|_| {
4639            matches!(output_mode, OutputMode::Screenshot).then(|| {
4640                self.screenshot_converter
4641                    .bind_group(&self.device, &root.view)
4642            })
4643        });
4644        let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
4645        let result = self.render_graph(root, packet, returns, output_mode, output);
4646        #[cfg(not(target_arch = "wasm32"))]
4647        self.effect_renderer
4648            .compiler()
4649            .spread_demand(thread_builds() == builds_before);
4650        if let FrameRoot::Composition(composition) = frame_root {
4651            self.composition_target = Some(composition);
4652        }
4653        let after_graph = Instant::now();
4654        self.flush_deferred_offscreen_releases();
4655        self.scratch_glyph_instances.end_frame();
4656
4657        self.frame_stats
4658            .layer_cache_size
4659            .set(self.layer_cache.len() as u32);
4660        self.frame_stats
4661            .layer_cache_bytes
4662            .set(self.layer_cache.bytes());
4663        self.frame_stats.offscreen_pool_size.set(
4664            self.effect_renderer
4665                .retained_offscreen_count()
4666                .saturating_add(self.frame_graph_executor.retained_texture_count())
4667                .saturating_add(usize::from(self.composition_target.is_some())) as u32,
4668        );
4669        self.frame_stats.offscreen_pool_bytes.set(
4670            (self.effect_renderer.retained_offscreen_bytes() as u64)
4671                .saturating_add(self.frame_graph_executor.retained_texture_bytes())
4672                .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
4673                    u64::from(target.target.width)
4674                        .saturating_mul(u64::from(target.target.height))
4675                        .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
4676                })),
4677        );
4678        self.frame_stats
4679            .text_pool_size
4680            .set(self.text_image_cache.len() as u32);
4681        self.frame_stats
4682            .image_cache_size
4683            .set(self.image_texture_cache.len() as u32);
4684        self.frame_stats.text_cache_size.set(text_cache_len as u32);
4685        self.effect_renderer
4686            .merge_and_reset_debug_counters(&self.frame_stats);
4687        self.frame_graph_executor.reset_upload_allocators();
4688        let snapshot = self.frame_stats.snapshot();
4689        if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
4690            log::warn!(
4691                "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
4692                 offscreen_acq={} offscreen_new={} isolated={} draws={}",
4693                snapshot.layer_cache_hits,
4694                snapshot.layer_cache_misses,
4695                snapshot.layer_cache_miss_pixels,
4696                snapshot.offscreen_acquires,
4697                snapshot.offscreen_news,
4698                snapshot.isolated_layer_renders,
4699                snapshot.draw_calls,
4700            );
4701        }
4702        self.last_frame_stats = Some(snapshot);
4703        PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4704        update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
4705        let gpu_stats_on = gpu_stats_enabled();
4706        self.frame_stats
4707            .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
4708        if gpu_stats_on && self.frame_count.is_multiple_of(60) {
4709            gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
4710        }
4711        self.frame_graph_executor
4712            .end_pass_timing_frame(&self.device, &self.queue);
4713        self.frame_stats.reset();
4714        let after_stats = Instant::now();
4715        if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
4716            log::warn!(
4717                "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
4718                instant_ms(render_start, after_graph),
4719                instant_ms(after_graph, after_stats),
4720            );
4721        }
4722        if result.is_ok() {
4723            returns.outcome = PresentOutcome::Presented;
4724        }
4725        result
4726    }
4727
4728    /// Returns a packet unrendered, handing its scene back for recycling.
4729    pub(crate) fn cancel_packet(
4730        packet: FramePacket,
4731        reason: CancelReason,
4732        returns: &mut RenderReturns,
4733    ) -> Result<(), String> {
4734        returns.scene = Some(FrameSceneStorage {
4735            root: packet.root,
4736            overlay: packet.overlay,
4737        });
4738        returns.frame_id = packet.frame_id;
4739        returns.outcome = PresentOutcome::Cancelled(reason);
4740        Ok(())
4741    }
4742
4743    pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
4744        self.last_frame_stats
4745    }
4746
4747    pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
4748        self.frame_graph_executor.pass_timing_report()
4749    }
4750
4751    pub fn needs_frame_warmup(&self) -> bool {
4752        self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
4753    }
4754
4755    #[cfg(target_arch = "wasm32")]
4756    pub(crate) fn pipeline_compiler(&self) -> &PipelineCompiler {
4757        &self.pipeline_compiler
4758    }
4759
4760    /// Whether a frame must follow to replace a placeholder: a pipeline it
4761    /// waited for landed, or, with nothing to wake the app when one does,
4762    /// this frame drew one.
4763    fn placeholder_awaits_frame(&self) -> bool {
4764        #[cfg(not(target_arch = "wasm32"))]
4765        if let Some(landing) = &self.landing {
4766            return landing.landed() || (self.drew_placeholder && !landing.has_wake());
4767        }
4768        self.drew_placeholder
4769    }
4770
4771    /// Starts a frame: once a pipeline a placeholder waited for has landed,
4772    /// the retained layers, which may hold that placeholder, are dropped.
4773    fn begin_placeholder_frame(&mut self) {
4774        self.drew_placeholder = false;
4775        #[cfg(not(target_arch = "wasm32"))]
4776        if let Some(landing) = &self.landing {
4777            self.built_at_frame_start = landing.built();
4778            if landing.take_landed() {
4779                self.layer_cache.clear();
4780            }
4781        }
4782    }
4783
4784    /// Drops what earlier frames drew and kept, the layers and the blurred
4785    /// shadows: pipelines the browser compiled in the background landed, and
4786    /// those were drawn while the draws that use them were left out.
4787    #[cfg(target_arch = "wasm32")]
4788    pub(crate) fn background_pipelines_landed(&mut self) {
4789        self.drop_kept_drawing();
4790    }
4791
4792    /// See [`crate::WgpuRenderer::compile_pipelines_in_background`].
4793    #[cfg(target_arch = "wasm32")]
4794    pub(crate) fn compile_pipelines_in_background(&mut self) {
4795        self.shape_pipelines.build_in_background();
4796    }
4797
4798    /// Drops the layers and the blurred shadows earlier frames drew and kept.
4799    fn drop_kept_drawing(&mut self) {
4800        self.layer_cache.clear();
4801        self.shadow_surface_cache.clear();
4802        self.shadow_surface_cache_bytes = 0;
4803    }
4804
4805    /// Notes an effect drawn as its placeholder, or left out, while its
4806    /// pipelines compile, and waits for the next one to land.
4807    pub(crate) fn note_placeholder(&mut self) {
4808        self.drew_placeholder = true;
4809        self.recorder.hold_first_screen();
4810        self.frame_stats
4811            .placeholder_draws
4812            .set(self.frame_stats.placeholder_draws.get() + 1);
4813        #[cfg(not(target_arch = "wasm32"))]
4814        if let Some(landing) = &self.landing {
4815            landing.await_since(self.built_at_frame_start);
4816        }
4817    }
4818
4819    /// Queues every pipeline the cache file records, as the first frame of
4820    /// an updated build does, and returns whether any is left to build: for
4821    /// a renderer that prepares an app's pipelines without drawing.
4822    #[cfg(not(target_arch = "wasm32"))]
4823    pub(crate) fn prepare_recorded(&mut self) -> bool {
4824        self.effect_renderer.warm_after_first_frame();
4825        if let Some(records) = self.recent_after_update.take() {
4826            self.warm_recent(&records);
4827        }
4828        self.compiling()
4829    }
4830
4831    /// Whether the background compiler has a queued pipeline left to build.
4832    #[cfg(not(target_arch = "wasm32"))]
4833    pub(crate) fn compiling(&self) -> bool {
4834        self.landing
4835            .as_ref()
4836            .is_some_and(|landing| landing.in_flight())
4837    }
4838
4839    /// Whether the last frame drew a placeholder and pipelines are still
4840    /// compiling, so its picture is not final yet.
4841    pub(crate) fn awaits_pipelines(&self) -> bool {
4842        #[cfg(not(target_arch = "wasm32"))]
4843        if let Some(landing) = &self.landing {
4844            return self.drew_placeholder && landing.in_flight();
4845        }
4846        self.drew_placeholder
4847    }
4848
4849    /// The compiler's account of the pipelines it builds, for a runtime that
4850    /// reads it off the present thread.
4851    #[cfg(not(target_arch = "wasm32"))]
4852    pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
4853        self.landing.clone()
4854    }
4855
4856    /// Calls `wake` from the compiling thread when a pipeline a placeholder
4857    /// waited for lands, so an app with nothing else to draw draws again.
4858    #[cfg(not(target_arch = "wasm32"))]
4859    pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
4860        if let Some(landing) = &self.landing {
4861            landing.wake_with(wake);
4862        }
4863    }
4864
4865    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
4866        DebugCpuAllocationStats {
4867            scene_graph_node_count: 0,
4868            scene_graph_heap_bytes: 0,
4869            scene_hits_len: 0,
4870            scene_hits_cap: 0,
4871            scene_node_index_len: 0,
4872            scene_node_index_cap: 0,
4873            text_renderer_pool_len: self.text_image_cache.len(),
4874            text_renderer_pool_cap: self.text_image_cache.cap().get(),
4875            image_texture_cache_len: self.image_texture_cache.len(),
4876            image_texture_cache_cap: self.image_texture_cache.cap().get(),
4877            run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
4878            run_store_bytes: self.run_store.stored_bytes(),
4879            run_store_runs: self.run_store.stored_count(),
4880            scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
4881            scratch_image_indices_cap: self.scratch_image_indices.capacity(),
4882            scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
4883            scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
4884                + self.scratch_glyph_instances.turned.capacity(),
4885            layer_cache_len: self.layer_cache.len(),
4886            layer_cache_bytes: self.layer_cache.bytes(),
4887        }
4888    }
4889    pub fn render_to_rgba_pixels(
4890        &mut self,
4891        width: u32,
4892        height: u32,
4893        packet: FramePacket,
4894        surface_epoch: u64,
4895        returns: &mut RenderReturns,
4896    ) -> Result<Vec<u8>, String> {
4897        if width == 0 || height == 0 {
4898            return Err("Screenshot size must be non-zero".to_string());
4899        }
4900        let errors_before = self.device_errors.error_count();
4901
4902        let output_texture = crate::offscreen::create_2d_texture(
4903            &self.device,
4904            wgpu::TextureFormat::Rgba8Unorm,
4905            width,
4906            height,
4907            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4908            Some("Screenshot Output Texture"),
4909        );
4910        let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
4911        self.render_internal(
4912            width,
4913            height,
4914            packet,
4915            surface_epoch,
4916            returns,
4917            OutputMode::Screenshot,
4918            Some(&output_view),
4919            None,
4920        )?;
4921        if returns.outcome != PresentOutcome::Presented {
4922            return Err(format!(
4923                "Screenshot rendering did not complete: {:?}",
4924                returns.outcome
4925            ));
4926        }
4927        self.read_screenshot_pixels(&output_texture, errors_before)
4928    }
4929
4930    fn read_screenshot_pixels(
4931        &mut self,
4932        output_texture: &wgpu::Texture,
4933        errors_before: u64,
4934    ) -> Result<Vec<u8>, String> {
4935        let width = output_texture.width();
4936        let height = output_texture.height();
4937        let bytes_per_pixel = 4u32;
4938        let unpadded_bytes_per_row = width
4939            .checked_mul(bytes_per_pixel)
4940            .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
4941        let padded_bytes_per_row =
4942            align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
4943        let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
4944
4945        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
4946            label: Some("Screenshot Readback Buffer"),
4947            size: output_buffer_size,
4948            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4949            mapped_at_creation: false,
4950        });
4951
4952        let device = self.device.clone();
4953        let queue = self.queue.clone();
4954        let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
4955        let source = graph.import_surface("screenshot-copy-source");
4956        graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
4957            context.encoder.copy_texture_to_buffer(
4958                wgpu::TexelCopyTextureInfo {
4959                    texture: output_texture,
4960                    mip_level: 0,
4961                    origin: wgpu::Origin3d::ZERO,
4962                    aspect: wgpu::TextureAspect::All,
4963                },
4964                wgpu::TexelCopyBufferInfo {
4965                    buffer: &output_buffer,
4966                    layout: wgpu::TexelCopyBufferLayout {
4967                        offset: 0,
4968                        bytes_per_row: Some(padded_bytes_per_row),
4969                        rows_per_image: Some(height),
4970                    },
4971                },
4972                wgpu::Extent3d {
4973                    width,
4974                    height,
4975                    depth_or_array_layers: 1,
4976                },
4977            );
4978            Ok(())
4979        });
4980        let mut executor = std::mem::take(&mut self.frame_graph_executor);
4981        let execution = executor.execute_recorded_graph(&device, &queue, graph);
4982        self.frame_graph_executor = executor;
4983        self.recall_frame_uploads();
4984        let execution = execution.map_err(|error| error.to_string())?;
4985        let submission_index = execution.submission;
4986        let copy_stats = execution.stats;
4987        self.last_frame_stats = self
4988            .last_frame_stats
4989            .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
4990
4991        let buffer_slice = output_buffer.slice(..);
4992        let (tx, rx) = mpsc::channel();
4993        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
4994            let _ = tx.send(result);
4995        });
4996        self.device
4997            .poll(wgpu::PollType::Wait {
4998                submission_index: Some(submission_index),
4999                timeout: None,
5000            })
5001            .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
5002
5003        match rx.recv_timeout(Duration::from_secs(3)) {
5004            Ok(Ok(())) => {}
5005            Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
5006            Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
5007        }
5008        if self.device_errors.error_count() != errors_before {
5009            output_buffer.unmap();
5010            return Err("GPU errors occurred while capturing the screenshot".to_string());
5011        }
5012
5013        let mapped = buffer_slice
5014            .get_mapped_range()
5015            .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
5016        let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
5017
5018        let src_row_len = padded_bytes_per_row as usize;
5019        let dst_row_len = unpadded_bytes_per_row as usize;
5020        for row in 0..height as usize {
5021            let src_offset = row * src_row_len;
5022            let dst_offset = row * dst_row_len;
5023            pixels[dst_offset..dst_offset + dst_row_len]
5024                .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
5025        }
5026        drop(mapped);
5027        output_buffer.unmap();
5028
5029        self.convert_surface_pixels_to_rgba(&pixels)
5030    }
5031
5032    /// Asks the buffers the submitted frame unmapped back for later frames.
5033    fn recall_frame_uploads(&mut self) {
5034        self.viewport_uniforms.uploads.recall();
5035        self.run_store.recall();
5036    }
5037
5038    fn render_graph(
5039        &mut self,
5040        root_target: &Rc<OffscreenTarget>,
5041        packet: FramePacket,
5042        returns: &mut RenderReturns,
5043        output_mode: OutputMode,
5044        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5045    ) -> Result<(), String> {
5046        #[cfg(target_arch = "wasm32")]
5047        let (device, queue, graph_start) =
5048            (self.device.clone(), self.queue.clone(), Instant::now());
5049        let FramePacket {
5050            root,
5051            overlay,
5052            root_scale,
5053            clear,
5054            ..
5055        } = packet;
5056        let page = Rc::clone(root_target);
5057
5058        #[cfg(not(target_arch = "wasm32"))]
5059        let (result, submitted) = {
5060            if std::mem::take(&mut self.discovers_next_frame) {
5061                self.discover_frame_pipelines(
5062                    &root,
5063                    overlay.as_ref(),
5064                    &page,
5065                    root_scale,
5066                    clear,
5067                    output_mode,
5068                    output,
5069                );
5070            }
5071            self.execute_frame_graph(
5072                &root,
5073                overlay.as_ref(),
5074                &page,
5075                root_scale,
5076                clear,
5077                output_mode,
5078                output,
5079            )
5080        };
5081
5082        #[cfg(target_arch = "wasm32")]
5083        let (result, submitted) = {
5084            let mut executor = std::mem::take(&mut self.frame_graph_executor);
5085            let (result, execution) = {
5086                let mut frame_encoder =
5087                    executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
5088                let initial_pass_count = frame_encoder.recorded_pass_count();
5089                let result = self.encode_frame(
5090                    &mut frame_encoder,
5091                    &root,
5092                    overlay.as_ref(),
5093                    Rc::clone(&page),
5094                    root_scale,
5095                    clear,
5096                    output_mode,
5097                    output,
5098                );
5099                let execution =
5100                    if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
5101                        Some(frame_encoder.finish())
5102                    } else {
5103                        None
5104                    };
5105                (result, execution)
5106            };
5107            let after_execute = Instant::now();
5108            self.frame_graph_executor = executor;
5109            if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5110                log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
5111            }
5112            let submitted = execution.is_some();
5113            if let Some(execution) = execution {
5114                self.frame_stats.record_command_stats(execution.stats);
5115            }
5116            (result, submitted)
5117        };
5118        #[cfg(not(target_arch = "wasm32"))]
5119        if submitted {
5120            self.recorder.note_frame_drawn();
5121            self.effect_renderer.warm_after_first_frame();
5122            if let Some(records) = self.recent_after_update.take() {
5123                self.warm_recent(&records);
5124            }
5125        }
5126        if !submitted {
5127            self.run_store.invalidate_uploads();
5128            self.text_glyph_gpu_run_cache.clear();
5129            self.text_glyph_run_arena = GlyphRunArena::new(self.copy_free);
5130        }
5131        returns.scene = Some(FrameSceneStorage { root, overlay });
5132        result
5133    }
5134
5135    /// Records and submits the frame through the frame graph: whether it
5136    /// recorded without error, and whether it submitted anything.
5137    #[cfg(not(target_arch = "wasm32"))]
5138    #[expect(clippy::too_many_arguments)]
5139    fn execute_frame_graph(
5140        &mut self,
5141        root: &LayerScene,
5142        overlay: Option<&LayerScene>,
5143        page: &Rc<OffscreenTarget>,
5144        root_scale: f32,
5145        clear: wgpu::Color,
5146        output_mode: OutputMode,
5147        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5148    ) -> (Result<(), String>, bool) {
5149        let device = self.device.clone();
5150        let queue = self.queue.clone();
5151        let graph_start = Instant::now();
5152        let mut executor = std::mem::take(&mut self.frame_graph_executor);
5153        let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
5154        let surface = frame_graph.import_surface("renderer-surface");
5155        frame_graph.add_fallible_recorded_command_pass(
5156            Some("Renderer Frame Pass"),
5157            &[],
5158            &[surface],
5159            |frame_encoder| {
5160                self.encode_frame(
5161                    frame_encoder,
5162                    root,
5163                    overlay,
5164                    Rc::clone(page),
5165                    root_scale,
5166                    clear,
5167                    output_mode,
5168                    output,
5169                )
5170            },
5171        );
5172        let after_build = Instant::now();
5173        let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
5174        let after_execute = Instant::now();
5175        self.frame_graph_executor = executor;
5176        self.recall_frame_uploads();
5177        if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5178            log::warn!(
5179                "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
5180                instant_ms(graph_start, after_build),
5181                instant_ms(after_build, after_execute),
5182            );
5183        }
5184        match execution {
5185            Ok(execution) => {
5186                if execution.stats.pass_count > 0 {
5187                    self.frame_stats.record_command_stats(execution.stats);
5188                }
5189                (Ok(()), true)
5190            }
5191            Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
5192            Err(error) => (Err(error.to_string()), false),
5193        }
5194    }
5195
5196    /// Walks the frame once drawing nothing, so every pass queues the
5197    /// pipelines it lacks on the compiler's threads, and they compile side by
5198    /// side; the frame drawn next waits for them where it draws. Drawn pass
5199    /// after pass instead, each pass asked for its pipelines only after the
5200    /// passes before it had theirs: with no Metal shader cached, the
5201    /// gauntlet's first frame on an Apple M3 Pro waited for two such waves
5202    /// of pipelines. What the walk kept, the layers and the blurred shadows,
5203    /// holds nothing drawn and is dropped, and what it counted toward
5204    /// caching a layer, a fill, an effect or a source is forgotten: the
5205    /// frame drawn next starts from the state the walk found, a renderer's
5206    /// first frame's.
5207    #[cfg(not(target_arch = "wasm32"))]
5208    #[expect(clippy::too_many_arguments)]
5209    fn discover_frame_pipelines(
5210        &mut self,
5211        root: &LayerScene,
5212        overlay: Option<&LayerScene>,
5213        page: &Rc<OffscreenTarget>,
5214        root_scale: f32,
5215        clear: wgpu::Color,
5216        output_mode: OutputMode,
5217        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5218    ) {
5219        self.discovering = true;
5220        let (result, _) =
5221            self.execute_frame_graph(root, overlay, page, root_scale, clear, output_mode, output);
5222        self.discovering = false;
5223        if let Err(error) = result {
5224            log::warn!(
5225                "[gpu-pipeline] the walk that learns the first frame's pipelines failed: {error}"
5226            );
5227        }
5228        self.drop_kept_drawing();
5229        self.backdrop_gates.clear();
5230        self.fill_gates.clear();
5231        self.effect_gates.clear();
5232        self.source_gates.clear();
5233    }
5234
5235    /// Records the frame: the root and overlay layer scenes into the frame's
5236    /// target, the output conversion when the target is not the presented
5237    /// image, and the viewport uniforms the recorded passes claimed.
5238    #[expect(clippy::too_many_arguments)]
5239    fn encode_frame<C: FrameCommandRecorder>(
5240        &mut self,
5241        recorder: &mut C,
5242        root: &LayerScene,
5243        overlay: Option<&LayerScene>,
5244        page: Rc<OffscreenTarget>,
5245        root_scale: f32,
5246        clear: wgpu::Color,
5247        output_mode: OutputMode,
5248        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5249    ) -> Result<(), String> {
5250        FrameExecutor::new(self, recorder).render_frame(
5251            root,
5252            overlay,
5253            page,
5254            root_scale,
5255            wgpu::LoadOp::Clear(clear),
5256        )?;
5257        #[cfg(not(target_arch = "wasm32"))]
5258        let discovering = self.discovering;
5259        #[cfg(target_arch = "wasm32")]
5260        let discovering = false;
5261        if !discovering && let Some((output_view, bind_group)) = output {
5262            match output_mode {
5263                OutputMode::Display => &self.output_converter,
5264                OutputMode::Screenshot => &self.screenshot_converter,
5265            }
5266            .encode(
5267                &self.device,
5268                recorder,
5269                output_view,
5270                bind_group,
5271                self.adapter_backend,
5272                &self.recorder,
5273            );
5274            recorder.record_pass();
5275        }
5276        self.stage_frame_uploads(recorder);
5277        self.shape_pipelines.request_wanted();
5278        if !discovering {
5279            self.depth_gate.end_frame();
5280        }
5281        self.pipeline_compiler.end_frame();
5282        self.viewport_uniforms.uploads.finish_frame();
5283        self.run_store.finish_frame();
5284        Ok(())
5285    }
5286
5287    pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
5288        let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
5289        upload += self.run_store.stage_pending(&self.device, recorder);
5290        upload += self
5291            .text_glyph_run_arena
5292            .stage_pending(&self.device, recorder);
5293        self.run_store.fill_arena_trig(&self.device, recorder);
5294        self.frame_stats.record_command_stats(upload);
5295    }
5296    /// Claims this frame's next viewport uniform slot for `params`.
5297    pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
5298        let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
5299        self.viewport_uniforms
5300            .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
5301    }
5302
5303    /// Resolves a blurred shadow at `z` into a texture and queues its
5304    /// composites. The shadow's shapes and texts render into a source the
5305    /// size of their blur footprint, blur in place and take the post-blur
5306    /// cutouts; the source is then blitted over the rect the shadow covers.
5307    /// Shape-only shadows live in the shadow cache, keyed by their content
5308    /// and device placement, so a scrolling card re-blits its cached blur.
5309    /// The blurred shadow texture and whether the cache held it: a
5310    /// shape-only shadow is cached by content and placement, a shadow with
5311    /// text renders every frame.
5312    fn blurred_shadow_source<C: FrameCommandRecorder>(
5313        &mut self,
5314        recorder: &mut C,
5315        shadow: &ShadowDraw,
5316        source_device: DevicePixelBounds,
5317        pixel_radius: f32,
5318        root_scale: f32,
5319        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5320    ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
5321        let shape_only = shadow.texts.is_empty();
5322        let key = if shape_only {
5323            shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
5324        } else {
5325            None
5326        };
5327        let content = key.map_or(SourceContent::Transient, |key| {
5328            SourceContent::retained(&key)
5329        });
5330        if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
5331            return Some((Rc::clone(&entry.target), true, content));
5332        }
5333        // A shadow whose blur compiles is left out until the blur lands.
5334        if !self.effect_renderer.blur_draws_now(
5335            &self.device,
5336            TileMode::Decal,
5337            (source_device.width, source_device.height),
5338            pixel_radius,
5339            pixel_radius,
5340        ) {
5341            self.note_placeholder();
5342            return None;
5343        }
5344        if !shape_only {
5345            self.frame_stats.record_shadow_text_blur_fallback();
5346        }
5347        let source = self.render_shadow_source(
5348            recorder,
5349            shadow,
5350            source_device,
5351            pixel_radius,
5352            root_scale,
5353            key.is_some(),
5354            transients,
5355        )?;
5356        if let Some(key) = key {
5357            self.frame_stats
5358                .record_shadow_shape_cache_miss(source_device.width, source_device.height);
5359            self.frame_stats.maybe_print_shadow_shape_cache_miss(
5360                source_device.width,
5361                source_device.height,
5362                key.content_hash,
5363                pixel_radius,
5364                [source_device.x, source_device.y],
5365                shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
5366                shadow.clip,
5367            );
5368            self.insert_cached_shadow_surface(key, Rc::clone(&source));
5369        }
5370        Some((source, false, content))
5371    }
5372
5373    #[expect(clippy::too_many_arguments)]
5374    pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
5375        &mut self,
5376        recorder: &mut C,
5377        shadow: &ShadowDraw,
5378        z: usize,
5379        root_scale: f32,
5380        target_rect: DeviceRect4,
5381        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5382        resolved: &mut Vec<ResolvedComposite>,
5383    ) {
5384        if !shadow.requires_surface()
5385            || skip_shadow_draws()
5386            || !root_scale.is_finite()
5387            || root_scale <= 0.0
5388        {
5389            return;
5390        }
5391        let Some(bounds) = shadow_draw_bounds(shadow) else {
5392            return;
5393        };
5394        let margin = blur_reach(shadow.blur_radius, root_scale);
5395        let source_bounds = expand_rect(bounds, margin, margin);
5396        let mut visible = source_bounds;
5397        if let Some(clip) = shadow.clip {
5398            let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
5399                return;
5400            };
5401            visible = clipped;
5402        }
5403        let target_logical = Rect {
5404            x: target_rect.0 / root_scale,
5405            y: target_rect.1 / root_scale,
5406            width: target_rect.2 / root_scale,
5407            height: target_rect.3 / root_scale,
5408        };
5409        let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
5410            return;
5411        };
5412        let max_texture_dim = self.max_texture_dim();
5413        let shape_only = shadow.texts.is_empty();
5414        let anchor = shadow
5415            .shapes
5416            .as_ref()
5417            .and_then(|run| run.placement.snap_anchor);
5418        let source_device = shape_only
5419            .then(|| {
5420                translation_stable_anchored_device_pixel_bounds(
5421                    source_bounds,
5422                    anchor,
5423                    root_scale,
5424                    max_texture_dim,
5425                )
5426            })
5427            .flatten()
5428            .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
5429        let Some(source_device) = source_device else {
5430            return;
5431        };
5432        let pixel_radius = shadow.blur_radius * root_scale;
5433        let Some((source, hit, content)) = self.blurred_shadow_source(
5434            recorder,
5435            shadow,
5436            source_device,
5437            pixel_radius,
5438            root_scale,
5439            transients,
5440        ) else {
5441            return;
5442        };
5443        let dest = (
5444            source_device.x,
5445            source_device.y,
5446            source_device.width as f32,
5447            source_device.height as f32,
5448        );
5449        let mut coverage = intersect_device_rects(dest, target_rect);
5450        if let Some(clip) = shadow.clip {
5451            coverage = coverage.and_then(|coverage| {
5452                intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
5453            });
5454        }
5455        let Some(coverage) = coverage else {
5456            return;
5457        };
5458        if hit {
5459            self.frame_stats.record_shadow_shape_cache_hit(
5460                (coverage.2 as u64).saturating_mul(coverage.3 as u64),
5461            );
5462        }
5463        let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
5464        let downscaled =
5465            (source.width, source.height) != (source_device.width, source_device.height);
5466        let (sample_mode, source_viewport) = if downscaled {
5467            (
5468                CompositeSampleMode::Linear,
5469                Some((0.0, 0.0, source.width as f32, source.height as f32)),
5470            )
5471        } else {
5472            (CompositeSampleMode::Nearest, None)
5473        };
5474        resolved.push(ResolvedComposite {
5475            z_index: z,
5476            source,
5477            content,
5478            dest,
5479            scissor: Some(coverage),
5480            kind: ResolvedCompositeKind::Blit {
5481                alpha: 1.0,
5482                blend_mode: BlendMode::SrcOver,
5483                rounded_mask,
5484                sample_mode,
5485                source_viewport,
5486            },
5487        });
5488    }
5489
5490    /// Draws a shadow's shapes and texts into a surface covering `bounds`
5491    /// and blurs it. A wide blur runs at its scratch size and its result
5492    /// stays there, read bilinearly by the composite; a post-blur cutout
5493    /// needs the surface's full size, so the blurred result is interpolated
5494    /// back into it first and the cutout drawn at that size. A retained
5495    /// result feeds the shadow cache; a transient one is registered with
5496    /// the frame's transients and released with them. `None` when the
5497    /// shadow draws nothing.
5498    #[expect(clippy::too_many_arguments)]
5499    fn render_shadow_source<C: FrameCommandRecorder>(
5500        &mut self,
5501        recorder: &mut C,
5502        shadow: &ShadowDraw,
5503        bounds: DevicePixelBounds,
5504        pixel_radius: f32,
5505        root_scale: f32,
5506        retained: bool,
5507        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5508    ) -> Option<Rc<OffscreenTarget>> {
5509        let (width, height) = (bounds.width, bounds.height);
5510        let device = self.device.clone();
5511        let (scratch_width, scratch_height) =
5512            crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
5513        let full_size_result = shadow.post_blur_cutouts.is_some()
5514            || (scratch_width, scratch_height) == (width, height);
5515        let (result_width, result_height) = if full_size_result {
5516            (width, height)
5517        } else {
5518            (scratch_width, scratch_height)
5519        };
5520        let result = if retained {
5521            Rc::new(self.acquire_retained_surface(result_width, result_height))
5522        } else {
5523            self.shadow_transient(
5524                recorder,
5525                transients,
5526                "Shadow Result",
5527                result_width,
5528                result_height,
5529            )
5530        };
5531        let source = if full_size_result {
5532            Rc::clone(&result)
5533        } else {
5534            self.shadow_transient(recorder, transients, "Shadow Source", width, height)
5535        };
5536        let offset = [bounds.x, bounds.y];
5537        let target = PassTarget {
5538            view: &source.view,
5539            width,
5540            height,
5541        };
5542        let scene = shadow_scene(
5543            shadow.shapes.as_ref(),
5544            &shadow.texts,
5545            blur_reach(shadow.blur_radius, root_scale),
5546        );
5547        let segment = PassSegment {
5548            scene: &scene,
5549            ops: &scene.draw_ops,
5550            composites: &[],
5551            offset,
5552            scissor: None,
5553            first_run_window: None,
5554            transform: SegmentTransform::IDENTITY,
5555            scale: root_scale,
5556        };
5557        let drew = self.encode_pass(
5558            recorder,
5559            target,
5560            std::slice::from_ref(&segment),
5561            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
5562            "Shadow Source Pass",
5563        );
5564        match drew {
5565            Ok(true) => {}
5566            Ok(false) => {
5567                drop(source);
5568                if retained && let Ok(target) = Rc::try_unwrap(result) {
5569                    self.defer_offscreen_release(target);
5570                }
5571                return None;
5572            }
5573            Err(error) => {
5574                log::error!("shadow source pass failed: {error}");
5575                return None;
5576            }
5577        }
5578        if pixel_radius > 0.0 {
5579            let scratch_descriptor = self.transient_offscreen_descriptor(
5580                "Shadow Blur Scratch",
5581                scratch_width,
5582                scratch_height,
5583            );
5584            let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
5585            let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
5586            {
5587                Some(self.shadow_transient(
5588                    recorder,
5589                    transients,
5590                    "Shadow Blur Result",
5591                    scratch_width,
5592                    scratch_height,
5593                ))
5594            } else {
5595                None
5596            };
5597            let blur_dest = match &blurred {
5598                Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
5599                None => (&result.view, (result_width, result_height)),
5600            };
5601            let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
5602                recorder,
5603                &device,
5604                &source,
5605                &scratch,
5606                blur_dest,
5607                pixel_radius,
5608                pixel_radius,
5609                TileMode::Decal,
5610                None,
5611            );
5612            recorder.record_passes(passes);
5613            self.effect_renderer.record_blur_pass();
5614            recorder.release_transient_offscreen(scratch_descriptor, scratch);
5615            if let Some(blurred) = &blurred {
5616                self.effect_renderer
5617                    .encode_upscale_pass(recorder, &device, blurred, &result.view);
5618                recorder.record_pass();
5619            }
5620        }
5621        if let Some(cutout_run) = &shadow.post_blur_cutouts {
5622            let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
5623            let segment = PassSegment {
5624                scene: &cutouts,
5625                ops: &cutouts.draw_ops,
5626                composites: &[],
5627                offset,
5628                scissor: None,
5629                first_run_window: None,
5630                transform: SegmentTransform::IDENTITY,
5631                scale: root_scale,
5632            };
5633            if let Err(error) = self.encode_pass(
5634                recorder,
5635                target,
5636                std::slice::from_ref(&segment),
5637                wgpu::LoadOp::Load,
5638                "Shadow Cutout Pass",
5639            ) {
5640                log::error!("shadow cutout pass failed: {error}");
5641            }
5642        }
5643        Some(result)
5644    }
5645
5646    /// A transient surface of a shadow's frame, released with the frame's
5647    /// transients.
5648    fn shadow_transient<C: FrameCommandRecorder>(
5649        &self,
5650        recorder: &mut C,
5651        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5652        label: &'static str,
5653        width: u32,
5654        height: u32,
5655    ) -> Rc<OffscreenTarget> {
5656        let descriptor = self.transient_offscreen_descriptor(label, width, height);
5657        let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
5658        transients.push((descriptor, Rc::clone(&target)));
5659        target
5660    }
5661
5662    /// Whether `run` draws from retained buffers keyed by its command.
5663    pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
5664        self.run_store.is_stored(run)
5665    }
5666
5667    /// The pipeline `segment` of a run at `placement` draws with. `clipped`
5668    /// says the variant tests the run's clip: a turned run's, since an
5669    /// unturned one's clip is its paint's scissor (see [`clip_scissor`]).
5670    fn run_pipeline_key(
5671        segment: &RecordSegment,
5672        placement: &crate::scene::Placement,
5673        tier: RunTier,
5674        ablation: ShapeAblation,
5675        turns: ShapeTurns,
5676        (depth, clip): (bool, SegmentClip),
5677        viewport: ViewportUniformParams,
5678    ) -> ShapePipelineKey {
5679        let blend_mode = supported_blend_mode(segment.blend);
5680        let laid = depth
5681            && blend_mode == BlendMode::SrcOver
5682            && !placement.paints()
5683            && clip != SegmentClip::Rounded
5684            && !ablation.material
5685            && !ablation.fill;
5686        ShapePipelineKey {
5687            blend_mode,
5688            tier,
5689            variant: ShapeVariant::of_segment(
5690                segment,
5691                clip,
5692                ablation,
5693                laid,
5694                (
5695                    turns == ShapeTurns::None,
5696                    turns == ShapeTurns::None
5697                        && placement.snap_anchor.is_some()
5698                        && viewport.offset.iter().all(|value| value.fract() == 0.0),
5699                ),
5700            ),
5701            turns,
5702            depth: if depth {
5703                ShapeDepth::Tested
5704            } else {
5705                ShapeDepth::Off
5706            },
5707        }
5708    }
5709
5710    /// Queues for a later frame the shape pipelines `keys` name and the
5711    /// interiors they lay down, handing `awaited` each still to land.
5712    pub(crate) fn warm_shapes_later(
5713        &mut self,
5714        keys: &PipelineDemand,
5715        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
5716    ) {
5717        for key in keys.keys() {
5718            self.shape_pipelines.warm_later(key, awaited);
5719        }
5720    }
5721
5722    /// Prepares the pipeline of each key `pipelines` holds and, in a pass
5723    /// with a depth buffer, the one laying down its opaque interiors: the
5724    /// compiler's threads build the missing ones after the first while this
5725    /// thread builds that one.
5726    /// Queues every shape pipeline `pipelines` names that is missing, and
5727    /// forgets them: a pass that learns its pipelines draws none.
5728    #[cfg(not(target_arch = "wasm32"))]
5729    pub(crate) fn discover_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
5730        self.shape_pipelines.prefetch(pipelines, true);
5731        pipelines.clear();
5732    }
5733
5734    pub(crate) fn ensure_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
5735        self.shape_pipelines.prefetch(pipelines, false);
5736        for (key, vertices) in pipelines.drain() {
5737            self.ensure_shape_pipeline(key, vertices);
5738            if let Some(interior) = key.interior() {
5739                self.ensure_shape_pipeline(interior, vertices);
5740            }
5741        }
5742    }
5743
5744    /// Brings a stored run's tables up to date and appends its draws, under
5745    /// a placement uniform of its own, to the pass's run draws `draws`, and
5746    /// the pipelines they draw with to `pipelines`.
5747    #[expect(clippy::too_many_arguments)]
5748    pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
5749        &mut self,
5750        recorder: &mut C,
5751        run: &RunDraw,
5752        viewport: ViewportUniformParams,
5753        root_scale: f32,
5754        window: &std::ops::Range<u32>,
5755        (depth, mut depth_keys): (bool, Option<&mut PipelineDemand>),
5756        (draws, pipelines): (&mut Vec<RunDrawCall>, &mut PipelineDemand),
5757    ) -> StoreRunBatch {
5758        let placement = &run.placement;
5759        let ablation = self.ablation.shape;
5760        let turns = ShapeTurns::of(viewport.transform, false);
5761        let scissor = clip_scissor(placement, root_scale, viewport);
5762        let clip = SegmentClip::of(placement, scissor.is_some());
5763        let start = draws.len();
5764        self.run_store.stored_run_draws(
5765            &self.device,
5766            run,
5767            &mut |segment| {
5768                let key = |depth| {
5769                    Self::run_pipeline_key(
5770                        segment,
5771                        placement,
5772                        RunTier::Store,
5773                        ablation,
5774                        turns,
5775                        (depth, clip),
5776                        viewport,
5777                    )
5778                };
5779                if let Some(keys) = depth_keys.as_deref_mut() {
5780                    keys.add(key(true), 0);
5781                }
5782                key(depth)
5783            },
5784            draws,
5785        );
5786        window_draws(draws, start, window);
5787        let run_draws = &draws[start..];
5788        let upload_start = Instant::now();
5789        let (upload, fill, tables) = self.run_store.upload_stored(
5790            &self.device,
5791            recorder,
5792            run,
5793            root_scale,
5794            window,
5795            run_draws,
5796        );
5797        if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
5798            log::warn!(
5799                "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
5800                upload.upload_bytes,
5801                run.tables().shapes.len()
5802            );
5803        }
5804        self.frame_stats.record_command_stats(upload);
5805        if let Some(fill) = fill {
5806            self.frame_stats.add_shape_fill(fill);
5807        }
5808        let uniforms = Uniforms::of(
5809            viewport,
5810            PlacementData::of(&run.placement, root_scale, viewport.transform),
5811            RunTier::Store,
5812        );
5813        let uniform_slot =
5814            self.viewport_uniforms
5815                .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
5816        for draw in run_draws {
5817            pipelines.add(
5818                draw.key,
5819                crate::run_store::draw_vertices(
5820                    draw.records.end - draw.records.start,
5821                    draw.band_class,
5822                ),
5823            );
5824        }
5825        StoreRunBatch {
5826            tables,
5827            uniform_slot,
5828            draws: start..draws.len(),
5829            clip: scissor,
5830        }
5831    }
5832
5833    pub(crate) fn open_arena(&mut self) -> usize {
5834        self.run_store.open_arena()
5835    }
5836
5837    /// The records the open arena chunk holds so far.
5838    pub(crate) fn open_arena_records(&self) -> u32 {
5839        self.run_store.open_arena_records()
5840    }
5841
5842    pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
5843        self.run_store.arena_accepts(chunk, run)
5844    }
5845
5846    /// Appends `window` of `run`'s records to the open arena chunk, their
5847    /// placement under `turn`, keyed for a pass whose flat and turned
5848    /// records alternate often when `mixed_turns`, and the pipelines they
5849    /// draw with to `pipelines`. `clip` says how its variant tests its clip:
5850    /// an unturned run leaves a rect clip to its paint's scissor, never a
5851    /// rounded one.
5852    #[expect(clippy::too_many_arguments)]
5853    pub(crate) fn append_arena_run(
5854        &mut self,
5855        chunk: usize,
5856        run: &RunDraw,
5857        window: std::ops::Range<u32>,
5858        root_scale: f32,
5859        viewport: ViewportUniformParams,
5860        mixed_turns: bool,
5861        (depth, clip): (bool, SegmentClip),
5862        (pipelines, mut depth_keys): (&mut PipelineDemand, Option<&mut PipelineDemand>),
5863    ) -> u32 {
5864        let placement = &run.placement;
5865        let ablation = self.ablation.shape;
5866        let turn = viewport.transform;
5867        let turns = ShapeTurns::of(turn, mixed_turns);
5868        self.run_store.append_arena(
5869            chunk,
5870            run,
5871            window,
5872            (root_scale, turn),
5873            &mut |segment| {
5874                let key = |depth| {
5875                    Self::run_pipeline_key(
5876                        segment,
5877                        placement,
5878                        RunTier::Arena,
5879                        ablation,
5880                        turns,
5881                        (depth, clip),
5882                        viewport,
5883                    )
5884                };
5885                if let Some(keys) = depth_keys.as_deref_mut() {
5886                    keys.add(key(true), 0);
5887                }
5888                key(depth)
5889            },
5890            pipelines,
5891        )
5892    }
5893
5894    /// Moves the open chunk's draws since its last cut onto `out`, keeping
5895    /// it open.
5896    pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5897        self.run_store.cut_arena(&self.device, chunk, out);
5898    }
5899
5900    /// Uploads the open chunk and moves its draws since its last cut onto
5901    /// `out`.
5902    pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5903        if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
5904            self.frame_stats.add_shape_fill(fill);
5905        }
5906    }
5907
5908    pub(crate) fn draw_run_calls(
5909        &self,
5910        pass: &mut TrackedPass<'_, '_>,
5911        tables: ArenaBinding<'_>,
5912        uniform_slot: usize,
5913        draws: &[RunDrawCall],
5914        scissor: (u32, u32, u32, u32),
5915        stage: RunStage,
5916    ) -> Result<(), String> {
5917        match stage {
5918            RunStage::Paint => {
5919                if draws.is_empty() {
5920                    return Ok(());
5921                }
5922                self.frame_stats.bump_shapes();
5923                self.record_run_draws(
5924                    pass,
5925                    tables,
5926                    uniform_slot,
5927                    scissor,
5928                    draws.iter().map(PlannedRunDraw::paint),
5929                )
5930            }
5931            RunStage::Interiors => {
5932                let planned = interior_run_draws(draws);
5933                if planned.is_empty() {
5934                    return Ok(());
5935                }
5936                self.frame_stats
5937                    .shape_interior_draws
5938                    .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
5939                self.record_run_draws(pass, tables, uniform_slot, scissor, planned.into_iter())
5940            }
5941        }
5942    }
5943
5944    /// Records `planned` against one batch's tables, uniform and scissor.
5945    fn record_run_draws(
5946        &self,
5947        pass: &mut TrackedPass<'_, '_>,
5948        tables: ArenaBinding<'_>,
5949        uniform_slot: usize,
5950        scissor: (u32, u32, u32, u32),
5951        planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
5952    ) -> Result<(), String> {
5953        self.frame_stats.add_draw_calls(planned.len() as u32);
5954        let (x, y, width, height) = scissor;
5955        pass.set_scissor_rect(x, y, width, height);
5956        self.viewport_uniforms.bind(pass, uniform_slot)?;
5957        pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
5958        for (slot, buffer) in tables.records.into_iter().enumerate() {
5959            pass.set_vertex_buffer(slot as u32, buffer.slice(u64::from(tables.offsets[slot])..));
5960        }
5961        let mut bound_class = None;
5962        for draw in planned {
5963            let key = draw.key;
5964            let (pipeline, fallback) = self
5965                .shape_pipelines
5966                .get(key)
5967                .ok_or_else(|| format!("shape pipeline {key:?} was not prepared"))?;
5968            if fallback {
5969                self.frame_stats
5970                    .shape_pipeline_fallback_draws
5971                    .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5972            } else if !key.is_general() {
5973                self.frame_stats
5974                    .shape_specialized_draws
5975                    .set(self.frame_stats.shape_specialized_draws.get() + 1);
5976            }
5977            if bound_class != Some(draw.band_class) {
5978                pass.set_index_buffer(self.run_store.strip_index_buffer(draw.band_class).slice(..));
5979                bound_class = Some(draw.band_class);
5980            }
5981            pass.set_pipeline(pipeline);
5982            pass.draw_indexed(draw.indices, 0, draw.records);
5983        }
5984        Ok(())
5985    }
5986
5987    /// Draws a stored-run batch, whose draws are its range of `draws`.
5988    pub(crate) fn draw_store_run(
5989        &self,
5990        pass: &mut TrackedPass<'_, '_>,
5991        batch: &StoreRunBatch,
5992        draws: &[RunDrawCall],
5993        scissor: (u32, u32, u32, u32),
5994        stage: RunStage,
5995    ) -> Result<(), String> {
5996        self.draw_run_calls(
5997            pass,
5998            batch.tables.binding(),
5999            batch.uniform_slot,
6000            &draws[batch.draws.clone()],
6001            scissor,
6002            stage,
6003        )
6004    }
6005
6006    pub(crate) fn draw_arena(
6007        &self,
6008        pass: &mut TrackedPass<'_, '_>,
6009        chunk: usize,
6010        uniform_slot: usize,
6011        draws: &[RunDrawCall],
6012        scissor: (u32, u32, u32, u32),
6013        stage: RunStage,
6014    ) -> Result<(), String> {
6015        self.draw_run_calls(
6016            pass,
6017            self.run_store.arena_binding(chunk),
6018            uniform_slot,
6019            draws,
6020            scissor,
6021            stage,
6022        )
6023    }
6024    #[cfg(not(target_arch = "wasm32"))]
6025    pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
6026        self.display_format
6027    }
6028
6029    pub fn device_error_count(&self) -> u64 {
6030        self.device_errors.error_count()
6031    }
6032
6033    /// A pass that only applies `load_op` to the target, for a scene with
6034    /// nothing to draw that still needs its clear.
6035    pub(crate) fn clear_target<C: FrameCommandRecorder>(
6036        &self,
6037        recorder: &mut C,
6038        view: &wgpu::TextureView,
6039        load_op: wgpu::LoadOp<wgpu::Color>,
6040    ) {
6041        self.empty_pass(recorder, "Clear Pass", view, load_op);
6042    }
6043
6044    pub(crate) fn empty_pass<C: FrameCommandRecorder>(
6045        &self,
6046        recorder: &mut C,
6047        label: &'static str,
6048        view: &wgpu::TextureView,
6049        load_op: wgpu::LoadOp<wgpu::Color>,
6050    ) {
6051        let pass = recorder.begin_color_pass(label, view, load_op);
6052        drop(pass);
6053        recorder.record_pass();
6054    }
6055    pub(crate) fn draw_image_cmds(
6056        &self,
6057        pass: &mut TrackedPass<'_, '_>,
6058        image_slot: &ImageSlot,
6059        uniform_slot: usize,
6060        cmds: &[ImageDrawCmd],
6061        (blend_mode, depth): (BlendMode, bool),
6062        bound: Option<(u32, u32, u32, u32)>,
6063    ) -> Result<(), String> {
6064        if cmds.is_empty() {
6065            return Ok(());
6066        }
6067        self.frame_stats.bump_images();
6068        self.frame_stats.add_draw_calls(cmds.len() as u32);
6069        let mut bound_pipeline = None;
6070        self.viewport_uniforms.bind(pass, uniform_slot)?;
6071        pass.set_index_buffer(image_slot.indices.slice());
6072        pass.set_vertex_buffer(0, image_slot.vertices.slice());
6073        let mut clips_bound = false;
6074        for cmd in cmds {
6075            let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
6076                continue;
6077            };
6078            pass.set_scissor_rect(x, y, width, height);
6079            let variant = ImageVariant::of(cmd, depth);
6080            if bound_pipeline != Some(variant) {
6081                pass.set_pipeline(self.image_pipeline(blend_mode, variant));
6082                bound_pipeline = Some(variant);
6083            }
6084            pass.set_bind_group(1, &cmd.image.bind_group, &[]);
6085            let instance = match cmd.clip {
6086                Some(clip) => {
6087                    if !clips_bound {
6088                        let clips = image_slot
6089                            .clips
6090                            .as_ref()
6091                            .ok_or_else(|| "rounded image without clip instances".to_string())?;
6092                        pass.set_vertex_buffer(1, clips.slice());
6093                        clips_bound = true;
6094                    }
6095                    clip
6096                }
6097                None => 0,
6098            };
6099            pass.draw_indexed(
6100                cmd.index_start..(cmd.index_start + 6),
6101                0,
6102                instance..instance + 1,
6103            );
6104        }
6105        Ok(())
6106    }
6107
6108    pub(crate) fn draw_glyph_cmds(
6109        &self,
6110        pass: &mut TrackedPass<'_, '_>,
6111        (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
6112        uniform_slot: usize,
6113        cmds: &[GlyphDrawCmd],
6114        bound: Option<(u32, u32, u32, u32)>,
6115        frame: PassFrame,
6116    ) -> Result<(), String> {
6117        if cmds.is_empty() {
6118            return Ok(());
6119        }
6120        let whole_target = frame.scissor(bound);
6121        self.frame_stats.bump_text();
6122        let mut bound_atlas = None;
6123        // Which shared instances are bound, turned or plain, and which
6124        // pipeline; retained runs draw with a plain one.
6125        let mut shared_bound: Option<bool> = None;
6126        let mut bound_pipeline: Option<GlyphQuads> = None;
6127        let mut bound_run_instances: Option<&wgpu::Buffer> = None;
6128        let mut draws = 0u32;
6129        for draw in GlyphDraws::new(cmds) {
6130            let scissor = match draw.scissor {
6131                Some(scissor) => bounded_scissor(scissor, bound),
6132                None => Some(whole_target),
6133            };
6134            let Some((x, y, width, height)) = scissor else {
6135                continue;
6136            };
6137            pass.set_scissor_rect(x, y, width, height);
6138            if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
6139                pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
6140                bound_atlas = Some(draw.atlas);
6141            }
6142            draws += 1;
6143            match draw.step {
6144                GlyphDrawStep::Shared(instances, quads) => {
6145                    if bound_pipeline != Some(quads) {
6146                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
6147                        bound_pipeline = Some(quads);
6148                    }
6149                    let turned = quads.turned();
6150                    if shared_bound != Some(turned) {
6151                        let slot =
6152                            if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
6153                                "shared glyph draw without glyph instances".to_string()
6154                            })?;
6155                        self.viewport_uniforms.bind(pass, uniform_slot)?;
6156                        pass.set_vertex_buffer(0, slot.slice());
6157                        shared_bound = Some(turned);
6158                        bound_run_instances = None;
6159                    }
6160                    pass.draw(0..GLYPH_QUAD_CORNERS, instances);
6161                }
6162                GlyphDrawStep::Retained {
6163                    run,
6164                    uniform_slot: retained_slot,
6165                    aligned,
6166                } => {
6167                    let quads = GlyphQuads::plain(aligned);
6168                    if bound_pipeline != Some(quads) {
6169                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
6170                        bound_pipeline = Some(quads);
6171                    }
6172                    shared_bound = None;
6173                    self.viewport_uniforms.bind(pass, retained_slot)?;
6174                    let instances = run.span.instance_buffer();
6175                    if bound_run_instances != Some(instances) {
6176                        pass.set_vertex_buffer(0, instances.slice(..));
6177                        bound_run_instances = Some(instances);
6178                    }
6179                    pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
6180                }
6181            }
6182        }
6183        self.frame_stats.add_draw_calls(draws);
6184        Ok(())
6185    }
6186    pub(crate) fn append_image_draw_cmd(
6187        &mut self,
6188        image_draw: &ImageDraw,
6189        viewport: ViewportUniformParams,
6190        root_scale: f32,
6191        (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6192        image_clips: &mut Vec<DeviceRoundedClip>,
6193        image_cmds: &mut Vec<ImageDrawCmd>,
6194    ) -> Result<(), String> {
6195        let snap_delta = image_draw
6196            .snap_anchor
6197            .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6198            .unwrap_or_default();
6199        let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
6200        if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
6201            return Ok(());
6202        }
6203
6204        let (mut tint, cpu_filter) = tint_for_image(image_draw.color_filter, image_draw.alpha);
6205        if tint[3] <= 0.0 {
6206            return Ok(());
6207        }
6208
6209        let filtered_image = cpu_filter
6210            .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
6211            .transpose()?;
6212        let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
6213        if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
6214            for (channel, value) in tint[..3].iter_mut().zip(color) {
6215                *channel *= value as f32 / 255.0;
6216            }
6217        }
6218
6219        let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
6220        let Some(scissor) =
6221            scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
6222        else {
6223            return Ok(());
6224        };
6225
6226        let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
6227            return Ok(());
6228        };
6229        let device_quad = geometry.device_quad(root_scale);
6230        let index_start =
6231            push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
6232        let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
6233            image_clips.push(clip);
6234            image_clips.len() as u32 - 1
6235        });
6236        image_cmds.push(ImageDrawCmd {
6237            index_start,
6238            scissor,
6239            image: self.image_binding(prepared_image, geometry.sampling)?,
6240            clip,
6241        });
6242        Ok(())
6243    }
6244
6245    /// Uploads a pass's image and glyph quads into the frame's buffers.
6246    pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
6247        &self,
6248        recorder: &mut C,
6249        vertices: &[Vertex],
6250        indices: &[u32],
6251        clips: &[DeviceRoundedClip],
6252    ) -> ImageSlot {
6253        ImageSlot {
6254            vertices: recorder.upload_buffer(
6255                image_vertex_spec(),
6256                &self.device,
6257                bytemuck::cast_slice(vertices),
6258            ),
6259            indices: recorder.upload_buffer(
6260                image_index_spec(),
6261                &self.device,
6262                bytemuck::cast_slice(indices),
6263            ),
6264            clips: (!clips.is_empty()).then(|| {
6265                recorder.upload_buffer(
6266                    UploadAllocatorSpec::vertex(
6267                        "Image Clip Buffer",
6268                        std::mem::size_of::<DeviceRoundedClip>() as u64,
6269                    ),
6270                    &self.device,
6271                    bytemuck::cast_slice(clips),
6272                )
6273            }),
6274        }
6275    }
6276
6277    pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
6278        &self,
6279        recorder: &mut C,
6280        instances: &[GlyphInstance],
6281    ) -> BufferUpload {
6282        recorder.upload_buffer(
6283            glyph_instance_spec(),
6284            &self.device,
6285            bytemuck::cast_slice(instances),
6286        )
6287    }
6288
6289    pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
6290        &self,
6291        recorder: &mut C,
6292        glyphs: &[TurnedGlyph],
6293    ) -> BufferUpload {
6294        recorder.upload_buffer(
6295            turned_glyph_spec(),
6296            &self.device,
6297            bytemuck::cast_slice(glyphs),
6298        )
6299    }
6300
6301    fn glyph_atlas_entry_for(
6302        &mut self,
6303        glyph: &SoftwareGlyphAtlasGlyph,
6304    ) -> Result<GlyphAtlasEntry, String> {
6305        if let Some(entry) = self
6306            .text_glyph_atlas
6307            .upload_glyph(glyph, &mut self.frame_stats)
6308        {
6309            return Ok(entry);
6310        }
6311
6312        // The draws queued so far bind the full atlas: the glyphs they placed
6313        // reach it before a new atlas takes its place.
6314        self.flush_glyph_uploads();
6315        self.text_glyph_atlas.reset(
6316            &self.device,
6317            &self.image_bind_group_layout,
6318            GlyphSamplers {
6319                nearest: &self.image_nearest_sampler,
6320                linear: &self.image_linear_sampler,
6321            },
6322        );
6323        Err("text glyph atlas filled and was reset".to_string())
6324    }
6325
6326    /// Writes the glyphs the pass placed in the atlas to its texture, ahead
6327    /// of the submit that draws them.
6328    pub(crate) fn flush_glyph_uploads(&mut self) {
6329        self.text_glyph_atlas.flush_uploads(
6330            &self.queue,
6331            &mut self.frame_graph_executor,
6332            &mut self.frame_stats,
6333        );
6334    }
6335
6336    fn glyph_atlas_entry_for_cached(
6337        &mut self,
6338        glyph: &SoftwareGlyphAtlasPlacement,
6339    ) -> Option<GlyphAtlasEntry> {
6340        let entry = self
6341            .text_glyph_atlas
6342            .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
6343        self.frame_stats.record_text_glyph_atlas_hits(1);
6344        Some(entry)
6345    }
6346
6347    fn glyph_atlas_entry_for_placement(
6348        &mut self,
6349        glyph: &SoftwareGlyphAtlasPlacement,
6350    ) -> Result<GlyphAtlasEntry, String> {
6351        if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
6352            return Ok(entry);
6353        }
6354
6355        let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
6356            return Err("text glyph placement has no retained raster mask".to_string());
6357        };
6358        self.glyph_atlas_entry_for(&upload_glyph)
6359    }
6360
6361    /// The atlas entries of a run's drawing glyphs: of `cached_glyph_run`,
6362    /// which holds only those, or of the drawing glyphs of `collected_run`,
6363    /// a run just collected, whose new glyphs are uploaded here.
6364    fn prepare_text_glyph_entries(
6365        &mut self,
6366        run_key: TextGlyphRunCacheKey,
6367        atlas_generation: u64,
6368        cached_glyph_run: Option<&RunGlyphs>,
6369        collected_run: &[SoftwareGlyphAtlasRunGlyph],
6370        entries: &mut Vec<GlyphAtlasEntry>,
6371    ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
6372        entries.clear();
6373        let mut seen = RunAtlasEntries::new();
6374        if let Some(glyph_run) = cached_glyph_run {
6375            for glyph in glyph_run.iter() {
6376                entries.push(seen.entry(self, &glyph, |renderer| {
6377                    renderer.glyph_atlas_entry_for_placement(&glyph)
6378                })?);
6379            }
6380        } else {
6381            for run_glyph in collected_run {
6382                entries.push(seen.entry(
6383                    self,
6384                    &run_glyph.placement(),
6385                    |renderer| match run_glyph {
6386                        SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
6387                            renderer.glyph_atlas_entry_for_placement(placement)
6388                        }
6389                        SoftwareGlyphAtlasRunGlyph::New(glyph) => {
6390                            renderer.glyph_atlas_entry_for(glyph)
6391                        }
6392                    },
6393                )?);
6394            }
6395        }
6396
6397        let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
6398        if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
6399            cached.atlas_entries = Some(Rc::clone(&entries));
6400            cached.atlas_generation = atlas_generation;
6401        }
6402        Ok(entries)
6403    }
6404
6405    #[expect(clippy::too_many_arguments)]
6406    fn append_text_glyph_quad_run(
6407        &mut self,
6408        source_raster_rect: Rect,
6409        quads: GlyphRunQuads<'_>,
6410        (clip, cut): (Option<Rect>, Option<[f32; 4]>),
6411        viewport: ViewportUniformParams,
6412        root_scale: f32,
6413        glyph_instances: &mut GlyphInstances,
6414        record_cached_hits: bool,
6415    ) -> (GlyphQuads, GlyphExtent) {
6416        let start = glyph_instances.lens();
6417        let mut extent = GlyphExtent::EMPTY;
6418        let origin = [source_raster_rect.x, source_raster_rect.y];
6419        let bounds = quads.bounds.at(origin);
6420        let kind = if viewport.transform.is_identity()
6421            && cut.is_none_or(|edges| {
6422                bounds[0] >= edges[0]
6423                    && bounds[1] >= edges[1]
6424                    && bounds[2] <= edges[2]
6425                    && bounds[3] <= edges[3]
6426            })
6427            && quads
6428                .bounds
6429                .within_viewport(source_raster_rect, clip, viewport, root_scale)
6430        {
6431            // Every quad shows whole and uncut: they sit at whole pixels from
6432            // the run's origin, which then decides their alignment, and
6433            // their extent is the run's bounds.
6434            glyph_instances.plain.extend(quads.instances_at(origin));
6435            extent.add(bounds);
6436            GlyphQuads::plain(glyph_rect_aligned(
6437                [origin[0], origin[1], origin[0], origin[1]],
6438                viewport.offset,
6439            ))
6440        } else if viewport.transform.is_identity() {
6441            let plain = &mut glyph_instances.plain;
6442            let mut aligned = true;
6443            for_each_visible_glyph(
6444                source_raster_rect,
6445                quads,
6446                (clip, cut),
6447                viewport,
6448                root_scale,
6449                |glyph| {
6450                    aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
6451                    extent.add(glyph.rect);
6452                    plain.push(glyph);
6453                },
6454            );
6455            GlyphQuads::plain(aligned)
6456        } else {
6457            let turn = viewport.transform;
6458            let turned = &mut glyph_instances.turned;
6459            for_each_visible_glyph(
6460                source_raster_rect,
6461                quads,
6462                (clip, cut),
6463                viewport,
6464                root_scale,
6465                |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
6466            );
6467            GlyphQuads::Turned
6468        };
6469        let end = glyph_instances.lens();
6470        let appended = (end.0 - start.0) + (end.1 - start.1);
6471        if record_cached_hits {
6472            self.frame_stats
6473                .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
6474        }
6475        (kind, extent)
6476    }
6477
6478    /// The viewport a retained glyph run draws under: its vertices sit at
6479    /// its raster rect's origin, so an untransformed target moves its offset
6480    /// back by that origin, and a transformed one adds the origin to each
6481    /// vertex before its transform, as the shared path's vertices hold it.
6482    fn retained_glyph_viewport(
6483        viewport: ViewportUniformParams,
6484        source_raster_rect: Rect,
6485    ) -> ViewportUniformParams {
6486        if !viewport.transform.is_identity() {
6487            return ViewportUniformParams {
6488                origin: [source_raster_rect.x, source_raster_rect.y],
6489                ..viewport
6490            };
6491        }
6492        ViewportUniformParams {
6493            offset: [
6494                viewport.offset[0] - source_raster_rect.x,
6495                viewport.offset[1] - source_raster_rect.y,
6496            ],
6497            ..viewport
6498        }
6499    }
6500
6501    fn retained_text_glyph_run(
6502        &mut self,
6503        cache_key: TextGlyphRunCacheKey,
6504    ) -> Option<Rc<CachedGpuTextGlyphRun>> {
6505        let atlas_generation = self.text_glyph_atlas.generation();
6506        let frame = self.text_glyph_run_frame;
6507        self.text_glyph_gpu_run_cache
6508            .get(&cache_key)
6509            .filter(|cached| cached.atlas_generation == atlas_generation)
6510            .inspect(|cached| cached.last_frame.set(frame))
6511            .cloned()
6512    }
6513
6514    /// Opens a frame for text runs: runs no frame drew for
6515    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] leave the GPU cache and those no
6516    /// frame drew for [`TEXT_GLYPH_RUN_IDLE_FRAMES`] the CPU cache, and the
6517    /// arena takes back the quads dropped retained runs held.
6518    fn begin_text_glyph_run_frame(&mut self) {
6519        #[cfg(feature = "installed-fonts")]
6520        if let Some(fonts) = self.text_fonts.with_installed_faces() {
6521            // Text drawn before the install may show a missing glyph where an
6522            // installed face now has one.
6523            self.text_fonts = fonts;
6524            self.text_image_cache.clear();
6525            self.text_glyph_run_cache.clear();
6526            self.text_glyph_gpu_run_cache.clear();
6527        }
6528        self.text_glyph_run_frame += 1;
6529        let frame = self.text_glyph_run_frame;
6530        let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
6531        self.text_glyph_run_cache.set_cap(
6532            std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
6533                .unwrap_or(std::num::NonZeroUsize::MIN),
6534        );
6535        evict_idle(
6536            &mut self.text_glyph_gpu_run_cache,
6537            frame,
6538            TEXT_GLYPH_GPU_RUN_IDLE_FRAMES,
6539            |run| run.last_frame.get(),
6540        );
6541        evict_idle(
6542            &mut self.text_glyph_run_cache,
6543            frame,
6544            TEXT_GLYPH_RUN_IDLE_FRAMES,
6545            |run| run.last_frame.get(),
6546        );
6547        self.text_glyph_run_arena.begin_frame();
6548        let evacuating = self.text_glyph_run_arena.evacuating();
6549        if !evacuating.is_empty() {
6550            let moving: Vec<TextGlyphRunCacheKey> = self
6551                .text_glyph_gpu_run_cache
6552                .iter()
6553                .filter(|(_, run)| evacuating.contains(&run.span.chunk()))
6554                .map(|(key, _)| *key)
6555                .collect();
6556            for key in &moving {
6557                self.text_glyph_gpu_run_cache.pop(key);
6558            }
6559        }
6560    }
6561
6562    fn emit_retained_text_glyph_run_if_ready(
6563        &mut self,
6564        cache_key: TextGlyphRunCacheKey,
6565        quads: GlyphRunQuads<'_>,
6566        viewport: ViewportUniformParams,
6567        source_raster_rect: Rect,
6568        scissor: (u32, u32, u32, u32),
6569        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6570    ) -> bool {
6571        let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
6572            if self.ensure_retained_text_glyph_run(cache_key, quads) {
6573                self.retained_text_glyph_run(cache_key)
6574            } else {
6575                None
6576            }
6577        }) else {
6578            return false;
6579        };
6580        let uniform_slot =
6581            self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
6582        self.frame_stats
6583            .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
6584        // The run's quads sit at whole texels from its raster origin.
6585        let aligned = viewport.transform.is_identity()
6586            && glyph_rect_aligned(
6587                [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
6588                [viewport.offset[0], viewport.offset[1]],
6589            );
6590        glyph_cmds.push(GlyphDrawCmd::retained(
6591            (run, uniform_slot, aligned),
6592            scissor,
6593            self.text_glyph_atlas.bind_group(viewport.transform),
6594        ));
6595        true
6596    }
6597
6598    fn ensure_retained_text_glyph_run(
6599        &mut self,
6600        cache_key: TextGlyphRunCacheKey,
6601        quads: GlyphRunQuads<'_>,
6602    ) -> bool {
6603        let atlas_generation = self.text_glyph_atlas.generation();
6604        if self
6605            .text_glyph_gpu_run_cache
6606            .peek(&cache_key)
6607            .is_some_and(|cached| cached.atlas_generation == atlas_generation)
6608        {
6609            return true;
6610        }
6611
6612        let Some(span) = self
6613            .text_glyph_run_arena
6614            .insert(&self.device, quads.instances_at([0.0, 0.0]))
6615        else {
6616            return false;
6617        };
6618        self.text_glyph_gpu_run_cache.put(
6619            cache_key,
6620            Rc::new(CachedGpuTextGlyphRun {
6621                span,
6622                atlas_generation,
6623                last_frame: Cell::new(self.text_glyph_run_frame),
6624            }),
6625        );
6626        true
6627    }
6628    /// Appends the glyph atlas draws of `text_draw`, whose logical geometry
6629    /// `logical` the caller found drawing into a rect `viewport` shows.
6630    /// `false` when the text cannot draw from the atlas (animated motion, or
6631    /// a run the atlas cannot hold): nothing was appended, and the caller
6632    /// draws the text as a rasterized image instead.
6633    pub(crate) fn append_text_glyph_draws(
6634        &mut self,
6635        (text_draw, logical): (&TextDraw, (Rect, f32)),
6636        viewport: ViewportUniformParams,
6637        root_scale: f32,
6638        glyph_instances: &mut GlyphInstances,
6639        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6640    ) -> bool {
6641        let (_, raster_rect, _, text_scale, static_text_motion) =
6642            text_raster_geometry_at(text_draw, logical, root_scale);
6643        if !static_text_motion {
6644            return false;
6645        }
6646        let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
6647        let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
6648        let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
6649        let initial_instance_len = glyph_instances.lens();
6650        let initial_cmd_len = glyph_cmds.len();
6651        let drew = self
6652            .text_glyph_run(
6653                text_draw,
6654                raster_rect,
6655                text_scale,
6656                run_key,
6657                &mut collected_run,
6658            )
6659            .is_some_and(|run| {
6660                self.append_text_glyph_run(
6661                    TextGlyphRunDraw {
6662                        text_draw,
6663                        raster_rect,
6664                        run_key,
6665                        run,
6666                    },
6667                    (viewport, root_scale),
6668                    (&collected_run, &mut generated_entries),
6669                    glyph_instances,
6670                    glyph_cmds,
6671                )
6672            });
6673        self.scratch_text_glyph_run = collected_run;
6674        self.scratch_text_glyph_entries = generated_entries;
6675        if !drew {
6676            glyph_instances.truncate(initial_instance_len);
6677            glyph_cmds.truncate(initial_cmd_len);
6678        }
6679        drew
6680    }
6681
6682    /// The run of `text_draw` from the cache, or collected into
6683    /// `collected_run` and cached; `None` when the text cannot draw from the
6684    /// atlas.
6685    fn text_glyph_run(
6686        &mut self,
6687        text_draw: &TextDraw,
6688        raster_rect: Rect,
6689        text_scale: f32,
6690        run_key: TextGlyphRunCacheKey,
6691        collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
6692    ) -> Option<TextGlyphRunLookup> {
6693        let atlas_generation = self.text_glyph_atlas.generation();
6694        let frame = self.text_glyph_run_frame;
6695        self.text_glyph_runs_drawn += 1;
6696        if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
6697            cached.last_frame.set(frame);
6698            return Some(TextGlyphRunLookup {
6699                glyphs: cached.glyphs.clone(),
6700                bounds: cached.bounds,
6701                cached: true,
6702                entries: (cached.atlas_generation == atlas_generation)
6703                    .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
6704                    .flatten(),
6705            });
6706        }
6707        collected_run.clear();
6708        if collect_solid_text_atlas_run(
6709            text_draw.text.string().as_ref(),
6710            raster_rect,
6711            &text_draw.text_style,
6712            text_draw.color,
6713            text_draw.font_size,
6714            text_scale,
6715            &self.text_fonts,
6716            &mut self.text_glyph_mask_cache,
6717            collected_run,
6718        )
6719        .is_none()
6720        {
6721            log_text_atlas_fallback(text_draw);
6722            return None;
6723        }
6724        let Some(glyphs) = RunGlyphs::of(
6725            collected_run
6726                .iter()
6727                .map(SoftwareGlyphAtlasRunGlyph::placement),
6728            &mut self.run_glyph_scratch,
6729        ) else {
6730            log_text_atlas_fallback(text_draw);
6731            return None;
6732        };
6733        let bounds = GlyphRunBounds::of(glyphs.iter());
6734        self.frame_stats.record_text_glyph_run_collected();
6735        // A run this frame drew stays: the cache grows rather than evict it.
6736        let cache = &mut self.text_glyph_run_cache;
6737        if cache.len() == cache.cap().get()
6738            && cache
6739                .peek_lru()
6740                .is_some_and(|(_, run)| run.last_frame.get() == frame)
6741        {
6742            cache.set_cap(cache.cap().saturating_add(cache.len()));
6743        }
6744        self.text_glyph_run_cache.put(
6745            run_key,
6746            CachedTextGlyphRun {
6747                glyphs: glyphs.clone(),
6748                bounds,
6749                atlas_entries: None,
6750                atlas_generation: 0,
6751                last_frame: Cell::new(frame),
6752            },
6753        );
6754        Some(TextGlyphRunLookup {
6755            glyphs,
6756            bounds,
6757            cached: false,
6758            entries: None,
6759        })
6760    }
6761
6762    /// Appends the draws of a text's run: its retained quads when it has
6763    /// them, else its visible quads into the frame's shared glyphs. `false`
6764    /// when the atlas cannot hold its glyphs.
6765    fn append_text_glyph_run(
6766        &mut self,
6767        draw: TextGlyphRunDraw<'_>,
6768        (viewport, root_scale): (ViewportUniformParams, f32),
6769        (collected_run, generated_entries): (
6770            &[SoftwareGlyphAtlasRunGlyph],
6771            &mut Vec<GlyphAtlasEntry>,
6772        ),
6773        glyph_instances: &mut GlyphInstances,
6774        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6775    ) -> bool {
6776        let TextGlyphRunDraw {
6777            text_draw,
6778            raster_rect,
6779            run_key,
6780            run,
6781        } = draw;
6782        let draw_rect = Rect {
6783            x: raster_rect.x / root_scale,
6784            y: raster_rect.y / root_scale,
6785            width: raster_rect.width / root_scale,
6786            height: raster_rect.height / root_scale,
6787        };
6788        let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
6789        else {
6790            return true;
6791        };
6792        let texel = self.text_glyph_atlas.texel();
6793
6794        // A retained run's quads are uploaded whole: under a turn only the
6795        // shared path cuts them to a clip.
6796        let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
6797        if let Some(entries) = run.entries.as_ref()
6798            && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
6799            && !clip_needs_cut
6800            && self.emit_retained_text_glyph_run_if_ready(
6801                run_key,
6802                GlyphRunQuads {
6803                    glyphs: &run.glyphs,
6804                    entries,
6805                    texel,
6806                    bounds: run.bounds,
6807                },
6808                viewport,
6809                raster_rect,
6810                scissor,
6811                glyph_cmds,
6812            )
6813        {
6814            return true;
6815        }
6816
6817        let turned = !viewport.transform.is_identity();
6818        let instance_start = glyph_instances.len_of(turned);
6819        let (entries, entries_cached) = match run.entries {
6820            Some(entries) => (entries, true),
6821            None => {
6822                let Ok(entries) = self.prepare_text_glyph_entries(
6823                    run_key,
6824                    self.text_glyph_atlas.generation(),
6825                    run.cached.then_some(&run.glyphs),
6826                    collected_run,
6827                    generated_entries,
6828                ) else {
6829                    return false;
6830                };
6831                (entries, false)
6832            }
6833        };
6834        let quads = GlyphRunQuads {
6835            glyphs: &run.glyphs,
6836            entries: &entries,
6837            texel: self.text_glyph_atlas.texel(),
6838            bounds: run.bounds,
6839        };
6840        let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
6841        let (kind, extent) = self.append_text_glyph_quad_run(
6842            raster_rect,
6843            quads,
6844            (text_draw.clip, cut),
6845            viewport,
6846            root_scale,
6847            glyph_instances,
6848            entries_cached,
6849        );
6850        let instance_end = glyph_instances.len_of(turned);
6851        if instance_end > instance_start {
6852            let (clip, bounds) = if turned {
6853                (None, scissor)
6854            } else {
6855                shared_glyph_clip(extent, scissor, viewport)
6856            };
6857            glyph_cmds.push(GlyphDrawCmd::shared(
6858                (instance_start..instance_end, kind),
6859                clip,
6860                bounds,
6861                self.text_glyph_atlas.bind_group(viewport.transform),
6862            ));
6863        }
6864        true
6865    }
6866
6867    #[expect(clippy::too_many_arguments)]
6868    fn append_image_bitmap_draw_cmd(
6869        &mut self,
6870        image: &ImageBitmap,
6871        rect: Rect,
6872        clip: Option<Rect>,
6873        sampling: ImageSampling,
6874        viewport: ViewportUniformParams,
6875        root_scale: f32,
6876        image_vertices: &mut Vec<Vertex>,
6877        image_indices: &mut Vec<u32>,
6878        image_cmds: &mut Vec<ImageDrawCmd>,
6879    ) -> Result<(), String> {
6880        if rect.width <= 0.0 || rect.height <= 0.0 {
6881            return Ok(());
6882        }
6883
6884        let (device_quad, scissor_rect) =
6885            if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
6886                let left_px = (rect.x * root_scale).round();
6887                let top_px = (rect.y * root_scale).round();
6888                let width_px = (rect.width * root_scale).round().max(1.0);
6889                let height_px = (rect.height * root_scale).round().max(1.0);
6890                let snapped_rect = Rect {
6891                    x: left_px / root_scale,
6892                    y: top_px / root_scale,
6893                    width: width_px / root_scale,
6894                    height: height_px / root_scale,
6895                };
6896                let right_px = left_px + width_px;
6897                let bottom_px = top_px + height_px;
6898                (
6899                    [
6900                        [left_px, top_px],
6901                        [right_px, top_px],
6902                        [left_px, bottom_px],
6903                        [right_px, bottom_px],
6904                    ],
6905                    snapped_rect,
6906                )
6907            } else {
6908                (
6909                    rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
6910                    rect,
6911                )
6912            };
6913
6914        let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
6915            return Ok(());
6916        };
6917        let Some(uv_rect) = image_uv_rect(image, None) else {
6918            return Ok(());
6919        };
6920
6921        let index_start = push_image_quad(
6922            (image_vertices, image_indices),
6923            device_quad,
6924            [1.0, 1.0, 1.0, 1.0],
6925            &uv_rect,
6926        );
6927        image_cmds.push(ImageDrawCmd {
6928            index_start,
6929            scissor,
6930            image: self.image_binding(image, sampling)?,
6931            clip: None,
6932        });
6933        Ok(())
6934    }
6935
6936    /// Appends `text_draw` as a rasterized image if `viewport` shows it.
6937    pub(crate) fn append_text_image_draw_cmds(
6938        &mut self,
6939        text_draw: &TextDraw,
6940        viewport: ViewportUniformParams,
6941        root_scale: f32,
6942        image_vertices: &mut Vec<Vertex>,
6943        image_indices: &mut Vec<u32>,
6944        image_cmds: &mut Vec<ImageDrawCmd>,
6945    ) -> Result<(), String> {
6946        let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
6947            self.text_raster_geometry(text_draw, root_scale)
6948        else {
6949            return Ok(());
6950        };
6951        if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
6952            return Ok(());
6953        }
6954
6955        let raster_source = self.text_image_raster_source(
6956            text_draw,
6957            logical_rect,
6958            raster_rect,
6959            clip,
6960            root_scale,
6961            static_text_motion,
6962        );
6963        let source_draw = raster_source.draw.as_ref();
6964        let source_raster_rect = raster_source.raster_rect;
6965        let source_origin = if source_draw.text.string().span_styles().is_empty() {
6966            Point::new(source_raster_rect.x, source_raster_rect.y)
6967        } else {
6968            Point::new(raster_rect.x, raster_rect.y)
6969        };
6970
6971        let mut cache_key = Self::text_image_cache_key(
6972            source_draw,
6973            source_raster_rect,
6974            text_scale,
6975            static_text_motion,
6976        );
6977        if !source_draw.text.string().span_styles().is_empty() {
6978            let mut state = default_hash::new();
6979            cache_key.0.hash(&mut state);
6980            (source_origin.x - source_raster_rect.x)
6981                .to_bits()
6982                .hash(&mut state);
6983            (source_origin.y - source_raster_rect.y)
6984                .to_bits()
6985                .hash(&mut state);
6986            cache_key = TextImageCacheKey(state.finish());
6987        }
6988        let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
6989            self.frame_stats
6990                .record_text_image_cache_hit(cached.image.width(), cached.image.height());
6991            cached.image.clone()
6992        } else {
6993            let Some(image) = self.rasterize_text_draw_to_image(
6994                source_draw,
6995                source_raster_rect,
6996                source_origin,
6997                text_scale,
6998            ) else {
6999                return Ok(());
7000            };
7001            self.frame_stats
7002                .record_text_image_cache_miss(image.width(), image.height());
7003            self.text_image_cache.put(
7004                cache_key,
7005                CachedTextImage {
7006                    image: image.clone(),
7007                },
7008            );
7009            image
7010        };
7011
7012        let draw_origin = if static_text_motion {
7013            Point::new(
7014                source_raster_rect.x / root_scale,
7015                source_raster_rect.y / root_scale,
7016            )
7017        } else {
7018            Point::new(logical_rect.x, logical_rect.y)
7019        };
7020        let draw_rect = Rect {
7021            x: draw_origin.x,
7022            y: draw_origin.y,
7023            width: image.width() as f32 / root_scale,
7024            height: image.height() as f32 / root_scale,
7025        };
7026        self.append_image_bitmap_draw_cmd(
7027            &image,
7028            draw_rect,
7029            clip,
7030            sampling_under(ImageSampling::Nearest, viewport.transform),
7031            viewport,
7032            root_scale,
7033            image_vertices,
7034            image_indices,
7035            image_cmds,
7036        )
7037    }
7038
7039    fn text_image_raster_source<'a>(
7040        &mut self,
7041        text_draw: &'a TextDraw,
7042        logical_rect: Rect,
7043        raster_rect: Rect,
7044        clip: Option<Rect>,
7045        root_scale: f32,
7046        static_text_motion: bool,
7047    ) -> TextRasterSource<'a> {
7048        let Some(clip) = clip else {
7049            return TextRasterSource {
7050                draw: Cow::Borrowed(text_draw),
7051                raster_rect,
7052            };
7053        };
7054        if !static_text_motion || text_draw.text.string().text().find('\n').is_none() {
7055            return TextRasterSource {
7056                draw: Cow::Borrowed(text_draw),
7057                raster_rect,
7058            };
7059        }
7060
7061        if !text_draw.text.string().span_styles().is_empty() {
7062            let device_clip = Rect {
7063                x: (clip.x * root_scale).floor(),
7064                y: (clip.y * root_scale).floor(),
7065                width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
7066                height: ((clip.y + clip.height) * root_scale).ceil()
7067                    - (clip.y * root_scale).floor(),
7068            };
7069            return TextRasterSource {
7070                draw: Cow::Borrowed(text_draw),
7071                raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
7072            };
7073        }
7074
7075        let line_starts = self
7076            .text_line_index_cache
7077            .line_starts(text_draw.text.string());
7078        clipped_text_raster_source_with_line_starts(
7079            text_draw,
7080            logical_rect,
7081            raster_rect,
7082            clip,
7083            root_scale,
7084            line_starts.as_ref(),
7085        )
7086    }
7087
7088    fn text_raster_geometry(
7089        &self,
7090        text_draw: &TextDraw,
7091        root_scale: f32,
7092    ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
7093        text_raster_geometry_for_draw(text_draw, root_scale)
7094    }
7095
7096    fn text_image_cache_key(
7097        text_draw: &TextDraw,
7098        raster_rect: Rect,
7099        text_scale: f32,
7100        static_text_motion: bool,
7101    ) -> TextImageCacheKey {
7102        let mut state = default_hash::new();
7103        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7104        hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
7105        TextImageCacheKey(state.finish())
7106    }
7107
7108    /// The key of a static text's glyph run. A run places its glyphs from
7109    /// the text's origin and aligns its lines within the text block, so the
7110    /// size of the rect it draws in does not change it: only an empty rect,
7111    /// which draws nothing, does.
7112    fn text_glyph_run_cache_key(
7113        text_draw: &TextDraw,
7114        raster_rect: Rect,
7115        text_scale: f32,
7116    ) -> TextGlyphRunCacheKey {
7117        let mut state = default_hash::new();
7118        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7119        (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
7120        TextGlyphRunCacheKey(state.finish())
7121    }
7122
7123    fn rasterize_text_draw_to_image(
7124        &mut self,
7125        text_draw: &TextDraw,
7126        raster_rect: Rect,
7127        source_origin: Point,
7128        text_scale: f32,
7129    ) -> Option<ImageBitmap> {
7130        rasterize_annotated_text_region(
7131            text_draw.text.string().as_ref(),
7132            raster_rect,
7133            if text_draw.text.string().span_styles().is_empty() {
7134                Point::new(raster_rect.x, raster_rect.y)
7135            } else {
7136                source_origin
7137            },
7138            &text_draw.text_style,
7139            text_draw.color,
7140            text_draw.font_size,
7141            text_scale,
7142            &self.text_fonts,
7143            Some(&mut self.text_glyph_mask_cache),
7144        )
7145    }
7146}
7147
7148struct TextRasterSource<'a> {
7149    draw: Cow<'a, TextDraw>,
7150    raster_rect: Rect,
7151}
7152
7153fn clipped_text_raster_source_with_line_starts<'a>(
7154    text_draw: &'a TextDraw,
7155    logical_rect: Rect,
7156    raster_rect: Rect,
7157    clip: Rect,
7158    root_scale: f32,
7159    line_starts: &[usize],
7160) -> TextRasterSource<'a> {
7161    if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
7162        return TextRasterSource {
7163            draw: Cow::Borrowed(text_draw),
7164            raster_rect,
7165        };
7166    }
7167
7168    let Some(visible_rect) = logical_rect.intersect(clip) else {
7169        return TextRasterSource {
7170            draw: Cow::Borrowed(text_draw),
7171            raster_rect,
7172        };
7173    };
7174
7175    let line_count = line_starts.len().max(1);
7176    let line_height = logical_rect.height / line_count as f32;
7177    if !line_height.is_finite() || line_height <= 0.0 {
7178        return TextRasterSource {
7179            draw: Cow::Borrowed(text_draw),
7180            raster_rect,
7181        };
7182    }
7183
7184    let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
7185    let visible_bottom =
7186        ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
7187    let start_line = visible_top.saturating_sub(1).max(0) as usize;
7188    let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
7189    let end_line = end_line.min(line_count);
7190    if start_line == 0 && end_line >= line_count {
7191        return TextRasterSource {
7192            draw: Cow::Borrowed(text_draw),
7193            raster_rect,
7194        };
7195    }
7196
7197    let byte_start = line_starts[start_line];
7198    let byte_end = line_end_offset(text_draw.text.string().text(), line_starts, end_line - 1);
7199    if byte_start >= byte_end {
7200        return TextRasterSource {
7201            draw: Cow::Borrowed(text_draw),
7202            raster_rect,
7203        };
7204    }
7205
7206    let slice_y = logical_rect.y + start_line as f32 * line_height;
7207    let slice_height = (end_line - start_line) as f32 * line_height;
7208    let mut slice_raster_rect = Rect {
7209        x: logical_rect.x * root_scale,
7210        y: slice_y * root_scale,
7211        width: logical_rect.width * root_scale,
7212        height: slice_height * root_scale,
7213    };
7214    slice_raster_rect.x = slice_raster_rect.x.round();
7215    slice_raster_rect.y = slice_raster_rect.y.round();
7216    slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
7217    slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
7218
7219    let mut sliced_draw = text_draw.clone();
7220    sliced_draw.rect = Rect {
7221        x: logical_rect.x,
7222        y: slice_y,
7223        width: logical_rect.width,
7224        height: slice_height,
7225    };
7226    sliced_draw.text = DrawnText::of(
7227        Arc::new(text_draw.text.string().subsequence(byte_start..byte_end)),
7228        &text_draw.text_style,
7229    );
7230
7231    TextRasterSource {
7232        draw: Cow::Owned(sliced_draw),
7233        raster_rect: slice_raster_rect,
7234    }
7235}
7236
7237fn line_start_offsets(text: &str) -> Vec<usize> {
7238    let mut starts =
7239        Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
7240    starts.push(0);
7241    starts.extend(
7242        text.char_indices()
7243            .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
7244    );
7245    starts
7246}
7247
7248fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
7249    line_starts.get(line + 1).copied().unwrap_or(text.len())
7250}
7251
7252fn align_to(value: u32, alignment: u32) -> u32 {
7253    debug_assert!(alignment > 0);
7254    value.div_ceil(alignment) * alignment
7255}
7256
7257impl GpuRenderer {
7258    fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
7259        if !pixels.len().is_multiple_of(4) {
7260            return Err("Screenshot readback has an incomplete pixel".to_string());
7261        }
7262        Ok(pixels.to_vec())
7263    }
7264}
7265
7266/// The scissor of a logical rect in a target whose origin sits at
7267/// `viewport.offset` of the scene's device space, clamped to the target.
7268/// `None` when nothing of the rect lands in the target.
7269pub(crate) fn scissor_rect_for_rect(
7270    rect: Rect,
7271    root_scale: f32,
7272    viewport: ViewportUniformParams,
7273) -> Option<(u32, u32, u32, u32)> {
7274    let width = viewport.width as f32;
7275    let height = viewport.height as f32;
7276    let mut left = canonicalize_device_coordinate(rect.x * root_scale);
7277    let mut top = canonicalize_device_coordinate(rect.y * root_scale);
7278    let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
7279    let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
7280    if !viewport.transform.is_identity() {
7281        let bounds = viewport.transform.target_bounds(Rect {
7282            x: left,
7283            y: top,
7284            width: right - left,
7285            height: bottom - top,
7286        });
7287        (left, top) = (bounds.x, bounds.y);
7288        (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
7289    }
7290    let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
7291    let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
7292    let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
7293    let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
7294    if right <= left || bottom <= top {
7295        return None;
7296    }
7297    Some((
7298        left as u32,
7299        top as u32,
7300        (right - left) as u32,
7301        (bottom - top) as u32,
7302    ))
7303}
7304
7305fn scissor_rect_for_layer(
7306    rect: Rect,
7307    clip: Option<Rect>,
7308    root_scale: f32,
7309    viewport: ViewportUniformParams,
7310) -> Option<(u32, u32, u32, u32)> {
7311    let clipped_rect = match clip {
7312        Some(clip_rect) => rect.intersect(clip_rect)?,
7313        None => rect,
7314    };
7315    scissor_rect_for_rect(clipped_rect, root_scale, viewport)
7316}
7317fn tint_for_image(
7318    color_filter: Option<ColorFilter>,
7319    alpha: f32,
7320) -> ([f32; 4], Option<ColorFilter>) {
7321    let alpha = alpha.clamp(0.0, 1.0);
7322    match color_filter {
7323        Some(filter) if filter.supports_gpu_vertex_modulation() => {
7324            let Some(tint) = filter.gpu_vertex_tint() else {
7325                return ([1.0, 1.0, 1.0, alpha], Some(filter));
7326            };
7327            (
7328                [
7329                    tint[0].clamp(0.0, 1.0),
7330                    tint[1].clamp(0.0, 1.0),
7331                    tint[2].clamp(0.0, 1.0),
7332                    (tint[3] * alpha).clamp(0.0, 1.0),
7333                ],
7334                None,
7335            )
7336        }
7337        Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
7338        None => ([1.0, 1.0, 1.0, alpha], None),
7339    }
7340}
7341
7342/// The rounded clip an image takes in place, in device pixels: one instance
7343/// its draw reads, beside the quad's vertices.
7344#[repr(C)]
7345#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7346pub(crate) struct DeviceRoundedClip {
7347    rect: [f32; 4],
7348    radius: f32,
7349}
7350
7351impl DeviceRoundedClip {
7352    const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
7353        4 => Float32x4,
7354        5 => Float32,
7355    ];
7356
7357    fn desc() -> wgpu::VertexBufferLayout<'static> {
7358        wgpu::VertexBufferLayout {
7359            array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
7360            step_mode: wgpu::VertexStepMode::Instance,
7361            attributes: &Self::ATTRIBS,
7362        }
7363    }
7364
7365    /// The rounded clip `image` takes at `root_scale`, scaled as a run's
7366    /// placement scales its clip.
7367    fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
7368        let rounding = image.rounding.filter(|_| image.clip.is_some())?;
7369        let device =
7370            crate::geometry::device_rect(rounding.rect, root_scale, image.snap_anchor.is_some());
7371        Some(Self {
7372            rect: [device.x, device.y, device.width, device.height],
7373            radius: rounding.radius * root_scale,
7374        })
7375    }
7376}
7377
7378/// Appends an image quad over `device_quad` and its two triangles, and
7379/// returns the index its triangles start at.
7380fn push_image_quad(
7381    (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
7382    device_quad: [[f32; 2]; 4],
7383    color: [f32; 4],
7384    uv_rect: &ImageUvRect,
7385) -> u32 {
7386    let base_vertex = vertices.len() as u32;
7387    let index_start = indices.len() as u32;
7388    indices.extend_from_slice(&[
7389        base_vertex,
7390        base_vertex + 1,
7391        base_vertex + 2,
7392        base_vertex + 2,
7393        base_vertex + 1,
7394        base_vertex + 3,
7395    ]);
7396    let corners = [
7397        [uv_rect.min[0], uv_rect.min[1]],
7398        [uv_rect.max[0], uv_rect.min[1]],
7399        [uv_rect.min[0], uv_rect.max[1]],
7400        [uv_rect.max[0], uv_rect.max[1]],
7401    ];
7402    vertices.extend(
7403        device_quad
7404            .into_iter()
7405            .zip(corners)
7406            .map(|(position, uv)| Vertex {
7407                position,
7408                color,
7409                uv,
7410                uv_bounds: uv_rect.sample_bounds,
7411            }),
7412    );
7413    index_start
7414}
7415
7416fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
7417    let Some(src) = src_rect else {
7418        return Some(ImageUvRect {
7419            min: [0.0, 0.0],
7420            max: [1.0, 1.0],
7421            sample_bounds: [0.0, 0.0, 1.0, 1.0],
7422        });
7423    };
7424
7425    let (u_min, u_max, u_bound_min, u_bound_max) =
7426        source_axis_uv(src.x, src.width, image.width() as f32)?;
7427    let (v_min, v_max, v_bound_min, v_bound_max) =
7428        source_axis_uv(src.y, src.height, image.height() as f32)?;
7429
7430    Some(ImageUvRect {
7431        min: [u_min, v_min],
7432        max: [u_max, v_max],
7433        sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
7434    })
7435}
7436
7437/// `entry`'s rect in an atlas whose texel is `texel` of its side, an
7438/// exact power of two: the products are the quotients by the side.
7439fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, texel: f32) -> ImageUvRect {
7440    let min = [entry.x as f32 * texel, entry.y as f32 * texel];
7441    let max = [
7442        (entry.x + entry.width) as f32 * texel,
7443        (entry.y + entry.height) as f32 * texel,
7444    ];
7445    let center_min = [
7446        (entry.x as f32 + 0.5) * texel,
7447        (entry.y as f32 + 0.5) * texel,
7448    ];
7449    let center_max = [
7450        (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) * texel,
7451        (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) * texel,
7452    ];
7453    ImageUvRect {
7454        min,
7455        max,
7456        sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
7457    }
7458}
7459
7460#[derive(Clone, Copy)]
7461pub(crate) struct ResolvedImageGeometry {
7462    pub(crate) rect: Rect,
7463    pub(crate) clip: Option<Rect>,
7464    pub(crate) sampling: ImageSampling,
7465    quad: [[f32; 2]; 4],
7466    snap_anchored: bool,
7467}
7468
7469pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
7470    let snap_delta = image
7471        .snap_anchor
7472        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
7473        .unwrap_or_default();
7474    resolve_image_geometry_with_delta(image, root_scale, snap_delta)
7475}
7476
7477fn resolve_image_geometry_with_delta(
7478    image: &ImageDraw,
7479    root_scale: f32,
7480    snap_delta: Point,
7481) -> ResolvedImageGeometry {
7482    let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
7483    let mut quad = translate_quad(image.quad, snap_delta);
7484    snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
7485    ResolvedImageGeometry {
7486        rect,
7487        clip: image.clip,
7488        sampling: image.sampling,
7489        quad,
7490        snap_anchored: image.snap_anchor.is_some(),
7491    }
7492}
7493
7494impl ResolvedImageGeometry {
7495    pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
7496        nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
7497            if self.snap_anchored {
7498                canonicalized_scaled_quad(self.quad, root_scale)
7499            } else {
7500                scaled_quad(self.quad, root_scale)
7501            }
7502        })
7503    }
7504}
7505
7506fn snap_nearest_image_to_device_pixels(
7507    sampling: ImageSampling,
7508    rect: &mut Rect,
7509    quad: &mut [[f32; 2]; 4],
7510    root_scale: f32,
7511) {
7512    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7513        return;
7514    }
7515
7516    let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
7517        return;
7518    };
7519
7520    let left_px = (quad_rect.x * root_scale).round();
7521    let top_px = (quad_rect.y * root_scale).round();
7522    let width_px = (quad_rect.width * root_scale).round().max(1.0);
7523    let height_px = (quad_rect.height * root_scale).round().max(1.0);
7524    let snapped = Rect {
7525        x: left_px / root_scale,
7526        y: top_px / root_scale,
7527        width: width_px / root_scale,
7528        height: height_px / root_scale,
7529    };
7530
7531    *rect = snapped;
7532    *quad = crate::rect_to_quad(snapped);
7533}
7534
7535fn nearest_image_device_quad(
7536    sampling: ImageSampling,
7537    quad: [[f32; 2]; 4],
7538    root_scale: f32,
7539) -> Option<[[f32; 2]; 4]> {
7540    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7541        return None;
7542    }
7543
7544    let rect = axis_aligned_quad_rect(quad)?;
7545    let left_px = (rect.x * root_scale).round();
7546    let top_px = (rect.y * root_scale).round();
7547    let width_px = (rect.width * root_scale).round().max(1.0);
7548    let height_px = (rect.height * root_scale).round().max(1.0);
7549    let right_px = left_px + width_px;
7550    let bottom_px = top_px + height_px;
7551    Some([
7552        [left_px, top_px],
7553        [right_px, top_px],
7554        [left_px, bottom_px],
7555        [right_px, bottom_px],
7556    ])
7557}
7558
7559fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
7560    if !start.is_finite()
7561        || !extent.is_finite()
7562        || !image_extent.is_finite()
7563        || extent == 0.0
7564        || image_extent <= 0.0
7565    {
7566        return None;
7567    }
7568
7569    let end = start + extent;
7570    let edge_min = start.min(end).clamp(0.0, image_extent);
7571    let edge_max = start.max(end).clamp(0.0, image_extent);
7572    if edge_max <= edge_min {
7573        return None;
7574    }
7575
7576    let center_min = edge_min + 0.5;
7577    let center_max = edge_max - 0.5;
7578    let (bound_min, bound_max) = if center_min <= center_max {
7579        (center_min, center_max)
7580    } else {
7581        let center = (edge_min + edge_max) * 0.5;
7582        (center, center)
7583    };
7584
7585    Some((
7586        edge_min / image_extent,
7587        edge_max / image_extent,
7588        bound_min / image_extent,
7589        bound_max / image_extent,
7590    ))
7591}
7592
7593fn apply_filter_to_bitmap(image: &ImageBitmap, filter: ColorFilter) -> Result<ImageBitmap, String> {
7594    let pixel_count = image.width() as usize * image.height() as usize;
7595    let mut filtered = Vec::with_capacity(pixel_count * 4);
7596    for index in 0..pixel_count {
7597        let pixel = image.rgba8_pixel(index);
7598        let rgba = [
7599            pixel[0] as f32 / 255.0,
7600            pixel[1] as f32 / 255.0,
7601            pixel[2] as f32 / 255.0,
7602            pixel[3] as f32 / 255.0,
7603        ];
7604        let out = filter.apply_rgba(rgba);
7605        filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
7606        filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
7607        filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
7608        filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
7609    }
7610    ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
7611        .map_err(|error| format!("failed to build filtered bitmap: {error}"))
7612}
7613
7614/// How a text raster samples its texels under a segment transform: as it
7615/// asks on the pixel grid, and filtered once a transform turns it off the
7616/// grid, where no texel lands on a pixel for nearest sampling to keep.
7617fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
7618    if transform.is_identity() {
7619        sampling
7620    } else {
7621        ImageSampling::Linear
7622    }
7623}
7624
7625/// The rounded mask a shadow's composite applies, in the scene's device
7626/// pixels: an inner shadow masks itself to its fill shape, and a shadow
7627/// lowered out of a clipped layer masks itself to that layer's rounded clip.
7628pub(crate) fn shadow_composite_mask(
7629    shadow: &ShadowDraw,
7630    snap_anchor: Option<SnapAnchor>,
7631    root_scale: f32,
7632) -> Option<RoundedCompositeMask> {
7633    inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
7634        shadow.rounded_clip.map(|clip| RoundedCompositeMask {
7635            rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
7636            radii: clip.radii.map(|radius| radius * root_scale),
7637        })
7638    })
7639}
7640
7641/// A scene holding just a shadow's own draws, in the order they arrive, so
7642/// the shadow source renders through the same pass encoder as everything
7643/// else.
7644fn shadow_scene(
7645    shapes: Option<&RunDraw>,
7646    texts: &[TextDraw],
7647    input_margin: f32,
7648) -> CompositorScene {
7649    let mut scene = CompositorScene::new();
7650    if let Some(run) = shapes {
7651        scene.push_run(run.clone());
7652    }
7653    for text in texts {
7654        let z_index = scene.next_z();
7655        scene.draw_ops.push(DrawOp {
7656            z_index,
7657            kind: DrawOpKind::Text(scene.texts.len()),
7658        });
7659        let mut source_text = text.clone();
7660        source_text.clip = source_text
7661            .clip
7662            .map(|clip| expand_rect(clip, input_margin, input_margin));
7663        scene.texts.push(source_text);
7664        scene.next_z += 1;
7665    }
7666    scene
7667}
7668
7669/// The whole device pixels a logical rect covers, or `None` when it covers
7670/// none or more than a texture can hold.
7671fn device_pixel_bounds(
7672    rect: Rect,
7673    root_scale: f32,
7674    max_texture_dim: u32,
7675) -> Option<DevicePixelBounds> {
7676    let x = (rect.x * root_scale).floor();
7677    let y = (rect.y * root_scale).floor();
7678    let right = ((rect.x + rect.width) * root_scale).ceil();
7679    let bottom = ((rect.y + rect.height) * root_scale).ceil();
7680    let width = (right - x).max(0.0) as u32;
7681    let height = (bottom - y).max(0.0) as u32;
7682    if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
7683        return None;
7684    }
7685    Some(DevicePixelBounds {
7686        x,
7687        y,
7688        width,
7689        height,
7690    })
7691}
7692fn inner_shadow_composite_mask(
7693    shadow: &ShadowDraw,
7694    root_scale: f32,
7695) -> Option<RoundedCompositeMask> {
7696    let run = shadow.shapes.as_ref()?;
7697    if !run
7698        .tables()
7699        .shapes
7700        .iter()
7701        .any(|record| record.blend_mode() == BlendMode::DstOut)
7702    {
7703        return None;
7704    }
7705    let fill = run.tables().shapes.get(0)?;
7706    let rect = run.placement.translated_bounds(fill.stored_rect());
7707    if rect.width <= 0.0 || rect.height <= 0.0 {
7708        return None;
7709    }
7710    let resolved =
7711        cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
7712            top_left: fill.radii[0],
7713            top_right: fill.radii[1],
7714            bottom_right: fill.radii[2],
7715            bottom_left: fill.radii[3],
7716        })
7717        .resolve(rect.width, rect.height);
7718    let radii = [
7719        resolved.top_left * root_scale,
7720        resolved.top_right * root_scale,
7721        resolved.bottom_left * root_scale,
7722        resolved.bottom_right * root_scale,
7723    ];
7724
7725    Some(RoundedCompositeMask {
7726        rect: mask_rect(anchored_device_rect(
7727            rect,
7728            run.placement.snap_anchor,
7729            root_scale,
7730        )),
7731        radii,
7732    })
7733}
7734
7735/// One draw call of a run batch's stage: its pipeline, the strip index
7736/// buffer it binds and the indices and records it instances.
7737#[derive(Clone, Debug, PartialEq, Eq)]
7738pub(crate) struct PlannedRunDraw {
7739    pub(crate) key: ShapePipelineKey,
7740    pub(crate) band_class: u8,
7741    pub(crate) indices: std::ops::Range<u32>,
7742    pub(crate) records: std::ops::Range<u32>,
7743}
7744
7745impl PlannedRunDraw {
7746    /// A draw of the paint, as it was recorded.
7747    fn paint(draw: &RunDrawCall) -> Self {
7748        Self {
7749            key: draw.key,
7750            band_class: draw.band_class,
7751            indices: draw.indices(),
7752            records: draw.records.clone(),
7753        }
7754    }
7755}
7756
7757/// The draw calls laying a batch's opaque interiors down: last first, so
7758/// they go down front to back, one call over each stretch of neighbouring
7759/// draws that share the interior pipeline, cut to the span from the stretch's
7760/// first draw holding an occluder to its last. The draws between ride along:
7761/// the pipeline lays any record's exact interior down and skips the rest, so
7762/// taking them costs a few vertices rather than a call, and it shades only a
7763/// record's quad, the first two triangles of every band class's pattern.
7764pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
7765    struct Stretch {
7766        key: ShapePipelineKey,
7767        start: u32,
7768        span: Option<PlannedRunDraw>,
7769    }
7770    let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
7771    let mut stretch: Option<Stretch> = None;
7772    for draw in draws.iter().rev() {
7773        let Some(key) = draw.key.interior() else {
7774            planned.extend(stretch.take().and_then(|open| open.span));
7775            continue;
7776        };
7777        if stretch
7778            .as_ref()
7779            .is_some_and(|open| open.key != key || open.start != draw.records.end)
7780        {
7781            planned.extend(stretch.take().and_then(|open| open.span));
7782        }
7783        let open = stretch.get_or_insert(Stretch {
7784            key,
7785            start: draw.records.end,
7786            span: None,
7787        });
7788        open.start = draw.records.start;
7789        if !draw.occluders {
7790            continue;
7791        }
7792        match &mut open.span {
7793            Some(span) => span.records.start = draw.records.start,
7794            None => {
7795                open.span = Some(PlannedRunDraw {
7796                    key,
7797                    band_class: draw.band_class,
7798                    indices: 0..cranpose_ui_graphics::strip_indices(1),
7799                    records: draw.records.clone(),
7800                });
7801            }
7802        }
7803    }
7804    planned.extend(stretch.and_then(|open| open.span));
7805    planned
7806}
7807
7808/// Drops the entries of `cache` no frame drew for more than `idle_frames`
7809/// before `frame`: the least recently used first, which is the order they
7810/// were last drawn in.
7811fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
7812    cache: &mut BoundedLruCache<K, V>,
7813    frame: u64,
7814    idle_frames: u64,
7815    last_frame: impl Fn(&V) -> u64,
7816) {
7817    while cache
7818        .peek_lru()
7819        .is_some_and(|(_, value)| frame.saturating_sub(last_frame(value)) > idle_frames)
7820    {
7821        cache.pop_lru();
7822    }
7823}
7824
7825/// Cuts the run draws from `start` on to `window` of their records, counted
7826/// across them in order, and drops the draws left with none.
7827fn window_draws(draws: &mut Vec<RunDrawCall>, start: usize, window: &std::ops::Range<u32>) {
7828    let mut relative = 0u32;
7829    let mut kept = start;
7830    for index in start..draws.len() {
7831        let draw = &mut draws[index];
7832        let count = draw.records.end - draw.records.start;
7833        let first = relative;
7834        relative += count;
7835        let keep_start = window.start.max(first).min(first + count);
7836        let keep_end = window.end.min(first + count).max(keep_start);
7837        draw.records =
7838            draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
7839        if draw.records.start < draw.records.end {
7840            draws.swap(kept, index);
7841            kept += 1;
7842        }
7843    }
7844    draws.truncate(kept);
7845}
7846
7847#[cfg(test)]
7848#[path = "tests/render_text_bounds_tests.rs"]
7849mod text_bounds_tests;
7850
7851#[cfg(test)]
7852#[path = "tests/render_retained_glyph_tests.rs"]
7853mod retained_glyph_tests;
7854
7855#[cfg(test)]
7856#[path = "tests/frame_clear_tests.rs"]
7857mod frame_clear_tests;
7858
7859#[cfg(test)]
7860#[path = "tests/render_clip_scissor_tests.rs"]
7861mod clip_scissor_tests;
7862
7863#[cfg(test)]
7864#[path = "tests/glyph_kind_tests.rs"]
7865mod glyph_kind_tests;
7866
7867#[cfg(test)]
7868#[path = "tests/glyph_run_bounds_tests.rs"]
7869mod glyph_run_bounds_tests;
7870
7871#[cfg(test)]
7872#[path = "tests/shape_variant_tests.rs"]
7873mod shape_variant_tests;