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