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