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