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