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        self.app_shader_pipeline(kept.pipeline(variant as usize), || {
4155            crate::scene_pass::volume_pipeline_job(
4156                &self.device,
4157                self.pipeline_cache.clone(),
4158                (self.composition_format, self.adapter_backend, variant),
4159                (self.scene_pipeline_parts(), kept),
4160            )
4161        })
4162    }
4163
4164    /// The pipeline of `variant` of a shaded surface's shader a frame
4165    /// noted; `None` while it compiles, when the frame after it lands draws
4166    /// the surfaces with it, or when the shader does not build.
4167    pub(crate) fn scene_shaded_pipeline(
4168        &self,
4169        shader: &Arc<str>,
4170        variant: crate::scene_pass::ShadedVariant,
4171    ) -> Option<&wgpu::RenderPipeline> {
4172        let kept = self.scene_pass.shaded(shader)?;
4173        self.app_shader_pipeline(kept.pipeline(variant as usize), || {
4174            crate::scene_pass::shaded_pipeline_job(
4175                &self.device,
4176                self.pipeline_cache.clone(),
4177                (self.composition_format, self.adapter_backend, variant),
4178                (self.scene_pipeline_parts(), kept),
4179            )
4180        })
4181    }
4182
4183    /// One of an app shader's pipelines once built; `None` while `job`
4184    /// builds it, which the frame notes, or when the shader does not build.
4185    fn app_shader_pipeline<'p, J>(
4186        &'p self,
4187        pipeline: &'p crate::scene_pass::ShaderPipeline,
4188        job: impl FnOnce() -> J,
4189    ) -> Option<&'p wgpu::RenderPipeline>
4190    where
4191        J: FnOnce() -> Option<wgpu::RenderPipeline>
4192            + crate::pipeline_compiler::CompilerSend
4193            + 'static,
4194    {
4195        let ready = pipeline.when_ready(
4196            (
4197                &self.recorder,
4198                &self.pipeline_compiler,
4199                self.adapter_backend,
4200            ),
4201            job,
4202        );
4203        match ready {
4204            Some(built) => built.as_ref(),
4205            None => {
4206                self.note_placeholder();
4207                None
4208            }
4209        }
4210    }
4211
4212    /// The bind group layout of a scene surface's uniforms.
4213    pub(crate) fn scene_uniform_layout(&self) -> &wgpu::BindGroupLayout {
4214        &self.scene_pipeline_parts().uniform_layout
4215    }
4216
4217    /// What a scene binds in its shadow map's place when it casts none.
4218    pub(crate) fn scene_no_shadow(&self) -> &wgpu::BindGroup {
4219        &self.scene_pipeline_parts().no_shadow
4220    }
4221
4222    fn scene_pipeline_parts(&self) -> &crate::scene_pass::ScenePipelineParts {
4223        self.scene_pass.parts(
4224            &self.device,
4225            self.adapter_backend,
4226            &self.effect_renderer.effect_texture_bind_group_layout,
4227        )
4228    }
4229
4230    fn scene_surface_pipeline_job(
4231        &self,
4232        kind: crate::scene_pass::ScenePipeline,
4233    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4234        crate::scene_pass::scene_pipeline_job(
4235            &self.device,
4236            self.pipeline_cache.clone(),
4237            (self.composition_format, kind),
4238            self.scene_pipeline_parts(),
4239        )
4240    }
4241
4242    fn image_pipeline_resource(
4243        &self,
4244        blend_mode: BlendMode,
4245        variant: ImageVariant,
4246    ) -> &FixedPipeline {
4247        let pipelines = match blend_mode {
4248            BlendMode::DstOut => &self.image_pipeline_dst_out,
4249            _ => &self.image_pipeline,
4250        };
4251        &pipelines[usize::from(variant.depth)
4252            + 2 * usize::from(variant.alpha_mask)
4253            + 4 * usize::from(variant.rounded)]
4254    }
4255
4256    fn image_pipeline_job(
4257        &self,
4258        blend_mode: BlendMode,
4259        variant: ImageVariant,
4260    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4261        let device = Arc::clone(&self.device);
4262        let cache = self.pipeline_cache.clone();
4263        let format = self.composition_format;
4264        let shader = self.image_shader.clone();
4265        move || {
4266            create_image_pipeline(
4267                &device,
4268                cache.as_ref(),
4269                format,
4270                &shader,
4271                blend_mode,
4272                variant,
4273            )
4274        }
4275    }
4276
4277    /// Queues the builds of the image pipelines `cmds` draw with that are
4278    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4279    /// `awaited` each still to land.
4280    pub(crate) fn prefetch_image_pipelines(
4281        &self,
4282        cmds: &[ImageDrawCmd],
4283        blend_mode: BlendMode,
4284        (depth, lane): (bool, CompileLane),
4285        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4286    ) {
4287        let mut last = None;
4288        for cmd in cmds {
4289            let variant = ImageVariant::of(cmd, depth);
4290            if last.replace(variant) == Some(variant) {
4291                continue;
4292            }
4293            if let Some(pending) = self.image_pipeline_resource(blend_mode, variant).prefetch(
4294                lane,
4295                &self.pipeline_compiler,
4296                self.adapter_backend,
4297                || self.image_pipeline_job(blend_mode, variant),
4298            ) {
4299                awaited(pending);
4300            }
4301        }
4302    }
4303
4304    /// Queues the builds of the glyph pipelines `cmds` draw with that are
4305    /// missing on `lane` (see [`FixedPipeline::prefetch`]), handing
4306    /// `awaited` each still to land.
4307    pub(crate) fn prefetch_glyph_pipelines(
4308        &self,
4309        cmds: &[GlyphDrawCmd],
4310        (depth, lane): (bool, CompileLane),
4311        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4312    ) {
4313        let mut last = None;
4314        for cmd in cmds {
4315            let quads = cmd.quads();
4316            if last.replace(quads) == Some(quads) {
4317                continue;
4318            }
4319            if let Some(pending) = self.glyph_atlas_pipeline_resource(depth, quads).prefetch(
4320                lane,
4321                &self.pipeline_compiler,
4322                self.adapter_backend,
4323                || self.glyph_atlas_pipeline_job(depth, quads),
4324            ) {
4325                awaited(pending);
4326            }
4327        }
4328    }
4329
4330    /// Queues the build of the shadow pipeline on `lane` when it is missing
4331    /// (see [`FixedPipeline::prefetch`]), handing `awaited` the pipeline
4332    /// while it is still to land.
4333    pub(crate) fn prefetch_shadow_pipeline(
4334        &self,
4335        (depth, lane): (bool, CompileLane),
4336        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
4337    ) {
4338        if let Some(pending) = self.rrect_shadow_pipeline[usize::from(depth)].prefetch(
4339            lane,
4340            &self.pipeline_compiler,
4341            self.adapter_backend,
4342            || self.rrect_shadow_pipeline_job(depth),
4343        ) {
4344            awaited(pending);
4345        }
4346    }
4347
4348    /// The image pipeline for a draw, or `None` while it compiles: the draw
4349    /// is left out, and the frame after the pipeline lands draws it.
4350    pub(crate) fn image_pipeline(
4351        &self,
4352        blend_mode: BlendMode,
4353        variant: ImageVariant,
4354    ) -> Option<&wgpu::RenderPipeline> {
4355        self.ready_or_left_out(self.image_pipeline_resource(blend_mode, variant), || {
4356            self.image_pipeline_job(blend_mode, variant)
4357        })
4358    }
4359
4360    /// `pipeline` for a draw, or `None` while it compiles, noting the draw
4361    /// left out (see [`FixedPipeline::when_ready`]).
4362    fn ready_or_left_out<'a, J>(
4363        &self,
4364        pipeline: &'a FixedPipeline,
4365        job: impl FnOnce() -> J,
4366    ) -> Option<&'a wgpu::RenderPipeline>
4367    where
4368        J: FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static,
4369    {
4370        let ready = pipeline.when_ready(
4371            &self.recorder,
4372            &self.pipeline_compiler,
4373            self.adapter_backend,
4374            job,
4375        );
4376        if ready.is_none() {
4377            self.note_placeholder();
4378        }
4379        ready
4380    }
4381
4382    fn glyph_atlas_pipeline_job(
4383        &self,
4384        depth: bool,
4385        quads: GlyphQuads,
4386    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4387        let device = Arc::clone(&self.device);
4388        let cache = self.pipeline_cache.clone();
4389        let format = self.composition_format;
4390        let shader = self.glyph_atlas_shader.clone();
4391        move || {
4392            create_glyph_atlas_pipeline(&device, cache.as_ref(), format, &shader, (depth, quads))
4393        }
4394    }
4395
4396    /// The glyph pipeline for a pass with a depth buffer or not, drawing
4397    /// `quads`, or `None` while it compiles.
4398    fn glyph_atlas_pipeline(
4399        &self,
4400        depth: bool,
4401        quads: GlyphQuads,
4402    ) -> Option<&wgpu::RenderPipeline> {
4403        let resource = self.glyph_atlas_pipeline_resource(depth, quads);
4404        let ready = resource.when_ready(
4405            &self.recorder,
4406            &self.pipeline_compiler,
4407            self.adapter_backend,
4408            || self.glyph_atlas_pipeline_job(depth, quads),
4409        );
4410        // Quads on whole pixels draw the same through the plain pipeline
4411        // while their own compiles.
4412        let ready = ready.or_else(|| {
4413            (quads == GlyphQuads::Aligned).then_some(())?;
4414            self.glyph_atlas_pipeline_resource(depth, GlyphQuads::Plain)
4415                .built()
4416        });
4417        if ready.is_none() {
4418            self.note_placeholder();
4419        }
4420        ready
4421    }
4422
4423    /// Queues, ahead of every other pipeline, the fallback pipelines shape
4424    /// draws take while their own compile.
4425    #[cfg(not(target_arch = "wasm32"))]
4426    fn warm_mesh_fallback(&self) {
4427        for (depth, pipeline) in [false, true].into_iter().zip(&self.mesh_pipelines) {
4428            pipeline.queue(
4429                &self.pipeline_compiler,
4430                CompileLane::Demanded,
4431                self.adapter_backend,
4432                crate::mesh_fallback::mesh_pipeline_job(
4433                    &self.device,
4434                    self.pipeline_cache.clone(),
4435                    self.composition_format,
4436                    depth,
4437                ),
4438            );
4439        }
4440    }
4441
4442    /// The fallback pipeline for a pass with a depth buffer or not, once it
4443    /// is built; none on the web, which leaves every fallback out of its
4444    /// build.
4445    #[cfg_attr(target_arch = "wasm32", expect(unused_variables))]
4446    fn mesh_pipeline(&self, depth: bool) -> Option<&wgpu::RenderPipeline> {
4447        #[cfg(not(target_arch = "wasm32"))]
4448        return self.mesh_pipelines[usize::from(depth)].built();
4449        #[cfg(target_arch = "wasm32")]
4450        None
4451    }
4452
4453    /// Lays out as fallback triangles the run draws of `draws` in `range`
4454    /// whose shape pipelines still compile, each record of `tables` placed
4455    /// by `placement`.
4456    #[expect(clippy::too_many_arguments)]
4457    fn mesh_unready(
4458        &self,
4459        draws: &[RunDrawCall],
4460        range: std::ops::Range<usize>,
4461        tables: crate::mesh_fallback::MeshRecords<'_>,
4462        placement: &dyn Fn(
4463            &cranpose_ui_graphics::ShapeRecordBody,
4464        ) -> Option<crate::mesh_fallback::MeshPlacement>,
4465        viewport: ViewportUniformParams,
4466        depth: bool,
4467        meshes: &mut crate::mesh_fallback::PassMeshes,
4468    ) {
4469        let target = crate::mesh_fallback::MeshTarget {
4470            offset: viewport.offset,
4471            size: [viewport.width as f32, viewport.height as f32],
4472            depth_base: depth.then_some(viewport.depth_base),
4473        };
4474        for index in range {
4475            let Some(draw) = draws.get(index) else {
4476                continue;
4477            };
4478            if self.shape_pipelines.get(draw.key).is_some() {
4479                continue;
4480            }
4481            let indices =
4482                meshes
4483                    .builder
4484                    .push_records(tables, draw.records.clone(), placement, target);
4485            meshes.set(index, indices);
4486        }
4487    }
4488
4489    /// Whether a draw in `range` of `draws` still waits for its shape
4490    /// pipeline, so it takes fallback triangles.
4491    fn awaits_shape_pipeline(&self, draws: &[RunDrawCall], range: std::ops::Range<usize>) -> bool {
4492        draws.get(range).is_some_and(|draws| {
4493            draws
4494                .iter()
4495                .any(|draw| self.shape_pipelines.get(draw.key).is_none())
4496        })
4497    }
4498
4499    /// Lays out as fallback triangles a stored run's draws in `range` of
4500    /// `draws` whose shape pipelines still compile.
4501    #[expect(clippy::too_many_arguments)]
4502    pub(crate) fn mesh_store_run(
4503        &self,
4504        run: &RunDraw,
4505        viewport: ViewportUniformParams,
4506        root_scale: f32,
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 tables = run.tables();
4517        let records = crate::mesh_fallback::MeshRecords {
4518            bodies: tables.shapes.bodies(),
4519            curves: tables.shapes.curves(),
4520            brushes: &tables.brushes,
4521            stops: &tables.stops,
4522        };
4523        let placement =
4524            PlacementData::of(&run.placement, root_scale, viewport.transform, [0.0; 2]).mesh();
4525        self.mesh_unready(
4526            draws,
4527            range,
4528            records,
4529            &|_| Some(placement),
4530            viewport,
4531            depth,
4532            meshes,
4533        );
4534    }
4535
4536    /// Lays out as fallback triangles the arena draws in `range` of `draws`,
4537    /// just cut or closed, whose shape pipelines still compile.
4538    pub(crate) fn mesh_arena_draws(
4539        &self,
4540        viewport: ViewportUniformParams,
4541        range: std::ops::Range<usize>,
4542        draws: &[RunDrawCall],
4543        depth: bool,
4544        meshes: &mut crate::mesh_fallback::PassMeshes,
4545    ) {
4546        if self.mesh_pipeline(depth).is_none() || !self.awaits_shape_pipeline(draws, range.clone())
4547        {
4548            return;
4549        }
4550        let (records, placements) = self.run_store.arena_mesh_records();
4551        self.mesh_unready(
4552            draws,
4553            range,
4554            records,
4555            &|body| {
4556                placements
4557                    .get(body.placement as usize)
4558                    .map(PlacementData::mesh)
4559            },
4560            viewport,
4561            depth,
4562            meshes,
4563        );
4564    }
4565
4566    /// The lane a pass queues its image, glyph, shadow and composite
4567    /// pipelines on. Where the compiler's threads run, those draws are left
4568    /// out until their pipelines land, so they go on the demand lane, ahead
4569    /// of the shape pipelines, whose draws take fallback triangles.
4570    pub(crate) fn frame_lane(&self) -> CompileLane {
4571        if self.pipeline_compiler.is_active() {
4572            CompileLane::Demanded
4573        } else {
4574            CompileLane::WarmUp
4575        }
4576    }
4577
4578    fn rrect_shadow_pipeline_job(
4579        &self,
4580        depth: bool,
4581    ) -> impl FnOnce() -> wgpu::RenderPipeline + CompilerSend + 'static {
4582        let device = Arc::clone(&self.device);
4583        let cache = self.pipeline_cache.clone();
4584        let format = self.composition_format;
4585        let shader = self.rrect_shadow_shader.clone();
4586        move || create_rrect_shadow_pipeline(&device, cache.as_ref(), format, &shader, depth)
4587    }
4588
4589    /// Draws `instances` of the pass's uploaded shadow instances, bound with
4590    /// `uniform_slot` under `scissor`.
4591    pub(crate) fn draw_shadow_instances(
4592        &self,
4593        pass: &mut TrackedPass<'_, '_>,
4594        buffer: &BufferUpload,
4595        uniform_slot: usize,
4596        instances: std::ops::Range<u32>,
4597        scissor: Option<(u32, u32, u32, u32)>,
4598        frame: PassFrame,
4599    ) -> Result<(), String> {
4600        let depth = frame.depth;
4601        let Some(pipeline) = self
4602            .ready_or_left_out(&self.rrect_shadow_pipeline[usize::from(depth)], || {
4603                self.rrect_shadow_pipeline_job(depth)
4604            })
4605        else {
4606            return Ok(());
4607        };
4608        let (x, y, width, height) = frame.scissor(scissor);
4609        pass.set_scissor_rect(x, y, width, height);
4610        pass.set_pipeline(pipeline);
4611        self.viewport_uniforms.bind(pass, uniform_slot)?;
4612        pass.set_vertex_buffer(0, buffer.slice());
4613        pass.draw(0..SHADOW_QUAD_CORNERS, instances);
4614        self.frame_stats.add_draw_calls(1);
4615        Ok(())
4616    }
4617
4618    pub(crate) fn upload_shadow_instances<C: FrameCommandRecorder>(
4619        &self,
4620        recorder: &mut C,
4621        instances: &[ShadowInstance],
4622    ) -> BufferUpload {
4623        recorder.upload_buffer(
4624            UploadAllocatorSpec::vertex(
4625                "Shadow Instance Buffer",
4626                std::mem::size_of::<ShadowInstance>() as u64,
4627            ),
4628            &self.device,
4629            bytemuck::cast_slice(instances),
4630        )
4631    }
4632
4633    fn glyph_atlas_pipeline_resource(&self, depth: bool, quads: GlyphQuads) -> &FixedPipeline {
4634        let kind = match quads {
4635            GlyphQuads::Plain => 0,
4636            GlyphQuads::Aligned => 1,
4637            GlyphQuads::Turned => 2,
4638        };
4639        &self.glyph_atlas_pipeline[usize::from(depth) + 2 * kind]
4640    }
4641
4642    /// The transient depth buffer for a target of `size`, created on first
4643    /// use; the few sizes recent frames used are kept.
4644    /// The depth and stencil a scene's pass draws against at `size`, kept
4645    /// for the next frames of the same size.
4646    pub(crate) fn scene_depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
4647        const KEPT_SCENE_TARGETS: usize = 2;
4648        let view = match self.scene_depth_targets.take(|(kept, _)| *kept == size) {
4649            Some((_, view)) => view,
4650            None => transient_depth_target(
4651                &self.device,
4652                (
4653                    "Scene depth and stencil",
4654                    crate::scene_pass::SCENE_DEPTH_FORMAT,
4655                ),
4656                size,
4657            ),
4658        };
4659        self.scene_depth_targets
4660            .put((size, view.clone()), KEPT_SCENE_TARGETS, u64::MAX, |_| 0);
4661        view
4662    }
4663
4664    pub(crate) fn depth_target(&mut self, size: (u32, u32)) -> wgpu::TextureView {
4665        const KEPT_DEPTH_TARGETS: usize = 4;
4666        let view = match self.depth_targets.take(|(kept, _)| *kept == size) {
4667            Some((_, view)) => view,
4668            None => self.create_depth_target(size),
4669        };
4670        self.depth_targets
4671            .put((size, view.clone()), KEPT_DEPTH_TARGETS, u64::MAX, |_| 0);
4672        view
4673    }
4674
4675    fn create_depth_target(&self, size: (u32, u32)) -> wgpu::TextureView {
4676        transient_depth_target(&self.device, ("Opaque interior depth", DEPTH_FORMAT), size)
4677    }
4678
4679    /// The binding a draw of `image` sampled by `sampling` takes, uploading
4680    /// the image the first time a draw needs it.
4681    fn image_binding(
4682        &mut self,
4683        image: &ImageBitmap,
4684        sampling: ImageSampling,
4685    ) -> Result<ImageBinding, String> {
4686        if image.format() == cranpose_ui_graphics::ImagePixelFormat::External {
4687            return self.external_texture_binding(image, sampling);
4688        }
4689        if let Some(cached) = self.image_texture_cache.get(&image.id()) {
4690            return Ok(cached.bind_groups.binding(sampling));
4691        }
4692
4693        let size = wgpu::Extent3d {
4694            width: image.width(),
4695            height: image.height(),
4696            depth_or_array_layers: 1,
4697        };
4698
4699        let alpha_mask = matches!(
4700            image.format(),
4701            cranpose_ui_graphics::ImagePixelFormat::Alpha8 { .. }
4702        );
4703        let (format, bytes_per_pixel) = if alpha_mask {
4704            (wgpu::TextureFormat::R8Unorm, 1)
4705        } else {
4706            (wgpu::TextureFormat::Rgba8Unorm, 4)
4707        };
4708
4709        let texture = self.device.create_texture(&wgpu::TextureDescriptor {
4710            label: Some("Image Texture"),
4711            size,
4712            mip_level_count: 1,
4713            sample_count: 1,
4714            dimension: wgpu::TextureDimension::D2,
4715            format,
4716            usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
4717            view_formats: &[],
4718        });
4719
4720        let upload_stats = self.frame_graph_executor.upload_texture(
4721            &self.queue,
4722            wgpu::TexelCopyTextureInfo {
4723                texture: &texture,
4724                mip_level: 0,
4725                origin: wgpu::Origin3d::ZERO,
4726                aspect: wgpu::TextureAspect::All,
4727            },
4728            image.pixels(),
4729            wgpu::TexelCopyBufferLayout {
4730                offset: 0,
4731                bytes_per_row: Some(bytes_per_pixel * image.width()),
4732                rows_per_image: Some(image.height()),
4733            },
4734            size,
4735        );
4736        self.frame_stats.record_command_stats(upload_stats);
4737
4738        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
4739        let bytes = image.pixels().len();
4740        let cached = CachedImageTexture {
4741            bind_groups: self.image_bind_groups(&view, alpha_mask),
4742            _texture: texture,
4743            _view: view,
4744            bytes,
4745        };
4746        let binding = cached.bind_groups.binding(sampling);
4747        if let Some(replaced) = self.image_texture_cache.put(image.id(), cached) {
4748            self.image_texture_cache_bytes = self
4749                .image_texture_cache_bytes
4750                .saturating_sub(replaced.bytes);
4751        }
4752        self.image_texture_cache_bytes += bytes;
4753        while self.image_texture_cache_bytes > MAX_IMAGE_TEXTURE_CACHE_BYTES
4754            && self.image_texture_cache.len() > 1
4755        {
4756            let Some((_, evicted)) = self.image_texture_cache.pop_lru() else {
4757                break;
4758            };
4759            self.image_texture_cache_bytes =
4760                self.image_texture_cache_bytes.saturating_sub(evicted.bytes);
4761        }
4762        Ok(binding)
4763    }
4764
4765    fn external_texture_binding(
4766        &mut self,
4767        image: &ImageBitmap,
4768        sampling: ImageSampling,
4769    ) -> Result<ImageBinding, String> {
4770        let key = image.storage_id();
4771        if let Some(bind_groups) = self.external_texture_bindings.get(&key) {
4772            return Ok(bind_groups.binding(sampling));
4773        }
4774        let view = image
4775            .external_handle::<wgpu::TextureView>()
4776            .ok_or("an external texture's handle is not a wgpu::TextureView")?;
4777        let bind_groups = self.image_bind_groups(view, false);
4778        let binding = bind_groups.binding(sampling);
4779        self.external_texture_bindings.put(key, bind_groups);
4780        Ok(binding)
4781    }
4782
4783    fn image_bind_groups(&self, view: &wgpu::TextureView, alpha_mask: bool) -> ImageBindGroups {
4784        ImageBindGroups {
4785            alpha_mask,
4786            nearest: self.image_bind_group(view, &self.image_nearest_sampler),
4787            linear: self.image_bind_group(view, &self.image_linear_sampler),
4788        }
4789    }
4790
4791    fn image_bind_group(
4792        &self,
4793        view: &wgpu::TextureView,
4794        sampler: &wgpu::Sampler,
4795    ) -> wgpu::BindGroup {
4796        self.device.create_bind_group(&wgpu::BindGroupDescriptor {
4797            label: Some("Image Texture Bind Group"),
4798            layout: &self.image_bind_group_layout,
4799            entries: &[
4800                wgpu::BindGroupEntry {
4801                    binding: 0,
4802                    resource: wgpu::BindingResource::TextureView(view),
4803                },
4804                wgpu::BindGroupEntry {
4805                    binding: 1,
4806                    resource: wgpu::BindingResource::Sampler(sampler),
4807                },
4808            ],
4809        })
4810    }
4811
4812    pub(crate) fn max_texture_dim(&self) -> u32 {
4813        self.effect_renderer.max_texture_dim()
4814    }
4815
4816    /// A pooled texture that outlives the frame: layer cache entries and
4817    /// cached shadow surfaces.
4818    pub(crate) fn acquire_retained_surface(&mut self, width: u32, height: u32) -> OffscreenTarget {
4819        self.effect_renderer
4820            .acquire_offscreen(&self.device, width, height, Some(&self.frame_stats))
4821    }
4822
4823    fn frame_root(
4824        &mut self,
4825        output_mode: OutputMode,
4826        output_view: Option<&wgpu::TextureView>,
4827        output_texture: Option<&wgpu::Texture>,
4828        viewport: (u32, u32),
4829        reads_page: bool,
4830    ) -> FrameRoot {
4831        if let (OutputMode::Display, Some(view), Some(texture)) =
4832            (output_mode, output_view, output_texture)
4833            && surface_is_direct_root(texture, self.composition_format, viewport, reads_page)
4834        {
4835            return FrameRoot::Surface(Rc::new(OffscreenTarget::from_surface(
4836                texture.clone(),
4837                view.clone(),
4838            )));
4839        }
4840        FrameRoot::Composition(self.take_composition_target(viewport.0.max(1), viewport.1.max(1)))
4841    }
4842
4843    fn take_composition_target(&mut self, width: u32, height: u32) -> CompositionTarget {
4844        if let Some(target) = self.composition_target.take()
4845            && target.target.width == width
4846            && target.target.height == height
4847        {
4848            return target;
4849        }
4850        let target = Rc::new(OffscreenTarget::new(
4851            &self.device,
4852            self.composition_format,
4853            width,
4854            height,
4855        ));
4856        let output_bind_group = self.output_converter.bind_group(&self.device, &target.view);
4857        CompositionTarget {
4858            target,
4859            output_bind_group,
4860        }
4861    }
4862
4863    fn transient_offscreen_descriptor(
4864        &self,
4865        label: &'static str,
4866        width: u32,
4867        height: u32,
4868    ) -> FrameTextureDescriptor {
4869        let max_texture_dim = self.max_texture_dim();
4870        FrameTextureDescriptor::render_attachment(
4871            label,
4872            width.min(max_texture_dim),
4873            height.min(max_texture_dim),
4874            self.composition_format,
4875        )
4876    }
4877
4878    /// A texture of the given size that stays transparent: the input of a
4879    /// runtime shader whose layer draws nothing itself, so the shader needs
4880    /// no surface pass and reads the same empty content every frame.
4881    #[inline(never)]
4882    pub(crate) fn transparent_source<C: FrameCommandRecorder>(
4883        &mut self,
4884        recorder: &mut C,
4885        width: u32,
4886        height: u32,
4887    ) -> Rc<OffscreenTarget> {
4888        if let Some(source) = self.transparent_sources.get(&(width, height)) {
4889            return Rc::clone(source);
4890        }
4891        if self.transparent_sources.len() >= MAX_TRANSPARENT_SOURCES {
4892            for (_, source) in self.transparent_sources.drain() {
4893                if let Ok(target) = Rc::try_unwrap(source) {
4894                    self.deferred_offscreen_releases.push(target);
4895                }
4896            }
4897        }
4898        let source = Rc::new(self.acquire_retained_surface(width, height));
4899        self.clear_target(
4900            recorder,
4901            &source.view,
4902            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
4903        );
4904        self.transparent_sources
4905            .insert((width, height), Rc::clone(&source));
4906        source
4907    }
4908
4909    fn defer_offscreen_release(&mut self, target: OffscreenTarget) {
4910        self.deferred_offscreen_releases.push(target);
4911    }
4912
4913    fn flush_deferred_offscreen_releases(&mut self) {
4914        let layer_cache = &mut self.layer_cache;
4915        let mut retire = |gate: &mut AdmissionGate| {
4916            let seen = gate.end_frame();
4917            if !seen && let Some(dead) = gate.dead_entry() {
4918                layer_cache.remove(&dead);
4919            }
4920            seen
4921        };
4922        self.backdrop_gates.retain(|_, gate| retire(gate));
4923        self.fill_gates.retain(|_, gate| retire(gate));
4924        self.effect_gates.retain(|_, gate| retire(gate));
4925        self.source_gates.retain(|_, gate| retire(gate));
4926        for target in self.deferred_offscreen_releases.drain(..) {
4927            self.effect_renderer.release_offscreen(target);
4928        }
4929        self.layer_cache.end_frame();
4930        for (transient, target) in self.layer_cache.take_released() {
4931            match transient {
4932                Some(descriptor) => self
4933                    .frame_graph_executor
4934                    .return_cached_transient(descriptor, target),
4935                None => self.effect_renderer.release_offscreen(target),
4936            }
4937        }
4938        self.effect_renderer.end_offscreen_frame();
4939        self.frame_graph_executor.end_transient_frame();
4940        self.depth_targets.end_frame();
4941        self.scene_pass.end_frame();
4942        self.surface_atlas_sizes.end_frame();
4943    }
4944
4945    fn insert_cached_shadow_surface(
4946        &mut self,
4947        key: ShadowSurfaceCacheKey,
4948        target: Rc<OffscreenTarget>,
4949    ) {
4950        let byte_size = offscreen_byte_size(target.width, target.height);
4951        while self.shadow_surface_cache_bytes + byte_size > MAX_SHADOW_SURFACE_CACHE_BYTES {
4952            let Some((_, evicted)) = self.shadow_surface_cache.pop_lru() else {
4953                break;
4954            };
4955            self.shadow_surface_cache_bytes = self
4956                .shadow_surface_cache_bytes
4957                .saturating_sub(evicted.byte_size);
4958        }
4959        let cached = CachedShadowSurface { target, byte_size };
4960        if let Some((_, replaced)) = self.shadow_surface_cache.push(key, cached) {
4961            self.shadow_surface_cache_bytes = self
4962                .shadow_surface_cache_bytes
4963                .saturating_sub(replaced.byte_size);
4964        }
4965        self.shadow_surface_cache_bytes = self.shadow_surface_cache_bytes.saturating_add(byte_size);
4966    }
4967}
4968fn frame_stats_need_warmup_frame(snapshot: &gpu_stats::FrameStatsSnapshot) -> bool {
4969    snapshot.layer_cache_misses > 0
4970        || snapshot.shadow_shape_cache_misses > 0
4971        || snapshot.text_image_cache_misses > 0
4972        || snapshot.text_glyph_atlas_misses > 0
4973}
4974
4975fn update_frame_warmup_budget(pending_frames: &mut u8, snapshot: &gpu_stats::FrameStatsSnapshot) {
4976    if *pending_frames > 0 {
4977        *pending_frames = pending_frames.saturating_sub(1);
4978    } else if frame_stats_need_warmup_frame(snapshot) {
4979        *pending_frames = CACHE_MISS_WARMUP_FRAMES;
4980    }
4981}
4982
4983impl GpuRenderer {
4984    #[expect(clippy::too_many_arguments)]
4985    pub fn render(
4986        &mut self,
4987        texture: &wgpu::Texture,
4988        view: &wgpu::TextureView,
4989        width: u32,
4990        height: u32,
4991        packet: FramePacket,
4992        surface_epoch: u64,
4993        returns: &mut RenderReturns,
4994    ) -> Result<(), String> {
4995        self.render_internal(
4996            width,
4997            height,
4998            packet,
4999            surface_epoch,
5000            returns,
5001            OutputMode::Display,
5002            Some(view),
5003            Some(texture),
5004        )
5005    }
5006
5007    #[expect(clippy::too_many_arguments)]
5008    fn render_internal(
5009        &mut self,
5010        width: u32,
5011        height: u32,
5012        packet: FramePacket,
5013        surface_epoch: u64,
5014        returns: &mut RenderReturns,
5015        output_mode: OutputMode,
5016        output_view: Option<&wgpu::TextureView>,
5017        output_texture: Option<&wgpu::Texture>,
5018    ) -> Result<(), String> {
5019        let cancel_reason = if packet.renderer_epoch != self.renderer_epoch {
5020            Some(CancelReason::RendererEpoch)
5021        } else if packet.surface_epoch != surface_epoch {
5022            Some(CancelReason::SurfaceEpoch)
5023        } else if packet.viewport != (width, height) {
5024            Some(CancelReason::Viewport)
5025        } else {
5026            None
5027        };
5028        if let Some(reason) = cancel_reason {
5029            return Self::cancel_packet(packet, reason, returns);
5030        }
5031        if self.device_errors.take_poison() {
5032            return Self::cancel_packet(packet, CancelReason::DeviceError, returns);
5033        }
5034        returns.frame_id = packet.frame_id;
5035        let render_start = Instant::now();
5036        #[cfg(not(target_arch = "wasm32"))]
5037        let builds_before = thread_builds();
5038        self.warm_requested_shaders();
5039        self.shape_pipelines.begin_frame();
5040        self.recorder.begin_frame((width, height));
5041        self.begin_placeholder_frame();
5042        self.viewport_uniforms.begin_frame();
5043        self.run_store.begin_frame(gpu_stats_enabled());
5044        self.begin_text_glyph_run_frame();
5045        self.scratch_meshes.begin_frame();
5046
5047        let reads_page = packet.root.contains_backdrop()
5048            || packet
5049                .overlay
5050                .as_ref()
5051                .is_some_and(|overlay| overlay.contains_backdrop());
5052        let frame_root = self.frame_root(
5053            output_mode,
5054            output_view,
5055            output_texture,
5056            (width, height),
5057            reads_page,
5058        );
5059        let root = frame_root.target();
5060        let screenshot_bind_group = output_view.and_then(|_| {
5061            matches!(output_mode, OutputMode::Screenshot).then(|| {
5062                self.screenshot_converter
5063                    .bind_group(&self.device, &root.view)
5064            })
5065        });
5066        let output = frame_root.output(output_view, screenshot_bind_group.as_ref());
5067        let result = self.render_graph(root, packet, returns, output_mode, output);
5068        #[cfg(not(target_arch = "wasm32"))]
5069        self.effect_renderer
5070            .compiler()
5071            .spread_demand(thread_builds() == builds_before);
5072        if let FrameRoot::Composition(composition) = frame_root {
5073            self.composition_target = Some(composition);
5074        }
5075        let after_graph = Instant::now();
5076        if self.effect_renderer.take_skipped_draw() {
5077            self.note_placeholder();
5078        }
5079        self.flush_deferred_offscreen_releases();
5080        self.scratch_glyph_instances.end_frame();
5081
5082        self.frame_stats
5083            .layer_cache_size
5084            .set(self.layer_cache.len() as u32);
5085        self.frame_stats
5086            .layer_cache_bytes
5087            .set(self.layer_cache.bytes());
5088        self.frame_stats.offscreen_pool_size.set(
5089            self.effect_renderer
5090                .retained_offscreen_count()
5091                .saturating_add(self.frame_graph_executor.retained_texture_count())
5092                .saturating_add(usize::from(self.composition_target.is_some())) as u32,
5093        );
5094        self.frame_stats.offscreen_pool_bytes.set(
5095            (self.effect_renderer.retained_offscreen_bytes() as u64)
5096                .saturating_add(self.frame_graph_executor.retained_texture_bytes())
5097                .saturating_add(self.composition_target.as_ref().map_or(0, |target| {
5098                    u64::from(target.target.width)
5099                        .saturating_mul(u64::from(target.target.height))
5100                        .saturating_mul(COMPOSITION_BYTES_PER_PIXEL)
5101                })),
5102        );
5103        self.frame_stats
5104            .text_pool_size
5105            .set(self.text_image_cache.len() as u32);
5106        self.frame_stats
5107            .image_cache_size
5108            .set(self.image_texture_cache.len() as u32);
5109        self.effect_renderer
5110            .merge_and_reset_debug_counters(&self.frame_stats);
5111        self.frame_graph_executor.reset_upload_allocators();
5112        let snapshot = self.frame_stats.snapshot();
5113        if crate::frame_graph::frame_graph_pass_telemetry_threshold_ms().is_some() {
5114            log::warn!(
5115                "[wgpu-render-stage:frame-stats] layer_hit={} layer_miss={} miss_px={} \
5116                 offscreen_acq={} offscreen_new={} isolated={} draws={}",
5117                snapshot.layer_cache_hits,
5118                snapshot.layer_cache_misses,
5119                snapshot.layer_cache_miss_pixels,
5120                snapshot.offscreen_acquires,
5121                snapshot.offscreen_news,
5122                snapshot.isolated_layer_renders,
5123                snapshot.draw_calls,
5124            );
5125        }
5126        self.last_frame_stats = Some(snapshot);
5127        PRESENTED_FRAMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5128        update_frame_warmup_budget(&mut self.pending_frame_warmup_frames, &snapshot);
5129        let gpu_stats_on = gpu_stats_enabled();
5130        self.frame_stats
5131            .maybe_print_snapshot(snapshot, &mut self.frame_count, gpu_stats_on);
5132        if gpu_stats_on && self.frame_count.is_multiple_of(60) {
5133            gpu_stats::print_gpu_memory_report(&self.device, self.frame_count);
5134        }
5135        self.frame_graph_executor
5136            .end_pass_timing_frame(&self.device, &self.queue);
5137        self.frame_stats.reset();
5138        let after_stats = Instant::now();
5139        if let Some(total_ms) = should_log_wgpu_render_stage(render_start, after_stats) {
5140            log::warn!(
5141                "[wgpu-render-stage:render] total_ms={total_ms:.2} graph_ms={:.2} cleanup_stats_ms={:.2}",
5142                instant_ms(render_start, after_graph),
5143                instant_ms(after_graph, after_stats),
5144            );
5145        }
5146        if result.is_ok() {
5147            returns.outcome = PresentOutcome::Presented;
5148        }
5149        result
5150    }
5151
5152    /// Returns a packet unrendered, handing its scene back for recycling.
5153    pub(crate) fn cancel_packet(
5154        packet: FramePacket,
5155        reason: CancelReason,
5156        returns: &mut RenderReturns,
5157    ) -> Result<(), String> {
5158        returns.scene = Some(FrameSceneStorage {
5159            root: packet.root,
5160            overlay: packet.overlay,
5161        });
5162        returns.frame_id = packet.frame_id;
5163        returns.outcome = PresentOutcome::Cancelled(reason);
5164        Ok(())
5165    }
5166
5167    pub fn last_frame_stats(&self) -> Option<gpu_stats::FrameStatsSnapshot> {
5168        self.last_frame_stats
5169    }
5170
5171    pub fn gpu_pass_timings(&self) -> crate::pass_timing::GpuPassTimingReport {
5172        self.frame_graph_executor.pass_timing_report()
5173    }
5174
5175    pub fn needs_frame_warmup(&self) -> bool {
5176        self.pending_frame_warmup_frames > 0 || self.placeholder_awaits_frame()
5177    }
5178
5179    #[cfg(target_arch = "wasm32")]
5180    pub(crate) fn pipeline_compiler(&self) -> &PipelineCompiler {
5181        &self.pipeline_compiler
5182    }
5183
5184    /// Whether a frame must follow to replace a placeholder: a pipeline it
5185    /// waited for landed, or, with nothing to wake the app when one does,
5186    /// this frame drew one.
5187    fn placeholder_awaits_frame(&self) -> bool {
5188        #[cfg(not(target_arch = "wasm32"))]
5189        if let Some(landing) = &self.landing {
5190            return landing.landed() || (self.drew_placeholder.get() && !landing.has_wake());
5191        }
5192        self.drew_placeholder.get()
5193    }
5194
5195    /// Starts a frame: once a pipeline a placeholder waited for has landed,
5196    /// the retained layers, which may hold that placeholder, are dropped.
5197    fn begin_placeholder_frame(&mut self) {
5198        self.drew_placeholder.set(false);
5199        #[cfg(not(target_arch = "wasm32"))]
5200        if let Some(landing) = &self.landing {
5201            self.built_at_frame_start = landing.built();
5202            if landing.take_landed() {
5203                self.drop_kept_drawing();
5204            }
5205        }
5206    }
5207
5208    /// Drops what earlier frames drew and kept, the layers and the blurred
5209    /// shadows: pipelines the browser compiled in the background landed, and
5210    /// those were drawn while the draws that use them were left out.
5211    #[cfg(target_arch = "wasm32")]
5212    pub(crate) fn background_pipelines_landed(&mut self) {
5213        self.drop_kept_drawing();
5214    }
5215
5216    /// See [`crate::WgpuRenderer::compile_pipelines_in_background`].
5217    #[cfg(target_arch = "wasm32")]
5218    pub(crate) fn compile_pipelines_in_background(&mut self) {
5219        self.shape_pipelines.build_in_background();
5220    }
5221
5222    /// Drops the layers and the blurred shadows earlier frames drew and kept.
5223    fn drop_kept_drawing(&mut self) {
5224        self.layer_cache.clear();
5225        self.shadow_surface_cache.clear();
5226        self.shadow_surface_cache_bytes = 0;
5227    }
5228
5229    /// Notes an effect drawn as its placeholder, or a draw left out, while
5230    /// its pipelines compile, and waits for the next one to land.
5231    pub(crate) fn note_placeholder(&self) {
5232        self.frame_stats
5233            .placeholder_draws
5234            .set(self.frame_stats.placeholder_draws.get() + 1);
5235        self.await_landing();
5236    }
5237
5238    /// Notes a shape drawn as fallback triangles while its pipeline
5239    /// compiles, and waits for the next one to land.
5240    fn note_mesh_fallback(&self) {
5241        self.frame_stats
5242            .shape_pipeline_fallback_draws
5243            .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
5244        self.await_landing();
5245    }
5246
5247    /// Asks for the frame after the next pipeline lands: this one drew
5248    /// something in place of what that pipeline draws.
5249    fn await_landing(&self) {
5250        self.drew_placeholder.set(true);
5251        self.recorder.hold_first_screen();
5252        #[cfg(not(target_arch = "wasm32"))]
5253        if let Some(landing) = &self.landing {
5254            landing.await_since(self.built_at_frame_start);
5255        }
5256    }
5257
5258    /// Queues every pipeline the cache file records, as the first frame of
5259    /// an updated build does, and returns whether any is left to build: for
5260    /// a renderer that prepares an app's pipelines without drawing.
5261    #[cfg(not(target_arch = "wasm32"))]
5262    pub(crate) fn prepare_recorded(&mut self) -> bool {
5263        self.effect_renderer.warm_after_first_frame();
5264        if let Some(records) = self.recent_after_update.take() {
5265            self.warm_recent(&records);
5266        }
5267        self.compiling()
5268    }
5269
5270    /// Whether the background compiler has a queued pipeline left to build.
5271    #[cfg(not(target_arch = "wasm32"))]
5272    pub(crate) fn compiling(&self) -> bool {
5273        self.landing
5274            .as_ref()
5275            .is_some_and(|landing| landing.in_flight())
5276    }
5277
5278    /// Whether the last frame drew a placeholder and pipelines are still
5279    /// compiling, so its picture is not final yet.
5280    pub(crate) fn awaits_pipelines(&self) -> bool {
5281        #[cfg(not(target_arch = "wasm32"))]
5282        if let Some(landing) = &self.landing {
5283            return self.drew_placeholder.get() && landing.in_flight();
5284        }
5285        self.drew_placeholder.get()
5286    }
5287
5288    /// The compiler's account of the pipelines it builds, for a runtime that
5289    /// reads it off the present thread.
5290    #[cfg(not(target_arch = "wasm32"))]
5291    pub(crate) fn landing(&self) -> Option<Arc<crate::pipeline_compiler::Landing>> {
5292        self.landing.clone()
5293    }
5294
5295    /// Calls `wake` from the compiling thread when a pipeline a placeholder
5296    /// waited for lands, so an app with nothing else to draw draws again.
5297    #[cfg(not(target_arch = "wasm32"))]
5298    pub(crate) fn wake_on_landing(&self, wake: Box<dyn Fn() + Send + Sync>) {
5299        if let Some(landing) = &self.landing {
5300            landing.wake_with(wake);
5301        }
5302    }
5303
5304    pub fn debug_cpu_allocation_stats(&self) -> DebugCpuAllocationStats {
5305        DebugCpuAllocationStats {
5306            scene_graph_node_count: 0,
5307            scene_graph_heap_bytes: 0,
5308            scene_hits_len: 0,
5309            scene_hits_cap: 0,
5310            scene_node_index_len: 0,
5311            scene_node_index_cap: 0,
5312            text_renderer_pool_len: self.text_image_cache.len(),
5313            text_renderer_pool_cap: self.text_image_cache.cap().get(),
5314            image_texture_cache_len: self.image_texture_cache.len(),
5315            image_texture_cache_cap: self.image_texture_cache.cap().get(),
5316            run_arena_staging_bytes: self.run_store.arena_staging_bytes(),
5317            run_store_bytes: self.run_store.stored_bytes(),
5318            run_store_runs: self.run_store.stored_count(),
5319            scratch_image_vertices_cap: self.scratch_image_vertices.capacity(),
5320            scratch_image_indices_cap: self.scratch_image_indices.capacity(),
5321            scratch_image_cmds_cap: self.scratch_image_cmds.capacity(),
5322            scratch_glyph_instances_cap: self.scratch_glyph_instances.plain.capacity()
5323                + self.scratch_glyph_instances.turned.capacity(),
5324            layer_cache_len: self.layer_cache.len(),
5325            layer_cache_bytes: self.layer_cache.bytes(),
5326        }
5327    }
5328    pub fn render_to_rgba_pixels(
5329        &mut self,
5330        width: u32,
5331        height: u32,
5332        packet: FramePacket,
5333        surface_epoch: u64,
5334        returns: &mut RenderReturns,
5335    ) -> Result<Vec<u8>, String> {
5336        if width == 0 || height == 0 {
5337            return Err("Screenshot size must be non-zero".to_string());
5338        }
5339        let errors_before = self.device_errors.error_count();
5340
5341        let output_texture = crate::offscreen::create_2d_texture(
5342            &self.device,
5343            wgpu::TextureFormat::Rgba8Unorm,
5344            width,
5345            height,
5346            wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
5347            Some("Screenshot Output Texture"),
5348        );
5349        let output_view = output_texture.create_view(&wgpu::TextureViewDescriptor::default());
5350        self.render_internal(
5351            width,
5352            height,
5353            packet,
5354            surface_epoch,
5355            returns,
5356            OutputMode::Screenshot,
5357            Some(&output_view),
5358            None,
5359        )?;
5360        if returns.outcome != PresentOutcome::Presented {
5361            return Err(format!(
5362                "Screenshot rendering did not complete: {:?}",
5363                returns.outcome
5364            ));
5365        }
5366        self.read_screenshot_pixels(&output_texture, errors_before)
5367    }
5368
5369    fn read_screenshot_pixels(
5370        &mut self,
5371        output_texture: &wgpu::Texture,
5372        errors_before: u64,
5373    ) -> Result<Vec<u8>, String> {
5374        let width = output_texture.width();
5375        let height = output_texture.height();
5376        let bytes_per_pixel = 4u32;
5377        let unpadded_bytes_per_row = width
5378            .checked_mul(bytes_per_pixel)
5379            .ok_or_else(|| "Screenshot row byte size overflow".to_string())?;
5380        let padded_bytes_per_row =
5381            align_to(unpadded_bytes_per_row, wgpu::COPY_BYTES_PER_ROW_ALIGNMENT);
5382        let output_buffer_size = padded_bytes_per_row as u64 * height as u64;
5383
5384        let output_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
5385            label: Some("Screenshot Readback Buffer"),
5386            size: output_buffer_size,
5387            usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
5388            mapped_at_creation: false,
5389        });
5390
5391        let device = self.device.clone();
5392        let queue = self.queue.clone();
5393        let mut graph = WgpuFrameGraph::new(Some("Screenshot Copy Encoder"));
5394        let source = graph.import_surface("screenshot-copy-source");
5395        graph.add_fallible_command_pass(Some("Screenshot Copy Pass"), &[source], &[], |context| {
5396            context.encoder.copy_texture_to_buffer(
5397                wgpu::TexelCopyTextureInfo {
5398                    texture: output_texture,
5399                    mip_level: 0,
5400                    origin: wgpu::Origin3d::ZERO,
5401                    aspect: wgpu::TextureAspect::All,
5402                },
5403                wgpu::TexelCopyBufferInfo {
5404                    buffer: &output_buffer,
5405                    layout: wgpu::TexelCopyBufferLayout {
5406                        offset: 0,
5407                        bytes_per_row: Some(padded_bytes_per_row),
5408                        rows_per_image: Some(height),
5409                    },
5410                },
5411                wgpu::Extent3d {
5412                    width,
5413                    height,
5414                    depth_or_array_layers: 1,
5415                },
5416            );
5417            Ok(())
5418        });
5419        let mut executor = std::mem::take(&mut self.frame_graph_executor);
5420        let execution = executor.execute_recorded_graph(&device, &queue, graph);
5421        self.frame_graph_executor = executor;
5422        self.recall_frame_uploads();
5423        let execution = execution.map_err(|error| error.to_string())?;
5424        let submission_index = execution.submission;
5425        let copy_stats = execution.stats;
5426        self.last_frame_stats = self
5427            .last_frame_stats
5428            .map(|snapshot| snapshot.with_command_stats_added(copy_stats));
5429
5430        let buffer_slice = output_buffer.slice(..);
5431        let (tx, rx) = mpsc::channel();
5432        buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
5433            let _ = tx.send(result);
5434        });
5435        self.device
5436            .poll(wgpu::PollType::Wait {
5437                submission_index: Some(submission_index),
5438                timeout: None,
5439            })
5440            .map_err(|error| format!("Screenshot GPU wait failed: {error}"))?;
5441
5442        match rx.recv_timeout(Duration::from_secs(3)) {
5443            Ok(Ok(())) => {}
5444            Ok(Err(err)) => return Err(format!("Screenshot map_async failed: {err:?}")),
5445            Err(err) => return Err(format!("Screenshot readback timed out: {err}")),
5446        }
5447        if self.device_errors.error_count() != errors_before {
5448            output_buffer.unmap();
5449            return Err("GPU errors occurred while capturing the screenshot".to_string());
5450        }
5451
5452        let mapped = buffer_slice
5453            .get_mapped_range()
5454            .map_err(|err| format!("Screenshot readback could not be read: {err}"))?;
5455        let mut pixels = vec![0u8; (width as usize) * (height as usize) * 4];
5456
5457        let src_row_len = padded_bytes_per_row as usize;
5458        let dst_row_len = unpadded_bytes_per_row as usize;
5459        for row in 0..height as usize {
5460            let src_offset = row * src_row_len;
5461            let dst_offset = row * dst_row_len;
5462            pixels[dst_offset..dst_offset + dst_row_len]
5463                .copy_from_slice(&mapped[src_offset..src_offset + dst_row_len]);
5464        }
5465        drop(mapped);
5466        output_buffer.unmap();
5467
5468        self.convert_surface_pixels_to_rgba(&pixels)
5469    }
5470
5471    /// Asks the buffers the submitted frame unmapped back for later frames.
5472    fn recall_frame_uploads(&mut self) {
5473        self.viewport_uniforms.uploads.recall();
5474        self.run_store.recall();
5475    }
5476
5477    fn render_graph(
5478        &mut self,
5479        root_target: &Rc<OffscreenTarget>,
5480        packet: FramePacket,
5481        returns: &mut RenderReturns,
5482        output_mode: OutputMode,
5483        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5484    ) -> Result<(), String> {
5485        #[cfg(target_arch = "wasm32")]
5486        let (device, queue, graph_start) =
5487            (self.device.clone(), self.queue.clone(), Instant::now());
5488        let FramePacket {
5489            root,
5490            overlay,
5491            root_scale,
5492            clear,
5493            ..
5494        } = packet;
5495        let page = Rc::clone(root_target);
5496
5497        #[cfg(not(target_arch = "wasm32"))]
5498        let (result, submitted) = self.execute_frame_graph(
5499            &root,
5500            overlay.as_deref(),
5501            &page,
5502            root_scale,
5503            clear,
5504            output_mode,
5505            output,
5506        );
5507
5508        #[cfg(target_arch = "wasm32")]
5509        let (result, submitted) = {
5510            let mut executor = std::mem::take(&mut self.frame_graph_executor);
5511            let (result, execution) = {
5512                let mut frame_encoder =
5513                    executor.begin(&device, &queue, Some("Renderer Frame Encoder"));
5514                let initial_pass_count = frame_encoder.recorded_pass_count();
5515                let result = self.encode_frame(
5516                    &mut frame_encoder,
5517                    &root,
5518                    overlay.as_deref(),
5519                    Rc::clone(&page),
5520                    root_scale,
5521                    clear,
5522                    output_mode,
5523                    output,
5524                );
5525                let execution =
5526                    if result.is_ok() && frame_encoder.recorded_pass_count() > initial_pass_count {
5527                        Some(frame_encoder.finish())
5528                    } else {
5529                        None
5530                    };
5531                (result, execution)
5532            };
5533            let after_execute = Instant::now();
5534            self.frame_graph_executor = executor;
5535            if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5536                log::warn!("[wgpu-render-stage:graph] total_ms={total_ms:.2}",);
5537            }
5538            let submitted = execution.is_some();
5539            if let Some(execution) = execution {
5540                self.frame_stats.record_command_stats(execution.stats);
5541            }
5542            (result, submitted)
5543        };
5544        #[cfg(not(target_arch = "wasm32"))]
5545        if submitted {
5546            self.recorder.note_frame_drawn();
5547            self.effect_renderer.warm_after_first_frame();
5548            if let Some(records) = self.recent_after_update.take() {
5549                self.warm_recent(&records);
5550            }
5551        }
5552        if !submitted {
5553            self.run_store.invalidate_uploads();
5554            self.text_glyph_gpu_run_cache.clear();
5555            self.text_glyph_run_arena = GlyphRunArena::new(self.copy_free);
5556        }
5557        returns.scene = Some(FrameSceneStorage { root, overlay });
5558        result
5559    }
5560
5561    /// Records and submits the frame through the frame graph: whether it
5562    /// recorded without error, and whether it submitted anything.
5563    #[cfg(not(target_arch = "wasm32"))]
5564    #[expect(clippy::too_many_arguments)]
5565    fn execute_frame_graph(
5566        &mut self,
5567        root: &LayerScene,
5568        overlay: Option<&LayerScene>,
5569        page: &Rc<OffscreenTarget>,
5570        root_scale: f32,
5571        clear: wgpu::Color,
5572        output_mode: OutputMode,
5573        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5574    ) -> (Result<(), String>, bool) {
5575        let device = self.device.clone();
5576        let queue = self.queue.clone();
5577        let graph_start = Instant::now();
5578        let mut executor = std::mem::take(&mut self.frame_graph_executor);
5579        let mut frame_graph = WgpuFrameGraph::new(Some("Renderer Frame Graph"));
5580        let surface = frame_graph.import_surface("renderer-surface");
5581        frame_graph.add_fallible_recorded_command_pass(
5582            Some("Renderer Frame Pass"),
5583            &[],
5584            &[surface],
5585            |frame_encoder| {
5586                self.encode_frame(
5587                    frame_encoder,
5588                    root,
5589                    overlay,
5590                    Rc::clone(page),
5591                    root_scale,
5592                    clear,
5593                    output_mode,
5594                    output,
5595                )
5596            },
5597        );
5598        let after_build = Instant::now();
5599        let execution = executor.execute_recorded_graph(&device, &queue, frame_graph);
5600        let after_execute = Instant::now();
5601        self.frame_graph_executor = executor;
5602        self.recall_frame_uploads();
5603        if let Some(total_ms) = should_log_wgpu_render_stage(graph_start, after_execute) {
5604            log::warn!(
5605                "[wgpu-render-stage:graph] total_ms={total_ms:.2} build_ms={:.2} execute_ms={:.2}",
5606                instant_ms(graph_start, after_build),
5607                instant_ms(after_build, after_execute),
5608            );
5609        }
5610        match execution {
5611            Ok(execution) => {
5612                if execution.stats.pass_count > 0 {
5613                    self.frame_stats.record_command_stats(execution.stats);
5614                }
5615                (Ok(()), true)
5616            }
5617            Err(crate::frame_graph::FrameGraphError::NoDeclaredPasses) => (Ok(()), false),
5618            Err(error) => (Err(error.to_string()), false),
5619        }
5620    }
5621
5622    /// Records the frame: the root and overlay layer scenes into the frame's
5623    /// target, the output conversion when the target is not the presented
5624    /// image, and the viewport uniforms the recorded passes claimed.
5625    #[expect(clippy::too_many_arguments)]
5626    fn encode_frame<C: FrameCommandRecorder>(
5627        &mut self,
5628        recorder: &mut C,
5629        root: &LayerScene,
5630        overlay: Option<&LayerScene>,
5631        page: Rc<OffscreenTarget>,
5632        root_scale: f32,
5633        clear: wgpu::Color,
5634        output_mode: OutputMode,
5635        output: Option<(&wgpu::TextureView, &wgpu::BindGroup)>,
5636    ) -> Result<(), String> {
5637        FrameExecutor::new(self, recorder).render_frame(
5638            root,
5639            overlay,
5640            page,
5641            root_scale,
5642            wgpu::LoadOp::Clear(clear),
5643        )?;
5644        if let Some((output_view, bind_group)) = output {
5645            match output_mode {
5646                OutputMode::Display => &self.output_converter,
5647                OutputMode::Screenshot => &self.screenshot_converter,
5648            }
5649            .encode(
5650                &self.device,
5651                recorder,
5652                output_view,
5653                bind_group,
5654                self.adapter_backend,
5655                &self.recorder,
5656            );
5657            recorder.record_pass();
5658        }
5659        self.stage_frame_uploads(recorder);
5660        self.shape_pipelines.build_wanted();
5661        self.depth_gate.end_frame();
5662        self.pipeline_compiler.end_frame();
5663        self.viewport_uniforms.uploads.finish_frame();
5664        self.run_store.finish_frame();
5665        Ok(())
5666    }
5667
5668    pub(crate) fn stage_frame_uploads(&mut self, recorder: &mut impl FrameCommandRecorder) {
5669        let mut upload = self.viewport_uniforms.stage_pending(&self.device, recorder);
5670        upload += self.run_store.stage_pending(&self.device, recorder);
5671        upload += self
5672            .text_glyph_run_arena
5673            .stage_pending(&self.device, recorder);
5674        self.run_store.fill_arena_trig(&self.device, recorder);
5675        self.frame_stats.record_command_stats(upload);
5676    }
5677    /// Claims this frame's next viewport uniform slot for `params`.
5678    pub(crate) fn claim_uniform_slot(&mut self, params: ViewportUniformParams) -> usize {
5679        let uniforms = Uniforms::of(params, PlacementData::zeroed(), RunTier::Arena);
5680        self.viewport_uniforms
5681            .claim(&self.device, &self.uniform_bind_group_layout, &uniforms)
5682    }
5683
5684    /// Resolves a blurred shadow at `z` into a texture and queues its
5685    /// composites. The shadow's shapes and texts render into a source the
5686    /// size of their blur footprint, blur in place and take the post-blur
5687    /// cutouts; the source is then blitted over the rect the shadow covers.
5688    /// Shape-only shadows live in the shadow cache, keyed by their content
5689    /// and device placement, so a scrolling card re-blits its cached blur.
5690    /// The blurred shadow texture and whether the cache held it: a
5691    /// shape-only shadow is cached by content and placement, a shadow with
5692    /// text renders every frame.
5693    fn blurred_shadow_source<C: FrameCommandRecorder>(
5694        &mut self,
5695        recorder: &mut C,
5696        shadow: &ShadowDraw,
5697        source_device: DevicePixelBounds,
5698        pixel_radius: f32,
5699        root_scale: f32,
5700        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5701    ) -> Option<(Rc<OffscreenTarget>, bool, SourceContent)> {
5702        let shape_only = shadow.texts.is_empty();
5703        let key = if shape_only {
5704            shape_shadow_surface_cache_key(shadow, source_device, pixel_radius, root_scale)
5705        } else {
5706            None
5707        };
5708        let content = key.map_or(SourceContent::Transient, |key| {
5709            SourceContent::retained(&key)
5710        });
5711        if let Some(entry) = key.and_then(|key| self.shadow_surface_cache.get(&key)) {
5712            return Some((Rc::clone(&entry.target), true, content));
5713        }
5714        // A shadow whose blur compiles is left out until the blur lands.
5715        if !self.effect_renderer.blur_draws_now(
5716            &self.device,
5717            TileMode::Decal,
5718            (source_device.width, source_device.height),
5719            pixel_radius,
5720            pixel_radius,
5721        ) {
5722            self.note_placeholder();
5723            return None;
5724        }
5725        if !shape_only {
5726            self.frame_stats.record_shadow_text_blur_fallback();
5727        }
5728        let source = self.render_shadow_source(
5729            recorder,
5730            shadow,
5731            source_device,
5732            pixel_radius,
5733            root_scale,
5734            key.is_some(),
5735            transients,
5736        )?;
5737        if let Some(key) = key {
5738            self.frame_stats
5739                .record_shadow_shape_cache_miss(source_device.width, source_device.height);
5740            self.frame_stats.maybe_print_shadow_shape_cache_miss(
5741                source_device.width,
5742                source_device.height,
5743                key.content_hash,
5744                pixel_radius,
5745                [source_device.x, source_device.y],
5746                shadow.shapes.as_ref().map_or(0, RunDraw::record_count) as usize,
5747                shadow.clip,
5748            );
5749            self.insert_cached_shadow_surface(key, Rc::clone(&source));
5750        }
5751        Some((source, false, content))
5752    }
5753
5754    #[expect(clippy::too_many_arguments)]
5755    pub(crate) fn resolve_blurred_shadow<C: FrameCommandRecorder>(
5756        &mut self,
5757        recorder: &mut C,
5758        shadow: &ShadowDraw,
5759        z: usize,
5760        root_scale: f32,
5761        target_rect: DeviceRect4,
5762        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5763        resolved: &mut Vec<ResolvedComposite>,
5764    ) {
5765        if !shadow.requires_surface()
5766            || skip_shadow_draws()
5767            || !root_scale.is_finite()
5768            || root_scale <= 0.0
5769        {
5770            return;
5771        }
5772        let Some(bounds) = shadow_draw_bounds(shadow) else {
5773            return;
5774        };
5775        let margin = blur_reach(shadow.blur_radius, root_scale);
5776        let source_bounds = expand_rect(bounds, margin, margin);
5777        let mut visible = source_bounds;
5778        if let Some(clip) = shadow.clip {
5779            let Some(clipped) = visible.intersect(expand_rect(clip, margin, margin)) else {
5780                return;
5781            };
5782            visible = clipped;
5783        }
5784        let target_logical = Rect {
5785            x: target_rect.0 / root_scale,
5786            y: target_rect.1 / root_scale,
5787            width: target_rect.2 / root_scale,
5788            height: target_rect.3 / root_scale,
5789        };
5790        let Some(visible) = visible.intersect(expand_rect(target_logical, margin, margin)) else {
5791            return;
5792        };
5793        let max_texture_dim = self.max_texture_dim();
5794        let shape_only = shadow.texts.is_empty();
5795        let anchor = shadow
5796            .shapes
5797            .as_ref()
5798            .and_then(|run| run.placement.snap_anchor);
5799        let source_device = shape_only
5800            .then(|| {
5801                translation_stable_anchored_device_pixel_bounds(
5802                    source_bounds,
5803                    anchor,
5804                    root_scale,
5805                    max_texture_dim,
5806                )
5807            })
5808            .flatten()
5809            .or_else(|| device_pixel_bounds(visible, root_scale, max_texture_dim));
5810        let Some(source_device) = source_device else {
5811            return;
5812        };
5813        let pixel_radius = shadow.blur_radius * root_scale;
5814        let Some((source, hit, content)) = self.blurred_shadow_source(
5815            recorder,
5816            shadow,
5817            source_device,
5818            pixel_radius,
5819            root_scale,
5820            transients,
5821        ) else {
5822            return;
5823        };
5824        let dest = (
5825            source_device.x,
5826            source_device.y,
5827            source_device.width as f32,
5828            source_device.height as f32,
5829        );
5830        let mut coverage = intersect_device_rects(dest, target_rect);
5831        if let Some(clip) = shadow.clip {
5832            coverage = coverage.and_then(|coverage| {
5833                intersect_device_rects(coverage, anchored_rect_to_device(clip, anchor, root_scale))
5834            });
5835        }
5836        let Some(coverage) = coverage else {
5837            return;
5838        };
5839        if hit {
5840            self.frame_stats.record_shadow_shape_cache_hit(
5841                (coverage.2 as u64).saturating_mul(coverage.3 as u64),
5842            );
5843        }
5844        let rounded_mask = shadow_composite_mask(shadow, anchor, root_scale);
5845        let downscaled =
5846            (source.width, source.height) != (source_device.width, source_device.height);
5847        let (sample_mode, source_viewport) = if downscaled {
5848            (
5849                CompositeSampleMode::Linear,
5850                Some((0.0, 0.0, source.width as f32, source.height as f32)),
5851            )
5852        } else {
5853            (CompositeSampleMode::Nearest, None)
5854        };
5855        resolved.push(ResolvedComposite {
5856            z_index: z,
5857            source,
5858            content,
5859            dest,
5860            scissor: Some(coverage),
5861            kind: ResolvedCompositeKind::Blit {
5862                alpha: 1.0,
5863                blend_mode: BlendMode::SrcOver,
5864                rounded_mask,
5865                sample_mode,
5866                source_viewport,
5867            },
5868        });
5869    }
5870
5871    /// Draws a shadow's shapes and texts into a surface covering `bounds`
5872    /// and blurs it. A wide blur runs at its scratch size and its result
5873    /// stays there, read bilinearly by the composite; a post-blur cutout
5874    /// needs the surface's full size, so the blurred result is interpolated
5875    /// back into it first and the cutout drawn at that size. A retained
5876    /// result feeds the shadow cache; a transient one is registered with
5877    /// the frame's transients and released with them. `None` when the
5878    /// shadow draws nothing.
5879    #[expect(clippy::too_many_arguments)]
5880    fn render_shadow_source<C: FrameCommandRecorder>(
5881        &mut self,
5882        recorder: &mut C,
5883        shadow: &ShadowDraw,
5884        bounds: DevicePixelBounds,
5885        pixel_radius: f32,
5886        root_scale: f32,
5887        retained: bool,
5888        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
5889    ) -> Option<Rc<OffscreenTarget>> {
5890        let (width, height) = (bounds.width, bounds.height);
5891        let device = self.device.clone();
5892        let (scratch_width, scratch_height) =
5893            crate::effect_renderer::blur_scratch_size(pixel_radius, pixel_radius, width, height);
5894        let full_size_result = shadow.post_blur_cutouts.is_some()
5895            || (scratch_width, scratch_height) == (width, height);
5896        let (result_width, result_height) = if full_size_result {
5897            (width, height)
5898        } else {
5899            (scratch_width, scratch_height)
5900        };
5901        let result = if retained {
5902            Rc::new(self.acquire_retained_surface(result_width, result_height))
5903        } else {
5904            self.shadow_transient(
5905                recorder,
5906                transients,
5907                "Shadow Result",
5908                result_width,
5909                result_height,
5910            )
5911        };
5912        let source = if full_size_result {
5913            Rc::clone(&result)
5914        } else {
5915            self.shadow_transient(recorder, transients, "Shadow Source", width, height)
5916        };
5917        let offset = [bounds.x, bounds.y];
5918        let target = PassTarget {
5919            view: &source.view,
5920            width,
5921            height,
5922        };
5923        let scene = shadow_scene(
5924            shadow.shapes.as_ref(),
5925            &shadow.texts,
5926            blur_reach(shadow.blur_radius, root_scale),
5927        );
5928        let segment = PassSegment {
5929            scene: &scene,
5930            ops: &scene.draw_ops,
5931            composites: &[],
5932            offset,
5933            scissor: None,
5934            first_run_window: None,
5935            transform: SegmentTransform::IDENTITY,
5936            scale: root_scale,
5937        };
5938        let drew = self.encode_pass(
5939            recorder,
5940            target,
5941            (std::slice::from_ref(&segment), SegmentLayout::Stacked),
5942            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
5943            "Shadow Source Pass",
5944        );
5945        match drew {
5946            Ok(true) => {}
5947            Ok(false) => {
5948                drop(source);
5949                if retained && let Ok(target) = Rc::try_unwrap(result) {
5950                    self.defer_offscreen_release(target);
5951                }
5952                return None;
5953            }
5954            Err(error) => {
5955                log::error!("shadow source pass failed: {error}");
5956                return None;
5957            }
5958        }
5959        if pixel_radius > 0.0 {
5960            let scratch_descriptor = self.transient_offscreen_descriptor(
5961                "Shadow Blur Scratch",
5962                scratch_width,
5963                scratch_height,
5964            );
5965            let scratch = recorder.acquire_transient_offscreen(&device, scratch_descriptor);
5966            let blurred = if full_size_result && (scratch_width, scratch_height) != (width, height)
5967            {
5968                Some(self.shadow_transient(
5969                    recorder,
5970                    transients,
5971                    "Shadow Blur Result",
5972                    scratch_width,
5973                    scratch_height,
5974                ))
5975            } else {
5976                None
5977            };
5978            let blur_dest = match &blurred {
5979                Some(blurred) => (&blurred.view, (scratch_width, scratch_height)),
5980                None => (&result.view, (result_width, result_height)),
5981            };
5982            let passes = self.effect_renderer.encode_blur_scissored_ping_pong_passes(
5983                recorder,
5984                &device,
5985                &source,
5986                &scratch,
5987                blur_dest,
5988                pixel_radius,
5989                pixel_radius,
5990                TileMode::Decal,
5991                None,
5992            );
5993            recorder.record_passes(passes);
5994            self.effect_renderer.record_blur_pass();
5995            recorder.release_transient_offscreen(scratch_descriptor, scratch);
5996            if let Some(blurred) = &blurred {
5997                self.effect_renderer
5998                    .encode_upscale_pass(recorder, &device, blurred, &result.view);
5999                recorder.record_pass();
6000            }
6001        }
6002        if let Some(cutout_run) = &shadow.post_blur_cutouts {
6003            let cutouts = shadow_scene(Some(cutout_run), &[], 0.0);
6004            let segment = PassSegment {
6005                scene: &cutouts,
6006                ops: &cutouts.draw_ops,
6007                composites: &[],
6008                offset,
6009                scissor: None,
6010                first_run_window: None,
6011                transform: SegmentTransform::IDENTITY,
6012                scale: root_scale,
6013            };
6014            if let Err(error) = self.encode_pass(
6015                recorder,
6016                target,
6017                (std::slice::from_ref(&segment), SegmentLayout::Stacked),
6018                wgpu::LoadOp::Load,
6019                "Shadow Cutout Pass",
6020            ) {
6021                log::error!("shadow cutout pass failed: {error}");
6022            }
6023        }
6024        Some(result)
6025    }
6026
6027    /// A transient surface of a shadow's frame, released with the frame's
6028    /// transients.
6029    fn shadow_transient<C: FrameCommandRecorder>(
6030        &self,
6031        recorder: &mut C,
6032        transients: &mut Vec<(FrameTextureDescriptor, Rc<OffscreenTarget>)>,
6033        label: &'static str,
6034        width: u32,
6035        height: u32,
6036    ) -> Rc<OffscreenTarget> {
6037        let descriptor = self.transient_offscreen_descriptor(label, width, height);
6038        let target = Rc::new(recorder.acquire_transient_offscreen(&self.device, descriptor));
6039        transients.push((descriptor, Rc::clone(&target)));
6040        target
6041    }
6042
6043    /// Whether `run` draws from retained buffers keyed by its command.
6044    pub(crate) fn run_is_stored(&self, run: &RunDraw) -> bool {
6045        self.run_store.is_stored(run)
6046    }
6047
6048    /// The pipeline `segment` of a run at `placement` draws with. `clipped`
6049    /// says the variant tests the run's clip: a turned run's, since an
6050    /// unturned one's clip is its paint's scissor (see [`clip_scissor`]).
6051    fn run_pipeline_key(
6052        segment: &RecordSegment,
6053        placement: &crate::scene::Placement,
6054        tier: RunTier,
6055        ablation: ShapeAblation,
6056        turns: ShapeTurns,
6057        (depth, clip): (bool, SegmentClip),
6058        viewport: ViewportUniformParams,
6059    ) -> ShapePipelineKey {
6060        let blend_mode = supported_blend_mode(segment.blend);
6061        let laid = depth
6062            && blend_mode == BlendMode::SrcOver
6063            && !placement.paints()
6064            && clip != SegmentClip::Rounded
6065            && !ablation.material
6066            && !ablation.fill;
6067        ShapePipelineKey {
6068            blend_mode,
6069            tier,
6070            variant: ShapeVariant::of_segment(
6071                segment,
6072                clip,
6073                ablation,
6074                laid,
6075                (
6076                    turns == ShapeTurns::None,
6077                    turns == ShapeTurns::None
6078                        && placement.snap_anchor.is_some()
6079                        && viewport.offset.iter().all(|value| value.fract() == 0.0),
6080                ),
6081            ),
6082            turns,
6083            depth: if depth {
6084                ShapeDepth::Tested
6085            } else {
6086                ShapeDepth::Off
6087            },
6088        }
6089    }
6090
6091    /// Queues for a later frame the shape pipelines `keys` name and the
6092    /// interiors they lay down, handing `awaited` each still to land.
6093    pub(crate) fn warm_shapes_later(
6094        &mut self,
6095        keys: &PipelineDemand,
6096        awaited: &mut impl FnMut(Pending<wgpu::RenderPipeline>),
6097    ) {
6098        for key in keys.keys() {
6099            self.shape_pipelines.warm_later(key, awaited);
6100        }
6101    }
6102
6103    /// Readies the pipeline of each key `pipelines` holds and, in a pass
6104    /// with a depth buffer, the one laying down its opaque interiors (see
6105    /// [`ShapePipelines::ensure`]), leaving `pipelines` empty.
6106    pub(crate) fn ensure_run_pipelines(&mut self, pipelines: &mut PipelineDemand) {
6107        for key in pipelines.drain() {
6108            self.shape_pipelines.ensure(key);
6109            if let Some(interior) = key.interior() {
6110                self.shape_pipelines.ensure(interior);
6111            }
6112        }
6113    }
6114
6115    /// Brings a stored run's tables up to date and appends its draws, under
6116    /// a placement uniform of its own, to the pass's run draws `draws`, and
6117    /// the pipelines they draw with to `pipelines`.
6118    #[expect(clippy::too_many_arguments)]
6119    pub(crate) fn prepare_store_run<C: FrameCommandRecorder>(
6120        &mut self,
6121        recorder: &mut C,
6122        run: &RunDraw,
6123        viewport: ViewportUniformParams,
6124        root_scale: f32,
6125        window: &std::ops::Range<u32>,
6126        (depth, mut depth_keys): (bool, Option<&mut PipelineDemand>),
6127        (draws, pipelines): (&mut Vec<RunDrawCall>, &mut PipelineDemand),
6128    ) -> StoreRunBatch {
6129        let placement = &run.placement;
6130        let ablation = self.ablation.shape;
6131        let turns = ShapeTurns::of(viewport.transform, false);
6132        let scissor = clip_scissor(placement, root_scale, viewport);
6133        let clip = SegmentClip::of(placement, scissor.is_some());
6134        let start = draws.len();
6135        self.run_store.stored_run_draws(
6136            &self.device,
6137            run,
6138            &mut |segment| {
6139                let key = |depth| {
6140                    Self::run_pipeline_key(
6141                        segment,
6142                        placement,
6143                        RunTier::Store,
6144                        ablation,
6145                        turns,
6146                        (depth, clip),
6147                        viewport,
6148                    )
6149                };
6150                if let Some(keys) = depth_keys.as_deref_mut() {
6151                    keys.add(key(true));
6152                }
6153                key(depth)
6154            },
6155            draws,
6156        );
6157        window_draws(draws, start, window);
6158        let run_draws = &draws[start..];
6159        let upload_start = Instant::now();
6160        let (upload, fill, tables) = self.run_store.upload_stored(
6161            &self.device,
6162            recorder,
6163            run,
6164            root_scale,
6165            window,
6166            run_draws,
6167        );
6168        if let Some(total_ms) = should_log_wgpu_render_stage(upload_start, Instant::now()) {
6169            log::warn!(
6170                "[wgpu-render-stage:run-upload] total_ms={total_ms:.2} bytes={} records={}",
6171                upload.upload_bytes,
6172                run.tables().shapes.len()
6173            );
6174        }
6175        self.frame_stats.record_command_stats(upload);
6176        if let Some(fill) = fill {
6177            self.frame_stats.add_shape_fill(fill);
6178        }
6179        let uniforms = Uniforms::of(
6180            viewport,
6181            PlacementData::of(&run.placement, root_scale, viewport.transform, [0.0; 2]),
6182            RunTier::Store,
6183        );
6184        let uniform_slot =
6185            self.viewport_uniforms
6186                .claim(&self.device, &self.uniform_bind_group_layout, &uniforms);
6187        for draw in run_draws {
6188            pipelines.add(draw.key);
6189        }
6190        StoreRunBatch {
6191            tables,
6192            uniform_slot,
6193            draws: start..draws.len(),
6194            clip: scissor,
6195        }
6196    }
6197
6198    pub(crate) fn open_arena(&mut self) -> usize {
6199        self.run_store.open_arena()
6200    }
6201
6202    /// The records the open arena chunk holds so far.
6203    pub(crate) fn open_arena_records(&self) -> u32 {
6204        self.run_store.open_arena_records()
6205    }
6206
6207    pub(crate) fn arena_accepts(&self, chunk: usize, run: &RunDraw) -> bool {
6208        self.run_store.arena_accepts(chunk, run)
6209    }
6210
6211    /// Appends `window` of `run`'s records to the open arena chunk, their
6212    /// placement under `turn` and moved by `shift` (see
6213    /// [`PlacementData::of`]), keyed for a pass whose flat and turned
6214    /// records alternate often when `mixed_turns`, and the pipelines they
6215    /// draw with to `pipelines`. `clip` says how its variant tests its clip:
6216    /// an unturned run leaves a rect clip to its paint's scissor, never a
6217    /// rounded one.
6218    #[expect(clippy::too_many_arguments)]
6219    pub(crate) fn append_arena_run(
6220        &mut self,
6221        chunk: usize,
6222        run: &RunDraw,
6223        window: std::ops::Range<u32>,
6224        (root_scale, shift): (f32, [f32; 2]),
6225        viewport: ViewportUniformParams,
6226        mixed_turns: bool,
6227        (depth, clip): (bool, SegmentClip),
6228        (pipelines, mut depth_keys): (&mut PipelineDemand, Option<&mut PipelineDemand>),
6229    ) -> u32 {
6230        let placement = &run.placement;
6231        let ablation = self.ablation.shape;
6232        let turn = viewport.transform;
6233        let turns = ShapeTurns::of(turn, mixed_turns);
6234        self.run_store.append_arena(
6235            chunk,
6236            run,
6237            window,
6238            (root_scale, turn, shift),
6239            &mut |segment| {
6240                let key = |depth| {
6241                    Self::run_pipeline_key(
6242                        segment,
6243                        placement,
6244                        RunTier::Arena,
6245                        ablation,
6246                        turns,
6247                        (depth, clip),
6248                        viewport,
6249                    )
6250                };
6251                if let Some(keys) = depth_keys.as_deref_mut() {
6252                    keys.add(key(true));
6253                }
6254                key(depth)
6255            },
6256            pipelines,
6257        )
6258    }
6259
6260    /// Moves the open chunk's draws since its last cut onto `out`, keeping
6261    /// it open.
6262    pub(crate) fn cut_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
6263        self.run_store.cut_arena(&self.device, chunk, out);
6264    }
6265
6266    /// Uploads the open chunk and moves its draws since its last cut onto
6267    /// `out`.
6268    pub(crate) fn close_arena(&mut self, chunk: usize, out: &mut Vec<RunDrawCall>) {
6269        if let Some(fill) = self.run_store.close_arena(&self.device, chunk, out) {
6270            self.frame_stats.add_shape_fill(fill);
6271        }
6272    }
6273
6274    #[expect(clippy::too_many_arguments)]
6275    pub(crate) fn draw_run_calls(
6276        &self,
6277        pass: &mut TrackedPass<'_, '_>,
6278        tables: ArenaBinding<'_>,
6279        uniform_slot: usize,
6280        draws: &[RunDrawCall],
6281        scissor: (u32, u32, u32, u32),
6282        stage: RunStage,
6283        meshes: Option<(crate::mesh_fallback::RunMeshes<'_>, bool)>,
6284    ) -> Result<(), String> {
6285        match stage {
6286            RunStage::Paint => {
6287                if draws.is_empty() {
6288                    return Ok(());
6289                }
6290                self.frame_stats.bump_shapes();
6291                self.record_run_draws(
6292                    pass,
6293                    tables,
6294                    uniform_slot,
6295                    scissor,
6296                    draws.iter().map(PlannedRunDraw::paint),
6297                    meshes,
6298                )
6299            }
6300            RunStage::Interiors => {
6301                let planned = interior_run_draws(draws);
6302                if planned.is_empty() {
6303                    return Ok(());
6304                }
6305                self.frame_stats
6306                    .shape_interior_draws
6307                    .set(self.frame_stats.shape_interior_draws.get() + planned.len() as u32);
6308                self.record_run_draws(
6309                    pass,
6310                    tables,
6311                    uniform_slot,
6312                    scissor,
6313                    planned.into_iter(),
6314                    None,
6315                )
6316            }
6317        }
6318    }
6319
6320    /// Records `planned` against one batch's tables, uniform and scissor. A
6321    /// draw whose pipeline still compiles draws its fallback triangles from
6322    /// `meshes`, with the depth buffer or not, else it is left out.
6323    fn record_run_draws(
6324        &self,
6325        pass: &mut TrackedPass<'_, '_>,
6326        tables: ArenaBinding<'_>,
6327        uniform_slot: usize,
6328        scissor: (u32, u32, u32, u32),
6329        planned: impl ExactSizeIterator<Item = PlannedRunDraw>,
6330        meshes: Option<(crate::mesh_fallback::RunMeshes<'_>, bool)>,
6331    ) -> Result<(), String> {
6332        self.frame_stats.add_draw_calls(planned.len() as u32);
6333        let (x, y, width, height) = scissor;
6334        pass.set_scissor_rect(x, y, width, height);
6335        self.viewport_uniforms.bind(pass, uniform_slot)?;
6336        pass.set_bind_group(1, tables.bind_group, &tables.offsets[2..]);
6337        let bind_records = |pass: &mut TrackedPass<'_, '_>| {
6338            for (slot, buffer) in tables.records.into_iter().enumerate() {
6339                pass.set_vertex_buffer(
6340                    slot as u32,
6341                    buffer.slice(u64::from(tables.offsets[slot])..),
6342                );
6343            }
6344        };
6345        bind_records(pass);
6346        let mut bound_class = None;
6347        let mut records_bound = true;
6348        for (position, draw) in planned.enumerate() {
6349            let key = draw.key;
6350            let Some((pipeline, fallback)) = self.shape_pipelines.get(key) else {
6351                // Its pipeline compiles: the draw takes its fallback
6352                // triangles, or is left out, until it lands.
6353                let mesh = meshes.and_then(|(meshes, depth)| {
6354                    let range = meshes.ranges.get(position)?.clone()?;
6355                    Some((range, meshes, self.mesh_pipeline(depth)?))
6356                });
6357                let Some((range, meshes, mesh_pipeline)) = mesh else {
6358                    self.note_placeholder();
6359                    continue;
6360                };
6361                self.note_mesh_fallback();
6362                pass.set_pipeline(mesh_pipeline);
6363                meshes.draw(pass, range);
6364                bound_class = None;
6365                records_bound = false;
6366                continue;
6367            };
6368            if !records_bound {
6369                bind_records(pass);
6370                records_bound = true;
6371            }
6372            if fallback {
6373                self.frame_stats
6374                    .shape_pipeline_fallback_draws
6375                    .set(self.frame_stats.shape_pipeline_fallback_draws.get() + 1);
6376            } else if !key.is_general() {
6377                self.frame_stats
6378                    .shape_specialized_draws
6379                    .set(self.frame_stats.shape_specialized_draws.get() + 1);
6380            }
6381            if bound_class != Some(draw.band_class) {
6382                pass.set_index_buffer(
6383                    self.run_store.strip_index_buffer(draw.band_class).slice(..),
6384                    wgpu::IndexFormat::Uint32,
6385                );
6386                bound_class = Some(draw.band_class);
6387            }
6388            pass.set_pipeline(pipeline);
6389            pass.draw_indexed(draw.indices, 0, draw.records);
6390        }
6391        Ok(())
6392    }
6393
6394    /// Draws a stored-run batch, whose draws are its range of `draws`.
6395    pub(crate) fn draw_store_run(
6396        &self,
6397        pass: &mut TrackedPass<'_, '_>,
6398        batch: &StoreRunBatch,
6399        draws: &[RunDrawCall],
6400        scissor: (u32, u32, u32, u32),
6401        stage: RunStage,
6402        meshes: Option<(crate::mesh_fallback::RunMeshes<'_>, bool)>,
6403    ) -> Result<(), String> {
6404        self.draw_run_calls(
6405            pass,
6406            batch.tables.binding(),
6407            batch.uniform_slot,
6408            &draws[batch.draws.clone()],
6409            scissor,
6410            stage,
6411            meshes.map(|(meshes, depth)| (meshes.of(batch.draws.clone()), depth)),
6412        )
6413    }
6414
6415    #[expect(clippy::too_many_arguments)]
6416    pub(crate) fn draw_arena(
6417        &self,
6418        pass: &mut TrackedPass<'_, '_>,
6419        chunk: usize,
6420        uniform_slot: usize,
6421        draws: &[RunDrawCall],
6422        scissor: (u32, u32, u32, u32),
6423        stage: RunStage,
6424        meshes: Option<(crate::mesh_fallback::RunMeshes<'_>, bool)>,
6425    ) -> Result<(), String> {
6426        self.draw_run_calls(
6427            pass,
6428            self.run_store.arena_binding(chunk),
6429            uniform_slot,
6430            draws,
6431            scissor,
6432            stage,
6433            meshes,
6434        )
6435    }
6436    #[cfg(not(target_arch = "wasm32"))]
6437    pub(crate) fn surface_format(&self) -> wgpu::TextureFormat {
6438        self.display_format
6439    }
6440
6441    pub fn device_error_count(&self) -> u64 {
6442        self.device_errors.error_count()
6443    }
6444
6445    /// A pass that only applies `load_op` to the target, for a scene with
6446    /// nothing to draw that still needs its clear.
6447    pub(crate) fn clear_target<C: FrameCommandRecorder>(
6448        &self,
6449        recorder: &mut C,
6450        view: &wgpu::TextureView,
6451        load_op: wgpu::LoadOp<wgpu::Color>,
6452    ) {
6453        self.empty_pass(recorder, "Clear Pass", view, load_op);
6454    }
6455
6456    pub(crate) fn empty_pass<C: FrameCommandRecorder>(
6457        &self,
6458        recorder: &mut C,
6459        label: &'static str,
6460        view: &wgpu::TextureView,
6461        load_op: wgpu::LoadOp<wgpu::Color>,
6462    ) {
6463        let pass = recorder.begin_color_pass(label, view, load_op);
6464        drop(pass);
6465        recorder.record_pass();
6466    }
6467    pub(crate) fn draw_image_cmds(
6468        &self,
6469        pass: &mut TrackedPass<'_, '_>,
6470        image_slot: &ImageSlot,
6471        uniform_slot: usize,
6472        cmds: &[ImageDrawCmd],
6473        (blend_mode, depth): (BlendMode, bool),
6474        bound: Option<(u32, u32, u32, u32)>,
6475    ) -> Result<(), String> {
6476        if cmds.is_empty() {
6477            return Ok(());
6478        }
6479        self.frame_stats.bump_images();
6480        self.frame_stats.add_draw_calls(cmds.len() as u32);
6481        let mut bound_pipeline = None;
6482        self.viewport_uniforms.bind(pass, uniform_slot)?;
6483        pass.set_index_buffer(image_slot.indices.slice(), wgpu::IndexFormat::Uint32);
6484        pass.set_vertex_buffer(0, image_slot.vertices.slice());
6485        let mut clips_bound = false;
6486        for cmd in cmds {
6487            let Some((x, y, width, height)) = bounded_scissor(cmd.scissor, bound) else {
6488                continue;
6489            };
6490            pass.set_scissor_rect(x, y, width, height);
6491            let variant = ImageVariant::of(cmd, depth);
6492            if bound_pipeline != Some(variant) {
6493                let Some(pipeline) = self.image_pipeline(blend_mode, variant) else {
6494                    continue;
6495                };
6496                pass.set_pipeline(pipeline);
6497                bound_pipeline = Some(variant);
6498            }
6499            pass.set_bind_group(1, &cmd.image.bind_group, &[]);
6500            let instance = match cmd.clip {
6501                Some(clip) => {
6502                    if !clips_bound {
6503                        let clips = image_slot
6504                            .clips
6505                            .as_ref()
6506                            .ok_or_else(|| "rounded image without clip instances".to_string())?;
6507                        pass.set_vertex_buffer(1, clips.slice());
6508                        clips_bound = true;
6509                    }
6510                    clip
6511                }
6512                None => 0,
6513            };
6514            pass.draw_indexed(
6515                cmd.index_start..(cmd.index_start + 6),
6516                0,
6517                instance..instance + 1,
6518            );
6519        }
6520        Ok(())
6521    }
6522
6523    pub(crate) fn draw_glyph_cmds(
6524        &self,
6525        pass: &mut TrackedPass<'_, '_>,
6526        (glyph_slot, turned_slot): (Option<&BufferUpload>, Option<&BufferUpload>),
6527        uniform_slot: usize,
6528        cmds: &[GlyphDrawCmd],
6529        bound: Option<(u32, u32, u32, u32)>,
6530        frame: PassFrame,
6531    ) -> Result<(), String> {
6532        if cmds.is_empty() {
6533            return Ok(());
6534        }
6535        let whole_target = frame.scissor(bound);
6536        self.frame_stats.bump_text();
6537        let mut bound_atlas = None;
6538        // Which shared instances are bound, turned or plain, and which
6539        // pipeline; retained runs draw with a plain one.
6540        let mut shared_bound: Option<bool> = None;
6541        let mut bound_pipeline: Option<GlyphQuads> = None;
6542        let mut bound_run_instances: Option<&wgpu::Buffer> = None;
6543        let mut draws = 0u32;
6544        for draw in GlyphDraws::new(cmds) {
6545            let scissor = match draw.scissor {
6546                Some(scissor) => bounded_scissor(scissor, bound),
6547                None => Some(whole_target),
6548            };
6549            let Some((x, y, width, height)) = scissor else {
6550                continue;
6551            };
6552            pass.set_scissor_rect(x, y, width, height);
6553            if !bound_atlas.is_some_and(|atlas| Rc::ptr_eq(atlas, draw.atlas)) {
6554                pass.set_bind_group(1, draw.atlas.as_ref(), &[]);
6555                bound_atlas = Some(draw.atlas);
6556            }
6557            draws += 1;
6558            match draw.step {
6559                GlyphDrawStep::Shared(instances, quads) => {
6560                    if bound_pipeline != Some(quads) {
6561                        let Some(pipeline) = self.glyph_atlas_pipeline(frame.depth, quads) else {
6562                            continue;
6563                        };
6564                        pass.set_pipeline(pipeline);
6565                        bound_pipeline = Some(quads);
6566                    }
6567                    let turned = quads.turned();
6568                    if shared_bound != Some(turned) {
6569                        let slot =
6570                            if turned { turned_slot } else { glyph_slot }.ok_or_else(|| {
6571                                "shared glyph draw without glyph instances".to_string()
6572                            })?;
6573                        self.viewport_uniforms.bind(pass, uniform_slot)?;
6574                        pass.set_vertex_buffer(0, slot.slice());
6575                        shared_bound = Some(turned);
6576                        bound_run_instances = None;
6577                    }
6578                    pass.draw(0..GLYPH_QUAD_CORNERS, instances);
6579                }
6580                GlyphDrawStep::Retained {
6581                    run,
6582                    uniform_slot: retained_slot,
6583                    aligned,
6584                } => {
6585                    let quads = GlyphQuads::plain(aligned);
6586                    if bound_pipeline != Some(quads) {
6587                        let Some(pipeline) = self.glyph_atlas_pipeline(frame.depth, quads) else {
6588                            continue;
6589                        };
6590                        pass.set_pipeline(pipeline);
6591                        bound_pipeline = Some(quads);
6592                    }
6593                    shared_bound = None;
6594                    self.viewport_uniforms.bind(pass, retained_slot)?;
6595                    let instances = run.span.instance_buffer();
6596                    if bound_run_instances != Some(instances) {
6597                        pass.set_vertex_buffer(0, instances.slice(..));
6598                        bound_run_instances = Some(instances);
6599                    }
6600                    pass.draw(0..GLYPH_QUAD_CORNERS, run.span.instances());
6601                }
6602            }
6603        }
6604        self.frame_stats.add_draw_calls(draws);
6605        Ok(())
6606    }
6607    pub(crate) fn append_image_draw_cmd(
6608        &mut self,
6609        image_draw: &ImageDraw,
6610        viewport: ViewportUniformParams,
6611        root_scale: f32,
6612        (image_vertices, image_indices): (&mut Vec<Vertex>, &mut Vec<u32>),
6613        image_clips: &mut Vec<DeviceRoundedClip>,
6614        image_cmds: &mut Vec<ImageDrawCmd>,
6615    ) -> Result<(), String> {
6616        let snap_delta = image_draw
6617            .snap_anchor
6618            .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
6619            .unwrap_or_default();
6620        let rect = image_draw.rect.translate(snap_delta.x, snap_delta.y);
6621        if rect.width <= 0.0 || rect.height <= 0.0 || image_draw.alpha <= 0.0 {
6622            return Ok(());
6623        }
6624
6625        let (mut tint, cpu_filter) =
6626            tint_for_image(image_draw.color_filter.as_ref(), image_draw.alpha);
6627        if tint[3] <= 0.0 {
6628            return Ok(());
6629        }
6630
6631        let filtered_image = cpu_filter
6632            .map(|filter| apply_filter_to_bitmap(&image_draw.image, filter))
6633            .transpose()?;
6634        let prepared_image = filtered_image.as_ref().unwrap_or(&image_draw.image);
6635        if let cranpose_ui_graphics::ImagePixelFormat::Alpha8 { color } = prepared_image.format() {
6636            for (channel, value) in tint[..3].iter_mut().zip(color) {
6637                *channel *= value as f32 / 255.0;
6638            }
6639        }
6640
6641        let geometry = resolve_image_geometry_with_delta(image_draw, root_scale, snap_delta);
6642        let Some(scissor) =
6643            scissor_rect_for_layer(geometry.rect, geometry.clip, root_scale, viewport)
6644        else {
6645            return Ok(());
6646        };
6647
6648        let Some(uv_rect) = image_uv_rect(&image_draw.image, image_draw.src_rect) else {
6649            return Ok(());
6650        };
6651        let device_quad = geometry.device_quad(root_scale);
6652        let index_start =
6653            push_image_quad((image_vertices, image_indices), device_quad, tint, &uv_rect);
6654        let clip = DeviceRoundedClip::of(image_draw, root_scale).map(|clip| {
6655            image_clips.push(clip);
6656            image_clips.len() as u32 - 1
6657        });
6658        image_cmds.push(ImageDrawCmd {
6659            index_start,
6660            scissor,
6661            image: self.image_binding(prepared_image, geometry.sampling)?,
6662            clip,
6663        });
6664        Ok(())
6665    }
6666
6667    /// Uploads a pass's image and glyph quads into the frame's buffers.
6668    pub(crate) fn upload_image_slot<C: FrameCommandRecorder>(
6669        &self,
6670        recorder: &mut C,
6671        vertices: &[Vertex],
6672        indices: &[u32],
6673        clips: &[DeviceRoundedClip],
6674    ) -> ImageSlot {
6675        ImageSlot {
6676            vertices: recorder.upload_buffer(
6677                image_vertex_spec(),
6678                &self.device,
6679                bytemuck::cast_slice(vertices),
6680            ),
6681            indices: recorder.upload_buffer(
6682                image_index_spec(),
6683                &self.device,
6684                bytemuck::cast_slice(indices),
6685            ),
6686            clips: (!clips.is_empty()).then(|| {
6687                recorder.upload_buffer(
6688                    UploadAllocatorSpec::vertex(
6689                        "Image Clip Buffer",
6690                        std::mem::size_of::<DeviceRoundedClip>() as u64,
6691                    ),
6692                    &self.device,
6693                    bytemuck::cast_slice(clips),
6694                )
6695            }),
6696        }
6697    }
6698
6699    pub(crate) fn upload_glyph_instances<C: FrameCommandRecorder>(
6700        &self,
6701        recorder: &mut C,
6702        instances: &[GlyphInstance],
6703    ) -> BufferUpload {
6704        recorder.upload_buffer(
6705            glyph_instance_spec(),
6706            &self.device,
6707            bytemuck::cast_slice(instances),
6708        )
6709    }
6710
6711    pub(crate) fn upload_turned_glyphs<C: FrameCommandRecorder>(
6712        &self,
6713        recorder: &mut C,
6714        glyphs: &[TurnedGlyph],
6715    ) -> BufferUpload {
6716        recorder.upload_buffer(
6717            turned_glyph_spec(),
6718            &self.device,
6719            bytemuck::cast_slice(glyphs),
6720        )
6721    }
6722
6723    fn glyph_atlas_entry_for(
6724        &mut self,
6725        glyph: &SoftwareGlyphAtlasGlyph,
6726    ) -> Result<GlyphAtlasEntry, String> {
6727        if let Some(entry) = self
6728            .text_glyph_atlas
6729            .upload_glyph(glyph, &mut self.frame_stats)
6730        {
6731            return Ok(entry);
6732        }
6733
6734        // The draws queued so far bind the full atlas: the glyphs they placed
6735        // reach it before a new atlas takes its place.
6736        self.flush_glyph_uploads();
6737        self.text_glyph_atlas.reset(
6738            &self.device,
6739            &self.image_bind_group_layout,
6740            GlyphSamplers {
6741                nearest: &self.image_nearest_sampler,
6742                linear: &self.image_linear_sampler,
6743            },
6744        );
6745        Err("text glyph atlas filled and was reset".to_string())
6746    }
6747
6748    /// Writes the glyphs the pass placed in the atlas to its texture, ahead
6749    /// of the submit that draws them.
6750    pub(crate) fn flush_glyph_uploads(&mut self) {
6751        self.text_glyph_atlas.flush_uploads(
6752            &self.queue,
6753            &mut self.frame_graph_executor,
6754            &mut self.frame_stats,
6755        );
6756    }
6757
6758    fn glyph_atlas_entry_for_cached(
6759        &mut self,
6760        glyph: &SoftwareGlyphAtlasPlacement,
6761    ) -> Option<GlyphAtlasEntry> {
6762        let entry = self
6763            .text_glyph_atlas
6764            .entry(&GlyphAtlasSlotKey::new(glyph.key, glyph.color))?;
6765        self.frame_stats.record_text_glyph_atlas_hits(1);
6766        Some(entry)
6767    }
6768
6769    fn glyph_atlas_entry_for_placement(
6770        &mut self,
6771        glyph: &SoftwareGlyphAtlasPlacement,
6772    ) -> Result<GlyphAtlasEntry, String> {
6773        if let Some(entry) = self.glyph_atlas_entry_for_cached(glyph) {
6774            return Ok(entry);
6775        }
6776
6777        let Some(upload_glyph) = self.text_glyph_mask_cache.atlas_glyph_for_placement(glyph) else {
6778            return Err("text glyph placement has no retained raster mask".to_string());
6779        };
6780        self.glyph_atlas_entry_for(&upload_glyph)
6781    }
6782
6783    /// The atlas entries of a run's drawing glyphs: of `cached_glyph_run`,
6784    /// which holds only those, or of the drawing glyphs of `collected_run`,
6785    /// a run just collected, whose new glyphs are uploaded here.
6786    fn prepare_text_glyph_entries(
6787        &mut self,
6788        run_key: TextGlyphRunCacheKey,
6789        atlas_generation: u64,
6790        cached_glyph_run: Option<&RunGlyphs>,
6791        collected_run: &[SoftwareGlyphAtlasRunGlyph],
6792        entries: &mut Vec<GlyphAtlasEntry>,
6793    ) -> Result<Rc<[GlyphAtlasEntry]>, String> {
6794        entries.clear();
6795        let mut seen = RunAtlasEntries::new();
6796        if let Some(glyph_run) = cached_glyph_run {
6797            for glyph in glyph_run.iter() {
6798                entries.push(seen.entry(self, &glyph, |renderer| {
6799                    renderer.glyph_atlas_entry_for_placement(&glyph)
6800                })?);
6801            }
6802        } else {
6803            for run_glyph in collected_run {
6804                entries.push(seen.entry(
6805                    self,
6806                    &run_glyph.placement(),
6807                    |renderer| match run_glyph {
6808                        SoftwareGlyphAtlasRunGlyph::Cached(placement) => {
6809                            renderer.glyph_atlas_entry_for_placement(placement)
6810                        }
6811                        SoftwareGlyphAtlasRunGlyph::New(glyph) => {
6812                            renderer.glyph_atlas_entry_for(glyph)
6813                        }
6814                    },
6815                )?);
6816            }
6817        }
6818
6819        let entries: Rc<[GlyphAtlasEntry]> = Rc::from(entries.as_slice());
6820        if let Some(cached) = self.text_glyph_run_cache.get_mut(&run_key) {
6821            cached.atlas_entries = Some(Rc::clone(&entries));
6822            cached.atlas_generation = atlas_generation;
6823        }
6824        Ok(entries)
6825    }
6826
6827    #[expect(clippy::too_many_arguments)]
6828    fn append_text_glyph_quad_run(
6829        &mut self,
6830        source_raster_rect: Rect,
6831        quads: GlyphRunQuads<'_>,
6832        (clip, cut): (Option<Rect>, Option<[f32; 4]>),
6833        viewport: ViewportUniformParams,
6834        root_scale: f32,
6835        glyph_instances: &mut GlyphInstances,
6836        record_cached_hits: bool,
6837    ) -> (GlyphQuads, GlyphExtent) {
6838        let start = glyph_instances.lens();
6839        let mut extent = GlyphExtent::EMPTY;
6840        let origin = [source_raster_rect.x, source_raster_rect.y];
6841        let bounds = quads.bounds.at(origin);
6842        let kind = if viewport.transform.is_identity()
6843            && cut.is_none_or(|edges| {
6844                bounds[0] >= edges[0]
6845                    && bounds[1] >= edges[1]
6846                    && bounds[2] <= edges[2]
6847                    && bounds[3] <= edges[3]
6848            })
6849            && quads
6850                .bounds
6851                .within_viewport(source_raster_rect, clip, viewport, root_scale)
6852        {
6853            // Every quad shows whole and uncut: they sit at whole pixels from
6854            // the run's origin, which then decides their alignment, and
6855            // their extent is the run's bounds.
6856            glyph_instances.plain.extend(quads.instances_at(origin));
6857            extent.add(bounds);
6858            GlyphQuads::plain(glyph_rect_aligned(
6859                [origin[0], origin[1], origin[0], origin[1]],
6860                viewport.offset,
6861            ))
6862        } else if viewport.transform.is_identity() {
6863            let plain = &mut glyph_instances.plain;
6864            let mut aligned = true;
6865            for_each_visible_glyph(
6866                source_raster_rect,
6867                quads,
6868                (clip, cut),
6869                viewport,
6870                root_scale,
6871                |glyph| {
6872                    aligned &= glyph_rect_aligned(glyph.rect, viewport.offset);
6873                    extent.add(glyph.rect);
6874                    plain.push(glyph);
6875                },
6876            );
6877            GlyphQuads::plain(aligned)
6878        } else {
6879            let turn = viewport.transform;
6880            let turned = &mut glyph_instances.turned;
6881            for_each_visible_glyph(
6882                source_raster_rect,
6883                quads,
6884                (clip, cut),
6885                viewport,
6886                root_scale,
6887                |glyph| turned.push(TurnedGlyph::new(glyph, turn)),
6888            );
6889            GlyphQuads::Turned
6890        };
6891        let end = glyph_instances.lens();
6892        let appended = (end.0 - start.0) + (end.1 - start.1);
6893        if record_cached_hits {
6894            self.frame_stats
6895                .record_text_glyph_atlas_hits(u32::try_from(appended).unwrap_or(u32::MAX));
6896        }
6897        (kind, extent)
6898    }
6899
6900    /// The viewport a retained glyph run draws under: its vertices sit at
6901    /// its raster rect's origin, so an untransformed target moves its offset
6902    /// back by that origin, and a transformed one adds the origin to each
6903    /// vertex before its transform, as the shared path's vertices hold it.
6904    fn retained_glyph_viewport(
6905        viewport: ViewportUniformParams,
6906        source_raster_rect: Rect,
6907    ) -> ViewportUniformParams {
6908        if !viewport.transform.is_identity() {
6909            return ViewportUniformParams {
6910                origin: [source_raster_rect.x, source_raster_rect.y],
6911                ..viewport
6912            };
6913        }
6914        ViewportUniformParams {
6915            offset: [
6916                viewport.offset[0] - source_raster_rect.x,
6917                viewport.offset[1] - source_raster_rect.y,
6918            ],
6919            ..viewport
6920        }
6921    }
6922
6923    fn retained_text_glyph_run(
6924        &mut self,
6925        cache_key: TextGlyphRunCacheKey,
6926    ) -> Option<Rc<CachedGpuTextGlyphRun>> {
6927        let atlas_generation = self.text_glyph_atlas.generation();
6928        let frame = self.text_glyph_run_frame;
6929        self.text_glyph_gpu_run_cache
6930            .get(&cache_key)
6931            .filter(|cached| cached.atlas_generation == atlas_generation)
6932            .inspect(|cached| cached.last_frame.set(frame))
6933            .cloned()
6934    }
6935
6936    /// Opens a frame for text runs: runs no frame drew for
6937    /// [`TEXT_GLYPH_GPU_RUN_IDLE_FRAMES`] leave the GPU cache and those no
6938    /// frame drew for [`TEXT_GLYPH_RUN_IDLE_FRAMES`] the CPU cache, and the
6939    /// arena takes back the quads dropped retained runs held.
6940    fn begin_text_glyph_run_frame(&mut self) {
6941        #[cfg(feature = "installed-fonts")]
6942        if let Some(fonts) = self.text_fonts.with_installed_faces() {
6943            // Text drawn before the install may show a missing glyph where an
6944            // installed face now has one.
6945            self.text_fonts = fonts;
6946            self.text_image_cache.clear();
6947            self.text_glyph_run_cache.clear();
6948            self.text_glyph_gpu_run_cache.clear();
6949        }
6950        self.text_glyph_run_frame += 1;
6951        let frame = self.text_glyph_run_frame;
6952        let demand = std::mem::take(&mut self.text_glyph_runs_drawn).saturating_mul(2);
6953        self.text_glyph_run_cache.set_cap(
6954            std::num::NonZeroUsize::new(demand.max(MIN_TEXT_GLYPH_RUN_CACHE_ITEMS))
6955                .unwrap_or(std::num::NonZeroUsize::MIN),
6956        );
6957        evict_idle(
6958            &mut self.text_glyph_gpu_run_cache,
6959            frame,
6960            TEXT_GLYPH_GPU_RUN_IDLE_FRAMES,
6961            |run| run.last_frame.get(),
6962        );
6963        evict_idle(
6964            &mut self.text_glyph_run_cache,
6965            frame,
6966            TEXT_GLYPH_RUN_IDLE_FRAMES,
6967            |run| run.last_frame.get(),
6968        );
6969        self.text_glyph_run_arena.begin_frame();
6970        let evacuating = self.text_glyph_run_arena.evacuating();
6971        if !evacuating.is_empty() {
6972            let moving: Vec<TextGlyphRunCacheKey> = self
6973                .text_glyph_gpu_run_cache
6974                .iter()
6975                .filter(|(_, run)| evacuating.contains(&run.span.chunk()))
6976                .map(|(key, _)| *key)
6977                .collect();
6978            for key in &moving {
6979                self.text_glyph_gpu_run_cache.pop(key);
6980            }
6981        }
6982    }
6983
6984    fn emit_retained_text_glyph_run_if_ready(
6985        &mut self,
6986        cache_key: TextGlyphRunCacheKey,
6987        quads: GlyphRunQuads<'_>,
6988        viewport: ViewportUniformParams,
6989        source_raster_rect: Rect,
6990        scissor: (u32, u32, u32, u32),
6991        glyph_cmds: &mut Vec<GlyphDrawCmd>,
6992    ) -> bool {
6993        let Some(run) = self.retained_text_glyph_run(cache_key).or_else(|| {
6994            if self.ensure_retained_text_glyph_run(cache_key, quads) {
6995                self.retained_text_glyph_run(cache_key)
6996            } else {
6997                None
6998            }
6999        }) else {
7000            return false;
7001        };
7002        let uniform_slot =
7003            self.claim_uniform_slot(Self::retained_glyph_viewport(viewport, source_raster_rect));
7004        self.frame_stats
7005            .record_text_glyph_atlas_hits(u32::try_from(quads.len()).unwrap_or(u32::MAX));
7006        // The run's quads sit at whole texels from its raster origin.
7007        let aligned = viewport.transform.is_identity()
7008            && glyph_rect_aligned(
7009                [source_raster_rect.x, source_raster_rect.y, 0.0, 0.0],
7010                [viewport.offset[0], viewport.offset[1]],
7011            );
7012        glyph_cmds.push(GlyphDrawCmd::retained(
7013            (run, uniform_slot, aligned),
7014            scissor,
7015            self.text_glyph_atlas.bind_group(viewport.transform),
7016        ));
7017        true
7018    }
7019
7020    fn ensure_retained_text_glyph_run(
7021        &mut self,
7022        cache_key: TextGlyphRunCacheKey,
7023        quads: GlyphRunQuads<'_>,
7024    ) -> bool {
7025        let atlas_generation = self.text_glyph_atlas.generation();
7026        if self
7027            .text_glyph_gpu_run_cache
7028            .peek(&cache_key)
7029            .is_some_and(|cached| cached.atlas_generation == atlas_generation)
7030        {
7031            return true;
7032        }
7033
7034        let Some(span) = self
7035            .text_glyph_run_arena
7036            .insert(&self.device, quads.instances_at([0.0, 0.0]))
7037        else {
7038            return false;
7039        };
7040        self.text_glyph_gpu_run_cache.put(
7041            cache_key,
7042            Rc::new(CachedGpuTextGlyphRun {
7043                span,
7044                atlas_generation,
7045                last_frame: Cell::new(self.text_glyph_run_frame),
7046            }),
7047        );
7048        true
7049    }
7050    /// Appends the glyph atlas draws of `text_draw`, whose logical geometry
7051    /// `logical` the caller found drawing into a rect `viewport` shows.
7052    /// `false` when the text cannot draw from the atlas (animated motion, or
7053    /// a run the atlas cannot hold): nothing was appended, and the caller
7054    /// draws the text as a rasterized image instead.
7055    pub(crate) fn append_text_glyph_draws(
7056        &mut self,
7057        (text_draw, logical): (&TextDraw, (Rect, f32)),
7058        viewport: ViewportUniformParams,
7059        root_scale: f32,
7060        glyph_instances: &mut GlyphInstances,
7061        glyph_cmds: &mut Vec<GlyphDrawCmd>,
7062    ) -> bool {
7063        let (_, raster_rect, _, text_scale, static_text_motion) =
7064            text_raster_geometry_at(text_draw, logical, root_scale);
7065        if !static_text_motion {
7066            return false;
7067        }
7068        let run_key = Self::text_glyph_run_cache_key(text_draw, raster_rect, text_scale);
7069        let mut collected_run = std::mem::take(&mut self.scratch_text_glyph_run);
7070        let mut generated_entries = std::mem::take(&mut self.scratch_text_glyph_entries);
7071        let initial_instance_len = glyph_instances.lens();
7072        let initial_cmd_len = glyph_cmds.len();
7073        let drew = self
7074            .text_glyph_run(
7075                text_draw,
7076                raster_rect,
7077                text_scale,
7078                run_key,
7079                &mut collected_run,
7080            )
7081            .is_some_and(|run| {
7082                self.append_text_glyph_run(
7083                    TextGlyphRunDraw {
7084                        text_draw,
7085                        raster_rect,
7086                        run_key,
7087                        run,
7088                    },
7089                    (viewport, root_scale),
7090                    (&collected_run, &mut generated_entries),
7091                    glyph_instances,
7092                    glyph_cmds,
7093                )
7094            });
7095        self.scratch_text_glyph_run = collected_run;
7096        self.scratch_text_glyph_entries = generated_entries;
7097        if !drew {
7098            glyph_instances.truncate(initial_instance_len);
7099            glyph_cmds.truncate(initial_cmd_len);
7100        }
7101        drew
7102    }
7103
7104    /// The run of `text_draw` from the cache, or collected into
7105    /// `collected_run` and cached; `None` when the text cannot draw from the
7106    /// atlas.
7107    fn text_glyph_run(
7108        &mut self,
7109        text_draw: &TextDraw,
7110        raster_rect: Rect,
7111        text_scale: f32,
7112        run_key: TextGlyphRunCacheKey,
7113        collected_run: &mut Vec<SoftwareGlyphAtlasRunGlyph>,
7114    ) -> Option<TextGlyphRunLookup> {
7115        let atlas_generation = self.text_glyph_atlas.generation();
7116        let frame = self.text_glyph_run_frame;
7117        self.text_glyph_runs_drawn += 1;
7118        if let Some(cached) = self.text_glyph_run_cache.get(&run_key) {
7119            cached.last_frame.set(frame);
7120            return Some(TextGlyphRunLookup {
7121                glyphs: cached.glyphs.clone(),
7122                bounds: cached.bounds,
7123                cached: true,
7124                entries: (cached.atlas_generation == atlas_generation)
7125                    .then(|| cached.atlas_entries.as_ref().map(Rc::clone))
7126                    .flatten(),
7127            });
7128        }
7129        collected_run.clear();
7130        if collect_solid_text_atlas_run(
7131            text_draw.text.string().as_ref(),
7132            raster_rect,
7133            &text_draw.text_style,
7134            text_draw.color,
7135            text_draw.font_size,
7136            text_scale,
7137            &self.text_fonts,
7138            &mut self.text_glyph_mask_cache,
7139            collected_run,
7140        )
7141        .is_none()
7142        {
7143            log_text_atlas_fallback(text_draw);
7144            return None;
7145        }
7146        let Some(glyphs) = RunGlyphs::of(
7147            collected_run
7148                .iter()
7149                .map(SoftwareGlyphAtlasRunGlyph::placement),
7150            &mut self.run_glyph_scratch,
7151        ) else {
7152            log_text_atlas_fallback(text_draw);
7153            return None;
7154        };
7155        let bounds = GlyphRunBounds::of(glyphs.iter());
7156        self.frame_stats.record_text_glyph_run_collected();
7157        // A run this frame drew stays: the cache grows rather than evict it.
7158        let cache = &mut self.text_glyph_run_cache;
7159        if cache.len() == cache.cap().get()
7160            && cache
7161                .peek_lru()
7162                .is_some_and(|(_, run)| run.last_frame.get() == frame)
7163        {
7164            cache.set_cap(cache.cap().saturating_add(cache.len()));
7165        }
7166        self.text_glyph_run_cache.put(
7167            run_key,
7168            CachedTextGlyphRun {
7169                glyphs: glyphs.clone(),
7170                bounds,
7171                atlas_entries: None,
7172                atlas_generation: 0,
7173                last_frame: Cell::new(frame),
7174            },
7175        );
7176        Some(TextGlyphRunLookup {
7177            glyphs,
7178            bounds,
7179            cached: false,
7180            entries: None,
7181        })
7182    }
7183
7184    /// Appends the draws of a text's run: its retained quads when it has
7185    /// them, else its visible quads into the frame's shared glyphs. `false`
7186    /// when the atlas cannot hold its glyphs.
7187    fn append_text_glyph_run(
7188        &mut self,
7189        draw: TextGlyphRunDraw<'_>,
7190        (viewport, root_scale): (ViewportUniformParams, f32),
7191        (collected_run, generated_entries): (
7192            &[SoftwareGlyphAtlasRunGlyph],
7193            &mut Vec<GlyphAtlasEntry>,
7194        ),
7195        glyph_instances: &mut GlyphInstances,
7196        glyph_cmds: &mut Vec<GlyphDrawCmd>,
7197    ) -> bool {
7198        let TextGlyphRunDraw {
7199            text_draw,
7200            raster_rect,
7201            run_key,
7202            run,
7203        } = draw;
7204        let draw_rect = Rect {
7205            x: raster_rect.x / root_scale,
7206            y: raster_rect.y / root_scale,
7207            width: raster_rect.width / root_scale,
7208            height: raster_rect.height / root_scale,
7209        };
7210        let Some(scissor) = scissor_rect_for_layer(draw_rect, text_draw.clip, root_scale, viewport)
7211        else {
7212            return true;
7213        };
7214        let texel = self.text_glyph_atlas.texel();
7215
7216        // A retained run's quads are uploaded whole: under a turn only the
7217        // shared path cuts them to a clip.
7218        let clip_needs_cut = !viewport.transform.is_identity() && text_draw.clip.is_some();
7219        if let Some(entries) = run.entries.as_ref()
7220            && entries.len() >= RETAINED_TEXT_GLYPH_RUN_MIN_QUADS
7221            && !clip_needs_cut
7222            && self.emit_retained_text_glyph_run_if_ready(
7223                run_key,
7224                GlyphRunQuads {
7225                    glyphs: &run.glyphs,
7226                    entries,
7227                    texel,
7228                    bounds: run.bounds,
7229                },
7230                viewport,
7231                raster_rect,
7232                scissor,
7233                glyph_cmds,
7234            )
7235        {
7236            return true;
7237        }
7238
7239        let turned = !viewport.transform.is_identity();
7240        let instance_start = glyph_instances.len_of(turned);
7241        let (entries, entries_cached) = match run.entries {
7242            Some(entries) => (entries, true),
7243            None => {
7244                let Ok(entries) = self.prepare_text_glyph_entries(
7245                    run_key,
7246                    self.text_glyph_atlas.generation(),
7247                    run.cached.then_some(&run.glyphs),
7248                    collected_run,
7249                    generated_entries,
7250                ) else {
7251                    return false;
7252                };
7253                (entries, false)
7254            }
7255        };
7256        let quads = GlyphRunQuads {
7257            glyphs: &run.glyphs,
7258            entries: &entries,
7259            texel: self.text_glyph_atlas.texel(),
7260            bounds: run.bounds,
7261        };
7262        let cut = glyph_cut_edges(text_draw.clip, scissor, viewport, root_scale);
7263        let (kind, extent) = self.append_text_glyph_quad_run(
7264            raster_rect,
7265            quads,
7266            (text_draw.clip, cut),
7267            viewport,
7268            root_scale,
7269            glyph_instances,
7270            entries_cached,
7271        );
7272        let instance_end = glyph_instances.len_of(turned);
7273        if instance_end > instance_start {
7274            let (clip, bounds) = if turned {
7275                (None, scissor)
7276            } else {
7277                shared_glyph_clip(extent, scissor, viewport)
7278            };
7279            glyph_cmds.push(GlyphDrawCmd::shared(
7280                (instance_start..instance_end, kind),
7281                clip,
7282                bounds,
7283                self.text_glyph_atlas.bind_group(viewport.transform),
7284            ));
7285        }
7286        true
7287    }
7288
7289    #[expect(clippy::too_many_arguments)]
7290    fn append_image_bitmap_draw_cmd(
7291        &mut self,
7292        image: &ImageBitmap,
7293        rect: Rect,
7294        clip: Option<Rect>,
7295        sampling: ImageSampling,
7296        viewport: ViewportUniformParams,
7297        root_scale: f32,
7298        image_vertices: &mut Vec<Vertex>,
7299        image_indices: &mut Vec<u32>,
7300        image_cmds: &mut Vec<ImageDrawCmd>,
7301    ) -> Result<(), String> {
7302        if rect.width <= 0.0 || rect.height <= 0.0 {
7303            return Ok(());
7304        }
7305
7306        let (device_quad, scissor_rect) =
7307            if sampling == ImageSampling::Nearest && root_scale.is_finite() && root_scale > 0.0 {
7308                let left_px = (rect.x * root_scale).round();
7309                let top_px = (rect.y * root_scale).round();
7310                let width_px = (rect.width * root_scale).round().max(1.0);
7311                let height_px = (rect.height * root_scale).round().max(1.0);
7312                let snapped_rect = Rect {
7313                    x: left_px / root_scale,
7314                    y: top_px / root_scale,
7315                    width: width_px / root_scale,
7316                    height: height_px / root_scale,
7317                };
7318                let right_px = left_px + width_px;
7319                let bottom_px = top_px + height_px;
7320                (
7321                    [
7322                        [left_px, top_px],
7323                        [right_px, top_px],
7324                        [left_px, bottom_px],
7325                        [right_px, bottom_px],
7326                    ],
7327                    snapped_rect,
7328                )
7329            } else {
7330                (
7331                    rect_to_quad(rect).map(|[x, y]| [x * root_scale, y * root_scale]),
7332                    rect,
7333                )
7334            };
7335
7336        let Some(scissor) = scissor_rect_for_layer(scissor_rect, clip, root_scale, viewport) else {
7337            return Ok(());
7338        };
7339        let Some(uv_rect) = image_uv_rect(image, None) else {
7340            return Ok(());
7341        };
7342
7343        let index_start = push_image_quad(
7344            (image_vertices, image_indices),
7345            device_quad,
7346            [1.0, 1.0, 1.0, 1.0],
7347            &uv_rect,
7348        );
7349        image_cmds.push(ImageDrawCmd {
7350            index_start,
7351            scissor,
7352            image: self.image_binding(image, sampling)?,
7353            clip: None,
7354        });
7355        Ok(())
7356    }
7357
7358    /// Appends `text_draw` as a rasterized image if `viewport` shows it.
7359    pub(crate) fn append_text_image_draw_cmds(
7360        &mut self,
7361        text_draw: &TextDraw,
7362        viewport: ViewportUniformParams,
7363        root_scale: f32,
7364        image_vertices: &mut Vec<Vertex>,
7365        image_indices: &mut Vec<u32>,
7366        image_cmds: &mut Vec<ImageDrawCmd>,
7367    ) -> Result<(), String> {
7368        let Some((logical_rect, raster_rect, clip, text_scale, static_text_motion)) =
7369            self.text_raster_geometry(text_draw, root_scale)
7370        else {
7371            return Ok(());
7372        };
7373        if !text_draw_is_visible_in_viewport(logical_rect, clip, viewport, root_scale) {
7374            return Ok(());
7375        }
7376
7377        let raster_source = self.text_image_raster_source(
7378            text_draw,
7379            logical_rect,
7380            raster_rect,
7381            clip,
7382            root_scale,
7383            static_text_motion,
7384        );
7385        let source_draw = raster_source.draw.as_ref();
7386        let source_raster_rect = raster_source.raster_rect;
7387        let source_origin = if source_draw.text.string().span_styles().is_empty() {
7388            Point::new(source_raster_rect.x, source_raster_rect.y)
7389        } else {
7390            Point::new(raster_rect.x, raster_rect.y)
7391        };
7392
7393        let mut cache_key = Self::text_image_cache_key(
7394            source_draw,
7395            source_raster_rect,
7396            text_scale,
7397            static_text_motion,
7398        );
7399        if !source_draw.text.string().span_styles().is_empty() {
7400            let mut state = default_hash::new();
7401            cache_key.0.hash(&mut state);
7402            (source_origin.x - source_raster_rect.x)
7403                .to_bits()
7404                .hash(&mut state);
7405            (source_origin.y - source_raster_rect.y)
7406                .to_bits()
7407                .hash(&mut state);
7408            cache_key = TextImageCacheKey(state.finish());
7409        }
7410        let image = if let Some(cached) = self.text_image_cache.get(&cache_key) {
7411            self.frame_stats
7412                .record_text_image_cache_hit(cached.image.width(), cached.image.height());
7413            cached.image.clone()
7414        } else {
7415            let Some(image) = self.rasterize_text_draw_to_image(
7416                source_draw,
7417                source_raster_rect,
7418                source_origin,
7419                text_scale,
7420            ) else {
7421                return Ok(());
7422            };
7423            self.frame_stats
7424                .record_text_image_cache_miss(image.width(), image.height());
7425            self.text_image_cache.put(
7426                cache_key,
7427                CachedTextImage {
7428                    image: image.clone(),
7429                },
7430            );
7431            image
7432        };
7433
7434        let draw_origin = if static_text_motion {
7435            Point::new(
7436                source_raster_rect.x / root_scale,
7437                source_raster_rect.y / root_scale,
7438            )
7439        } else {
7440            Point::new(logical_rect.x, logical_rect.y)
7441        };
7442        let draw_rect = Rect {
7443            x: draw_origin.x,
7444            y: draw_origin.y,
7445            width: image.width() as f32 / root_scale,
7446            height: image.height() as f32 / root_scale,
7447        };
7448        self.append_image_bitmap_draw_cmd(
7449            &image,
7450            draw_rect,
7451            clip,
7452            sampling_under(ImageSampling::Nearest, viewport.transform),
7453            viewport,
7454            root_scale,
7455            image_vertices,
7456            image_indices,
7457            image_cmds,
7458        )
7459    }
7460
7461    fn text_image_raster_source<'a>(
7462        &mut self,
7463        text_draw: &'a TextDraw,
7464        logical_rect: Rect,
7465        raster_rect: Rect,
7466        clip: Option<Rect>,
7467        root_scale: f32,
7468        static_text_motion: bool,
7469    ) -> TextRasterSource<'a> {
7470        let Some(clip) = clip else {
7471            return TextRasterSource {
7472                draw: Cow::Borrowed(text_draw),
7473                raster_rect,
7474            };
7475        };
7476        if !static_text_motion || text_draw.text.string().text().find('\n').is_none() {
7477            return TextRasterSource {
7478                draw: Cow::Borrowed(text_draw),
7479                raster_rect,
7480            };
7481        }
7482
7483        if !text_draw.text.string().span_styles().is_empty() {
7484            let device_clip = Rect {
7485                x: (clip.x * root_scale).floor(),
7486                y: (clip.y * root_scale).floor(),
7487                width: ((clip.x + clip.width) * root_scale).ceil() - (clip.x * root_scale).floor(),
7488                height: ((clip.y + clip.height) * root_scale).ceil()
7489                    - (clip.y * root_scale).floor(),
7490            };
7491            return TextRasterSource {
7492                draw: Cow::Borrowed(text_draw),
7493                raster_rect: raster_rect.intersect(device_clip).unwrap_or(raster_rect),
7494            };
7495        }
7496
7497        let line_starts = self
7498            .text_line_index_cache
7499            .line_starts(text_draw.text.string());
7500        clipped_text_raster_source_with_line_starts(
7501            text_draw,
7502            logical_rect,
7503            raster_rect,
7504            clip,
7505            root_scale,
7506            line_starts.as_ref(),
7507        )
7508    }
7509
7510    fn text_raster_geometry(
7511        &self,
7512        text_draw: &TextDraw,
7513        root_scale: f32,
7514    ) -> Option<(Rect, Rect, Option<Rect>, f32, bool)> {
7515        text_raster_geometry_for_draw(text_draw, root_scale)
7516    }
7517
7518    fn text_image_cache_key(
7519        text_draw: &TextDraw,
7520        raster_rect: Rect,
7521        text_scale: f32,
7522        static_text_motion: bool,
7523    ) -> TextImageCacheKey {
7524        let mut state = default_hash::new();
7525        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7526        hash_text_raster_geometry_for_cache(raster_rect, static_text_motion, &mut state);
7527        TextImageCacheKey(state.finish())
7528    }
7529
7530    /// The key of a static text's glyph run. A run places its glyphs from
7531    /// the text's origin and aligns its lines within the text block, so the
7532    /// size of the rect it draws in does not change it: only an empty rect,
7533    /// which draws nothing, does.
7534    fn text_glyph_run_cache_key(
7535        text_draw: &TextDraw,
7536        raster_rect: Rect,
7537        text_scale: f32,
7538    ) -> TextGlyphRunCacheKey {
7539        let mut state = default_hash::new();
7540        hash_text_draw_for_cache(text_draw, raster_rect, text_scale, &mut state);
7541        (raster_rect.width <= 0.0 || raster_rect.height <= 0.0).hash(&mut state);
7542        TextGlyphRunCacheKey(state.finish())
7543    }
7544
7545    fn rasterize_text_draw_to_image(
7546        &mut self,
7547        text_draw: &TextDraw,
7548        raster_rect: Rect,
7549        source_origin: Point,
7550        text_scale: f32,
7551    ) -> Option<ImageBitmap> {
7552        rasterize_annotated_text_region(
7553            text_draw.text.string().as_ref(),
7554            raster_rect,
7555            if text_draw.text.string().span_styles().is_empty() {
7556                Point::new(raster_rect.x, raster_rect.y)
7557            } else {
7558                source_origin
7559            },
7560            &text_draw.text_style,
7561            text_draw.color,
7562            text_draw.font_size,
7563            text_scale,
7564            &self.text_fonts,
7565            Some(&mut self.text_glyph_mask_cache),
7566        )
7567    }
7568}
7569
7570struct TextRasterSource<'a> {
7571    draw: Cow<'a, TextDraw>,
7572    raster_rect: Rect,
7573}
7574
7575fn clipped_text_raster_source_with_line_starts<'a>(
7576    text_draw: &'a TextDraw,
7577    logical_rect: Rect,
7578    raster_rect: Rect,
7579    clip: Rect,
7580    root_scale: f32,
7581    line_starts: &[usize],
7582) -> TextRasterSource<'a> {
7583    if line_starts.len() < MIN_MULTILINE_TEXT_LINES_FOR_CLIPPED_RASTER {
7584        return TextRasterSource {
7585            draw: Cow::Borrowed(text_draw),
7586            raster_rect,
7587        };
7588    }
7589
7590    let Some(visible_rect) = logical_rect.intersect(clip) else {
7591        return TextRasterSource {
7592            draw: Cow::Borrowed(text_draw),
7593            raster_rect,
7594        };
7595    };
7596
7597    let line_count = line_starts.len().max(1);
7598    let line_height = logical_rect.height / line_count as f32;
7599    if !line_height.is_finite() || line_height <= 0.0 {
7600        return TextRasterSource {
7601            draw: Cow::Borrowed(text_draw),
7602            raster_rect,
7603        };
7604    }
7605
7606    let visible_top = ((visible_rect.y - logical_rect.y) / line_height).floor() as isize;
7607    let visible_bottom =
7608        ((visible_rect.y + visible_rect.height - logical_rect.y) / line_height).ceil() as isize;
7609    let start_line = visible_top.saturating_sub(1).max(0) as usize;
7610    let end_line = (visible_bottom + 1).max(start_line as isize + 1) as usize;
7611    let end_line = end_line.min(line_count);
7612    if start_line == 0 && end_line >= line_count {
7613        return TextRasterSource {
7614            draw: Cow::Borrowed(text_draw),
7615            raster_rect,
7616        };
7617    }
7618
7619    let byte_start = line_starts[start_line];
7620    let byte_end = line_end_offset(text_draw.text.string().text(), line_starts, end_line - 1);
7621    if byte_start >= byte_end {
7622        return TextRasterSource {
7623            draw: Cow::Borrowed(text_draw),
7624            raster_rect,
7625        };
7626    }
7627
7628    let slice_y = logical_rect.y + start_line as f32 * line_height;
7629    let slice_height = (end_line - start_line) as f32 * line_height;
7630    let mut slice_raster_rect = Rect {
7631        x: logical_rect.x * root_scale,
7632        y: slice_y * root_scale,
7633        width: logical_rect.width * root_scale,
7634        height: slice_height * root_scale,
7635    };
7636    slice_raster_rect.x = slice_raster_rect.x.round();
7637    slice_raster_rect.y = slice_raster_rect.y.round();
7638    slice_raster_rect.width = slice_raster_rect.width.ceil().max(1.0);
7639    slice_raster_rect.height = slice_raster_rect.height.ceil().max(1.0);
7640
7641    let mut sliced_draw = text_draw.clone();
7642    sliced_draw.rect = Rect {
7643        x: logical_rect.x,
7644        y: slice_y,
7645        width: logical_rect.width,
7646        height: slice_height,
7647    };
7648    sliced_draw.text = DrawnText::of(
7649        Arc::new(text_draw.text.string().subsequence(byte_start..byte_end)),
7650        &text_draw.text_style,
7651    );
7652
7653    TextRasterSource {
7654        draw: Cow::Owned(sliced_draw),
7655        raster_rect: slice_raster_rect,
7656    }
7657}
7658
7659fn line_start_offsets(text: &str) -> Vec<usize> {
7660    let mut starts =
7661        Vec::with_capacity(text.as_bytes().iter().filter(|b| **b == b'\n').count() + 1);
7662    starts.push(0);
7663    starts.extend(
7664        text.char_indices()
7665            .filter_map(|(index, ch)| (ch == '\n').then_some(index + ch.len_utf8())),
7666    );
7667    starts
7668}
7669
7670fn line_end_offset(text: &str, line_starts: &[usize], line: usize) -> usize {
7671    line_starts.get(line + 1).copied().unwrap_or(text.len())
7672}
7673
7674fn align_to(value: u32, alignment: u32) -> u32 {
7675    debug_assert!(alignment > 0);
7676    value.div_ceil(alignment) * alignment
7677}
7678
7679impl GpuRenderer {
7680    fn convert_surface_pixels_to_rgba(&self, pixels: &[u8]) -> Result<Vec<u8>, String> {
7681        if !pixels.len().is_multiple_of(4) {
7682            return Err("Screenshot readback has an incomplete pixel".to_string());
7683        }
7684        Ok(pixels.to_vec())
7685    }
7686}
7687
7688/// The scissor of a logical rect in a target whose origin sits at
7689/// `viewport.offset` of the scene's device space, clamped to the target.
7690/// `None` when nothing of the rect lands in the target.
7691pub(crate) fn scissor_rect_for_rect(
7692    rect: Rect,
7693    root_scale: f32,
7694    viewport: ViewportUniformParams,
7695) -> Option<(u32, u32, u32, u32)> {
7696    let width = viewport.width as f32;
7697    let height = viewport.height as f32;
7698    let mut left = canonicalize_device_coordinate(rect.x * root_scale);
7699    let mut top = canonicalize_device_coordinate(rect.y * root_scale);
7700    let mut right = canonicalize_device_coordinate((rect.x + rect.width) * root_scale);
7701    let mut bottom = canonicalize_device_coordinate((rect.y + rect.height) * root_scale);
7702    if !viewport.transform.is_identity() {
7703        let bounds = viewport.transform.target_bounds(Rect {
7704            x: left,
7705            y: top,
7706            width: right - left,
7707            height: bottom - top,
7708        });
7709        (left, top) = (bounds.x, bounds.y);
7710        (right, bottom) = (bounds.x + bounds.width, bounds.y + bounds.height);
7711    }
7712    let left = (left - viewport.offset[0]).clamp(0.0, width).floor();
7713    let top = (top - viewport.offset[1]).clamp(0.0, height).floor();
7714    let right = (right - viewport.offset[0]).clamp(0.0, width).ceil();
7715    let bottom = (bottom - viewport.offset[1]).clamp(0.0, height).ceil();
7716    if right <= left || bottom <= top {
7717        return None;
7718    }
7719    Some((
7720        left as u32,
7721        top as u32,
7722        (right - left) as u32,
7723        (bottom - top) as u32,
7724    ))
7725}
7726
7727fn scissor_rect_for_layer(
7728    rect: Rect,
7729    clip: Option<Rect>,
7730    root_scale: f32,
7731    viewport: ViewportUniformParams,
7732) -> Option<(u32, u32, u32, u32)> {
7733    let clipped_rect = match clip {
7734        Some(clip_rect) => rect.intersect(clip_rect)?,
7735        None => rect,
7736    };
7737    scissor_rect_for_rect(clipped_rect, root_scale, viewport)
7738}
7739fn tint_for_image(
7740    color_filter: Option<&ColorFilter>,
7741    alpha: f32,
7742) -> ([f32; 4], Option<&ColorFilter>) {
7743    let alpha = alpha.clamp(0.0, 1.0);
7744    match color_filter {
7745        Some(filter) if filter.supports_gpu_vertex_modulation() => {
7746            let Some(tint) = filter.gpu_vertex_tint() else {
7747                return ([1.0, 1.0, 1.0, alpha], Some(filter));
7748            };
7749            (
7750                [
7751                    tint[0].clamp(0.0, 1.0),
7752                    tint[1].clamp(0.0, 1.0),
7753                    tint[2].clamp(0.0, 1.0),
7754                    (tint[3] * alpha).clamp(0.0, 1.0),
7755                ],
7756                None,
7757            )
7758        }
7759        Some(filter) => ([1.0, 1.0, 1.0, alpha], Some(filter)),
7760        None => ([1.0, 1.0, 1.0, alpha], None),
7761    }
7762}
7763
7764/// The rounded clip an image takes in place, in device pixels: one instance
7765/// its draw reads, beside the quad's vertices.
7766#[repr(C)]
7767#[derive(Clone, Copy, Debug, Pod, Zeroable)]
7768pub(crate) struct DeviceRoundedClip {
7769    rect: [f32; 4],
7770    radius: f32,
7771}
7772
7773impl DeviceRoundedClip {
7774    const ATTRIBS: [wgpu::VertexAttribute; 2] = wgpu::vertex_attr_array![
7775        4 => Float32x4,
7776        5 => Float32,
7777    ];
7778
7779    fn desc() -> wgpu::VertexBufferLayout<'static> {
7780        wgpu::VertexBufferLayout {
7781            array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
7782            step_mode: wgpu::VertexStepMode::Instance,
7783            attributes: &Self::ATTRIBS,
7784        }
7785    }
7786
7787    /// The rounded clip `image` takes at `root_scale`, scaled as a run's
7788    /// placement scales its clip.
7789    fn of(image: &ImageDraw, root_scale: f32) -> Option<Self> {
7790        let rounding = image.rounding.filter(|_| image.clip.is_some())?;
7791        let device =
7792            crate::geometry::device_rect(rounding.rect, root_scale, image.snap_anchor.is_some());
7793        Some(Self {
7794            rect: [device.x, device.y, device.width, device.height],
7795            radius: rounding.radius * root_scale,
7796        })
7797    }
7798}
7799
7800/// Appends an image quad over `device_quad` and its two triangles, and
7801/// returns the index its triangles start at.
7802fn push_image_quad(
7803    (vertices, indices): (&mut Vec<Vertex>, &mut Vec<u32>),
7804    device_quad: [[f32; 2]; 4],
7805    color: [f32; 4],
7806    uv_rect: &ImageUvRect,
7807) -> u32 {
7808    let base_vertex = vertices.len() as u32;
7809    let index_start = indices.len() as u32;
7810    indices.extend_from_slice(&[
7811        base_vertex,
7812        base_vertex + 1,
7813        base_vertex + 2,
7814        base_vertex + 2,
7815        base_vertex + 1,
7816        base_vertex + 3,
7817    ]);
7818    let corners = [
7819        [uv_rect.min[0], uv_rect.min[1]],
7820        [uv_rect.max[0], uv_rect.min[1]],
7821        [uv_rect.min[0], uv_rect.max[1]],
7822        [uv_rect.max[0], uv_rect.max[1]],
7823    ];
7824    vertices.extend(
7825        device_quad
7826            .into_iter()
7827            .zip(corners)
7828            .map(|(position, uv)| Vertex {
7829                position,
7830                color,
7831                uv,
7832                uv_bounds: uv_rect.sample_bounds,
7833            }),
7834    );
7835    index_start
7836}
7837
7838fn image_uv_rect(image: &ImageBitmap, src_rect: Option<Rect>) -> Option<ImageUvRect> {
7839    let Some(src) = src_rect else {
7840        return Some(ImageUvRect {
7841            min: [0.0, 0.0],
7842            max: [1.0, 1.0],
7843            sample_bounds: [0.0, 0.0, 1.0, 1.0],
7844        });
7845    };
7846
7847    let (u_min, u_max, u_bound_min, u_bound_max) =
7848        source_axis_uv(src.x, src.width, image.width() as f32)?;
7849    let (v_min, v_max, v_bound_min, v_bound_max) =
7850        source_axis_uv(src.y, src.height, image.height() as f32)?;
7851
7852    Some(ImageUvRect {
7853        min: [u_min, v_min],
7854        max: [u_max, v_max],
7855        sample_bounds: [u_bound_min, v_bound_min, u_bound_max, v_bound_max],
7856    })
7857}
7858
7859/// `entry`'s rect in an atlas whose texel is `texel` of its side, an
7860/// exact power of two: the products are the quotients by the side.
7861fn glyph_atlas_uv_rect(entry: GlyphAtlasEntry, texel: f32) -> ImageUvRect {
7862    let min = [entry.x as f32 * texel, entry.y as f32 * texel];
7863    let max = [
7864        (entry.x + entry.width) as f32 * texel,
7865        (entry.y + entry.height) as f32 * texel,
7866    ];
7867    let center_min = [
7868        (entry.x as f32 + 0.5) * texel,
7869        (entry.y as f32 + 0.5) * texel,
7870    ];
7871    let center_max = [
7872        (entry.x as f32 + entry.width as f32 - 0.5).max(entry.x as f32 + 0.5) * texel,
7873        (entry.y as f32 + entry.height as f32 - 0.5).max(entry.y as f32 + 0.5) * texel,
7874    ];
7875    ImageUvRect {
7876        min,
7877        max,
7878        sample_bounds: [center_min[0], center_min[1], center_max[0], center_max[1]],
7879    }
7880}
7881
7882#[derive(Clone, Copy)]
7883pub(crate) struct ResolvedImageGeometry {
7884    pub(crate) rect: Rect,
7885    pub(crate) clip: Option<Rect>,
7886    pub(crate) sampling: ImageSampling,
7887    quad: [[f32; 2]; 4],
7888    snap_anchored: bool,
7889}
7890
7891pub(crate) fn resolve_image_geometry(image: &ImageDraw, root_scale: f32) -> ResolvedImageGeometry {
7892    let snap_delta = image
7893        .snap_anchor
7894        .map(|anchor| snap_delta_for_anchor(anchor, root_scale))
7895        .unwrap_or_default();
7896    resolve_image_geometry_with_delta(image, root_scale, snap_delta)
7897}
7898
7899fn resolve_image_geometry_with_delta(
7900    image: &ImageDraw,
7901    root_scale: f32,
7902    snap_delta: Point,
7903) -> ResolvedImageGeometry {
7904    let mut rect = image.rect.translate(snap_delta.x, snap_delta.y);
7905    let mut quad = translate_quad(image.quad, snap_delta);
7906    snap_nearest_image_to_device_pixels(image.sampling, &mut rect, &mut quad, root_scale);
7907    ResolvedImageGeometry {
7908        rect,
7909        clip: image.clip,
7910        sampling: image.sampling,
7911        quad,
7912        snap_anchored: image.snap_anchor.is_some(),
7913    }
7914}
7915
7916impl ResolvedImageGeometry {
7917    pub(crate) fn device_quad(self, root_scale: f32) -> [[f32; 2]; 4] {
7918        nearest_image_device_quad(self.sampling, self.quad, root_scale).unwrap_or_else(|| {
7919            if self.snap_anchored {
7920                canonicalized_scaled_quad(self.quad, root_scale)
7921            } else {
7922                scaled_quad(self.quad, root_scale)
7923            }
7924        })
7925    }
7926}
7927
7928fn snap_nearest_image_to_device_pixels(
7929    sampling: ImageSampling,
7930    rect: &mut Rect,
7931    quad: &mut [[f32; 2]; 4],
7932    root_scale: f32,
7933) {
7934    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7935        return;
7936    }
7937
7938    let Some(quad_rect) = axis_aligned_quad_rect(*quad) else {
7939        return;
7940    };
7941
7942    let left_px = (quad_rect.x * root_scale).round();
7943    let top_px = (quad_rect.y * root_scale).round();
7944    let width_px = (quad_rect.width * root_scale).round().max(1.0);
7945    let height_px = (quad_rect.height * root_scale).round().max(1.0);
7946    let snapped = Rect {
7947        x: left_px / root_scale,
7948        y: top_px / root_scale,
7949        width: width_px / root_scale,
7950        height: height_px / root_scale,
7951    };
7952
7953    *rect = snapped;
7954    *quad = crate::rect_to_quad(snapped);
7955}
7956
7957fn nearest_image_device_quad(
7958    sampling: ImageSampling,
7959    quad: [[f32; 2]; 4],
7960    root_scale: f32,
7961) -> Option<[[f32; 2]; 4]> {
7962    if sampling != ImageSampling::Nearest || !root_scale.is_finite() || root_scale <= 0.0 {
7963        return None;
7964    }
7965
7966    let rect = axis_aligned_quad_rect(quad)?;
7967    let left_px = (rect.x * root_scale).round();
7968    let top_px = (rect.y * root_scale).round();
7969    let width_px = (rect.width * root_scale).round().max(1.0);
7970    let height_px = (rect.height * root_scale).round().max(1.0);
7971    let right_px = left_px + width_px;
7972    let bottom_px = top_px + height_px;
7973    Some([
7974        [left_px, top_px],
7975        [right_px, top_px],
7976        [left_px, bottom_px],
7977        [right_px, bottom_px],
7978    ])
7979}
7980
7981fn source_axis_uv(start: f32, extent: f32, image_extent: f32) -> Option<(f32, f32, f32, f32)> {
7982    if !start.is_finite()
7983        || !extent.is_finite()
7984        || !image_extent.is_finite()
7985        || extent == 0.0
7986        || image_extent <= 0.0
7987    {
7988        return None;
7989    }
7990
7991    let end = start + extent;
7992    let edge_min = start.min(end).clamp(0.0, image_extent);
7993    let edge_max = start.max(end).clamp(0.0, image_extent);
7994    if edge_max <= edge_min {
7995        return None;
7996    }
7997
7998    let center_min = edge_min + 0.5;
7999    let center_max = edge_max - 0.5;
8000    let (bound_min, bound_max) = if center_min <= center_max {
8001        (center_min, center_max)
8002    } else {
8003        let center = (edge_min + edge_max) * 0.5;
8004        (center, center)
8005    };
8006
8007    Some((
8008        edge_min / image_extent,
8009        edge_max / image_extent,
8010        bound_min / image_extent,
8011        bound_max / image_extent,
8012    ))
8013}
8014
8015fn apply_filter_to_bitmap(
8016    image: &ImageBitmap,
8017    filter: &ColorFilter,
8018) -> Result<ImageBitmap, String> {
8019    let pixel_count = image.width() as usize * image.height() as usize;
8020    let mut filtered = Vec::with_capacity(pixel_count * 4);
8021    for index in 0..pixel_count {
8022        let pixel = image.rgba8_pixel(index);
8023        let rgba = [
8024            pixel[0] as f32 / 255.0,
8025            pixel[1] as f32 / 255.0,
8026            pixel[2] as f32 / 255.0,
8027            pixel[3] as f32 / 255.0,
8028        ];
8029        let out = filter.apply_rgba(rgba);
8030        filtered.push((out[0].clamp(0.0, 1.0) * 255.0).round() as u8);
8031        filtered.push((out[1].clamp(0.0, 1.0) * 255.0).round() as u8);
8032        filtered.push((out[2].clamp(0.0, 1.0) * 255.0).round() as u8);
8033        filtered.push((out[3].clamp(0.0, 1.0) * 255.0).round() as u8);
8034    }
8035    ImageBitmap::from_rgba8(image.width(), image.height(), filtered)
8036        .map_err(|error| format!("failed to build filtered bitmap: {error}"))
8037}
8038
8039/// How a text raster samples its texels under a segment transform: as it
8040/// asks on the pixel grid, and filtered once a transform turns it off the
8041/// grid, where no texel lands on a pixel for nearest sampling to keep.
8042fn sampling_under(sampling: ImageSampling, transform: SegmentTransform) -> ImageSampling {
8043    if transform.is_identity() {
8044        sampling
8045    } else {
8046        ImageSampling::Linear
8047    }
8048}
8049
8050/// The rounded mask a shadow's composite applies, in the scene's device
8051/// pixels: an inner shadow masks itself to its fill shape, and a shadow
8052/// lowered out of a clipped layer masks itself to that layer's rounded clip.
8053pub(crate) fn shadow_composite_mask(
8054    shadow: &ShadowDraw,
8055    snap_anchor: Option<SnapAnchor>,
8056    root_scale: f32,
8057) -> Option<RoundedCompositeMask> {
8058    inner_shadow_composite_mask(shadow, root_scale).or_else(|| {
8059        shadow.rounded_clip.map(|clip| RoundedCompositeMask {
8060            rect: mask_rect(anchored_device_rect(clip.rect, snap_anchor, root_scale)),
8061            radii: clip.radii.map(|radius| radius * root_scale),
8062        })
8063    })
8064}
8065
8066/// A scene holding just a shadow's own draws, in the order they arrive, so
8067/// the shadow source renders through the same pass encoder as everything
8068/// else.
8069fn shadow_scene(
8070    shapes: Option<&RunDraw>,
8071    texts: &[TextDraw],
8072    input_margin: f32,
8073) -> CompositorScene {
8074    let mut scene = CompositorScene::new();
8075    if let Some(run) = shapes {
8076        scene.push_run(run.clone());
8077    }
8078    for text in texts {
8079        let z_index = scene.next_z();
8080        scene.draw_ops.push(DrawOp {
8081            z_index,
8082            kind: DrawOpKind::Text(scene.texts.len()),
8083        });
8084        let mut source_text = text.clone();
8085        source_text.clip = source_text
8086            .clip
8087            .map(|clip| expand_rect(clip, input_margin, input_margin));
8088        scene.texts.push(source_text);
8089        scene.next_z += 1;
8090    }
8091    scene
8092}
8093
8094/// The whole device pixels a logical rect covers, or `None` when it covers
8095/// none or more than a texture can hold.
8096fn device_pixel_bounds(
8097    rect: Rect,
8098    root_scale: f32,
8099    max_texture_dim: u32,
8100) -> Option<DevicePixelBounds> {
8101    let x = (rect.x * root_scale).floor();
8102    let y = (rect.y * root_scale).floor();
8103    let right = ((rect.x + rect.width) * root_scale).ceil();
8104    let bottom = ((rect.y + rect.height) * root_scale).ceil();
8105    let width = (right - x).max(0.0) as u32;
8106    let height = (bottom - y).max(0.0) as u32;
8107    if width == 0 || height == 0 || width > max_texture_dim || height > max_texture_dim {
8108        return None;
8109    }
8110    Some(DevicePixelBounds {
8111        x,
8112        y,
8113        width,
8114        height,
8115    })
8116}
8117fn inner_shadow_composite_mask(
8118    shadow: &ShadowDraw,
8119    root_scale: f32,
8120) -> Option<RoundedCompositeMask> {
8121    let run = shadow.shapes.as_ref()?;
8122    if !run
8123        .tables()
8124        .shapes
8125        .iter()
8126        .any(|record| record.blend_mode() == BlendMode::DstOut)
8127    {
8128        return None;
8129    }
8130    let fill = run.tables().shapes.get(0)?;
8131    let rect = run.placement.translated_bounds(fill.stored_rect());
8132    if rect.width <= 0.0 || rect.height <= 0.0 {
8133        return None;
8134    }
8135    let resolved =
8136        cranpose_ui_graphics::RoundedCornerShape::with_radii(cranpose_ui_graphics::CornerRadii {
8137            top_left: fill.radii[0],
8138            top_right: fill.radii[1],
8139            bottom_right: fill.radii[2],
8140            bottom_left: fill.radii[3],
8141        })
8142        .resolve(rect.width, rect.height);
8143    let radii = [
8144        resolved.top_left * root_scale,
8145        resolved.top_right * root_scale,
8146        resolved.bottom_left * root_scale,
8147        resolved.bottom_right * root_scale,
8148    ];
8149
8150    Some(RoundedCompositeMask {
8151        rect: mask_rect(anchored_device_rect(
8152            rect,
8153            run.placement.snap_anchor,
8154            root_scale,
8155        )),
8156        radii,
8157    })
8158}
8159
8160/// One draw call of a run batch's stage: its pipeline, the strip index
8161/// buffer it binds and the indices and records it instances.
8162#[derive(Clone, Debug, PartialEq, Eq)]
8163pub(crate) struct PlannedRunDraw {
8164    pub(crate) key: ShapePipelineKey,
8165    pub(crate) band_class: u8,
8166    pub(crate) indices: std::ops::Range<u32>,
8167    pub(crate) records: std::ops::Range<u32>,
8168}
8169
8170impl PlannedRunDraw {
8171    /// A draw of the paint, as it was recorded.
8172    fn paint(draw: &RunDrawCall) -> Self {
8173        Self {
8174            key: draw.key,
8175            band_class: draw.band_class,
8176            indices: draw.indices(),
8177            records: draw.records.clone(),
8178        }
8179    }
8180}
8181
8182/// The draw calls laying a batch's opaque interiors down: last first, so
8183/// they go down front to back, one call over each stretch of neighbouring
8184/// draws that share the interior pipeline, cut to the span from the stretch's
8185/// first draw holding an occluder to its last. The draws between ride along:
8186/// the pipeline lays any record's exact interior down and skips the rest, so
8187/// taking them costs a few vertices rather than a call, and it shades only a
8188/// record's quad, the first two triangles of every band class's pattern.
8189pub(crate) fn interior_run_draws(draws: &[RunDrawCall]) -> SmallVec<[PlannedRunDraw; 4]> {
8190    struct Stretch {
8191        key: ShapePipelineKey,
8192        start: u32,
8193        span: Option<PlannedRunDraw>,
8194    }
8195    let mut planned: SmallVec<[PlannedRunDraw; 4]> = SmallVec::new();
8196    let mut stretch: Option<Stretch> = None;
8197    for draw in draws.iter().rev() {
8198        let Some(key) = draw.key.interior() else {
8199            planned.extend(stretch.take().and_then(|open| open.span));
8200            continue;
8201        };
8202        if stretch
8203            .as_ref()
8204            .is_some_and(|open| open.key != key || open.start != draw.records.end)
8205        {
8206            planned.extend(stretch.take().and_then(|open| open.span));
8207        }
8208        let open = stretch.get_or_insert(Stretch {
8209            key,
8210            start: draw.records.end,
8211            span: None,
8212        });
8213        open.start = draw.records.start;
8214        if !draw.occluders {
8215            continue;
8216        }
8217        match &mut open.span {
8218            Some(span) => span.records.start = draw.records.start,
8219            None => {
8220                open.span = Some(PlannedRunDraw {
8221                    key,
8222                    band_class: draw.band_class,
8223                    indices: 0..cranpose_ui_graphics::strip_indices(1),
8224                    records: draw.records.clone(),
8225                });
8226            }
8227        }
8228    }
8229    planned.extend(stretch.and_then(|open| open.span));
8230    planned
8231}
8232
8233/// Drops the entries of `cache` no frame drew for more than `idle_frames`
8234/// before `frame`: the least recently used first, which is the order they
8235/// were last drawn in.
8236fn evict_idle<K: Clone + Eq + std::hash::Hash, V>(
8237    cache: &mut BoundedLruCache<K, V>,
8238    frame: u64,
8239    idle_frames: u64,
8240    last_frame: impl Fn(&V) -> u64,
8241) {
8242    while cache
8243        .peek_lru()
8244        .is_some_and(|(_, value)| frame.saturating_sub(last_frame(value)) > idle_frames)
8245    {
8246        cache.pop_lru();
8247    }
8248}
8249
8250/// Cuts the run draws from `start` on to `window` of their records, counted
8251/// across them in order, and drops the draws left with none.
8252fn window_draws(draws: &mut Vec<RunDrawCall>, start: usize, window: &std::ops::Range<u32>) {
8253    let mut relative = 0u32;
8254    let mut kept = start;
8255    for index in start..draws.len() {
8256        let draw = &mut draws[index];
8257        let count = draw.records.end - draw.records.start;
8258        let first = relative;
8259        relative += count;
8260        let keep_start = window.start.max(first).min(first + count);
8261        let keep_end = window.end.min(first + count).max(keep_start);
8262        draw.records =
8263            draw.records.start + (keep_start - first)..draw.records.start + (keep_end - first);
8264        if draw.records.start < draw.records.end {
8265            draws.swap(kept, index);
8266            kept += 1;
8267        }
8268    }
8269    draws.truncate(kept);
8270}
8271
8272#[cfg(test)]
8273#[path = "tests/render_text_bounds_tests.rs"]
8274mod text_bounds_tests;
8275
8276#[cfg(test)]
8277#[path = "tests/render_retained_glyph_tests.rs"]
8278mod retained_glyph_tests;
8279
8280#[cfg(test)]
8281#[path = "tests/frame_clear_tests.rs"]
8282mod frame_clear_tests;
8283
8284#[cfg(test)]
8285#[path = "tests/render_clip_scissor_tests.rs"]
8286mod clip_scissor_tests;
8287
8288#[cfg(test)]
8289#[path = "tests/glyph_kind_tests.rs"]
8290mod glyph_kind_tests;
8291
8292#[cfg(test)]
8293#[path = "tests/glyph_run_bounds_tests.rs"]
8294mod glyph_run_bounds_tests;
8295
8296#[cfg(test)]
8297#[path = "tests/shape_variant_tests.rs"]
8298mod shape_variant_tests;