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    /// Whether the next frame first learns its pipelines: see
3398    /// [`Self::discover_frame_pipelines`].
3399    #[cfg(not(target_arch = "wasm32"))]
3400    discovers_next_frame: bool,
3401    /// Whether the frame drawing learns its pipelines and draws nothing.
3402    #[cfg(not(target_arch = "wasm32"))]
3403    pub(crate) discovering: bool,
3404    /// How many requested shader warm-ups this renderer has queued.
3405    shader_warm_ups_queued: usize,
3406}
3407
3408/// What a frame clears to before it draws: nothing for a transparent
3409/// window, the framework's background for every other surface.
3410pub fn frame_clear_color(transparent: bool) -> wgpu::Color {
3411    if transparent {
3412        wgpu::Color::TRANSPARENT
3413    } else {
3414        CLEAR_COLOR
3415    }
3416}
3417
3418fn image_sampler_descriptor(sampling: ImageSampling) -> wgpu::SamplerDescriptor<'static> {
3419    let filter = match sampling {
3420        ImageSampling::Nearest => wgpu::FilterMode::Nearest,
3421        ImageSampling::Linear => wgpu::FilterMode::Linear,
3422    };
3423    wgpu::SamplerDescriptor {
3424        label: Some(match sampling {
3425            ImageSampling::Nearest => "Nearest Image Sampler",
3426            ImageSampling::Linear => "Linear Image Sampler",
3427        }),
3428        address_mode_u: wgpu::AddressMode::ClampToEdge,
3429        address_mode_v: wgpu::AddressMode::ClampToEdge,
3430        address_mode_w: wgpu::AddressMode::ClampToEdge,
3431        mag_filter: filter,
3432        min_filter: filter,
3433        mipmap_filter: wgpu::MipmapFilterMode::Nearest,
3434        ..Default::default()
3435    }
3436}
3437
3438/// What a [`GpuRenderer`] is built from. It crosses to the present thread
3439/// whole, so it holds only owned, `Send` parts.
3440pub(crate) struct GpuRendererInit {
3441    pub(crate) device: Arc<wgpu::Device>,
3442    pub(crate) queue: Arc<wgpu::Queue>,
3443    pub(crate) surface_format: wgpu::TextureFormat,
3444    pub(crate) adapter_backend: wgpu::Backend,
3445    pub(crate) adapter_downlevel: wgpu::DownlevelFlags,
3446    pub(crate) text_fonts: SoftwareTextFontSet,
3447    pub(crate) renderer_epoch: u64,
3448    pub(crate) pipeline_compilation: PipelineCompilation,
3449}
3450
3451impl GpuRenderer {
3452    pub fn new(init: GpuRendererInit) -> Self {
3453        let GpuRendererInit {
3454            device,
3455            queue,
3456            surface_format,
3457            adapter_backend,
3458            adapter_downlevel,
3459            text_fonts,
3460            renderer_epoch,
3461            pipeline_compilation,
3462        } = init;
3463        let display_format = surface_format;
3464        let construction_started = Instant::now();
3465        let device_errors = Arc::new(DeviceErrorSentry::default());
3466        if survive_gpu_errors_enabled() {
3467            let sentry = Arc::clone(&device_errors);
3468            device.on_uncaptured_error(Arc::new(move |error| sentry.record(&error)));
3469        }
3470        let composition_format = crate::offscreen::composition_format(display_format);
3471        device.set_device_lost_callback(|reason, message| {
3472            log::error!("[gpu-device] device lost ({reason:?}): {message}");
3473        });
3474        let copy_free = UploadMode::copy_free(&device, adapter_backend);
3475        let mut run_store = RunStore::new(
3476            &device,
3477            RunBufferMode::for_device(&device, adapter_downlevel),
3478            copy_free,
3479        );
3480        let uniform_bind_group_layout =
3481            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3482                label: Some("Viewport Uniform Bind Group Layout"),
3483                entries: &[wgpu::BindGroupLayoutEntry {
3484                    binding: 0,
3485                    visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
3486                    ty: wgpu::BindingType::Buffer {
3487                        ty: wgpu::BufferBindingType::Uniform,
3488                        has_dynamic_offset: true,
3489                        min_binding_size: wgpu::BufferSize::new(
3490                            std::mem::size_of::<Uniforms>() as u64
3491                        ),
3492                    },
3493                    count: None,
3494                }],
3495            });
3496        let image_bind_group_layout =
3497            device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
3498                label: Some("Image Texture Bind Group Layout"),
3499                entries: &[
3500                    wgpu::BindGroupLayoutEntry {
3501                        binding: 0,
3502                        visibility: wgpu::ShaderStages::FRAGMENT,
3503                        ty: wgpu::BindingType::Texture {
3504                            multisampled: false,
3505                            view_dimension: wgpu::TextureViewDimension::D2,
3506                            sample_type: wgpu::TextureSampleType::Float { filterable: true },
3507                        },
3508                        count: None,
3509                    },
3510                    wgpu::BindGroupLayoutEntry {
3511                        binding: 1,
3512                        visibility: wgpu::ShaderStages::FRAGMENT,
3513                        ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
3514                        count: None,
3515                    },
3516                ],
3517            });
3518        let image_nearest_sampler =
3519            device.create_sampler(&image_sampler_descriptor(ImageSampling::Nearest));
3520        let image_linear_sampler =
3521            device.create_sampler(&image_sampler_descriptor(ImageSampling::Linear));
3522        let text_glyph_atlas = TextGlyphAtlas::new(
3523            &device,
3524            &image_bind_group_layout,
3525            GlyphSamplers {
3526                nearest: &image_nearest_sampler,
3527                linear: &image_linear_sampler,
3528            },
3529            TEXT_GLYPH_ATLAS_MIN_SIZE,
3530        );
3531        let viewport_uniforms = ViewportUniforms::default();
3532
3533        static GLASS_MATERIAL_FOLDS: DebugToggle =
3534            DebugToggle::new("CRANPOSE_GLASS_MATERIAL_FOLDS");
3535        if GLASS_MATERIAL_FOLDS.equals("1") {
3536            cranpose_ui_graphics::set_glass_material_folds(true);
3537        } else if GLASS_MATERIAL_FOLDS.equals("0") {
3538            cranpose_ui_graphics::set_glass_material_folds(false);
3539        }
3540        log::info!(
3541            "[gpu-init] liquid glass material folds {}",
3542            if cranpose_ui_graphics::glass_material_folds_enabled() {
3543                "on: a pipeline per material's feature set"
3544            } else {
3545                "off: one pipeline per blend mode"
3546            }
3547        );
3548
3549        #[cfg(not(target_arch = "wasm32"))]
3550        let crate::pipeline_disk_cache::Loaded {
3551            cache: pipeline_cache,
3552            records,
3553            updated,
3554            holds_recorded,
3555        } = crate::pipeline_disk_cache::load(&device);
3556        #[cfg(not(target_arch = "wasm32"))]
3557        let first_screen: Vec<u64> = records
3558            .shapes
3559            .iter()
3560            .filter(|shape| shape.first_screen)
3561            .map(|shape| shape.entry)
3562            .collect();
3563        #[cfg(target_arch = "wasm32")]
3564        let (pipeline_cache, first_screen): (Option<wgpu::PipelineCache>, Vec<u64>) =
3565            (None, Vec::new());
3566        let recorder = crate::pipeline_recorder::PipelineRecorder::default();
3567        #[cfg(not(target_arch = "wasm32"))]
3568        let pipeline_cache_watcher = crate::pipeline_disk_cache::spawn_persist_watcher(
3569            pipeline_cache.clone(),
3570            Arc::clone(&records),
3571            recorder.clone(),
3572        );
3573
3574        let effects_started = Instant::now();
3575        let pipeline_compiler =
3576            PipelineCompiler::for_compilation(pipeline_compilation, adapter_backend);
3577        // A launch with no record of its first screen learns its first
3578        // frame's pipelines before it draws, where they compile side by side.
3579        // `CRANPOSE_FIRST_FRAME_DISCOVERY=0` draws it pass by pass instead.
3580        #[cfg(not(target_arch = "wasm32"))]
3581        static FIRST_FRAME_DISCOVERY: DebugToggle =
3582            DebugToggle::new("CRANPOSE_FIRST_FRAME_DISCOVERY");
3583        #[cfg(not(target_arch = "wasm32"))]
3584        let discovers_first_frame = !FIRST_FRAME_DISCOVERY.equals("0")
3585            && adapter_backend == wgpu::Backend::Metal
3586            && pipeline_compiler.is_active()
3587            && !records.shapes.iter().any(|shape| shape.first_screen);
3588        let depth_gate = crate::depth_gate::DepthGate::new(
3589            crate::draw_pass::lays_interiors_first(adapter_backend),
3590            pipeline_compiler.is_active(),
3591        );
3592        let effect_renderer = EffectRenderer::new(
3593            &device,
3594            pipeline_compiler.clone(),
3595            pipeline_cache.clone(),
3596            composition_format,
3597            adapter_backend,
3598            recorder.clone(),
3599        );
3600        let output_converter = OutputConverter::new(&device, adapter_backend, display_format);
3601        let screenshot_converter =
3602            OutputConverter::new(&device, adapter_backend, wgpu::TextureFormat::Rgba8Unorm);
3603        let effects_ms = instant_ms(effects_started, Instant::now());
3604        let mut frame_graph_executor = WgpuFrameGraphExecutor::new();
3605        frame_graph_executor.init_pass_timing(&device, &queue);
3606        #[cfg(target_arch = "wasm32")]
3607        frame_graph_executor.batch_queue_writes(adapter_backend == wgpu::Backend::BrowserWebGpu);
3608        let shape_shader = SharedShader::new(
3609            &device,
3610            adapter_backend,
3611            "Shape Shader",
3612            shape_shader_code(run_store.mode()),
3613            &[Some(&uniform_bind_group_layout), Some(run_store.layout())],
3614        );
3615        if run_store.mode().trig_fill {
3616            let fill = ArcTrigFill::new(
3617                &device,
3618                adapter_backend,
3619                pipeline_cache.clone(),
3620                shape_shader.clone(),
3621                recorder.clone(),
3622            );
3623            if first_screen.contains(&crate::arc_trig_fill::FIRST_SCREEN_KEY) {
3624                fill.warm(&pipeline_compiler);
3625            }
3626            run_store.attach_trig_fill(fill);
3627        }
3628        let shape_pipelines = ShapePipelines::new(
3629            ShapePipelineFactory {
3630                device: Arc::clone(&device),
3631                cache: pipeline_cache.clone(),
3632                format: composition_format,
3633                shader: shape_shader,
3634                mode: run_store.mode(),
3635            },
3636            adapter_backend,
3637            &pipeline_compiler,
3638            first_screen
3639                .into_iter()
3640                .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3641                .filter_map(ShapePipelineKey::from_bits),
3642            recorder.clone(),
3643        );
3644        let image_layouts = [
3645            Some(&uniform_bind_group_layout),
3646            Some(&image_bind_group_layout),
3647        ];
3648        let image_shader = SharedShader::new(
3649            &device,
3650            adapter_backend,
3651            "Image Shader",
3652            shaders::IMAGE,
3653            &image_layouts,
3654        );
3655        let glyph_atlas_shader = SharedShader::new(
3656            &device,
3657            adapter_backend,
3658            "Glyph Atlas Shader",
3659            shaders::GLYPH_ATLAS,
3660            &image_layouts,
3661        );
3662        let rrect_shadow_shader = SharedShader::new(
3663            &device,
3664            adapter_backend,
3665            "Round Rect Shadow Shader",
3666            shaders::RRECT_SHADOW,
3667            &[Some(&uniform_bind_group_layout)],
3668        );
3669
3670        let mut renderer = Self {
3671            device,
3672            queue,
3673            device_errors,
3674            renderer_epoch,
3675            composition_format,
3676            #[cfg(not(target_arch = "wasm32"))]
3677            display_format,
3678            composition_target: None,
3679            output_converter,
3680            screenshot_converter,
3681            adapter_backend,
3682            pipeline_cache,
3683            #[cfg(not(target_arch = "wasm32"))]
3684            _pipeline_cache_watcher: pipeline_cache_watcher,
3685            #[cfg(not(target_arch = "wasm32"))]
3686            recent_after_update: updated.then(|| Arc::clone(&records)),
3687            recorder,
3688            #[cfg(not(target_arch = "wasm32"))]
3689            landing: pipeline_compiler.landing(),
3690            pipeline_compiler,
3691            #[cfg(not(target_arch = "wasm32"))]
3692            built_at_frame_start: 0,
3693            drew_placeholder: false,
3694            shape_pipelines,
3695            image_pipeline: [
3696                FixedPipeline::new("image/src-over"),
3697                FixedPipeline::new("image/src-over/depth"),
3698                FixedPipeline::new("image/src-over/alpha-mask"),
3699                FixedPipeline::new("image/src-over/alpha-mask/depth"),
3700                FixedPipeline::new("image/src-over/rounded"),
3701                FixedPipeline::new("image/src-over/rounded/depth"),
3702                FixedPipeline::new("image/src-over/alpha-mask/rounded"),
3703                FixedPipeline::new("image/src-over/alpha-mask/rounded/depth"),
3704            ],
3705            image_pipeline_dst_out: [
3706                FixedPipeline::new("image/dst-out"),
3707                FixedPipeline::new("image/dst-out/depth"),
3708                FixedPipeline::new("image/dst-out/alpha-mask"),
3709                FixedPipeline::new("image/dst-out/alpha-mask/depth"),
3710                FixedPipeline::new("image/dst-out/rounded"),
3711                FixedPipeline::new("image/dst-out/rounded/depth"),
3712                FixedPipeline::new("image/dst-out/alpha-mask/rounded"),
3713                FixedPipeline::new("image/dst-out/alpha-mask/rounded/depth"),
3714            ],
3715            glyph_atlas_pipeline: [
3716                FixedPipeline::new("glyph/atlas"),
3717                FixedPipeline::new("glyph/atlas/depth"),
3718                FixedPipeline::new("glyph/atlas/aligned"),
3719                FixedPipeline::new("glyph/atlas/aligned/depth"),
3720                FixedPipeline::new("glyph/atlas/turned"),
3721                FixedPipeline::new("glyph/atlas/turned/depth"),
3722            ],
3723            rrect_shadow_pipeline: [
3724                FixedPipeline::new("shadow/rrect"),
3725                FixedPipeline::new("shadow/rrect/depth"),
3726            ],
3727            image_shader,
3728            glyph_atlas_shader,
3729            rrect_shadow_shader,
3730            depth_targets: crate::idle_pool::IdlePool::default(),
3731            depth_gate,
3732            surface_atlas_sizes: crate::frame::SurfaceAtlasSizes::for_backend(adapter_backend),
3733            uniform_bind_group_layout,
3734            image_bind_group_layout,
3735            image_nearest_sampler,
3736            image_linear_sampler,
3737            text_fonts,
3738            viewport_uniforms,
3739            run_store,
3740            image_texture_cache: BoundedLruCache::with_capacity_at_least_one(
3741                MAX_TEXTURE_CACHE_ITEMS,
3742            ),
3743            image_texture_cache_bytes: 0,
3744            external_texture_bindings: BoundedLruCache::with_capacity_at_least_one(
3745                MAX_EXTERNAL_TEXTURE_BINDINGS,
3746            ),
3747            text_image_cache: BoundedLruCache::with_capacity_at_least_one(
3748                MAX_TEXT_IMAGE_CACHE_ITEMS,
3749            ),
3750            text_glyph_atlas,
3751            text_glyph_run_cache: BoundedLruCache::with_capacity_at_least_one(
3752                MIN_TEXT_GLYPH_RUN_CACHE_ITEMS,
3753            ),
3754            text_glyph_runs_drawn: 0,
3755            text_glyph_gpu_run_cache: BoundedLruCache::with_capacity_at_least_one(
3756                MAX_TEXT_GLYPH_GPU_RUN_CACHE_ITEMS,
3757            ),
3758            text_glyph_run_arena: GlyphRunArena::new(copy_free),
3759            copy_free,
3760            text_glyph_run_frame: 0,
3761            text_glyph_mask_cache: SoftwareGlyphRasterCache::with_capacity_at_least_one(
3762                MAX_TEXT_GLYPH_MASK_CACHE_ITEMS,
3763            ),
3764            text_line_index_cache: TextLineIndexCache::new(MAX_TEXT_LINE_INDEX_CACHE_ITEMS),
3765            scratch_image_vertices: Vec::new(),
3766            scratch_image_indices: Vec::new(),
3767            scratch_glyph_instances: GlyphInstances::default(),
3768            scratch_image_cmds: Vec::new(),
3769            scratch_image_clips: Vec::new(),
3770            scratch_glyph_cmds: Vec::new(),
3771            scratch_glyph_moved: Vec::new(),
3772            scratch_shadow_instances: Vec::new(),
3773            scratch_arena_draws: Vec::new(),
3774            scratch_pipelines: PipelineDemand::default(),
3775            scratch_held: crate::draw_pass::HeldDraws::default(),
3776            scratch_text_glyph_run: Vec::new(),
3777            scratch_text_glyph_entries: Vec::new(),
3778            run_glyph_scratch: RunGlyphScratch::default(),
3779            frame_graph_executor,
3780            stage_side_scratch: StageSideScratch::default(),
3781            deferred_offscreen_releases: Vec::new(),
3782            effect_renderer,
3783            layer_cache: LayerCache::new(),
3784            ablation: Ablation::default(),
3785            ablation_frames: 0,
3786            nesting_overflow_reported: false,
3787            backdrop_gates: HashMap::default(),
3788            fill_gates: HashMap::default(),
3789            effect_gates: HashMap::default(),
3790            source_gates: HashMap::default(),
3791            transparent_sources: HashMap::default(),
3792            shadow_surface_cache: BoundedLruCache::with_capacity_at_least_one(
3793                MAX_SHADOW_SURFACE_CACHE_ITEMS,
3794            ),
3795            shadow_surface_cache_bytes: 0,
3796            frame_stats: gpu_stats::FrameStats::default(),
3797            last_frame_stats: None,
3798            pending_frame_warmup_frames: 0,
3799            frame_count: 0,
3800            #[cfg(not(target_arch = "wasm32"))]
3801            discovers_next_frame: discovers_first_frame,
3802            #[cfg(not(target_arch = "wasm32"))]
3803            discovering: false,
3804            shader_warm_ups_queued: 0,
3805        };
3806        #[cfg(not(target_arch = "wasm32"))]
3807        renderer.warm_first_screen(&records, holds_recorded);
3808        renderer.warm_requested_shaders();
3809        log::info!(
3810            "[gpu-init] {:?} renderer ready in {:.1} ms (effects {:.1} ms)",
3811            adapter_backend,
3812            instant_ms(construction_started, Instant::now()),
3813            effects_ms,
3814        );
3815        renderer
3816    }
3817
3818    /// Prepares the first screen the last launches recorded. The first frame
3819    /// waits for its shapes and fixed pipelines, but draws placeholders for
3820    /// runtime shaders that have not compiled: those queue behind, since a
3821    /// Mali driver compiles largely one pipeline at a time. A driver cache
3822    /// that `holds_recorded` pipelines builds them as cache hits, so those
3823    /// draw from it, and need no stand-in.
3824    #[cfg(not(target_arch = "wasm32"))]
3825    fn warm_first_screen(
3826        &mut self,
3827        records: &crate::pipeline_records::PipelineRecords,
3828        holds_recorded: bool,
3829    ) {
3830        self.warm_fixed_pipelines(&|label| {
3831            records
3832                .fixed
3833                .iter()
3834                .any(|fixed| fixed.first_screen && fixed.entry == label)
3835        });
3836        if holds_recorded {
3837            self.effect_renderer.trust_cached(records);
3838        }
3839        self.effect_renderer.warm_first_screen_shaders(
3840            records
3841                .shaders
3842                .iter()
3843                .filter(|shader| shader.first_screen)
3844                .map(|shader| &shader.entry),
3845        );
3846        if !records.shapes.iter().any(|shape| shape.first_screen) {
3847            self.warm_every_screen();
3848        }
3849    }
3850
3851    /// Queues the pipelines every screen draws with, for a launch with no
3852    /// record of its first screen: flat solid rects and text on whole
3853    /// pixels. They build while the first screen composes, when the
3854    /// compiler's threads have nothing else; on a Mate 20 X the gauntlet's
3855    /// first content showed 333-366 ms after the first frame with them
3856    /// against 383-399 ms without.
3857    #[cfg(not(target_arch = "wasm32"))]
3858    fn warm_every_screen(&mut self) {
3859        self.shape_pipelines.warm(ShapePipelineKey::SOLID_RECT);
3860        self.glyph_atlas_pipeline_resource(false, GlyphQuads::Aligned)
3861            .prefetch(
3862                CompileLane::WarmUp,
3863                &self.pipeline_compiler,
3864                self.adapter_backend,
3865                || self.glyph_atlas_pipeline_job(false, GlyphQuads::Aligned),
3866            );
3867    }
3868
3869    fn ensure_shape_pipeline(&mut self, key: ShapePipelineKey, vertices: u64) {
3870        self.shape_pipelines.ensure(key, vertices);
3871    }
3872
3873    /// Queues the shader warm-ups requested since the last call, each at the
3874    /// target it draws to (`cranpose_ui_graphics::request_shader_warm_ups`).
3875    fn warm_requested_shaders(&mut self) {
3876        let requested = cranpose_ui_graphics::shader_warm_ups_after(self.shader_warm_ups_queued);
3877        if requested.is_empty() {
3878            return;
3879        }
3880        self.shader_warm_ups_queued += requested.len();
3881        self.effect_renderer.warm_shaders(&requested);
3882    }
3883
3884    /// Queues every pipeline recent launches of another build drew with:
3885    /// after an update their compiled pipelines are gone, and each would
3886    /// otherwise compile inside the first frame that draws with it.
3887    #[cfg(not(target_arch = "wasm32"))]
3888    fn warm_recent(&mut self, records: &crate::pipeline_records::PipelineRecords) {
3889        self.warm_fixed_pipelines(&|label| records.fixed.iter().any(|fixed| fixed.entry == label));
3890        let shapes = records
3891            .shapes
3892            .iter()
3893            .map(|shape| shape.entry)
3894            .filter(|&bits| bits != crate::arc_trig_fill::FIRST_SCREEN_KEY)
3895            .filter_map(ShapePipelineKey::from_bits);
3896        for key in shapes {
3897            self.shape_pipelines.warm(key);
3898        }
3899        self.effect_renderer
3900            .warm_recorded_shaders(records.shaders.iter().map(|shader| &shader.entry));
3901    }
3902
3903    /// Queues the fixed pipelines whose labels `wanted` accepts.
3904    #[cfg(not(target_arch = "wasm32"))]
3905    fn warm_fixed_pipelines(&self, wanted: &dyn Fn(&str) -> bool) {
3906        let compiler = self.effect_renderer.compiler();
3907        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3908            if wanted(pipeline.label()) {
3909                pipeline.queue(
3910                    compiler,
3911                    crate::pipeline_compiler::CompileLane::WarmUp,
3912                    self.adapter_backend,
3913                    job(),
3914                );
3915            }
3916        });
3917    }
3918
3919    /// Builds here, ahead of the first frame, the pipelines named by the
3920    /// first screens in `records` that this renderer's backend drew (see
3921    /// [`crate::WgpuRenderer::build_first_screen_pipelines`]).
3922    pub(crate) fn build_first_screen(&mut self, records: &[u8]) {
3923        let records = crate::pipeline_records::decode_first_screens(records, self.adapter_backend);
3924        for shape in &records.shapes {
3925            if let Some(key) = ShapePipelineKey::from_bits(shape.entry) {
3926                self.shape_pipelines.build_ahead(key);
3927            }
3928        }
3929        self.for_each_fixed_pipeline(&mut |pipeline, job| {
3930            if records
3931                .fixed
3932                .iter()
3933                .any(|fixed| fixed.entry == pipeline.label())
3934            {
3935                pipeline.build_ahead(&self.recorder, self.adapter_backend, job());
3936            }
3937        });
3938    }
3939
3940    /// See [`crate::WgpuRenderer::first_screen_pipelines`].
3941    #[cold]
3942    #[inline(never)]
3943    pub(crate) fn first_screen_pipelines(&self) -> Option<Vec<u8>> {
3944        self.recorder.first_screen_records(self.adapter_backend)
3945    }
3946
3947    /// Hands `visit` every fixed pipeline, the effect renderer's too, with
3948    /// the job that builds it.
3949    fn for_each_fixed_pipeline(
3950        &self,
3951        visit: &mut dyn FnMut(&FixedPipeline, &dyn Fn() -> FixedPipelineJob),
3952    ) {
3953        self.effect_renderer.for_each_fixed(&self.device, visit);
3954        for depth in [false, true] {
3955            for (alpha_mask, rounded) in
3956                [(false, false), (true, false), (false, true), (true, true)]
3957            {
3958                let variant = ImageVariant {
3959                    depth,
3960                    alpha_mask,
3961                    rounded,
3962                };
3963                for blend_mode in [BlendMode::SrcOver, BlendMode::DstOut] {
3964                    visit(self.image_pipeline_resource(blend_mode, variant), &|| {
3965                        Box::new(self.image_pipeline_job(blend_mode, variant))
3966                    });
3967                }
3968            }
3969            for quads in [GlyphQuads::Plain, GlyphQuads::Aligned, GlyphQuads::Turned] {
3970                visit(self.glyph_atlas_pipeline_resource(depth, quads), &|| {
3971                    Box::new(self.glyph_atlas_pipeline_job(depth, quads))
3972                });
3973            }
3974            visit(&self.rrect_shadow_pipeline[usize::from(depth)], &|| {
3975                Box::new(self.rrect_shadow_pipeline_job(depth))
3976            });
3977        }
3978    }
3979
3980    fn image_pipeline_resource(
3981        &self,
3982        blend_mode: BlendMode,
3983        variant: ImageVariant,
3984    ) -> &FixedPipeline {
3985        let pipelines = match blend_mode {
3986            BlendMode::DstOut => &self.image_pipeline_dst_out,
3987            _ => &self.image_pipeline,
3988        };
3989        &pipelines[usize::from(variant.depth)
3990            + 2 * usize::from(variant.alpha_mask)
3991            + 4 * usize::from(variant.rounded)]
3992    }
3993
3994    fn image_pipeline_job(
3995        &self,
3996        blend_mode: BlendMode,
3997        variant: ImageVariant,
3998    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
3999        let device = Arc::clone(&self.device);
4000        let cache = self.pipeline_cache.clone();
4001        let format = self.composition_format;
4002        let shader = self.image_shader.clone();
4003        move || {
4004            create_image_pipeline(
4005                &device,
4006                cache.as_ref(),
4007                format,
4008                &shader,
4009                blend_mode,
4010                variant,
4011            )
4012        }
4013    }
4014
4015    /// Queues the builds of the image pipelines `cmds` draw with that are
4016    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4017    /// `awaited` each still to land.
4018    pub(crate) fn prefetch_image_pipelines(
4019        &self,
4020        cmds: &[ImageDrawCmd],
4021        blend_mode: BlendMode,
4022        (depth, lane): (bool, CompileLane),
4023        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4024    ) {
4025        let mut last = None;
4026        for cmd in cmds {
4027            let variant = ImageVariant::of(cmd, depth);
4028            if last.replace(variant) == Some(variant) {
4029                continue;
4030            }
4031            if let Some(pending) = self.image_pipeline_resource(blend_mode, variant).prefetch(
4032                lane,
4033                &self.pipeline_compiler,
4034                self.adapter_backend,
4035                || self.image_pipeline_job(blend_mode, variant),
4036            ) {
4037                awaited(pending);
4038            }
4039        }
4040    }
4041
4042    /// Queues the builds of the glyph pipelines `cmds` draw with that are
4043    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4044    /// `awaited` each still to land.
4045    pub(crate) fn prefetch_glyph_pipelines(
4046        &self,
4047        cmds: &[GlyphDrawCmd],
4048        (depth, lane): (bool, CompileLane),
4049        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4050    ) {
4051        let mut last = None;
4052        for cmd in cmds {
4053            let quads = cmd.quads();
4054            if last.replace(quads) == Some(quads) {
4055                continue;
4056            }
4057            if let Some(pending) = self.glyph_atlas_pipeline_resource(depth, quads).prefetch(
4058                lane,
4059                &self.pipeline_compiler,
4060                self.adapter_backend,
4061                || self.glyph_atlas_pipeline_job(depth, quads),
4062            ) {
4063                awaited(pending);
4064            }
4065        }
4066    }
4067
4068    /// Queues the build of the shadow pipeline on `lane` when it is missing
4069    /// (see [`FixedPipeline::prefetch`]), handing `awaited` the pipeline
4070    /// while it is still to land.
4071    pub(crate) fn prefetch_shadow_pipeline(
4072        &self,
4073        (depth, lane): (bool, CompileLane),
4074        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4075    ) {
4076        if let Some(pending) = self.rrect_shadow_pipeline[usize::from(depth)].prefetch(
4077            lane,
4078            &self.pipeline_compiler,
4079            self.adapter_backend,
4080            || self.rrect_shadow_pipeline_job(depth),
4081        ) {
4082            awaited(pending);
4083        }
4084    }
4085
4086    pub(crate) fn image_pipeline(
4087        &self,
4088        blend_mode: BlendMode,
4089        variant: ImageVariant,
4090    ) -> &wgpu::RenderPipeline {
4091        self.image_pipeline_resource(blend_mode, variant).for_draw(
4092            &self.recorder,
4093            self.adapter_backend,
4094            || self.image_pipeline_job(blend_mode, variant)(),
4095        )
4096    }
4097
4098    fn glyph_atlas_pipeline_job(
4099        &self,
4100        depth: bool,
4101        quads: GlyphQuads,
4102    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4103        let device = Arc::clone(&self.device);
4104        let cache = self.pipeline_cache.clone();
4105        let format = self.composition_format;
4106        let shader = self.glyph_atlas_shader.clone();
4107        move || {
4108            create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
4109        }
4110    }
4111
4112    /// The glyph pipeline for a pass with a depth buffer or not, drawing
4113    /// `quads`.
4114    fn glyph_atlas_pipeline(&self, depth: bool, quads: GlyphQuads) -> &wgpu::RenderPipeline {
4115        self.glyph_atlas_pipeline_resource(depth, quads).for_draw(
4116            &self.recorder,
4117            self.adapter_backend,
4118            || self.glyph_atlas_pipeline_job(depth, quads)(),
4119        )
4120    }
4121
4122    fn rrect_shadow_pipeline_job(
4123        &self,
4124        depth: bool,
4125    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4126        let device = Arc::clone(&self.device);
4127        let cache = self.pipeline_cache.clone();
4128        let format = self.composition_format;
4129        let shader = self.rrect_shadow_shader.clone();
4130        move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
4131    }
4132
4133    /// Draws `instances` of the pass's uploaded shadow instances, bound with
4134    /// `uniform_slot` under `scissor`.
4135    pub(crate) fn draw_shadow_instances(
4136        &self,
4137        pass: &mut TrackedPass<'_, '_>,
4138        buffer: &BufferUpload,
4139        uniform_slot: usize,
4140        instances: std::ops::Range<u32>,
4141        scissor: Option<(u32, u32, u32, u32)>,
4142        frame: PassFrame,
4143    ) -> Result<(), String> {
4144        let depth = frame.depth;
4145        let pipeline = self.rrect_shadow_pipeline[usize::from(depth)].for_draw(
4146            &self.recorder,
4147            self.adapter_backend,
4148            || self.rrect_shadow_pipeline_job(depth)(),
4149        );
4150        let (x, y, width, height) = frame.scissor(scissor);
4151        pass.set_scissor_rect(x, y, width, height);
4152        pass.set_pipeline(pipeline);
4153        self.viewport_uniforms.bind(pass, uniform_slot)?;
4154        pass.set_vertex_buffer(0, buffer.slice());
4155        pass.draw(0..SHADOW_QUAD_CORNERS, instances);
4156        self.frame_stats.add_draw_calls(1);
4157        Ok(())
4158    }
4159
4160    pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
4161        &self,
4162        recorder: &mut C,
4163        instances: &[ShadowInstance],
4164    ) -> BufferUpload {
4165        recorder.upload_buffer(
4166            UploadAllocatorSpec::vertex(
4167                "Shadow Instance Buffer",
4168                std::mem::size_of::<ShadowInstance>() as u64,
4169            ),
4170            &self.device,
4171            bytemuck::cast_slice(instances),
4172        )
4173    }
4174
4175    fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
4176        let kind = match quads {
4177            GlyphQuads::Plain => 0,
4178            GlyphQuads::Aligned => 1,
4179            GlyphQuads::Turned => 2,
4180        };
4181        &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
4182    }
4183
4184    /// The transient depth buffer for a target of `size`, created on first
4185    /// use; the few sizes recent frames used are kept.
4186    pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
4187        const KEPT_DEPTH_TARGETS: usize = 4;
4188        let view = match self.depth_targets.take(|(kept, _)| *kept == size) {
4189            Some((_, view)) => view,
4190            None => self.create_depth_target(size),
4191        };
4192        self.depth_targets
4193            .put((size, view.clone()), KEPT_DEPTH_TARGETS, u64::MAX, |_| 0);
4194        view
4195    }
4196
4197    fn create_depth_target(&self, size: (u32, u32)) -> wgpu::TextureView {
4198        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4199            label: Some("Opaque interior depth"),
4200            size: wgpu::Extent3d {
4201                width: size.0,
4202                height: size.1,
4203                depth_or_array_layers: 1,
4204            },
4205            mip_level_count: 1,
4206            sample_count: 1,
4207            dimension: wgpu::TextureDimension::D2,
4208            format: DEPTH_FORMAT,
4209            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
4210                | wgpu::TextureUsages::TRANSIENT_ATTACHMENT,
4211            view_formats: &[],
4212        });
4213        texture.create_view(&wgpu::TextureViewDescriptor::default())
4214    }
4215
4216    /// The binding a draw of `image` sampled by `sampling` takes, uploading
4217    /// the image the first time a draw needs it.
4218    fn image_binding(
4219        &mut self,
4220        image: &ImageBitmap,
4221        sampling: ImageSampling,
4222    ) -> Result<ImageBinding, String> {
4223        if image.format() == cranpose_ui_graphics::ImagePixelFormat::External {
4224            return self.external_texture_binding(image, sampling);
4225        }
4226        if let Some(cached) = self.image_texture_cache.get(&image.id()) {
4227            return Ok(cached.bind_groups.binding(sampling));
4228        }
4229
4230        let size = wgpu::Extent3d {
4231            width: image.width(),
4232            height: image.height(),
4233            depth_or_array_layers: 1,
4234        };
4235
4236        let alpha_mask = matches!(
4237            image.format(),
4238            cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
4239        );
4240        let (format, bytes_per_pixel) = if alpha_mask {
4241            (wgpu::TextureFormat::R8Unorm, 1)
4242        } else {
4243            (wgpu::TextureFormat::Rgba8Unorm, 4)
4244        };
4245
4246        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4247            label: Some("Image Texture"),
4248            size,
4249            mip_level_count: 1,
4250            sample_count: 1,
4251            dimension: wgpu::TextureDimension::D2,
4252            format,
4253            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4254            view_formats: &[],
4255        });
4256
4257        let upload_stats = self.frame_graph_executor.upload_texture(
4258            &self.queue,
4259            wgpu::TexelCopyTextureInfo {
4260                texture: &texture,
4261                mip_level: 0,
4262                origin: wgpu::Origin3d::ZERO,
4263                aspect: wgpu::TextureAspect::All,
4264            },
4265            image.pixels(),
4266            wgpu::TexelCopyBufferLayout {
4267                offset: 0,
4268                bytes_per_row: Some(bytes_per_pixel * image.width()),
4269                rows_per_image: Some(image.height()),
4270            },
4271            size,
4272        );
4273        self.frame_stats.record_command_stats(upload_stats);
4274
4275        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4276        let bytes = image.pixels().len();
4277        let cached = CachedImageTexture {
4278            bind_groups: self.image_bind_groups(&view, alpha_mask),
4279            _texture: texture,
4280            _view: view,
4281            bytes,
4282        };
4283        let binding = cached.bind_groups.binding(sampling);
4284        if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
4285            self.image_texture_cache_bytes = self
4286                .image_texture_cache_bytes
4287                .saturating_sub(replaced.bytes);
4288        }
4289        self.image_texture_cache_bytes += bytes;
4290        while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
4291            && self.image_texture_cache.len() > 1
4292        {
4293            let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
4294                break;
4295            };
4296            self.image_texture_cache_bytes =
4297                self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
4298        }
4299        Ok(binding)
4300    }
4301
4302    fn external_texture_binding(
4303        &mut self,
4304        image: &ImageBitmap,
4305        sampling: ImageSampling,
4306    ) -> Result<ImageBinding, String> {
4307        let key = image.storage_id();
4308        if let Some(bind_groups) = self.external_texture_bindings.get(&key) {
4309            return Ok(bind_groups.binding(sampling));
4310        }
4311        let view = image
4312            .external_handle::<wgpu::TextureView>()
4313            .ok_or("an external texture's handle is not a wgpu::TextureView")?;
4314        let bind_groups = self.image_bind_groups(view, false);
4315        let binding = bind_groups.binding(sampling);
4316        self.external_texture_bindings.put(key, bind_groups);
4317        Ok(binding)
4318    }
4319
4320    fn image_bind_groups(&self, view: &wgpu::TextureView, alpha_mask: bool) -> ImageBindGroups {
4321        ImageBindGroups {
4322            alpha_mask,
4323            nearest: self.image_bind_group(view, &self.image_nearest_sampler),
4324            linear: self.image_bind_group(view, &self.image_linear_sampler),
4325        }
4326    }
4327
4328    fn image_bind_group(
4329        &self,
4330        view: &wgpu::TextureView,
4331        sampler: &wgpu::Sampler,
4332    ) -> wgpu::BindGroup {
4333        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4334            label: Some("Image Texture Bind Group"),
4335            layout: &self.image_bind_group_layout,
4336            entries: &[
4337                wgpu::BindGroupEntry {
4338                    binding: 0,
4339                    resource: wgpu::BindingResource::TextureView(view),
4340                },
4341                wgpu::BindGroupEntry {
4342                    binding: 1,
4343                    resource: wgpu::BindingResource::Sampler(sampler),
4344                },
4345            ],
4346        })
4347    }
4348
4349    pub(crate) fn max_texture_dim(&self) -> u32 {
4350        self.effect_renderer.max_texture_dim()
4351    }
4352
4353    /// A pooled texture that outlives the frame: layer cache entries and
4354    /// cached shadow surfaces.
4355    pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
4356        self.effect_renderer
4357            .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
4358    }
4359
4360    fn frame_root(
4361        &mut self,
4362        output_mode: OutputMode,
4363        output_view: Option<&wgpu::TextureView>,
4364        output_texture: Option<&wgpu::Texture>,
4365        viewport: (u32, u32),
4366        reads_page: bool,
4367    ) -> FrameRoot {
4368        if let (OutputMode::Display, Some(view), Some(texture)) =
4369            (output_mode, output_view, output_texture)
4370            && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
4371        {
4372            return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
4373                texture.clone(),
4374                view.clone(),
4375            )));
4376        }
4377        FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
4378    }
4379
4380    fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
4381        if let Some(target) = self.composition_target.take()
4382            && target.target.width == width
4383            && target.target.height == height
4384        {
4385            return target;
4386        }
4387        let target = Rc::new(OffscreenTarget::new(
4388            &self.device,
4389            self.composition_format,
4390            width,
4391            height,
4392        ));
4393        let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
4394        CompositionTarget {
4395            target,
4396            output_bind_group,
4397        }
4398    }
4399
4400    fn transient_offscreen_descriptor(
4401        &self,
4402        label: &'static str,
4403        width: u32,
4404        height: u32,
4405    ) -> FrameTextureDescriptor {
4406        let max_texture_dim = self.max_texture_dim();
4407        FrameTextureDescriptor::render_attachment(
4408            label,
4409            width.min(max_texture_dim),
4410            height.min(max_texture_dim),
4411            self.composition_format,
4412        )
4413    }
4414
4415    /// A texture of the given size that stays transparent: the input of a
4416    /// runtime shader whose layer draws nothing itself, so the shader needs
4417    /// no surface pass and reads the same empty content every frame.
4418    #[inline(never)]
4419    pub(crate) fn transparent_source<C: FrameCommandRecorder>(
4420        &mut self,
4421        recorder: &mut C,
4422        width: u32,
4423        height: u32,
4424    ) -> Rc<OffscreenTarget> {
4425        if let Some(source) = self.transparent_sources.get(&(width, height)) {
4426            return Rc::clone(source);
4427        }
4428        if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
4429            for (_, source) in self.transparent_sources.drain() {
4430                if let Ok(target) = Rc::try_unwrap(source) {
4431                    self.deferred_offscreen_releases.push(target);
4432                }
4433            }
4434        }
4435        let source = Rc::new(self.acquire_retained_surface(width, height));
4436        self.clear_target(
4437            recorder,
4438            &source.view,
4439            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4440        );
4441        self.transparent_sources
4442            .insert((width, height), Rc::clone(&source));
4443        source
4444    }
4445
4446    fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
4447        self.deferred_offscreen_releases.push(target);
4448    }
4449
4450    fn flush_deferred_offscreen_releases(&mut self) {
4451        let layer_cache = &mut self.layer_cache;
4452        let mut retire = |gate: &mut AdmissionGate| {
4453            let seen = gate.end_frame();
4454            if !seen && let Some(dead) = gate.dead_entry() {
4455                layer_cache.remove(&dead);
4456            }
4457            seen
4458        };
4459        self.backdrop_gates.retain(|_, gate| retire(gate));
4460        self.fill_gates.retain(|_, gate| retire(gate));
4461        self.effect_gates.retain(|_, gate| retire(gate));
4462        self.source_gates.retain(|_, gate| retire(gate));
4463        for target in self.deferred_offscreen_releases.drain(..) {
4464            self.effect_renderer.release_offscreen(target);
4465        }
4466        self.layer_cache.end_frame();
4467        for (transient, target) in self.layer_cache.take_released() {
4468            match transient {
4469                Some(descriptor) => self
4470                    .frame_graph_executor
4471                    .return_cached_transient(descriptor, target),
4472                None => self.effect_renderer.release_offscreen(target),
4473            }
4474        }
4475        self.effect_renderer.end_offscreen_frame();
4476        self.frame_graph_executor.end_transient_frame();
4477        self.depth_targets.end_frame();
4478        self.surface_atlas_sizes.end_frame();
4479    }
4480
4481    fn insert_cached_shadow_surface(
4482        &mut self,
4483        key: ShadowSurfaceCacheKey,
4484        target: Rc<OffscreenTarget>,
4485    ) {
4486        let byte_size = offscreen_byte_size(target.width, target.height);
4487        while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
4488            let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
4489                break;
4490            };
4491            self.shadow_surface_cache_bytes = self
4492                .shadow_surface_cache_bytes
4493                .saturating_sub(evicted.byte_size);
4494        }
4495        let cached = CachedShadowSurface { target, byte_size };
4496        if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4497            self.shadow_surface_cache_bytes = self
4498                .shadow_surface_cache_bytes
4499                .saturating_sub(replaced.byte_size);
4500        }
4501        self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4502    }
4503}
4504fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4505    snapshot.layer_cache_misses > 0
4506        || snapshot.shadow_shape_cache_misses > 0
4507        || snapshot.text_image_cache_misses > 0
4508        || snapshot.text_glyph_atlas_misses > 0
4509}
4510
4511fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4512    if *pending_frames > 0 {
4513        *pending_frames = pending_frames.saturating_sub(1);
4514    } else if frame_stats_need_warmup_frame(snapshot) {
4515        *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4516    }
4517}
4518
4519impl GpuRenderer {
4520    #[expect(clippy::too_many_arguments)]
4521    pub fn render(
4522        &mut self,
4523        texture: &wgpu::Texture,
4524        view: &wgpu::TextureView,
4525        width: u32,
4526        height: u32,
4527        packet: FramePacket,
4528        surface_epoch: u64,
4529        returns: &mut RenderReturns,
4530    ) -> Result<(), String> {
4531        self.render_internal(
4532            width,
4533            height,
4534            packet,
4535            surface_epoch,
4536            returns,
4537            OutputMode::Display,
4538            Some(view),
4539            Some(texture),
4540        )
4541    }
4542
4543    #[expect(clippy::too_many_arguments)]
4544    fn render_internal(
4545        &mut self,
4546        width: u32,
4547        height: u32,
4548        packet: FramePacket,
4549        surface_epoch: u64,
4550        returns: &mut RenderReturns,
4551        output_mode: OutputMode,
4552        output_view: Option<&wgpu::TextureView>,
4553        output_texture: Option<&wgpu::Texture>,
4554    ) -> Result<(), String> {
4555        let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
4556            Some(CancelReason::RendererEpoch)
4557        } else if packet.surface_epoch != surface_epoch {
4558            Some(CancelReason::SurfaceEpoch)
4559        } else if packet.viewport != (width, height) {
4560            Some(CancelReason::Viewport)
4561        } else {
4562            None
4563        };
4564        if let Some(reason) = cancel_reason {
4565            return Self::cancel_packet(packet, reason, returns);
4566        }
4567        if self.device_errors.take_poison() {
4568            return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
4569        }
4570        returns.frame_id = packet.frame_id;
4571        let render_start = Instant::now();
4572        #[cfg(not(target_arch = "wasm32"))]
4573        let builds_before = thread_builds();
4574        self.warm_requested_shaders();
4575        self.shape_pipelines.begin_frame();
4576        self.recorder.begin_frame();
4577        self.begin_placeholder_frame();
4578        self.viewport_uniforms.begin_frame();
4579        self.run_store.begin_frame(gpu_stats_enabled());
4580        self.begin_text_glyph_run_frame();
4581
4582        let text_cache_len = packet.text_cache_len;
4583        let reads_page = packet.root.contains_backdrop()
4584            || packet
4585                .overlay
4586                .as_ref()
4587                .is_some_and(LayerScene::contains_backdrop);
4588        let frame_root = self.frame_root(
4589            output_mode,
4590            output_view,
4591            output_texture,
4592            (width, height),
4593            reads_page,
4594        );
4595        let root = frame_root.target();
4596        let screenshot_bind_group = output_view.and_then(|_| {
4597            matches!(output_mode, OutputMode::Screenshot).then(|| {
4598                self.screenshot_converter
4599                    .bind_group(&self.device, &root.view)
4600            })
4601        });
4602        let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
4603        let result = self.render_graph(root, packet, returns, output_mode, output);
4604        #[cfg(not(target_arch = "wasm32"))]
4605        self.effect_renderer
4606            .compiler()
4607            .spread_demand(thread_builds() == builds_before);
4608        if let FrameRoot::Composition(composition) = frame_root {
4609            self.composition_target = Some(composition);
4610        }
4611        let after_graph = Instant::now();
4612        self.flush_deferred_offscreen_releases();
4613        self.scratch_glyph_instances.end_frame();
4614
4615        self.frame_stats
4616            .layer_cache_size
4617            .set(self.layer_cache.len() as u32);
4618        self.frame_stats
4619            .layer_cache_bytes
4620            .set(self.layer_cache.bytes());
4621        self.frame_stats.offscreen_pool_size.set(
4622            self.effect_renderer
4623                .retained_offscreen_count()
4624                .saturating_add(self.frame_graph_executor.retained_texture_count())
4625                .saturating_add(usize::from(self.composition_target.is_some())) as u32,
4626        );
4627        self.frame_stats.offscreen_pool_bytes.set(
4628            (self.effect_renderer.retained_offscreen_bytes() as u64)
4629                .saturating_add(self.frame_graph_executor.retained_texture_bytes())
4630                .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
4631                    u64::from(target.target.width)
4632                        .saturating_mul(u64::from(target.target.height))
4633                        .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
4634                })),
4635        );
4636        self.frame_stats
4637            .text_pool_size
4638            .set(self.text_image_cache.len() as u32);
4639        self.frame_stats
4640            .image_cache_size
4641            .set(self.image_texture_cache.len() as u32);
4642        self.frame_stats.text_cache_size.set(text_cache_len as u32);
4643        self.effect_renderer
4644            .merge_and_reset_debug_counters(&self.frame_stats);
4645        self.frame_graph_executor.reset_upload_allocators();
4646        let snapshot = self.frame_stats.snapshot();
4647        if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
4648            log::warn!(
4649                "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
4650                 offscreen_acq={} offscreen_new={} isolated={} draws={}",
4651                snapshot.layer_cache_hits,
4652                snapshot.layer_cache_misses,
4653                snapshot.layer_cache_miss_pixels,
4654                snapshot.offscreen_acquires,
4655                snapshot.offscreen_news,
4656                snapshot.isolated_layer_renders,
4657                snapshot.draw_calls,
4658            );
4659        }
4660        self.last_frame_stats = Some(snapshot);
4661        PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4662        update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
4663        let gpu_stats_on = gpu_stats_enabled();
4664        self.frame_stats
4665            .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
4666        if gpu_stats_on && self.frame_count.is_multiple_of(60) {
4667            gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
4668        }
4669        self.frame_graph_executor
4670            .end_pass_timing_frame(&self.device, &self.queue);
4671        self.frame_stats.reset();
4672        let after_stats = Instant::now();
4673        if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
4674            log::warn!(
4675                "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
4676                instant_ms(render_start, after_graph),
4677                instant_ms(after_graph, after_stats),
4678            );
4679        }
4680        if result.is_ok() {
4681            returns.outcome = PresentOutcome::Presented;
4682        }
4683        result
4684    }
4685
4686    /// Returns a packet unrendered, handing its scene back for recycling.
4687    pub(crate) fn cancel_packet(
4688        packet: FramePacket,
4689        reason: CancelReason,
4690        returns: &mut RenderReturns,
4691    ) -> Result<(), String> {
4692        returns.scene = Some(FrameSceneStorage {
4693            root: packet.root,
4694            overlay: packet.overlay,
4695        });
4696        returns.frame_id = packet.frame_id;
4697        returns.outcome = PresentOutcome::Cancelled(reason);
4698        Ok(())
4699    }
4700
4701    pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
4702        self.last_frame_stats
4703    }
4704
4705    pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
4706        self.frame_graph_executor.pass_timing_report()
4707    }
4708
4709    pub fn needs_frame_warmup(&self) -> bool {
4710        self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
4711    }
4712
4713    #[cfg(target_arch = "wasm32")]
4714    pub(crate) fn pipeline_compiler(&self) -> &PipelineCompiler {
4715        &self.pipeline_compiler
4716    }
4717
4718    /// Whether a frame must follow to replace a placeholder: a pipeline it
4719    /// waited for landed, or, with nothing to wake the app when one does,
4720    /// this frame drew one.
4721    fn placeholder_awaits_frame(&self) -> bool {
4722        #[cfg(not(target_arch = "wasm32"))]
4723        if let Some(landing) = &self.landing {
4724            return landing.landed() || (self.drew_placeholder && !landing.has_wake());
4725        }
4726        self.drew_placeholder
4727    }
4728
4729    /// Starts a frame: once a pipeline a placeholder waited for has landed,
4730    /// the retained layers, which may hold that placeholder, are dropped.
4731    fn begin_placeholder_frame(&mut self) {
4732        self.drew_placeholder = false;
4733        #[cfg(not(target_arch = "wasm32"))]
4734        if let Some(landing) = &self.landing {
4735            self.built_at_frame_start = landing.built();
4736            if landing.take_landed() {
4737                self.layer_cache.clear();
4738            }
4739        }
4740    }
4741
4742    /// Drops what earlier frames drew and kept, the layers and the blurred
4743    /// shadows: pipelines the browser compiled in the background landed, and
4744    /// those were drawn while the draws that use them were left out.
4745    #[cfg(target_arch = "wasm32")]
4746    pub(crate) fn background_pipelines_landed(&mut self) {
4747        self.drop_kept_drawing();
4748    }
4749
4750    /// Drops the layers and the blurred shadows earlier frames drew and kept.
4751    fn drop_kept_drawing(&mut self) {
4752        self.layer_cache.clear();
4753        self.shadow_surface_cache.clear();
4754        self.shadow_surface_cache_bytes = 0;
4755    }
4756
4757    /// Notes an effect drawn as its placeholder, or left out, while its
4758    /// pipelines compile, and waits for the next one to land.
4759    pub(crate) fn note_placeholder(&mut self) {
4760        self.drew_placeholder = true;
4761        self.recorder.hold_first_screen();
4762        self.frame_stats
4763            .placeholder_draws
4764            .set(self.frame_stats.placeholder_draws.get() + 1);
4765        #[cfg(not(target_arch = "wasm32"))]
4766        if let Some(landing) = &self.landing {
4767            landing.await_since(self.built_at_frame_start);
4768        }
4769    }
4770
4771    /// Queues every pipeline the cache file records, as the first frame of
4772    /// an updated build does, and returns whether any is left to build: for
4773    /// a renderer that prepares an app's pipelines without drawing.
4774    #[cfg(not(target_arch = "wasm32"))]
4775    pub(crate) fn prepare_recorded(&mut self) -> bool {
4776        self.effect_renderer.warm_after_first_frame();
4777        if let Some(records) = self.recent_after_update.take() {
4778            self.warm_recent(&records);
4779        }
4780        self.compiling()
4781    }
4782
4783    /// Whether the background compiler has a queued pipeline left to build.
4784    #[cfg(not(target_arch = "wasm32"))]
4785    pub(crate) fn compiling(&self) -> bool {
4786        self.landing
4787            .as_ref()
4788            .is_some_and(|landing| landing.in_flight())
4789    }
4790
4791    /// Whether the last frame drew a placeholder and pipelines are still
4792    /// compiling, so its picture is not final yet.
4793    pub(crate) fn awaits_pipelines(&self) -> bool {
4794        #[cfg(not(target_arch = "wasm32"))]
4795        if let Some(landing) = &self.landing {
4796            return self.drew_placeholder && landing.in_flight();
4797        }
4798        self.drew_placeholder
4799    }
4800
4801    /// The compiler's account of the pipelines it builds, for a runtime that
4802    /// reads it off the present thread.
4803    #[cfg(not(target_arch = "wasm32"))]
4804    pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
4805        self.landing.clone()
4806    }
4807
4808    /// Calls `wake` from the compiling thread when a pipeline a placeholder
4809    /// waited for lands, so an app with nothing else to draw draws again.
4810    #[cfg(not(target_arch = "wasm32"))]
4811    pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
4812        if let Some(landing) = &self.landing {
4813            landing.wake_with(wake);
4814        }
4815    }
4816
4817    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
4818        DebugCpuAllocationStats {
4819            scene_graph_node_count: 0,
4820            scene_graph_heap_bytes: 0,
4821            scene_hits_len: 0,
4822            scene_hits_cap: 0,
4823            scene_node_index_len: 0,
4824            scene_node_index_cap: 0,
4825            text_renderer_pool_len: self.text_image_cache.len(),
4826            text_renderer_pool_cap: self.text_image_cache.cap().get(),
4827            image_texture_cache_len: self.image_texture_cache.len(),
4828            image_texture_cache_cap: self.image_texture_cache.cap().get(),
4829            run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
4830            run_store_bytes: self.run_store.stored_bytes(),
4831            run_store_runs: self.run_store.stored_count(),
4832            scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
4833            scratch_image_indices_cap: self.scratch_image_indices.capacity(),
4834            scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
4835            scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
4836                + self.scratch_glyph_instances.turned.capacity(),
4837            layer_cache_len: self.layer_cache.len(),
4838            layer_cache_bytes: self.layer_cache.bytes(),
4839        }
4840    }
4841    pub fn render_to_rgba_pixels(
4842        &mut self,
4843        width: u32,
4844        height: u32,
4845        packet: FramePacket,
4846        surface_epoch: u64,
4847        returns: &mut RenderReturns,
4848    ) -> Result<Vec<u8>, String> {
4849        if width == 0 || height == 0 {
4850            return Err("Screenshot size must be non-zero".to_string());
4851        }
4852        let errors_before = self.device_errors.error_count();
4853
4854        let output_texture = crate::offscreen::create_2d_texture(
4855            &self.device,
4856            wgpu::TextureFormat::Rgba8Unorm,
4857            width,
4858            height,
4859            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
4860            Some("Screenshot Output Texture"),
4861        );
4862        let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
4863        self.render_internal(
4864            width,
4865            height,
4866            packet,
4867            surface_epoch,
4868            returns,
4869            OutputMode::Screenshot,
4870            Some(&output_view),
4871            None,
4872        )?;
4873        if returns.outcome != PresentOutcome::Presented {
4874            return Err(format!(
4875                "Screenshot rendering did not complete: {:?}",
4876                returns.outcome
4877            ));
4878        }
4879        self.read_screenshot_pixels(&output_texture, errors_before)
4880    }
4881
4882    fn read_screenshot_pixels(
4883        &mut self,
4884        output_texture: &wgpu::Texture,
4885        errors_before: u64,
4886    ) -> Result<Vec<u8>, String> {
4887        let width = output_texture.width();
4888        let height = output_texture.height();
4889        let bytes_per_pixel = 4u32;
4890        let unpadded_bytes_per_row = width
4891            .checked_mul(bytes_per_pixel)
4892            .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
4893        let padded_bytes_per_row =
4894            align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
4895        let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
4896
4897        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
4898            label: Some("Screenshot Readback Buffer"),
4899            size: output_buffer_size,
4900            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
4901            mapped_at_creation: false,
4902        });
4903
4904        let device = self.device.clone();
4905        let queue = self.queue.clone();
4906        let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
4907        let source = graph.import_surface("screenshot-copy-source");
4908        graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
4909            context.encoder.copy_texture_to_buffer(
4910                wgpu::TexelCopyTextureInfo {
4911                    texture: output_texture,
4912                    mip_level: 0,
4913                    origin: wgpu::Origin3d::ZERO,
4914                    aspect: wgpu::TextureAspect::All,
4915                },
4916                wgpu::TexelCopyBufferInfo {
4917                    buffer: &output_buffer,
4918                    layout: wgpu::TexelCopyBufferLayout {
4919                        offset: 0,
4920                        bytes_per_row: Some(padded_bytes_per_row),
4921                        rows_per_image: Some(height),
4922                    },
4923                },
4924                wgpu::Extent3d {
4925                    width,
4926                    height,
4927                    depth_or_array_layers: 1,
4928                },
4929            );
4930            Ok(())
4931        });
4932        let mut executor = std::mem::take(&mut self.frame_graph_executor);
4933        let execution = executor.execute_recorded_graph(&device, &queue, graph);
4934        self.frame_graph_executor = executor;
4935        self.recall_frame_uploads();
4936        let execution = execution.map_err(|error| error.to_string())?;
4937        let submission_index = execution.submission;
4938        let copy_stats = execution.stats;
4939        self.last_frame_stats = self
4940            .last_frame_stats
4941            .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
4942
4943        let buffer_slice = output_buffer.slice(..);
4944        let (tx, rx) = mpsc::channel();
4945        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
4946            let _ = tx.send(result);
4947        });
4948        self.device
4949            .poll(wgpu::PollType::Wait {
4950                submission_index: Some(submission_index),
4951                timeout: None,
4952            })
4953            .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
4954
4955        match rx.recv_timeout(Duration::from_secs(3)) {
4956            Ok(Ok(())) => {}
4957            Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
4958            Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
4959        }
4960        if self.device_errors.error_count() != errors_before {
4961            output_buffer.unmap();
4962            return Err("GPU errors occurred while capturing the screenshot".to_string());
4963        }
4964
4965        let mapped = buffer_slice
4966            .get_mapped_range()
4967            .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
4968        let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
4969
4970        let src_row_len = padded_bytes_per_row as usize;
4971        let dst_row_len = unpadded_bytes_per_row as usize;
4972        for row in 0..height as usize {
4973            let src_offset = row * src_row_len;
4974            let dst_offset = row * dst_row_len;
4975            pixels[dst_offset..dst_offset + dst_row_len]
4976                .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
4977        }
4978        drop(mapped);
4979        output_buffer.unmap();
4980
4981        self.convert_surface_pixels_to_rgba(&pixels)
4982    }
4983
4984    /// Asks the buffers the submitted frame unmapped back for later frames.
4985    fn recall_frame_uploads(&mut self) {
4986        self.viewport_uniforms.uploads.recall();
4987        self.run_store.recall();
4988    }
4989
4990    fn render_graph(
4991        &mut self,
4992        root_target: &Rc<OffscreenTarget>,
4993        packet: FramePacket,
4994        returns: &mut RenderReturns,
4995        output_mode: OutputMode,
4996        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
4997    ) -> Result<(), String> {
4998        #[cfg(target_arch = "wasm32")]
4999        let (device, queue, graph_start) =
5000            (self.device.clone(), self.queue.clone(), Instant::now());
5001        let FramePacket {
5002            root,
5003            overlay,
5004            root_scale,
5005            clear,
5006            ..
5007        } = packet;
5008        let page = Rc::clone(root_target);
5009
5010        #[cfg(not(target_arch = "wasm32"))]
5011        let (result, submitted) = {
5012            if std::mem::take(&mut self.discovers_next_frame) {
5013                self.discover_frame_pipelines(
5014                    &root,
5015                    overlay.as_ref(),
5016                    &page,
5017                    root_scale,
5018                    clear,
5019                    output_mode,
5020                    output,
5021                );
5022            }
5023            self.execute_frame_graph(
5024                &root,
5025                overlay.as_ref(),
5026                &page,
5027                root_scale,
5028                clear,
5029                output_mode,
5030                output,
5031            )
5032        };
5033
5034        #[cfg(target_arch = "wasm32")]
5035        let (result, submitted) = {
5036            let mut executor = std::mem::take(&mut self.frame_graph_executor);
5037            let (result, execution) = {
5038                let mut frame_encoder =
5039                    executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
5040                let initial_pass_count = frame_encoder.recorded_pass_count();
5041                let result = self.encode_frame(
5042                    &mut frame_encoder,
5043                    &root,
5044                    overlay.as_ref(),
5045                    Rc::clone(&page),
5046                    root_scale,
5047                    clear,
5048                    output_mode,
5049                    output,
5050                );
5051                let execution =
5052                    if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
5053                        Some(frame_encoder.finish())
5054                    } else {
5055                        None
5056                    };
5057                (result, execution)
5058            };
5059            let after_execute = Instant::now();
5060            self.frame_graph_executor = executor;
5061            if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5062                log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
5063            }
5064            let submitted = execution.is_some();
5065            if let Some(execution) = execution {
5066                self.frame_stats.record_command_stats(execution.stats);
5067            }
5068            (result, submitted)
5069        };
5070        #[cfg(not(target_arch = "wasm32"))]
5071        if submitted {
5072            self.recorder.note_frame_drawn();
5073            self.effect_renderer.warm_after_first_frame();
5074            if let Some(records) = self.recent_after_update.take() {
5075                self.warm_recent(&records);
5076            }
5077        }
5078        if !submitted {
5079            self.run_store.invalidate_uploads();
5080            self.text_glyph_gpu_run_cache.clear();
5081            self.text_glyph_run_arena = GlyphRunArena::new(self.copy_free);
5082        }
5083        returns.scene = Some(FrameSceneStorage { root, overlay });
5084        result
5085    }
5086
5087    /// Records and submits the frame through the frame graph: whether it
5088    /// recorded without error, and whether it submitted anything.
5089    #[cfg(not(target_arch = "wasm32"))]
5090    #[expect(clippy::too_many_arguments)]
5091    fn execute_frame_graph(
5092        &mut self,
5093        root: &LayerScene,
5094        overlay: Option<&LayerScene>,
5095        page: &Rc<OffscreenTarget>,
5096        root_scale: f32,
5097        clear: wgpu::Color,
5098        output_mode: OutputMode,
5099        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5100    ) -> (Result<(), String>, bool) {
5101        let device = self.device.clone();
5102        let queue = self.queue.clone();
5103        let graph_start = Instant::now();
5104        let mut executor = std::mem::take(&mut self.frame_graph_executor);
5105        let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
5106        let surface = frame_graph.import_surface("renderer-surface");
5107        frame_graph.add_fallible_recorded_command_pass(
5108            Some("Renderer Frame Pass"),
5109            &[],
5110            &[surface],
5111            |frame_encoder| {
5112                self.encode_frame(
5113                    frame_encoder,
5114                    root,
5115                    overlay,
5116                    Rc::clone(page),
5117                    root_scale,
5118                    clear,
5119                    output_mode,
5120                    output,
5121                )
5122            },
5123        );
5124        let after_build = Instant::now();
5125        let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
5126        let after_execute = Instant::now();
5127        self.frame_graph_executor = executor;
5128        self.recall_frame_uploads();
5129        if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5130            log::warn!(
5131                "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
5132                instant_ms(graph_start, after_build),
5133                instant_ms(after_build, after_execute),
5134            );
5135        }
5136        match execution {
5137            Ok(execution) => {
5138                if execution.stats.pass_count > 0 {
5139                    self.frame_stats.record_command_stats(execution.stats);
5140                }
5141                (Ok(()), true)
5142            }
5143            Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
5144            Err(error) => (Err(error.to_string()), false),
5145        }
5146    }
5147
5148    /// Walks the frame once drawing nothing, so every pass queues the
5149    /// pipelines it lacks on the compiler's threads, and they compile side by
5150    /// side; the frame drawn next waits for them where it draws. Drawn pass
5151    /// after pass instead, each pass asked for its pipelines only after the
5152    /// passes before it had theirs: with no Metal shader cached, the
5153    /// gauntlet's first frame on an Apple M3 Pro waited for two such waves
5154    /// of pipelines. What the walk kept, the layers and the blurred shadows,
5155    /// holds nothing drawn and is dropped, and what it counted toward
5156    /// caching a layer, a fill, an effect or a source is forgotten: the
5157    /// frame drawn next starts from the state the walk found, a renderer's
5158    /// first frame's.
5159    #[cfg(not(target_arch = "wasm32"))]
5160    #[expect(clippy::too_many_arguments)]
5161    fn discover_frame_pipelines(
5162        &mut self,
5163        root: &LayerScene,
5164        overlay: Option<&LayerScene>,
5165        page: &Rc<OffscreenTarget>,
5166        root_scale: f32,
5167        clear: wgpu::Color,
5168        output_mode: OutputMode,
5169        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5170    ) {
5171        self.discovering = true;
5172        let (result, _) =
5173            self.execute_frame_graph(root, overlay, page, root_scale, clear, output_mode, output);
5174        self.discovering = false;
5175        if let Err(error) = result {
5176            log::warn!(
5177                "[gpu-pipeline] the walk that learns the first frame's pipelines failed: {error}"
5178            );
5179        }
5180        self.drop_kept_drawing();
5181        self.backdrop_gates.clear();
5182        self.fill_gates.clear();
5183        self.effect_gates.clear();
5184        self.source_gates.clear();
5185    }
5186
5187    /// Records the frame: the root and overlay layer scenes into the frame's
5188    /// target, the output conversion when the target is not the presented
5189    /// image, and the viewport uniforms the recorded passes claimed.
5190    #[expect(clippy::too_many_arguments)]
5191    fn encode_frame<C: FrameCommandRecorder>(
5192        &mut self,
5193        recorder: &mut C,
5194        root: &LayerScene,
5195        overlay: Option<&LayerScene>,
5196        page: Rc<OffscreenTarget>,
5197        root_scale: f32,
5198        clear: wgpu::Color,
5199        output_mode: OutputMode,
5200        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5201    ) -> Result<(), String> {
5202        FrameExecutor::new(self, recorder).render_frame(
5203            root,
5204            overlay,
5205            page,
5206            root_scale,
5207            wgpu::LoadOp::Clear(clear),
5208        )?;
5209        #[cfg(not(target_arch = "wasm32"))]
5210        let discovering = self.discovering;
5211        #[cfg(target_arch = "wasm32")]
5212        let discovering = false;
5213        if !discovering && let Some((output_view, bind_group)) = output {
5214            match output_mode {
5215                OutputMode::Display => &self.output_converter,
5216                OutputMode::Screenshot => &self.screenshot_converter,
5217            }
5218            .encode(
5219                &self.device,
5220                recorder,
5221                output_view,
5222                bind_group,
5223                self.adapter_backend,
5224                &self.recorder,
5225            );
5226            recorder.record_pass();
5227        }
5228        self.stage_frame_uploads(recorder);
5229        self.shape_pipelines.request_wanted();
5230        if !discovering {
5231            self.depth_gate.end_frame();
5232        }
5233        self.pipeline_compiler.end_frame();
5234        self.viewport_uniforms.uploads.finish_frame();
5235        self.run_store.finish_frame();
5236        Ok(())
5237    }
5238
5239    pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
5240        let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
5241        upload += self.run_store.stage_pending(&self.device, recorder);
5242        upload += self
5243            .text_glyph_run_arena
5244            .stage_pending(&self.device, recorder);
5245        self.run_store.fill_arena_trig(&self.device, recorder);
5246        self.frame_stats.record_command_stats(upload);
5247    }
5248    /// Claims this frame's next viewport uniform slot for `params`.
5249    pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
5250        let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
5251        self.viewport_uniforms
5252            .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
5253    }
5254
5255    /// Resolves a blurred shadow at `z` into a texture and queues its
5256    /// composites. The shadow's shapes and texts render into a source the
5257    /// size of their blur footprint, blur in place and take the post-blur
5258    /// cutouts; the source is then blitted over the rect the shadow covers.
5259    /// Shape-only shadows live in the shadow cache, keyed by their content
5260    /// and device placement, so a scrolling card re-blits its cached blur.
5261    /// The blurred shadow texture and whether the cache held it: a
5262    /// shape-only shadow is cached by content and placement, a shadow with
5263    /// text renders every frame.
5264    fn blurred_shadow_source<C: FrameCommandRecorder>(
5265        &mut self,
5266        recorder: &mut C,
5267        shadow: &ShadowDraw,
5268        source_device: DevicePixelBounds,
5269        pixel_radius: f32,
5270        root_scale: f32,
5271        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5272    ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
5273        let shape_only = shadow.texts.is_empty();
5274        let key = if shape_only {
5275            shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
5276        } else {
5277            None
5278        };
5279        let content = key.map_or(SourceContent::Transient, |key| {
5280            SourceContent::retained(&key)
5281        });
5282        if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
5283            return Some((Rc::clone(&entry.target), true, content));
5284        }
5285        // A shadow whose blur compiles is left out until the blur lands.
5286        if !self.effect_renderer.blur_draws_now(
5287            &self.device,
5288            TileMode::Decal,
5289            (source_device.width, source_device.height),
5290            pixel_radius,
5291            pixel_radius,
5292        ) {
5293            self.note_placeholder();
5294            return None;
5295        }
5296        if !shape_only {
5297            self.frame_stats.record_shadow_text_blur_fallback();
5298        }
5299        let source = self.render_shadow_source(
5300            recorder,
5301            shadow,
5302            source_device,
5303            pixel_radius,
5304            root_scale,
5305            key.is_some(),
5306            transients,
5307        )?;
5308        if let Some(key) = key {
5309            self.frame_stats
5310                .record_shadow_shape_cache_miss(source_device.width, source_device.height);
5311            self.frame_stats.maybe_print_shadow_shape_cache_miss(
5312                source_device.width,
5313                source_device.height,
5314                key.content_hash,
5315                pixel_radius,
5316                [source_device.x, source_device.y],
5317                shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
5318                shadow.clip,
5319            );
5320            self.insert_cached_shadow_surface(key, Rc::clone(&source));
5321        }
5322        Some((source, false, content))
5323    }
5324
5325    #[expect(clippy::too_many_arguments)]
5326    pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
5327        &mut self,
5328        recorder: &mut C,
5329        shadow: &ShadowDraw,
5330        z: usize,
5331        root_scale: f32,
5332        target_rect: DeviceRect4,
5333        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5334        resolved: &mut Vec<ResolvedComposite>,
5335    ) {
5336        if !shadow.requires_surface()
5337            || skip_shadow_draws()
5338            || !root_scale.is_finite()
5339            || root_scale <= 0.0
5340        {
5341            return;
5342        }
5343        let Some(bounds) = shadow_draw_bounds(shadow) else {
5344            return;
5345        };
5346        let margin = blur_reach(shadow.blur_radius, root_scale);
5347        let source_bounds = expand_rect(bounds, margin, margin);
5348        let mut visible = source_bounds;
5349        if let Some(clip) = shadow.clip {
5350            let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
5351                return;
5352            };
5353            visible = clipped;
5354        }
5355        let target_logical = Rect {
5356            x: target_rect.0 / root_scale,
5357            y: target_rect.1 / root_scale,
5358            width: target_rect.2 / root_scale,
5359            height: target_rect.3 / root_scale,
5360        };
5361        let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
5362            return;
5363        };
5364        let max_texture_dim = self.max_texture_dim();
5365        let shape_only = shadow.texts.is_empty();
5366        let anchor = shadow
5367            .shapes
5368            .as_ref()
5369            .and_then(|run| run.placement.snap_anchor);
5370        let source_device = shape_only
5371            .then(|| {
5372                translation_stable_anchored_device_pixel_bounds(
5373                    source_bounds,
5374                    anchor,
5375                    root_scale,
5376                    max_texture_dim,
5377                )
5378            })
5379            .flatten()
5380            .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
5381        let Some(source_device) = source_device else {
5382            return;
5383        };
5384        let pixel_radius = shadow.blur_radius * root_scale;
5385        let Some((source, hit, content)) = self.blurred_shadow_source(
5386            recorder,
5387            shadow,
5388            source_device,
5389            pixel_radius,
5390            root_scale,
5391            transients,
5392        ) else {
5393            return;
5394        };
5395        let dest = (
5396            source_device.x,
5397            source_device.y,
5398            source_device.width as f32,
5399            source_device.height as f32,
5400        );
5401        let mut coverage = intersect_device_rects(dest, target_rect);
5402        if let Some(clip) = shadow.clip {
5403            coverage = coverage.and_then(|coverage| {
5404                intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
5405            });
5406        }
5407        let Some(coverage) = coverage else {
5408            return;
5409        };
5410        if hit {
5411            self.frame_stats.record_shadow_shape_cache_hit(
5412                (coverage.2 as u64).saturating_mul(coverage.3 as u64),
5413            );
5414        }
5415        let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
5416        let downscaled =
5417            (source.width, source.height) != (source_device.width, source_device.height);
5418        let (sample_mode, source_viewport) = if downscaled {
5419            (
5420                CompositeSampleMode::Linear,
5421                Some((0.0, 0.0, source.width as f32, source.height as f32)),
5422            )
5423        } else {
5424            (CompositeSampleMode::Nearest, None)
5425        };
5426        resolved.push(ResolvedComposite {
5427            z_index: z,
5428            source,
5429            content,
5430            dest,
5431            scissor: Some(coverage),
5432            kind: ResolvedCompositeKind::Blit {
5433                alpha: 1.0,
5434                blend_mode: BlendMode::SrcOver,
5435                rounded_mask,
5436                sample_mode,
5437                source_viewport,
5438            },
5439        });
5440    }
5441
5442    /// Draws a shadow's shapes and texts into a surface covering `bounds`
5443    /// and blurs it. A wide blur runs at its scratch size and its result
5444    /// stays there, read bilinearly by the composite; a post-blur cutout
5445    /// needs the surface's full size, so the blurred result is interpolated
5446    /// back into it first and the cutout drawn at that size. A retained
5447    /// result feeds the shadow cache; a transient one is registered with
5448    /// the frame's transients and released with them. `None` when the
5449    /// shadow draws nothing.
5450    #[expect(clippy::too_many_arguments)]
5451    fn render_shadow_source<C: FrameCommandRecorder>(
5452        &mut self,
5453        recorder: &mut C,
5454        shadow: &ShadowDraw,
5455        bounds: DevicePixelBounds,
5456        pixel_radius: f32,
5457        root_scale: f32,
5458        retained: bool,
5459        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5460    ) -> Option<Rc<OffscreenTarget>> {
5461        let (width, height) = (bounds.width, bounds.height);
5462        let device = self.device.clone();
5463        let (scratch_width, scratch_height) =
5464            crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
5465        let full_size_result = shadow.post_blur_cutouts.is_some()
5466            || (scratch_width, scratch_height) == (width, height);
5467        let (result_width, result_height) = if full_size_result {
5468            (width, height)
5469        } else {
5470            (scratch_width, scratch_height)
5471        };
5472        let result = if retained {
5473            Rc::new(self.acquire_retained_surface(result_width, result_height))
5474        } else {
5475            self.shadow_transient(
5476                recorder,
5477                transients,
5478                "Shadow Result",
5479                result_width,
5480                result_height,
5481            )
5482        };
5483        let source = if full_size_result {
5484            Rc::clone(&result)
5485        } else {
5486            self.shadow_transient(recorder, transients, "Shadow Source", width, height)
5487        };
5488        let offset = [bounds.x, bounds.y];
5489        let target = PassTarget {
5490            view: &source.view,
5491            width,
5492            height,
5493        };
5494        let scene = shadow_scene(
5495            shadow.shapes.as_ref(),
5496            &shadow.texts,
5497            blur_reach(shadow.blur_radius, root_scale),
5498        );
5499        let segment = PassSegment {
5500            scene: &scene,
5501            ops: &scene.draw_ops,
5502            composites: &[],
5503            offset,
5504            scissor: None,
5505            first_run_window: None,
5506            transform: SegmentTransform::IDENTITY,
5507            scale: root_scale,
5508        };
5509        let drew = self.encode_pass(
5510            recorder,
5511            target,
5512            std::slice::from_ref(&segment),
5513            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
5514            "Shadow Source Pass",
5515        );
5516        match drew {
5517            Ok(true) => {}
5518            Ok(false) => {
5519                drop(source);
5520                if retained && let Ok(target) = Rc::try_unwrap(result) {
5521                    self.defer_offscreen_release(target);
5522                }
5523                return None;
5524            }
5525            Err(error) => {
5526                log::error!("shadow source pass failed: {error}");
5527                return None;
5528            }
5529        }
5530        if pixel_radius > 0.0 {
5531            let scratch_descriptor = self.transient_offscreen_descriptor(
5532                "Shadow Blur Scratch",
5533                scratch_width,
5534                scratch_height,
5535            );
5536            let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
5537            let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
5538            {
5539                Some(self.shadow_transient(
5540                    recorder,
5541                    transients,
5542                    "Shadow Blur Result",
5543                    scratch_width,
5544                    scratch_height,
5545                ))
5546            } else {
5547                None
5548            };
5549            let blur_dest = match &blurred {
5550                Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
5551                None => (&result.view, (result_width, result_height)),
5552            };
5553            let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
5554                recorder,
5555                &device,
5556                &source,
5557                &scratch,
5558                blur_dest,
5559                pixel_radius,
5560                pixel_radius,
5561                TileMode::Decal,
5562                None,
5563            );
5564            recorder.record_passes(passes);
5565            self.effect_renderer.record_blur_pass();
5566            recorder.release_transient_offscreen(scratch_descriptor, scratch);
5567            if let Some(blurred) = &blurred {
5568                self.effect_renderer
5569                    .encode_upscale_pass(recorder, &device, blurred, &result.view);
5570                recorder.record_pass();
5571            }
5572        }
5573        if let Some(cutout_run) = &shadow.post_blur_cutouts {
5574            let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
5575            let segment = PassSegment {
5576                scene: &cutouts,
5577                ops: &cutouts.draw_ops,
5578                composites: &[],
5579                offset,
5580                scissor: None,
5581                first_run_window: None,
5582                transform: SegmentTransform::IDENTITY,
5583                scale: root_scale,
5584            };
5585            if let Err(error) = self.encode_pass(
5586                recorder,
5587                target,
5588                std::slice::from_ref(&segment),
5589                wgpu::LoadOp::Load,
5590                "Shadow Cutout Pass",
5591            ) {
5592                log::error!("shadow cutout pass failed: {error}");
5593            }
5594        }
5595        Some(result)
5596    }
5597
5598    /// A transient surface of a shadow's frame, released with the frame's
5599    /// transients.
5600    fn shadow_transient<C: FrameCommandRecorder>(
5601        &self,
5602        recorder: &mut C,
5603        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5604        label: &'static str,
5605        width: u32,
5606        height: u32,
5607    ) -> Rc<OffscreenTarget> {
5608        let descriptor = self.transient_offscreen_descriptor(label, width, height);
5609        let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
5610        transients.push((descriptor, Rc::clone(&target)));
5611        target
5612    }
5613
5614    /// Whether `run` draws from retained buffers keyed by its command.
5615    pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
5616        self.run_store.is_stored(run)
5617    }
5618
5619    /// The pipeline `segment` of a run at `placement` draws with. `clipped`
5620    /// says the variant tests the run's clip: a turned run's, since an
5621    /// unturned one's clip is its paint's scissor (see [`clip_scissor`]).
5622    fn run_pipeline_key(
5623        segment: &RecordSegment,
5624        placement: &crate::scene::Placement,
5625        tier: RunTier,
5626        ablation: ShapeAblation,
5627        turns: ShapeTurns,
5628        (depth, clip): (bool, SegmentClip),
5629        viewport: ViewportUniformParams,
5630    ) -> ShapePipelineKey {
5631        let blend_mode = supported_blend_mode(segment.blend);
5632        let laid = depth
5633            && blend_mode == BlendMode::SrcOver
5634            && !placement.paints()
5635            && clip != SegmentClip::Rounded
5636            && !ablation.material
5637            && !ablation.fill;
5638        ShapePipelineKey {
5639            blend_mode,
5640            tier,
5641            variant: ShapeVariant::of_segment(
5642                segment,
5643                clip,
5644                ablation,
5645                laid,
5646                (
5647                    turns == ShapeTurns::None,
5648                    turns == ShapeTurns::None
5649                        && placement.snap_anchor.is_some()
5650                        && viewport.offset.iter().all(|value| value.fract() == 0.0),
5651                ),
5652            ),
5653            turns,
5654            depth: if depth {
5655                ShapeDepth::Tested
5656            } else {
5657                ShapeDepth::Off
5658            },
5659        }
5660    }
5661
5662    /// Queues for a later frame the shape pipelines `keys` name and the
5663    /// interiors they lay down, handing `awaited` each still to land.
5664    pub(crate) fn warm_shapes_later(
5665        &mut self,
5666        keys: &PipelineDemand,
5667        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
5668    ) {
5669        for key in keys.keys() {
5670            self.shape_pipelines.warm_later(key, awaited);
5671        }
5672    }
5673
5674    /// Prepares the pipeline of each key `pipelines` holds and, in a pass
5675    /// with a depth buffer, the one laying down its opaque interiors: the
5676    /// compiler's threads build the missing ones after the first while this
5677    /// thread builds that one.
5678    /// Queues every shape pipeline `pipelines` names that is missing, and
5679    /// forgets them: a pass that learns its pipelines draws none.
5680    #[cfg(not(target_arch = "wasm32"))]
5681    pub(crate) fn discover_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
5682        self.shape_pipelines.prefetch(pipelines, true);
5683        pipelines.clear();
5684    }
5685
5686    pub(crate) fn ensure_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
5687        self.shape_pipelines.prefetch(pipelines, false);
5688        for (key, vertices) in pipelines.drain() {
5689            self.ensure_shape_pipeline(key, vertices);
5690            if let Some(interior) = key.interior() {
5691                self.ensure_shape_pipeline(interior, vertices);
5692            }
5693        }
5694    }
5695
5696    /// Brings a stored run's tables up to date and appends its draws, under
5697    /// a placement uniform of its own, to the pass's run draws `draws`, and
5698    /// the pipelines they draw with to `pipelines`.
5699    #[expect(clippy::too_many_arguments)]
5700    pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
5701        &mut self,
5702        recorder: &mut C,
5703        run: &RunDraw,
5704        viewport: ViewportUniformParams,
5705        root_scale: f32,
5706        window: &std::ops::Range<u32>,
5707        (depth, mut depth_keys): (bool, Option<&mut PipelineDemand>),
5708        (draws, pipelines): (&mut Vec<RunDrawCall>, &mut PipelineDemand),
5709    ) -> StoreRunBatch {
5710        let placement = &run.placement;
5711        let ablation = self.ablation.shape;
5712        let turns = ShapeTurns::of(viewport.transform, false);
5713        let scissor = clip_scissor(placement, root_scale, viewport);
5714        let clip = SegmentClip::of(placement, scissor.is_some());
5715        let start = draws.len();
5716        self.run_store.stored_run_draws(
5717            &self.device,
5718            run,
5719            &mut |segment| {
5720                let key = |depth| {
5721                    Self::run_pipeline_key(
5722                        segment,
5723                        placement,
5724                        RunTier::Store,
5725                        ablation,
5726                        turns,
5727                        (depth, clip),
5728                        viewport,
5729                    )
5730                };
5731                if let Some(keys) = depth_keys.as_deref_mut() {
5732                    keys.add(key(true), 0);
5733                }
5734                key(depth)
5735            },
5736            draws,
5737        );
5738        window_draws(draws, start, window);
5739        let run_draws = &draws[start..];
5740        let upload_start = Instant::now();
5741        let (upload, fill, tables) = self.run_store.upload_stored(
5742            &self.device,
5743            recorder,
5744            run,
5745            root_scale,
5746            window,
5747            run_draws,
5748        );
5749        if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
5750            log::warn!(
5751                "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
5752                upload.upload_bytes,
5753                run.tables().shapes.len()
5754            );
5755        }
5756        self.frame_stats.record_command_stats(upload);
5757        if let Some(fill) = fill {
5758            self.frame_stats.add_shape_fill(fill);
5759        }
5760        let uniforms = Uniforms::of(
5761            viewport,
5762            PlacementData::of(&run.placement, root_scale, viewport.transform),
5763            RunTier::Store,
5764        );
5765        let uniform_slot =
5766            self.viewport_uniforms
5767                .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
5768        for draw in run_draws {
5769            pipelines.add(
5770                draw.key,
5771                crate::run_store::draw_vertices(
5772                    draw.records.end - draw.records.start,
5773                    draw.band_class,
5774                ),
5775            );
5776        }
5777        StoreRunBatch {
5778            tables,
5779            uniform_slot,
5780            draws: start..draws.len(),
5781            clip: scissor,
5782        }
5783    }
5784
5785    pub(crate) fn open_arena(&mut self) -> usize {
5786        self.run_store.open_arena()
5787    }
5788
5789    /// The records the open arena chunk holds so far.
5790    pub(crate) fn open_arena_records(&self) -> u32 {
5791        self.run_store.open_arena_records()
5792    }
5793
5794    pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
5795        self.run_store.arena_accepts(chunk, run)
5796    }
5797
5798    /// Appends `window` of `run`'s records to the open arena chunk, their
5799    /// placement under `turn`, keyed for a pass whose flat and turned
5800    /// records alternate often when `mixed_turns`, and the pipelines they
5801    /// draw with to `pipelines`. `clip` says how its variant tests its clip:
5802    /// an unturned run leaves a rect clip to its paint's scissor, never a
5803    /// rounded one.
5804    #[expect(clippy::too_many_arguments)]
5805    pub(crate) fn append_arena_run(
5806        &mut self,
5807        chunk: usize,
5808        run: &RunDraw,
5809        window: std::ops::Range<u32>,
5810        root_scale: f32,
5811        viewport: ViewportUniformParams,
5812        mixed_turns: bool,
5813        (depth, clip): (bool, SegmentClip),
5814        (pipelines, mut depth_keys): (&mut PipelineDemand, Option<&mut PipelineDemand>),
5815    ) -> u32 {
5816        let placement = &run.placement;
5817        let ablation = self.ablation.shape;
5818        let turn = viewport.transform;
5819        let turns = ShapeTurns::of(turn, mixed_turns);
5820        self.run_store.append_arena(
5821            chunk,
5822            run,
5823            window,
5824            (root_scale, turn),
5825            &mut |segment| {
5826                let key = |depth| {
5827                    Self::run_pipeline_key(
5828                        segment,
5829                        placement,
5830                        RunTier::Arena,
5831                        ablation,
5832                        turns,
5833                        (depth, clip),
5834                        viewport,
5835                    )
5836                };
5837                if let Some(keys) = depth_keys.as_deref_mut() {
5838                    keys.add(key(true), 0);
5839                }
5840                key(depth)
5841            },
5842            pipelines,
5843        )
5844    }
5845
5846    /// Moves the open chunk's draws since its last cut onto `out`, keeping
5847    /// it open.
5848    pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5849        self.run_store.cut_arena(&self.device, chunk, out);
5850    }
5851
5852    /// Uploads the open chunk and moves its draws since its last cut onto
5853    /// `out`.
5854    pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
5855        if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
5856            self.frame_stats.add_shape_fill(fill);
5857        }
5858    }
5859
5860    pub(crate) fn draw_run_calls(
5861        &self,
5862        pass: &mut TrackedPass<'_, '_>,
5863        tables: ArenaBinding<'_>,
5864        uniform_slot: usize,
5865        draws: &[RunDrawCall],
5866        scissor: (u32, u32, u32, u32),
5867        stage: RunStage,
5868    ) -> Result<(), String> {
5869        match stage {
5870            RunStage::Paint => {
5871                if draws.is_empty() {
5872                    return Ok(());
5873                }
5874                self.frame_stats.bump_shapes();
5875                self.record_run_draws(
5876                    pass,
5877                    tables,
5878                    uniform_slot,
5879                    scissor,
5880                    draws.iter().map(PlannedRunDraw::paint),
5881                )
5882            }
5883            RunStage::Interiors => {
5884                let planned = interior_run_draws(draws);
5885                if planned.is_empty() {
5886                    return Ok(());
5887                }
5888                self.frame_stats
5889                    .shape_interior_draws
5890                    .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
5891                self.record_run_draws(pass, tables, uniform_slot, scissor, planned.into_iter())
5892            }
5893        }
5894    }
5895
5896    /// Records `planned` against one batch's tables, uniform and scissor.
5897    fn record_run_draws(
5898        &self,
5899        pass: &mut TrackedPass<'_, '_>,
5900        tables: ArenaBinding<'_>,
5901        uniform_slot: usize,
5902        scissor: (u32, u32, u32, u32),
5903        planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
5904    ) -> Result<(), String> {
5905        self.frame_stats.add_draw_calls(planned.len() as u32);
5906        let (x, y, width, height) = scissor;
5907        pass.set_scissor_rect(x, y, width, height);
5908        self.viewport_uniforms.bind(pass, uniform_slot)?;
5909        pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
5910        for (slot, buffer) in tables.records.into_iter().enumerate() {
5911            pass.set_vertex_buffer(slot as u32, buffer.slice(u64::from(tables.offsets[slot])..));
5912        }
5913        let mut bound_class = None;
5914        for draw in planned {
5915            let key = draw.key;
5916            let (pipeline, fallback) = self
5917                .shape_pipelines
5918                .get(key)
5919                .ok_or_else(|| format!("shape pipeline {key:?} was not prepared"))?;
5920            if fallback {
5921                self.frame_stats
5922                    .shape_pipeline_fallback_draws
5923                    .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5924            } else if !key.is_general() {
5925                self.frame_stats
5926                    .shape_specialized_draws
5927                    .set(self.frame_stats.shape_specialized_draws.get() + 1);
5928            }
5929            if bound_class != Some(draw.band_class) {
5930                pass.set_index_buffer(self.run_store.strip_index_buffer(draw.band_class).slice(..));
5931                bound_class = Some(draw.band_class);
5932            }
5933            pass.set_pipeline(pipeline);
5934            pass.draw_indexed(draw.indices, 0, draw.records);
5935        }
5936        Ok(())
5937    }
5938
5939    /// Draws a stored-run batch, whose draws are its range of `draws`.
5940    pub(crate) fn draw_store_run(
5941        &self,
5942        pass: &mut TrackedPass<'_, '_>,
5943        batch: &StoreRunBatch,
5944        draws: &[RunDrawCall],
5945        scissor: (u32, u32, u32, u32),
5946        stage: RunStage,
5947    ) -> Result<(), String> {
5948        self.draw_run_calls(
5949            pass,
5950            batch.tables.binding(),
5951            batch.uniform_slot,
5952            &draws[batch.draws.clone()],
5953            scissor,
5954            stage,
5955        )
5956    }
5957
5958    pub(crate) fn draw_arena(
5959        &self,
5960        pass: &mut TrackedPass<'_, '_>,
5961        chunk: usize,
5962        uniform_slot: usize,
5963        draws: &[RunDrawCall],
5964        scissor: (u32, u32, u32, u32),
5965        stage: RunStage,
5966    ) -> Result<(), String> {
5967        self.draw_run_calls(
5968            pass,
5969            self.run_store.arena_binding(chunk),
5970            uniform_slot,
5971            draws,
5972            scissor,
5973            stage,
5974        )
5975    }
5976    #[cfg(not(target_arch = "wasm32"))]
5977    pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
5978        self.display_format
5979    }
5980
5981    pub fn device_error_count(&self) -> u64 {
5982        self.device_errors.error_count()
5983    }
5984
5985    /// A pass that only applies `load_op` to the target, for a scene with
5986    /// nothing to draw that still needs its clear.
5987    pub(crate) fn clear_target<C: FrameCommandRecorder>(
5988        &self,
5989        recorder: &mut C,
5990        view: &wgpu::TextureView,
5991        load_op: wgpu::LoadOp<wgpu::Color>,
5992    ) {
5993        self.empty_pass(recorder, "Clear Pass", view, load_op);
5994    }
5995
5996    pub(crate) fn empty_pass<C: FrameCommandRecorder>(
5997        &self,
5998        recorder: &mut C,
5999        label: &'static str,
6000        view: &wgpu::TextureView,
6001        load_op: wgpu::LoadOp<wgpu::Color>,
6002    ) {
6003        let pass = recorder.begin_color_pass(label, view, load_op);
6004        drop(pass);
6005        recorder.record_pass();
6006    }
6007    pub(crate) fn draw_image_cmds(
6008        &self,
6009        pass: &mut TrackedPass<'_, '_>,
6010        image_slot: &ImageSlot,
6011        uniform_slot: usize,
6012        cmds: &[ImageDrawCmd],
6013        (blend_mode, depth): (BlendMode, bool),
6014        bound: Option<(u32, u32, u32, u32)>,
6015    ) -> Result<(), String> {
6016        if cmds.is_empty() {
6017            return Ok(());
6018        }
6019        self.frame_stats.bump_images();
6020        self.frame_stats.add_draw_calls(cmds.len() as u32);
6021        let mut bound_pipeline = None;
6022        self.viewport_uniforms.bind(pass, uniform_slot)?;
6023        pass.set_index_buffer(image_slot.indices.slice());
6024        pass.set_vertex_buffer(0, image_slot.vertices.slice());
6025        let mut clips_bound = false;
6026        for cmd in cmds {
6027            let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
6028                continue;
6029            };
6030            pass.set_scissor_rect(x, y, width, height);
6031            let variant = ImageVariant::of(cmd, depth);
6032            if bound_pipeline != Some(variant) {
6033                pass.set_pipeline(self.image_pipeline(blend_mode, variant));
6034                bound_pipeline = Some(variant);
6035            }
6036            pass.set_bind_group(1, &cmd.image.bind_group, &[]);
6037            let instance = match cmd.clip {
6038                Some(clip) => {
6039                    if !clips_bound {
6040                        let clips = image_slot
6041                            .clips
6042                            .as_ref()
6043                            .ok_or_else(|| "rounded image without clip instances".to_string())?;
6044                        pass.set_vertex_buffer(1, clips.slice());
6045                        clips_bound = true;
6046                    }
6047                    clip
6048                }
6049                None => 0,
6050            };
6051            pass.draw_indexed(
6052                cmd.index_start..(cmd.index_start + 6),
6053                0,
6054                instance..instance + 1,
6055            );
6056        }
6057        Ok(())
6058    }
6059
6060    pub(crate) fn draw_glyph_cmds(
6061        &self,
6062        pass: &mut TrackedPass<'_, '_>,
6063        (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
6064        uniform_slot: usize,
6065        cmds: &[GlyphDrawCmd],
6066        bound: Option<(u32, u32, u32, u32)>,
6067        frame: PassFrame,
6068    ) -> Result<(), String> {
6069        if cmds.is_empty() {
6070            return Ok(());
6071        }
6072        let whole_target = frame.scissor(bound);
6073        self.frame_stats.bump_text();
6074        let mut bound_atlas = None;
6075        // Which shared instances are bound, turned or plain, and which
6076        // pipeline; retained runs draw with a plain one.
6077        let mut shared_bound: Option<bool> = None;
6078        let mut bound_pipeline: Option<GlyphQuads> = None;
6079        let mut bound_run_instances: Option<&wgpu::Buffer> = None;
6080        let mut draws = 0u32;
6081        for draw in GlyphDraws::new(cmds) {
6082            let scissor = match draw.scissor {
6083                Some(scissor) => bounded_scissor(scissor, bound),
6084                None => Some(whole_target),
6085            };
6086            let Some((x, y, width, height)) = scissor else {
6087                continue;
6088            };
6089            pass.set_scissor_rect(x, y, width, height);
6090            if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
6091                pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
6092                bound_atlas = Some(draw.atlas);
6093            }
6094            draws += 1;
6095            match draw.step {
6096                GlyphDrawStep::Shared(instances, quads) => {
6097                    if bound_pipeline != Some(quads) {
6098                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
6099                        bound_pipeline = Some(quads);
6100                    }
6101                    let turned = quads.turned();
6102                    if shared_bound != Some(turned) {
6103                        let slot =
6104                            if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
6105                                "shared glyph draw without glyph instances".to_string()
6106                            })?;
6107                        self.viewport_uniforms.bind(pass, uniform_slot)?;
6108                        pass.set_vertex_buffer(0, slot.slice());
6109                        shared_bound = Some(turned);
6110                        bound_run_instances = None;
6111                    }
6112                    pass.draw(0..GLYPH_QUAD_CORNERS, instances);
6113                }
6114                GlyphDrawStep::Retained {
6115                    run,
6116                    uniform_slot: retained_slot,
6117                    aligned,
6118                } => {
6119                    let quads = GlyphQuads::plain(aligned);
6120                    if bound_pipeline != Some(quads) {
6121                        pass.set_pipeline(self.glyph_atlas_pipeline(frame.depth, quads));
6122                        bound_pipeline = Some(quads);
6123                    }
6124                    shared_bound = None;
6125                    self.viewport_uniforms.bind(pass, retained_slot)?;
6126                    let instances = run.span.instance_buffer();
6127                    if bound_run_instances != Some(instances) {
6128                        pass.set_vertex_buffer(0, instances.slice(..));
6129                        bound_run_instances = Some(instances);
6130                    }
6131                    pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
6132                }
6133            }
6134        }
6135        self.frame_stats.add_draw_calls(draws);
6136        Ok(())
6137    }
6138    pub(crate) fn append_image_draw_cmd(
6139        &mut self,
6140        image_draw: &ImageDraw,
6141        viewport: ViewportUniformParams,
6142        root_scale: f32,
6143        (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6144        image_clips: &mut Vec<DeviceRoundedClip>,
6145        image_cmds: &mut Vec<ImageDrawCmd>,
6146    ) -> Result<(), String> {
6147        let snap_delta = image_draw
6148            .snap_anchor
6149            .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6150            .unwrap_or_default();
6151        let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
6152        if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
6153            return Ok(());
6154        }
6155
6156        let (mut tint, cpu_filter) = tint_for_image(image_draw.color_filter, image_draw.alpha);
6157        if tint[3] <= 0.0 {
6158            return Ok(());
6159        }
6160
6161        let filtered_image = cpu_filter
6162            .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
6163            .transpose()?;
6164        let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
6165        if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
6166            for (channel, value) in tint[..3].iter_mut().zip(color) {
6167                *channel *= value as f32 / 255.0;
6168            }
6169        }
6170
6171        let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
6172        let Some(scissor) =
6173            scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
6174        else {
6175            return Ok(());
6176        };
6177
6178        let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
6179            return Ok(());
6180        };
6181        let device_quad = geometry.device_quad(root_scale);
6182        let index_start =
6183            push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
6184        let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
6185            image_clips.push(clip);
6186            image_clips.len() as u32 - 1
6187        });
6188        image_cmds.push(ImageDrawCmd {
6189            index_start,
6190            scissor,
6191            image: self.image_binding(prepared_image, geometry.sampling)?,
6192            clip,
6193        });
6194        Ok(())
6195    }
6196
6197    /// Uploads a pass's image and glyph quads into the frame's buffers.
6198    pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
6199        &self,
6200        recorder: &mut C,
6201        vertices: &[Vertex],
6202        indices: &[u32],
6203        clips: &[DeviceRoundedClip],
6204    ) -> ImageSlot {
6205        ImageSlot {
6206            vertices: recorder.upload_buffer(
6207                image_vertex_spec(),
6208                &self.device,
6209                bytemuck::cast_slice(vertices),
6210            ),
6211            indices: recorder.upload_buffer(
6212                image_index_spec(),
6213                &self.device,
6214                bytemuck::cast_slice(indices),
6215            ),
6216            clips: (!clips.is_empty()).then(|| {
6217                recorder.upload_buffer(
6218                    UploadAllocatorSpec::vertex(
6219                        "Image Clip Buffer",
6220                        std::mem::size_of::<DeviceRoundedClip>() as u64,
6221                    ),
6222                    &self.device,
6223                    bytemuck::cast_slice(clips),
6224                )
6225            }),
6226        }
6227    }
6228
6229    pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
6230        &self,
6231        recorder: &mut C,
6232        instances: &[GlyphInstance],
6233    ) -> BufferUpload {
6234        recorder.upload_buffer(
6235            glyph_instance_spec(),
6236            &self.device,
6237            bytemuck::cast_slice(instances),
6238        )
6239    }
6240
6241    pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
6242        &self,
6243        recorder: &mut C,
6244        glyphs: &[TurnedGlyph],
6245    ) -> BufferUpload {
6246        recorder.upload_buffer(
6247            turned_glyph_spec(),
6248            &self.device,
6249            bytemuck::cast_slice(glyphs),
6250        )
6251    }
6252
6253    fn glyph_atlas_entry_for(
6254        &mut self,
6255        glyph: &SoftwareGlyphAtlasGlyph,
6256    ) -> Result<GlyphAtlasEntry, String> {
6257        if let Some(entry) = self
6258            .text_glyph_atlas
6259            .upload_glyph(glyph, &mut self.frame_stats)
6260        {
6261            return Ok(entry);
6262        }
6263
6264        // The draws queued so far bind the full atlas: the glyphs they placed
6265        // reach it before a new atlas takes its place.
6266        self.flush_glyph_uploads();
6267        self.text_glyph_atlas.reset(
6268            &self.device,
6269            &self.image_bind_group_layout,
6270            GlyphSamplers {
6271                nearest: &self.image_nearest_sampler,
6272                linear: &self.image_linear_sampler,
6273            },
6274        );
6275        Err("text glyph atlas filled and was reset".to_string())
6276    }
6277
6278    /// Writes the glyphs the pass placed in the atlas to its texture, ahead
6279    /// of the submit that draws them.
6280    pub(crate) fn flush_glyph_uploads(&mut self) {
6281        self.text_glyph_atlas.flush_uploads(
6282            &self.queue,
6283            &mut self.frame_graph_executor,
6284            &mut self.frame_stats,
6285        );
6286    }
6287
6288    fn glyph_atlas_entry_for_cached(
6289        &mut self,
6290        glyph: &SoftwareGlyphAtlasPlacement,
6291    ) -> Option<GlyphAtlasEntry> {
6292        let entry = self
6293            .text_glyph_atlas
6294            .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
6295        self.frame_stats.record_text_glyph_atlas_hits(1);
6296        Some(entry)
6297    }
6298
6299    fn glyph_atlas_entry_for_placement(
6300        &mut self,
6301        glyph: &SoftwareGlyphAtlasPlacement,
6302    ) -> Result<GlyphAtlasEntry, String> {
6303        if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
6304            return Ok(entry);
6305        }
6306
6307        let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
6308            return Err("text glyph placement has no retained raster mask".to_string());
6309        };
6310        self.glyph_atlas_entry_for(&upload_glyph)
6311    }
6312
6313    /// The atlas entries of a run's drawing glyphs: of `cached_glyph_run`,
6314    /// which holds only those, or of the drawing glyphs of `collected_run`,
6315    /// a run just collected, whose new glyphs are uploaded here.
6316    fn prepare_text_glyph_entries(
6317        &mut self,
6318        run_key: TextGlyphRunCacheKey,
6319        atlas_generation: u64,
6320        cached_glyph_run: Option<&RunGlyphs>,
6321        collected_run: &[SoftwareGlyphAtlasRunGlyph],
6322        entries: &mut Vec<GlyphAtlasEntry>,
6323    ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
6324        entries.clear();
6325        let mut seen = RunAtlasEntries::new();
6326        if let Some(glyph_run) = cached_glyph_run {
6327            for glyph in glyph_run.iter() {
6328                entries.push(seen.entry(self, &glyph, |renderer| {
6329                    renderer.glyph_atlas_entry_for_placement(&glyph)
6330                })?);
6331            }
6332        } else {
6333            for run_glyph in collected_run {
6334                entries.push(seen.entry(
6335                    self,
6336                    &run_glyph.placement(),
6337                    |renderer| match run_glyph {
6338                        SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
6339                            renderer.glyph_atlas_entry_for_placement(placement)
6340                        }
6341                        SoftwareGlyphAtlasRunGlyph::New(glyph) => {
6342                            renderer.glyph_atlas_entry_for(glyph)
6343                        }
6344                    },
6345                )?);
6346            }
6347        }
6348
6349        let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
6350        if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
6351            cached.atlas_entries = Some(Rc::clone(&entries));
6352            cached.atlas_generation = atlas_generation;
6353        }
6354        Ok(entries)
6355    }
6356
6357    #[expect(clippy::too_many_arguments)]
6358    fn append_text_glyph_quad_run(
6359        &mut self,
6360        source_raster_rect: Rect,
6361        quads: GlyphRunQuads<'_>,
6362        (clip, cut): (Option<Rect>, Option<[f32; 4]>),
6363        viewport: ViewportUniformParams,
6364        root_scale: f32,
6365        glyph_instances: &mut GlyphInstances,
6366        record_cached_hits: bool,
6367    ) -> (GlyphQuads, GlyphExtent) {
6368        let start = glyph_instances.lens();
6369        let mut extent = GlyphExtent::EMPTY;
6370        let origin = [source_raster_rect.x, source_raster_rect.y];
6371        let bounds = quads.bounds.at(origin);
6372        let kind = if viewport.transform.is_identity()
6373            && cut.is_none_or(|edges| {
6374                bounds[0] >= edges[0]
6375                    && bounds[1] >= edges[1]
6376                    && bounds[2] <= edges[2]
6377                    && bounds[3] <= edges[3]
6378            })
6379            && quads
6380                .bounds
6381                .within_viewport(source_raster_rect, clip, viewport, root_scale)
6382        {
6383            // Every quad shows whole and uncut: they sit at whole pixels from
6384            // the run's origin, which then decides their alignment, and
6385            // their extent is the run's bounds.
6386            glyph_instances.plain.extend(quads.instances_at(origin));
6387            extent.add(bounds);
6388            GlyphQuads::plain(glyph_rect_aligned(
6389                [origin[0], origin[1], origin[0], origin[1]],
6390                viewport.offset,
6391            ))
6392        } else if viewport.transform.is_identity() {
6393            let plain = &mut glyph_instances.plain;
6394            let mut aligned = true;
6395            for_each_visible_glyph(
6396                source_raster_rect,
6397                quads,
6398                (clip, cut),
6399                viewport,
6400                root_scale,
6401                |glyph| {
6402                    aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
6403                    extent.add(glyph.rect);
6404                    plain.push(glyph);
6405                },
6406            );
6407            GlyphQuads::plain(aligned)
6408        } else {
6409            let turn = viewport.transform;
6410            let turned = &mut glyph_instances.turned;
6411            for_each_visible_glyph(
6412                source_raster_rect,
6413                quads,
6414                (clip, cut),
6415                viewport,
6416                root_scale,
6417                |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
6418            );
6419            GlyphQuads::Turned
6420        };
6421        let end = glyph_instances.lens();
6422        let appended = (end.0 - start.0) + (end.1 - start.1);
6423        if record_cached_hits {
6424            self.frame_stats
6425                .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
6426        }
6427        (kind, extent)
6428    }
6429
6430    /// The viewport a retained glyph run draws under: its vertices sit at
6431    /// its raster rect's origin, so an untransformed target moves its offset
6432    /// back by that origin, and a transformed one adds the origin to each
6433    /// vertex before its transform, as the shared path's vertices hold it.
6434    fn retained_glyph_viewport(
6435        viewport: ViewportUniformParams,
6436        source_raster_rect: Rect,
6437    ) -> ViewportUniformParams {
6438        if !viewport.transform.is_identity() {
6439            return ViewportUniformParams {
6440                origin: [source_raster_rect.x, source_raster_rect.y],
6441                ..viewport
6442            };
6443        }
6444        ViewportUniformParams {
6445            offset: [
6446                viewport.offset[0] - source_raster_rect.x,
6447                viewport.offset[1] - source_raster_rect.y,
6448            ],
6449            ..viewport
6450        }
6451    }
6452
6453    fn retained_text_glyph_run(
6454        &mut self,
6455        cache_key: TextGlyphRunCacheKey,
6456    ) -> Option<Rc<CachedGpuTextGlyphRun>> {
6457        let atlas_generation = self.text_glyph_atlas.generation();
6458        let frame = self.text_glyph_run_frame;
6459        self.text_glyph_gpu_run_cache
6460            .get(&cache_key)
6461            .filter(|cached| cached.atlas_generation == atlas_generation)
6462            .inspect(|cached| cached.last_frame.set(frame))
6463            .cloned()
6464    }
6465
6466    /// Opens a frame for text runs: runs no frame drew for
6467    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] leave the GPU cache and those no
6468    /// frame drew for [`TEXT_GLYPH_RUN_IDLE_FRAMES`] the CPU cache, and the
6469    /// arena takes back the quads dropped retained runs held.
6470    fn begin_text_glyph_run_frame(&mut self) {
6471        #[cfg(feature = "installed-fonts")]
6472        if let Some(fonts) = self.text_fonts.with_installed_faces() {
6473            // Text drawn before the install may show a missing glyph where an
6474            // installed face now has one.
6475            self.text_fonts = fonts;
6476            self.text_image_cache.clear();
6477            self.text_glyph_run_cache.clear();
6478            self.text_glyph_gpu_run_cache.clear();
6479        }
6480        self.text_glyph_run_frame += 1;
6481        let frame = self.text_glyph_run_frame;
6482        let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
6483        self.text_glyph_run_cache.set_cap(
6484            std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
6485                .unwrap_or(std::num::NonZeroUsize::MIN),
6486        );
6487        evict_idle(
6488            &mut self.text_glyph_gpu_run_cache,
6489            frame,
6490            TEXT_GLYPH_GPU_RUN_IDLE_FRAMES,
6491            |run| run.last_frame.get(),
6492        );
6493        evict_idle(
6494            &mut self.text_glyph_run_cache,
6495            frame,
6496            TEXT_GLYPH_RUN_IDLE_FRAMES,
6497            |run| run.last_frame.get(),
6498        );
6499        self.text_glyph_run_arena.begin_frame();
6500        let evacuating = self.text_glyph_run_arena.evacuating();
6501        if !evacuating.is_empty() {
6502            let moving: Vec<TextGlyphRunCacheKey> = self
6503                .text_glyph_gpu_run_cache
6504                .iter()
6505                .filter(|(_, run)| evacuating.contains(&run.span.chunk()))
6506                .map(|(key, _)| *key)
6507                .collect();
6508            for key in &moving {
6509                self.text_glyph_gpu_run_cache.pop(key);
6510            }
6511        }
6512    }
6513
6514    fn emit_retained_text_glyph_run_if_ready(
6515        &mut self,
6516        cache_key: TextGlyphRunCacheKey,
6517        quads: GlyphRunQuads<'_>,
6518        viewport: ViewportUniformParams,
6519        source_raster_rect: Rect,
6520        scissor: (u32, u32, u32, u32),
6521        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6522    ) -> bool {
6523        let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
6524            if self.ensure_retained_text_glyph_run(cache_key, quads) {
6525                self.retained_text_glyph_run(cache_key)
6526            } else {
6527                None
6528            }
6529        }) else {
6530            return false;
6531        };
6532        let uniform_slot =
6533            self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
6534        self.frame_stats
6535            .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
6536        // The run's quads sit at whole texels from its raster origin.
6537        let aligned = viewport.transform.is_identity()
6538            && glyph_rect_aligned(
6539                [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
6540                [viewport.offset[0], viewport.offset[1]],
6541            );
6542        glyph_cmds.push(GlyphDrawCmd::retained(
6543            (run, uniform_slot, aligned),
6544            scissor,
6545            self.text_glyph_atlas.bind_group(viewport.transform),
6546        ));
6547        true
6548    }
6549
6550    fn ensure_retained_text_glyph_run(
6551        &mut self,
6552        cache_key: TextGlyphRunCacheKey,
6553        quads: GlyphRunQuads<'_>,
6554    ) -> bool {
6555        let atlas_generation = self.text_glyph_atlas.generation();
6556        if self
6557            .text_glyph_gpu_run_cache
6558            .peek(&cache_key)
6559            .is_some_and(|cached| cached.atlas_generation == atlas_generation)
6560        {
6561            return true;
6562        }
6563
6564        let Some(span) = self
6565            .text_glyph_run_arena
6566            .insert(&self.device, quads.instances_at([0.0, 0.0]))
6567        else {
6568            return false;
6569        };
6570        self.text_glyph_gpu_run_cache.put(
6571            cache_key,
6572            Rc::new(CachedGpuTextGlyphRun {
6573                span,
6574                atlas_generation,
6575                last_frame: Cell::new(self.text_glyph_run_frame),
6576            }),
6577        );
6578        true
6579    }
6580    /// Appends the glyph atlas draws of `text_draw`, whose logical geometry
6581    /// `logical` the caller found drawing into a rect `viewport` shows.
6582    /// `false` when the text cannot draw from the atlas (animated motion, or
6583    /// a run the atlas cannot hold): nothing was appended, and the caller
6584    /// draws the text as a rasterized image instead.
6585    pub(crate) fn append_text_glyph_draws(
6586        &mut self,
6587        (text_draw, logical): (&TextDraw, (Rect, f32)),
6588        viewport: ViewportUniformParams,
6589        root_scale: f32,
6590        glyph_instances: &mut GlyphInstances,
6591        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6592    ) -> bool {
6593        let (_, raster_rect, _, text_scale, static_text_motion) =
6594            text_raster_geometry_at(text_draw, logical, root_scale);
6595        if !static_text_motion {
6596            return false;
6597        }
6598        let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
6599        let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
6600        let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
6601        let initial_instance_len = glyph_instances.lens();
6602        let initial_cmd_len = glyph_cmds.len();
6603        let drew = self
6604            .text_glyph_run(
6605                text_draw,
6606                raster_rect,
6607                text_scale,
6608                run_key,
6609                &mut collected_run,
6610            )
6611            .is_some_and(|run| {
6612                self.append_text_glyph_run(
6613                    TextGlyphRunDraw {
6614                        text_draw,
6615                        raster_rect,
6616                        run_key,
6617                        run,
6618                    },
6619                    (viewport, root_scale),
6620                    (&collected_run, &mut generated_entries),
6621                    glyph_instances,
6622                    glyph_cmds,
6623                )
6624            });
6625        self.scratch_text_glyph_run = collected_run;
6626        self.scratch_text_glyph_entries = generated_entries;
6627        if !drew {
6628            glyph_instances.truncate(initial_instance_len);
6629            glyph_cmds.truncate(initial_cmd_len);
6630        }
6631        drew
6632    }
6633
6634    /// The run of `text_draw` from the cache, or collected into
6635    /// `collected_run` and cached; `None` when the text cannot draw from the
6636    /// atlas.
6637    fn text_glyph_run(
6638        &mut self,
6639        text_draw: &TextDraw,
6640        raster_rect: Rect,
6641        text_scale: f32,
6642        run_key: TextGlyphRunCacheKey,
6643        collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
6644    ) -> Option<TextGlyphRunLookup> {
6645        let atlas_generation = self.text_glyph_atlas.generation();
6646        let frame = self.text_glyph_run_frame;
6647        self.text_glyph_runs_drawn += 1;
6648        if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
6649            cached.last_frame.set(frame);
6650            return Some(TextGlyphRunLookup {
6651                glyphs: cached.glyphs.clone(),
6652                bounds: cached.bounds,
6653                cached: true,
6654                entries: (cached.atlas_generation == atlas_generation)
6655                    .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
6656                    .flatten(),
6657            });
6658        }
6659        collected_run.clear();
6660        if collect_solid_text_atlas_run(
6661            text_draw.text.string().as_ref(),
6662            raster_rect,
6663            &text_draw.text_style,
6664            text_draw.color,
6665            text_draw.font_size,
6666            text_scale,
6667            &self.text_fonts,
6668            &mut self.text_glyph_mask_cache,
6669            collected_run,
6670        )
6671        .is_none()
6672        {
6673            log_text_atlas_fallback(text_draw);
6674            return None;
6675        }
6676        let Some(glyphs) = RunGlyphs::of(
6677            collected_run
6678                .iter()
6679                .map(SoftwareGlyphAtlasRunGlyph::placement),
6680            &mut self.run_glyph_scratch,
6681        ) else {
6682            log_text_atlas_fallback(text_draw);
6683            return None;
6684        };
6685        let bounds = GlyphRunBounds::of(glyphs.iter());
6686        self.frame_stats.record_text_glyph_run_collected();
6687        // A run this frame drew stays: the cache grows rather than evict it.
6688        let cache = &mut self.text_glyph_run_cache;
6689        if cache.len() == cache.cap().get()
6690            && cache
6691                .peek_lru()
6692                .is_some_and(|(_, run)| run.last_frame.get() == frame)
6693        {
6694            cache.set_cap(cache.cap().saturating_add(cache.len()));
6695        }
6696        self.text_glyph_run_cache.put(
6697            run_key,
6698            CachedTextGlyphRun {
6699                glyphs: glyphs.clone(),
6700                bounds,
6701                atlas_entries: None,
6702                atlas_generation: 0,
6703                last_frame: Cell::new(frame),
6704            },
6705        );
6706        Some(TextGlyphRunLookup {
6707            glyphs,
6708            bounds,
6709            cached: false,
6710            entries: None,
6711        })
6712    }
6713
6714    /// Appends the draws of a text's run: its retained quads when it has
6715    /// them, else its visible quads into the frame's shared glyphs. `false`
6716    /// when the atlas cannot hold its glyphs.
6717    fn append_text_glyph_run(
6718        &mut self,
6719        draw: TextGlyphRunDraw<'_>,
6720        (viewport, root_scale): (ViewportUniformParams, f32),
6721        (collected_run, generated_entries): (
6722            &[SoftwareGlyphAtlasRunGlyph],
6723            &mut Vec<GlyphAtlasEntry>,
6724        ),
6725        glyph_instances: &mut GlyphInstances,
6726        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6727    ) -> bool {
6728        let TextGlyphRunDraw {
6729            text_draw,
6730            raster_rect,
6731            run_key,
6732            run,
6733        } = draw;
6734        let draw_rect = Rect {
6735            x: raster_rect.x / root_scale,
6736            y: raster_rect.y / root_scale,
6737            width: raster_rect.width / root_scale,
6738            height: raster_rect.height / root_scale,
6739        };
6740        let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
6741        else {
6742            return true;
6743        };
6744        let texel = self.text_glyph_atlas.texel();
6745
6746        // A retained run's quads are uploaded whole: under a turn only the
6747        // shared path cuts them to a clip.
6748        let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
6749        if let Some(entries) = run.entries.as_ref()
6750            && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
6751            && !clip_needs_cut
6752            && self.emit_retained_text_glyph_run_if_ready(
6753                run_key,
6754                GlyphRunQuads {
6755                    glyphs: &run.glyphs,
6756                    entries,
6757                    texel,
6758                    bounds: run.bounds,
6759                },
6760                viewport,
6761                raster_rect,
6762                scissor,
6763                glyph_cmds,
6764            )
6765        {
6766            return true;
6767        }
6768
6769        let turned = !viewport.transform.is_identity();
6770        let instance_start = glyph_instances.len_of(turned);
6771        let (entries, entries_cached) = match run.entries {
6772            Some(entries) => (entries, true),
6773            None => {
6774                let Ok(entries) = self.prepare_text_glyph_entries(
6775                    run_key,
6776                    self.text_glyph_atlas.generation(),
6777                    run.cached.then_some(&run.glyphs),
6778                    collected_run,
6779                    generated_entries,
6780                ) else {
6781                    return false;
6782                };
6783                (entries, false)
6784            }
6785        };
6786        let quads = GlyphRunQuads {
6787            glyphs: &run.glyphs,
6788            entries: &entries,
6789            texel: self.text_glyph_atlas.texel(),
6790            bounds: run.bounds,
6791        };
6792        let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
6793        let (kind, extent) = self.append_text_glyph_quad_run(
6794            raster_rect,
6795            quads,
6796            (text_draw.clip, cut),
6797            viewport,
6798            root_scale,
6799            glyph_instances,
6800            entries_cached,
6801        );
6802        let instance_end = glyph_instances.len_of(turned);
6803        if instance_end > instance_start {
6804            let (clip, bounds) = if turned {
6805                (None, scissor)
6806            } else {
6807                shared_glyph_clip(extent, scissor, viewport)
6808            };
6809            glyph_cmds.push(GlyphDrawCmd::shared(
6810                (instance_start..instance_end, kind),
6811                clip,
6812                bounds,
6813                self.text_glyph_atlas.bind_group(viewport.transform),
6814            ));
6815        }
6816        true
6817    }
6818
6819    #[expect(clippy::too_many_arguments)]
6820    fn append_image_bitmap_draw_cmd(
6821        &mut self,
6822        image: &ImageBitmap,
6823        rect: Rect,
6824        clip: Option<Rect>,
6825        sampling: ImageSampling,
6826        viewport: ViewportUniformParams,
6827        root_scale: f32,
6828        image_vertices: &mut Vec<Vertex>,
6829        image_indices: &mut Vec<u32>,
6830        image_cmds: &mut Vec<ImageDrawCmd>,
6831    ) -> Result<(), String> {
6832        if rect.width <= 0.0 || rect.height <= 0.0 {
6833            return Ok(());
6834        }
6835
6836        let (device_quad, scissor_rect) =
6837            if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
6838                let left_px = (rect.x * root_scale).round();
6839                let top_px = (rect.y * root_scale).round();
6840                let width_px = (rect.width * root_scale).round().max(1.0);
6841                let height_px = (rect.height * root_scale).round().max(1.0);
6842                let snapped_rect = Rect {
6843                    x: left_px / root_scale,
6844                    y: top_px / root_scale,
6845                    width: width_px / root_scale,
6846                    height: height_px / root_scale,
6847                };
6848                let right_px = left_px + width_px;
6849                let bottom_px = top_px + height_px;
6850                (
6851                    [
6852                        [left_px, top_px],
6853                        [right_px, top_px],
6854                        [left_px, bottom_px],
6855                        [right_px, bottom_px],
6856                    ],
6857                    snapped_rect,
6858                )
6859            } else {
6860                (
6861                    rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
6862                    rect,
6863                )
6864            };
6865
6866        let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
6867            return Ok(());
6868        };
6869        let Some(uv_rect) = image_uv_rect(image, None) else {
6870            return Ok(());
6871        };
6872
6873        let index_start = push_image_quad(
6874            (image_vertices, image_indices),
6875            device_quad,
6876            [1.0, 1.0, 1.0, 1.0],
6877            &uv_rect,
6878        );
6879        image_cmds.push(ImageDrawCmd {
6880            index_start,
6881            scissor,
6882            image: self.image_binding(image, sampling)?,
6883            clip: None,
6884        });
6885        Ok(())
6886    }
6887
6888    /// Appends `text_draw` as a rasterized image if `viewport` shows it.
6889    pub(crate) fn append_text_image_draw_cmds(
6890        &mut self,
6891        text_draw: &TextDraw,
6892        viewport: ViewportUniformParams,
6893        root_scale: f32,
6894        image_vertices: &mut Vec<Vertex>,
6895        image_indices: &mut Vec<u32>,
6896        image_cmds: &mut Vec<ImageDrawCmd>,
6897    ) -> Result<(), String> {
6898        let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
6899            self.text_raster_geometry(text_draw, root_scale)
6900        else {
6901            return Ok(());
6902        };
6903        if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
6904            return Ok(());
6905        }
6906
6907        let raster_source = self.text_image_raster_source(
6908            text_draw,
6909            logical_rect,
6910            raster_rect,
6911            clip,
6912            root_scale,
6913            static_text_motion,
6914        );
6915        let source_draw = raster_source.draw.as_ref();
6916        let source_raster_rect = raster_source.raster_rect;
6917        let source_origin = if source_draw.text.string().span_styles().is_empty() {
6918            Point::new(source_raster_rect.x, source_raster_rect.y)
6919        } else {
6920            Point::new(raster_rect.x, raster_rect.y)
6921        };
6922
6923        let mut cache_key = Self::text_image_cache_key(
6924            source_draw,
6925            source_raster_rect,
6926            text_scale,
6927            static_text_motion,
6928        );
6929        if !source_draw.text.string().span_styles().is_empty() {
6930            let mut state = default_hash::new();
6931            cache_key.0.hash(&mut state);
6932            (source_origin.x - source_raster_rect.x)
6933                .to_bits()
6934                .hash(&mut state);
6935            (source_origin.y - source_raster_rect.y)
6936                .to_bits()
6937                .hash(&mut state);
6938            cache_key = TextImageCacheKey(state.finish());
6939        }
6940        let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
6941            self.frame_stats
6942                .record_text_image_cache_hit(cached.image.width(), cached.image.height());
6943            cached.image.clone()
6944        } else {
6945            let Some(image) = self.rasterize_text_draw_to_image(
6946                source_draw,
6947                source_raster_rect,
6948                source_origin,
6949                text_scale,
6950            ) else {
6951                return Ok(());
6952            };
6953            self.frame_stats
6954                .record_text_image_cache_miss(image.width(), image.height());
6955            self.text_image_cache.put(
6956                cache_key,
6957                CachedTextImage {
6958                    image: image.clone(),
6959                },
6960            );
6961            image
6962        };
6963
6964        let draw_origin = if static_text_motion {
6965            Point::new(
6966                source_raster_rect.x / root_scale,
6967                source_raster_rect.y / root_scale,
6968            )
6969        } else {
6970            Point::new(logical_rect.x, logical_rect.y)
6971        };
6972        let draw_rect = Rect {
6973            x: draw_origin.x,
6974            y: draw_origin.y,
6975            width: image.width() as f32 / root_scale,
6976            height: image.height() as f32 / root_scale,
6977        };
6978        self.append_image_bitmap_draw_cmd(
6979            &image,
6980            draw_rect,
6981            clip,
6982            sampling_under(ImageSampling::Nearest, viewport.transform),
6983            viewport,
6984            root_scale,
6985            image_vertices,
6986            image_indices,
6987            image_cmds,
6988        )
6989    }
6990
6991    fn text_image_raster_source<'a>(
6992        &mut self,
6993        text_draw: &'a TextDraw,
6994        logical_rect: Rect,
6995        raster_rect: Rect,
6996        clip: Option<Rect>,
6997        root_scale: f32,
6998        static_text_motion: bool,
6999    ) -> TextRasterSource<'a> {
7000        let Some(clip) = clip else {
7001            return TextRasterSource {
7002                draw: Cow::Borrowed(text_draw),
7003                raster_rect,
7004            };
7005        };
7006        if !static_text_motion || text_draw.text.string().text().find('\n').is_none() {
7007            return TextRasterSource {
7008                draw: Cow::Borrowed(text_draw),
7009                raster_rect,
7010            };
7011        }
7012
7013        if !text_draw.text.string().span_styles().is_empty() {
7014            let device_clip = Rect {
7015                x: (clip.x * root_scale).floor(),
7016                y: (clip.y * root_scale).floor(),
7017                width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
7018                height: ((clip.y + clip.height) * root_scale).ceil()
7019                    - (clip.y * root_scale).floor(),
7020            };
7021            return TextRasterSource {
7022                draw: Cow::Borrowed(text_draw),
7023                raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
7024            };
7025        }
7026
7027        let line_starts = self
7028            .text_line_index_cache
7029            .line_starts(text_draw.text.string());
7030        clipped_text_raster_source_with_line_starts(
7031            text_draw,
7032            logical_rect,
7033            raster_rect,
7034            clip,
7035            root_scale,
7036            line_starts.as_ref(),
7037        )
7038    }
7039
7040    fn text_raster_geometry(
7041        &self,
7042        text_draw: &TextDraw,
7043        root_scale: f32,
7044    ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
7045        text_raster_geometry_for_draw(text_draw, root_scale)
7046    }
7047
7048    fn text_image_cache_key(
7049        text_draw: &TextDraw,
7050        raster_rect: Rect,
7051        text_scale: f32,
7052        static_text_motion: bool,
7053    ) -> TextImageCacheKey {
7054        let mut state = default_hash::new();
7055        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7056        hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
7057        TextImageCacheKey(state.finish())
7058    }
7059
7060    /// The key of a static text's glyph run. A run places its glyphs from
7061    /// the text's origin and aligns its lines within the text block, so the
7062    /// size of the rect it draws in does not change it: only an empty rect,
7063    /// which draws nothing, does.
7064    fn text_glyph_run_cache_key(
7065        text_draw: &TextDraw,
7066        raster_rect: Rect,
7067        text_scale: f32,
7068    ) -> TextGlyphRunCacheKey {
7069        let mut state = default_hash::new();
7070        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7071        (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
7072        TextGlyphRunCacheKey(state.finish())
7073    }
7074
7075    fn rasterize_text_draw_to_image(
7076        &mut self,
7077        text_draw: &TextDraw,
7078        raster_rect: Rect,
7079        source_origin: Point,
7080        text_scale: f32,
7081    ) -> Option<ImageBitmap> {
7082        rasterize_annotated_text_region(
7083            text_draw.text.string().as_ref(),
7084            raster_rect,
7085            if text_draw.text.string().span_styles().is_empty() {
7086                Point::new(raster_rect.x, raster_rect.y)
7087            } else {
7088                source_origin
7089            },
7090            &text_draw.text_style,
7091            text_draw.color,
7092            text_draw.font_size,
7093            text_scale,
7094            &self.text_fonts,
7095            Some(&mut self.text_glyph_mask_cache),
7096        )
7097    }
7098}
7099
7100struct TextRasterSource<'a> {
7101    draw: Cow<'a, TextDraw>,
7102    raster_rect: Rect,
7103}
7104
7105fn clipped_text_raster_source_with_line_starts<'a>(
7106    text_draw: &'a TextDraw,
7107    logical_rect: Rect,
7108    raster_rect: Rect,
7109    clip: Rect,
7110    root_scale: f32,
7111    line_starts: &[usize],
7112) -> TextRasterSource<'a> {
7113    if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
7114        return TextRasterSource {
7115            draw: Cow::Borrowed(text_draw),
7116            raster_rect,
7117        };
7118    }
7119
7120    let Some(visible_rect) = logical_rect.intersect(clip) else {
7121        return TextRasterSource {
7122            draw: Cow::Borrowed(text_draw),
7123            raster_rect,
7124        };
7125    };
7126
7127    let line_count = line_starts.len().max(1);
7128    let line_height = logical_rect.height / line_count as f32;
7129    if !line_height.is_finite() || line_height <= 0.0 {
7130        return TextRasterSource {
7131            draw: Cow::Borrowed(text_draw),
7132            raster_rect,
7133        };
7134    }
7135
7136    let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
7137    let visible_bottom =
7138        ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
7139    let start_line = visible_top.saturating_sub(1).max(0) as usize;
7140    let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
7141    let end_line = end_line.min(line_count);
7142    if start_line == 0 && end_line >= line_count {
7143        return TextRasterSource {
7144            draw: Cow::Borrowed(text_draw),
7145            raster_rect,
7146        };
7147    }
7148
7149    let byte_start = line_starts[start_line];
7150    let byte_end = line_end_offset(text_draw.text.string().text(), line_starts, end_line - 1);
7151    if byte_start >= byte_end {
7152        return TextRasterSource {
7153            draw: Cow::Borrowed(text_draw),
7154            raster_rect,
7155        };
7156    }
7157
7158    let slice_y = logical_rect.y + start_line as f32 * line_height;
7159    let slice_height = (end_line - start_line) as f32 * line_height;
7160    let mut slice_raster_rect = Rect {
7161        x: logical_rect.x * root_scale,
7162        y: slice_y * root_scale,
7163        width: logical_rect.width * root_scale,
7164        height: slice_height * root_scale,
7165    };
7166    slice_raster_rect.x = slice_raster_rect.x.round();
7167    slice_raster_rect.y = slice_raster_rect.y.round();
7168    slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
7169    slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
7170
7171    let mut sliced_draw = text_draw.clone();
7172    sliced_draw.rect = Rect {
7173        x: logical_rect.x,
7174        y: slice_y,
7175        width: logical_rect.width,
7176        height: slice_height,
7177    };
7178    sliced_draw.text = DrawnText::of(
7179        Arc::new(text_draw.text.string().subsequence(byte_start..byte_end)),
7180        &text_draw.text_style,
7181    );
7182
7183    TextRasterSource {
7184        draw: Cow::Owned(sliced_draw),
7185        raster_rect: slice_raster_rect,
7186    }
7187}
7188
7189fn line_start_offsets(text: &str) -> Vec<usize> {
7190    let mut starts =
7191        Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
7192    starts.push(0);
7193    starts.extend(
7194        text.char_indices()
7195            .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
7196    );
7197    starts
7198}
7199
7200fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
7201    line_starts.get(line + 1).copied().unwrap_or(text.len())
7202}
7203
7204fn align_to(value: u32, alignment: u32) -> u32 {
7205    debug_assert!(alignment > 0);
7206    value.div_ceil(alignment) * alignment
7207}
7208
7209impl GpuRenderer {
7210    fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
7211        if !pixels.len().is_multiple_of(4) {
7212            return Err("Screenshot readback has an incomplete pixel".to_string());
7213        }
7214        Ok(pixels.to_vec())
7215    }
7216}
7217
7218/// The scissor of a logical rect in a target whose origin sits at
7219/// `viewport.offset` of the scene's device space, clamped to the target.
7220/// `None` when nothing of the rect lands in the target.
7221pub(crate) fn scissor_rect_for_rect(
7222    rect: Rect,
7223    root_scale: f32,
7224    viewport: ViewportUniformParams,
7225) -> Option<(u32, u32, u32, u32)> {
7226    let width = viewport.width as f32;
7227    let height = viewport.height as f32;
7228    let mut left = canonicalize_device_coordinate(rect.x * root_scale);
7229    let mut top = canonicalize_device_coordinate(rect.y * root_scale);
7230    let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
7231    let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
7232    if !viewport.transform.is_identity() {
7233        let bounds = viewport.transform.target_bounds(Rect {
7234            x: left,
7235            y: top,
7236            width: right - left,
7237            height: bottom - top,
7238        });
7239        (left, top) = (bounds.x, bounds.y);
7240        (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
7241    }
7242    let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
7243    let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
7244    let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
7245    let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
7246    if right <= left || bottom <= top {
7247        return None;
7248    }
7249    Some((
7250        left as u32,
7251        top as u32,
7252        (right - left) as u32,
7253        (bottom - top) as u32,
7254    ))
7255}
7256
7257fn scissor_rect_for_layer(
7258    rect: Rect,
7259    clip: Option<Rect>,
7260    root_scale: f32,
7261    viewport: ViewportUniformParams,
7262) -> Option<(u32, u32, u32, u32)> {
7263    let clipped_rect = match clip {
7264        Some(clip_rect) => rect.intersect(clip_rect)?,
7265        None => rect,
7266    };
7267    scissor_rect_for_rect(clipped_rect, root_scale, viewport)
7268}
7269fn tint_for_image(
7270    color_filter: Option<ColorFilter>,
7271    alpha: f32,
7272) -> ([f32; 4], Option<ColorFilter>) {
7273    let alpha = alpha.clamp(0.0, 1.0);
7274    match color_filter {
7275        Some(filter) if filter.supports_gpu_vertex_modulation() => {
7276            let Some(tint) = filter.gpu_vertex_tint() else {
7277                return ([1.0, 1.0, 1.0, alpha], Some(filter));
7278            };
7279            (
7280                [
7281                    tint[0].clamp(0.0, 1.0),
7282                    tint[1].clamp(0.0, 1.0),
7283                    tint[2].clamp(0.0, 1.0),
7284                    (tint[3] * alpha).clamp(0.0, 1.0),
7285                ],
7286                None,
7287            )
7288        }
7289        Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
7290        None => ([1.0, 1.0, 1.0, alpha], None),
7291    }
7292}
7293
7294/// The rounded clip an image takes in place, in device pixels: one instance
7295/// its draw reads, beside the quad's vertices.
7296#[repr(C)]
7297#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7298pub(crate) struct DeviceRoundedClip {
7299    rect: [f32; 4],
7300    radius: f32,
7301}
7302
7303impl DeviceRoundedClip {
7304    const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
7305        4 => Float32x4,
7306        5 => Float32,
7307    ];
7308
7309    fn desc() -> wgpu::VertexBufferLayout<'static> {
7310        wgpu::VertexBufferLayout {
7311            array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
7312            step_mode: wgpu::VertexStepMode::Instance,
7313            attributes: &Self::ATTRIBS,
7314        }
7315    }
7316
7317    /// The rounded clip `image` takes at `root_scale`, scaled as a run's
7318    /// placement scales its clip.
7319    fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
7320        let rounding = image.rounding.filter(|_| image.clip.is_some())?;
7321        let device =
7322            crate::geometry::device_rect(rounding.rect, root_scale, image.snap_anchor.is_some());
7323        Some(Self {
7324            rect: [device.x, device.y, device.width, device.height],
7325            radius: rounding.radius * root_scale,
7326        })
7327    }
7328}
7329
7330/// Appends an image quad over `device_quad` and its two triangles, and
7331/// returns the index its triangles start at.
7332fn push_image_quad(
7333    (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
7334    device_quad: [[f32; 2]; 4],
7335    color: [f32; 4],
7336    uv_rect: &ImageUvRect,
7337) -> u32 {
7338    let base_vertex = vertices.len() as u32;
7339    let index_start = indices.len() as u32;
7340    indices.extend_from_slice(&[
7341        base_vertex,
7342        base_vertex + 1,
7343        base_vertex + 2,
7344        base_vertex + 2,
7345        base_vertex + 1,
7346        base_vertex + 3,
7347    ]);
7348    let corners = [
7349        [uv_rect.min[0], uv_rect.min[1]],
7350        [uv_rect.max[0], uv_rect.min[1]],
7351        [uv_rect.min[0], uv_rect.max[1]],
7352        [uv_rect.max[0], uv_rect.max[1]],
7353    ];
7354    vertices.extend(
7355        device_quad
7356            .into_iter()
7357            .zip(corners)
7358            .map(|(position, uv)| Vertex {
7359                position,
7360                color,
7361                uv,
7362                uv_bounds: uv_rect.sample_bounds,
7363            }),
7364    );
7365    index_start
7366}
7367
7368fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
7369    let Some(src) = src_rect else {
7370        return Some(ImageUvRect {
7371            min: [0.0, 0.0],
7372            max: [1.0, 1.0],
7373            sample_bounds: [0.0, 0.0, 1.0, 1.0],
7374        });
7375    };
7376
7377    let (u_min, u_max, u_bound_min, u_bound_max) =
7378        source_axis_uv(src.x, src.width, image.width() as f32)?;
7379    let (v_min, v_max, v_bound_min, v_bound_max) =
7380        source_axis_uv(src.y, src.height, image.height() as f32)?;
7381
7382    Some(ImageUvRect {
7383        min: [u_min, v_min],
7384        max: [u_max, v_max],
7385        sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
7386    })
7387}
7388
7389/// `entry`'s rect in an atlas whose texel is `texel` of its side, an
7390/// exact power of two: the products are the quotients by the side.
7391fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, texel: f32) -> ImageUvRect {
7392    let min = [entry.x as f32 * texel, entry.y as f32 * texel];
7393    let max = [
7394        (entry.x + entry.width) as f32 * texel,
7395        (entry.y + entry.height) as f32 * texel,
7396    ];
7397    let center_min = [
7398        (entry.x as f32 + 0.5) * texel,
7399        (entry.y as f32 + 0.5) * texel,
7400    ];
7401    let center_max = [
7402        (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) * texel,
7403        (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) * texel,
7404    ];
7405    ImageUvRect {
7406        min,
7407        max,
7408        sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
7409    }
7410}
7411
7412#[derive(Clone, Copy)]
7413pub(crate) struct ResolvedImageGeometry {
7414    pub(crate) rect: Rect,
7415    pub(crate) clip: Option<Rect>,
7416    pub(crate) sampling: ImageSampling,
7417    quad: [[f32; 2]; 4],
7418    snap_anchored: bool,
7419}
7420
7421pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
7422    let snap_delta = image
7423        .snap_anchor
7424        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
7425        .unwrap_or_default();
7426    resolve_image_geometry_with_delta(image, root_scale, snap_delta)
7427}
7428
7429fn resolve_image_geometry_with_delta(
7430    image: &ImageDraw,
7431    root_scale: f32,
7432    snap_delta: Point,
7433) -> ResolvedImageGeometry {
7434    let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
7435    let mut quad = translate_quad(image.quad, snap_delta);
7436    snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
7437    ResolvedImageGeometry {
7438        rect,
7439        clip: image.clip,
7440        sampling: image.sampling,
7441        quad,
7442        snap_anchored: image.snap_anchor.is_some(),
7443    }
7444}
7445
7446impl ResolvedImageGeometry {
7447    pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
7448        nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
7449            if self.snap_anchored {
7450                canonicalized_scaled_quad(self.quad, root_scale)
7451            } else {
7452                scaled_quad(self.quad, root_scale)
7453            }
7454        })
7455    }
7456}
7457
7458fn snap_nearest_image_to_device_pixels(
7459    sampling: ImageSampling,
7460    rect: &mut Rect,
7461    quad: &mut [[f32; 2]; 4],
7462    root_scale: f32,
7463) {
7464    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7465        return;
7466    }
7467
7468    let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
7469        return;
7470    };
7471
7472    let left_px = (quad_rect.x * root_scale).round();
7473    let top_px = (quad_rect.y * root_scale).round();
7474    let width_px = (quad_rect.width * root_scale).round().max(1.0);
7475    let height_px = (quad_rect.height * root_scale).round().max(1.0);
7476    let snapped = Rect {
7477        x: left_px / root_scale,
7478        y: top_px / root_scale,
7479        width: width_px / root_scale,
7480        height: height_px / root_scale,
7481    };
7482
7483    *rect = snapped;
7484    *quad = crate::rect_to_quad(snapped);
7485}
7486
7487fn nearest_image_device_quad(
7488    sampling: ImageSampling,
7489    quad: [[f32; 2]; 4],
7490    root_scale: f32,
7491) -> Option<[[f32; 2]; 4]> {
7492    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7493        return None;
7494    }
7495
7496    let rect = axis_aligned_quad_rect(quad)?;
7497    let left_px = (rect.x * root_scale).round();
7498    let top_px = (rect.y * root_scale).round();
7499    let width_px = (rect.width * root_scale).round().max(1.0);
7500    let height_px = (rect.height * root_scale).round().max(1.0);
7501    let right_px = left_px + width_px;
7502    let bottom_px = top_px + height_px;
7503    Some([
7504        [left_px, top_px],
7505        [right_px, top_px],
7506        [left_px, bottom_px],
7507        [right_px, bottom_px],
7508    ])
7509}
7510
7511fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
7512    if !start.is_finite()
7513        || !extent.is_finite()
7514        || !image_extent.is_finite()
7515        || extent == 0.0
7516        || image_extent <= 0.0
7517    {
7518        return None;
7519    }
7520
7521    let end = start + extent;
7522    let edge_min = start.min(end).clamp(0.0, image_extent);
7523    let edge_max = start.max(end).clamp(0.0, image_extent);
7524    if edge_max <= edge_min {
7525        return None;
7526    }
7527
7528    let center_min = edge_min + 0.5;
7529    let center_max = edge_max - 0.5;
7530    let (bound_min, bound_max) = if center_min <= center_max {
7531        (center_min, center_max)
7532    } else {
7533        let center = (edge_min + edge_max) * 0.5;
7534        (center, center)
7535    };
7536
7537    Some((
7538        edge_min / image_extent,
7539        edge_max / image_extent,
7540        bound_min / image_extent,
7541        bound_max / image_extent,
7542    ))
7543}
7544
7545fn apply_filter_to_bitmap(image: &ImageBitmap, filter: ColorFilter) -> Result<ImageBitmap, String> {
7546    let pixel_count = image.width() as usize * image.height() as usize;
7547    let mut filtered = Vec::with_capacity(pixel_count * 4);
7548    for index in 0..pixel_count {
7549        let pixel = image.rgba8_pixel(index);
7550        let rgba = [
7551            pixel[0] as f32 / 255.0,
7552            pixel[1] as f32 / 255.0,
7553            pixel[2] as f32 / 255.0,
7554            pixel[3] as f32 / 255.0,
7555        ];
7556        let out = filter.apply_rgba(rgba);
7557        filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
7558        filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
7559        filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
7560        filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
7561    }
7562    ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
7563        .map_err(|error| format!("failed to build filtered bitmap: {error}"))
7564}
7565
7566/// How a text raster samples its texels under a segment transform: as it
7567/// asks on the pixel grid, and filtered once a transform turns it off the
7568/// grid, where no texel lands on a pixel for nearest sampling to keep.
7569fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
7570    if transform.is_identity() {
7571        sampling
7572    } else {
7573        ImageSampling::Linear
7574    }
7575}
7576
7577/// The rounded mask a shadow's composite applies, in the scene's device
7578/// pixels: an inner shadow masks itself to its fill shape, and a shadow
7579/// lowered out of a clipped layer masks itself to that layer's rounded clip.
7580pub(crate) fn shadow_composite_mask(
7581    shadow: &ShadowDraw,
7582    snap_anchor: Option<SnapAnchor>,
7583    root_scale: f32,
7584) -> Option<RoundedCompositeMask> {
7585    inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
7586        shadow.rounded_clip.map(|clip| RoundedCompositeMask {
7587            rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
7588            radii: clip.radii.map(|radius| radius * root_scale),
7589        })
7590    })
7591}
7592
7593/// A scene holding just a shadow's own draws, in the order they arrive, so
7594/// the shadow source renders through the same pass encoder as everything
7595/// else.
7596fn shadow_scene(
7597    shapes: Option<&RunDraw>,
7598    texts: &[TextDraw],
7599    input_margin: f32,
7600) -> CompositorScene {
7601    let mut scene = CompositorScene::new();
7602    if let Some(run) = shapes {
7603        scene.push_run(run.clone());
7604    }
7605    for text in texts {
7606        let z_index = scene.next_z();
7607        scene.draw_ops.push(DrawOp {
7608            z_index,
7609            kind: DrawOpKind::Text(scene.texts.len()),
7610        });
7611        let mut source_text = text.clone();
7612        source_text.clip = source_text
7613            .clip
7614            .map(|clip| expand_rect(clip, input_margin, input_margin));
7615        scene.texts.push(source_text);
7616        scene.next_z += 1;
7617    }
7618    scene
7619}
7620
7621/// The whole device pixels a logical rect covers, or `None` when it covers
7622/// none or more than a texture can hold.
7623fn device_pixel_bounds(
7624    rect: Rect,
7625    root_scale: f32,
7626    max_texture_dim: u32,
7627) -> Option<DevicePixelBounds> {
7628    let x = (rect.x * root_scale).floor();
7629    let y = (rect.y * root_scale).floor();
7630    let right = ((rect.x + rect.width) * root_scale).ceil();
7631    let bottom = ((rect.y + rect.height) * root_scale).ceil();
7632    let width = (right - x).max(0.0) as u32;
7633    let height = (bottom - y).max(0.0) as u32;
7634    if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
7635        return None;
7636    }
7637    Some(DevicePixelBounds {
7638        x,
7639        y,
7640        width,
7641        height,
7642    })
7643}
7644fn inner_shadow_composite_mask(
7645    shadow: &ShadowDraw,
7646    root_scale: f32,
7647) -> Option<RoundedCompositeMask> {
7648    let run = shadow.shapes.as_ref()?;
7649    if !run
7650        .tables()
7651        .shapes
7652        .iter()
7653        .any(|record| record.blend_mode() == BlendMode::DstOut)
7654    {
7655        return None;
7656    }
7657    let fill = run.tables().shapes.get(0)?;
7658    let rect = run.placement.translated_bounds(fill.stored_rect());
7659    if rect.width <= 0.0 || rect.height <= 0.0 {
7660        return None;
7661    }
7662    let resolved =
7663        cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
7664            top_left: fill.radii[0],
7665            top_right: fill.radii[1],
7666            bottom_right: fill.radii[2],
7667            bottom_left: fill.radii[3],
7668        })
7669        .resolve(rect.width, rect.height);
7670    let radii = [
7671        resolved.top_left * root_scale,
7672        resolved.top_right * root_scale,
7673        resolved.bottom_left * root_scale,
7674        resolved.bottom_right * root_scale,
7675    ];
7676
7677    Some(RoundedCompositeMask {
7678        rect: mask_rect(anchored_device_rect(
7679            rect,
7680            run.placement.snap_anchor,
7681            root_scale,
7682        )),
7683        radii,
7684    })
7685}
7686
7687/// One draw call of a run batch's stage: its pipeline, the strip index
7688/// buffer it binds and the indices and records it instances.
7689#[derive(Clone, Debug, PartialEq, Eq)]
7690pub(crate) struct PlannedRunDraw {
7691    pub(crate) key: ShapePipelineKey,
7692    pub(crate) band_class: u8,
7693    pub(crate) indices: std::ops::Range<u32>,
7694    pub(crate) records: std::ops::Range<u32>,
7695}
7696
7697impl PlannedRunDraw {
7698    /// A draw of the paint, as it was recorded.
7699    fn paint(draw: &RunDrawCall) -> Self {
7700        Self {
7701            key: draw.key,
7702            band_class: draw.band_class,
7703            indices: draw.indices(),
7704            records: draw.records.clone(),
7705        }
7706    }
7707}
7708
7709/// The draw calls laying a batch's opaque interiors down: last first, so
7710/// they go down front to back, one call over each stretch of neighbouring
7711/// draws that share the interior pipeline, cut to the span from the stretch's
7712/// first draw holding an occluder to its last. The draws between ride along:
7713/// the pipeline lays any record's exact interior down and skips the rest, so
7714/// taking them costs a few vertices rather than a call, and it shades only a
7715/// record's quad, the first two triangles of every band class's pattern.
7716pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
7717    struct Stretch {
7718        key: ShapePipelineKey,
7719        start: u32,
7720        span: Option<PlannedRunDraw>,
7721    }
7722    let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
7723    let mut stretch: Option<Stretch> = None;
7724    for draw in draws.iter().rev() {
7725        let Some(key) = draw.key.interior() else {
7726            planned.extend(stretch.take().and_then(|open| open.span));
7727            continue;
7728        };
7729        if stretch
7730            .as_ref()
7731            .is_some_and(|open| open.key != key || open.start != draw.records.end)
7732        {
7733            planned.extend(stretch.take().and_then(|open| open.span));
7734        }
7735        let open = stretch.get_or_insert(Stretch {
7736            key,
7737            start: draw.records.end,
7738            span: None,
7739        });
7740        open.start = draw.records.start;
7741        if !draw.occluders {
7742            continue;
7743        }
7744        match &mut open.span {
7745            Some(span) => span.records.start = draw.records.start,
7746            None => {
7747                open.span = Some(PlannedRunDraw {
7748                    key,
7749                    band_class: draw.band_class,
7750                    indices: 0..cranpose_ui_graphics::strip_indices(1),
7751                    records: draw.records.clone(),
7752                });
7753            }
7754        }
7755    }
7756    planned.extend(stretch.and_then(|open| open.span));
7757    planned
7758}
7759
7760/// Drops the entries of `cache` no frame drew for more than `idle_frames`
7761/// before `frame`: the least recently used first, which is the order they
7762/// were last drawn in.
7763fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
7764    cache: &mut BoundedLruCache<K, V>,
7765    frame: u64,
7766    idle_frames: u64,
7767    last_frame: impl Fn(&V) -> u64,
7768) {
7769    while cache
7770        .peek_lru()
7771        .is_some_and(|(_, value)| frame.saturating_sub(last_frame(value)) > idle_frames)
7772    {
7773        cache.pop_lru();
7774    }
7775}
7776
7777/// Cuts the run draws from `start` on to `window` of their records, counted
7778/// across them in order, and drops the draws left with none.
7779fn window_draws(draws: &mut Vec<RunDrawCall>, start: usize, window: &std::ops::Range<u32>) {
7780    let mut relative = 0u32;
7781    let mut kept = start;
7782    for index in start..draws.len() {
7783        let draw = &mut draws[index];
7784        let count = draw.records.end - draw.records.start;
7785        let first = relative;
7786        relative += count;
7787        let keep_start = window.start.max(first).min(first + count);
7788        let keep_end = window.end.min(first + count).max(keep_start);
7789        draw.records =
7790            draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
7791        if draw.records.start < draw.records.end {
7792            draws.swap(kept, index);
7793            kept += 1;
7794        }
7795    }
7796    draws.truncate(kept);
7797}
7798
7799#[cfg(test)]
7800#[path = "tests/render_text_bounds_tests.rs"]
7801mod text_bounds_tests;
7802
7803#[cfg(test)]
7804#[path = "tests/render_retained_glyph_tests.rs"]
7805mod retained_glyph_tests;
7806
7807#[cfg(test)]
7808#[path = "tests/frame_clear_tests.rs"]
7809mod frame_clear_tests;
7810
7811#[cfg(test)]
7812#[path = "tests/render_clip_scissor_tests.rs"]
7813mod clip_scissor_tests;
7814
7815#[cfg(test)]
7816#[path = "tests/glyph_kind_tests.rs"]
7817mod glyph_kind_tests;
7818
7819#[cfg(test)]
7820#[path = "tests/glyph_run_bounds_tests.rs"]
7821mod glyph_run_bounds_tests;
7822
7823#[cfg(test)]
7824#[path = "tests/shape_variant_tests.rs"]
7825mod shape_variant_tests;